forked from rafia9005/GoLuva
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.go
54 lines (41 loc) · 1021 Bytes
/
middleware.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package middleware
import (
"net/http"
"github.com/gofiber/fiber/v2"
"github.com/rafia9005/GoLuva/utils"
"golang.org/x/crypto/bcrypt"
)
func Auth(c *fiber.Ctx) error {
token := c.Get("x-token")
if token == "" {
return c.Status(http.StatusUnauthorized).JSON(fiber.Map{
"message": "Unauthorized",
})
}
_, err := utils.VerifyToken(token)
claims, err := utils.DecodeToken(token)
if err != nil {
return c.Status(http.StatusUnauthorized).JSON(fiber.Map{
"message": "Unauthorized",
})
}
c.Locals("usersInfo", claims)
c.Locals("role", claims["role"])
return c.Next()
}
func AdminRole(c *fiber.Ctx) error {
role := c.Locals("role")
if role == "user" {
return c.Status(http.StatusForbidden).JSON(fiber.Map{
"message": "forbidden access",
})
}
return c.Next()
}
func HashPassword(password string) (string, error) {
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return "", err
}
return string(hashedPassword), nil
}