Skip to content

Instantly share code, notes, and snippets.

@audstanley
Created April 3, 2021 16:31
Show Gist options
  • Save audstanley/e8f838d54052763a5a4c3bf31969e8c2 to your computer and use it in GitHub Desktop.
Save audstanley/e8f838d54052763a5a4c3bf31969e8c2 to your computer and use it in GitHub Desktop.
package handlers
import (
"context"
"fmt"
"math/rand"
"time"
jwt "github.com/form3tech-oss/jwt-go"
"github.com/gofiber/fiber/v2"
)
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
func RandStringBytes(n int) string {
b := make([]byte, n)
for i := range b {
b[i] = letterBytes[rand.Intn(len(letterBytes))]
}
return string(b)
}
var RedisCtx = context.Background()
func Session(c *fiber.Ctx) error {
user := c.FormValue("user")
pass := c.FormValue("pass")
fmt.Println(c.Cookies("username"), c.Cookies("password"))
wwwAuthentication := c.Get("WWW-Authentication")
authorization := c.Get("Authorization")
switch wwwAuthentication {
case "upass":
fmt.Println(wwwAuthentication, authorization)
case "gtoken":
fmt.Println(wwwAuthentication, authorization)
case "token":
fmt.Println(wwwAuthentication, authorization)
default:
token := jwt.New(jwt.SigningMethodHS256)
claims := token.Claims.(jwt.MapClaims)
userString := RandStringBytes(16)
claims["user"] = userString
claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
fmt.Println(wwwAuthentication, authorization)
t, err := token.SignedString([]byte(Envs["ACCESS_TOKEN_SECRET"]))
if err != nil {
return c.SendStatus(fiber.StatusInternalServerError)
}
c.Set("WWW-Authentication", "gtoken")
c.Set("Authorization", t)
redisErr := GtokenClient.Set(RedisCtx, userString, t, 0).Err()
if redisErr != nil {
fmt.Println("REDIS SET ERROR", redisErr)
fmt.Println("Make sure to set the environment variable: REDIS_PASS")
panic(err)
}
return c.Next()
//return c.JSON(fiber.Map{"token": t, "type": "gtoken"})
}
// placeholder code:
token := jwt.New(jwt.SigningMethodHS256)
claims := token.Claims.(jwt.MapClaims)
claims["user"] = "placeholder"
t, _ := token.SignedString([]byte(Envs["ACCESS_TOKEN_SECRET"]))
return c.JSON(fiber.Map{"token": t})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment