-
Notifications
You must be signed in to change notification settings - Fork 0
/
accessmiddle.go
54 lines (48 loc) · 1.34 KB
/
accessmiddle.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 middlewares
import (
"net/http"
"github.com/IamStubborN/filmtracker/database"
"github.com/IamStubborN/filmtracker/handlers"
"github.com/IamStubborN/filmtracker/jwtmanager"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
)
var jmg *jwtmanager.JwtManager
var db *database.Database
func init() {
jmg = jwtmanager.GetJWTManager()
db = database.GetDB()
}
func AccessMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
accessTokenCookie, err := c.Cookie("Token")
if err != nil {
handlers.RespondWithError(c, http.StatusNotAcceptable, err.Error())
return
}
refreshTokenCookie, err := c.Cookie("Refresh")
if err != nil {
handlers.RespondWithError(c, http.StatusNotAcceptable, err.Error())
return
}
token, err := jmg.ParseToken(accessTokenCookie)
if err != nil {
handlers.RespondWithError(c, http.StatusNotAcceptable, err.Error())
return
}
if token.Valid {
if claims, ok := token.Claims.(jwt.MapClaims); ok {
UserID := claims["user_id"].(string)
user, err := db.GetUserByUserID(UserID)
if err != nil {
handlers.RespondWithError(c, http.StatusNotAcceptable, "User isn't exist")
}
if user.Role == "admin" && user.RefreshToken == refreshTokenCookie {
c.Next()
} else {
handlers.RespondWithError(c, http.StatusUnauthorized, "Access denied")
}
}
}
}
}