Created
May 10, 2020 20:34
-
-
Save LiamDotPro/03352d359762f8283436dc443031e1e5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func UserRoutes(configureGroup *fiber.Group) { | |
users := configureGroup.Group("/users") | |
//Get | |
//Post | |
users.Post("/login", login) | |
//Delete | |
//Patch | |
} | |
func login(c *fiber.Ctx) { | |
user := c.FormValue("user") | |
pass := c.FormValue("pass") | |
// Throws Unauthorized error | |
if user != "john" || pass != "doe" { | |
c.SendStatus(fiber.StatusUnauthorized) | |
return | |
} | |
// Create token | |
token := jwt.New(jwt.SigningMethodHS256) | |
// Set claims | |
claims := token.Claims.(jwt.MapClaims) | |
claims["name"] = "John Doe" | |
claims["admin"] = true | |
claims["exp"] = time.Now().Add(time.Hour * 72).Unix() | |
// Generate encoded token and send it as response. | |
t, err := token.SignedString([]byte("secret")) | |
if err != nil { | |
c.SendStatus(fiber.StatusInternalServerError) | |
return | |
} | |
c.JSON(fiber.Map{"token": t}) | |
} | |
func accessible(c *fiber.Ctx) { | |
c.Send("Accessible") | |
} | |
func restricted(c *fiber.Ctx) { | |
user := c.Locals("user").(*jwt.Token) | |
claims := user.Claims.(jwt.MapClaims) | |
name := claims["name"].(string) | |
c.Send("Welcome " + name) | |
} | |
// Middleware | |
// Load all middleware through here to clean main | |
func Middleware(app *fiber.App) { | |
JWT(app) | |
} | |
func JWT(app *fiber.App) { | |
// JWT Middleware | |
app.Use(jwtware.New(jwtware.Config{ | |
SigningKey: []byte("secret"), | |
Filter: publicRoute, | |
})) | |
} | |
func publicRoute(ctx *fiber.Ctx) bool { | |
return true | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment