-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.go
More file actions
57 lines (53 loc) · 1.33 KB
/
middleware.go
File metadata and controls
57 lines (53 loc) · 1.33 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
package auth
import (
"fmt"
"os"
"personal-erp-backend/database"
"personal-erp-backend/internal/profile"
"time"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
)
func RequireAuth(c *gin.Context) {
authMode := os.Getenv("AUTH_MODE")
if authMode == "false" {
c.Set("userID", 1)
c.Next()
return
}
var tokenString string
tokenString, err := c.Cookie("authorization")
if tokenString == "" {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.JSON(401, gin.H{"unauthorize": err.Error()})
return
}
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 SecretKey, nil
})
if err != nil || !token.Valid {
c.JSON(401, gin.H{"unauthorize": "token invalid"})
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"})
}
var user profile.User
if result := database.DB.First(&user, claims["sub"]); result.Error != nil {
c.AbortWithStatusJSON(401, gin.H{"error": "User no"})
return
}
c.Set("userID", user.ID)
c.Next()
} else {
c.JSON(401, gin.H{"message": "Invalid token"})
return
}
}