-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
85 lines (73 loc) 路 2.15 KB
/
auth.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
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 (
"log"
"net/http"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v4"
"github.com/isaqueveras/powersso/config"
"github.com/isaqueveras/powersso/domain/auth"
"github.com/isaqueveras/powersso/tokens"
)
// Session models the session data
type Session struct {
SessionID string
UserID string
UserLevel string
FirstName string
}
// GetSession gets the session data from the context
func GetSession(ctx *gin.Context) *Session {
session, ok := ctx.Get("SESSION")
if !ok {
ctx.AbortWithStatus(http.StatusUnauthorized)
return nil
}
value := session.(jwt.MapClaims)
return &Session{
SessionID: value["SessionID"].(string),
UserID: value["UserID"].(string),
UserLevel: value["UserLevel"].(string),
FirstName: value["FirstName"].(string),
}
}
// Auth is a middleware to check if the user is authorized to access the resource
func Auth() gin.HandlerFunc {
return func(ctx *gin.Context) {
var token string
if token = ctx.GetHeader("Authorization"); token == "" || len(token) < 30 {
ctx.AbortWithStatus(http.StatusUnauthorized)
return
}
if claims := tokens.ParseJWT(token[7:], config.Get().GetSecrets()); claims != nil {
ctx.Set("UID", claims["UserID"])
ctx.Set("SESSION", claims)
return
}
ctx.AbortWithStatus(http.StatusUnauthorized)
}
}
// OnlyAdmin check if the user is an administrator
func OnlyAdmin() gin.HandlerFunc {
return func(ctx *gin.Context) {
if GetSession(ctx).UserLevel != string(auth.AdminLevel) {
session := GetSession(ctx)
log.Printf("WARNING: user (%v - %v) tried to access user tried to access route for administrators only", session.UserID, session.FirstName)
ctx.AbortWithStatus(http.StatusForbidden)
return
}
ctx.Next()
}
}
// Yourself validates if the logged in user is the same as the request
func Yourself() gin.HandlerFunc {
return func(ctx *gin.Context) {
session := GetSession(ctx)
userIn := ctx.Param("user_uuid")
if session.UserID != userIn {
log.Printf("WARNING: user (%v - %v) tried to access information for user (%v)", session.UserID, session.FirstName, userIn)
ctx.AbortWithStatus(http.StatusForbidden)
return
}
ctx.Next()
}
}