-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.go
More file actions
85 lines (77 loc) · 1.86 KB
/
auth.go
File metadata and controls
85 lines (77 loc) · 1.86 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package middleware
import (
"fmt"
"strings"
"time"
"github.com/Arjuna-Ragil/Localbase/Internal/adapters/repository"
"github.com/Arjuna-Ragil/Localbase/Internal/config"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
)
func AuthMiddleware(userRepo *repository.UserRepository, cfg *config.Config) gin.HandlerFunc {
return func(c *gin.Context) {
if cfg.AuthMode == "false" {
c.Set("userID", uint(1))
c.Set("userRole", "admin")
c.Next()
return
}
tokenString, err := c.Cookie("authorization")
if tokenString == "" {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.JSON(401, gin.H{
"message": "Authorization header not found",
"data": err.Error(),
})
return
}
parts := strings.Split(authHeader, " ")
if len(parts) == 2 {
tokenString = parts[1]
} else {
tokenString = authHeader
}
}
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("method unknown")
}
return []byte(cfg.SecretKey), nil
})
if err != nil || !token.Valid {
c.JSON(401, gin.H{
"message": "Invalid token",
"data": err.Error(),
})
return
}
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
if float64(time.Now().Unix()) > claims["exp"].(float64) {
c.JSON(401, gin.H{
"message": "Token expired",
"data": err.Error(),
})
return
}
subID := uint(claims["sub"].(float64))
user, err := userRepo.FindById(subID)
if err != nil {
c.JSON(401, gin.H{
"message": "User not found",
"data": err.Error(),
})
return
}
c.Set("userID", user.Id)
c.Set("userRole", user.Role)
c.Next()
} else {
c.JSON(401, gin.H{
"message": "Invalid token",
"data": err.Error(),
})
return
}
}
}