forked from tbaehler/gin-keycloak
/
grant_checks.go
74 lines (65 loc) · 1.67 KB
/
grant_checks.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
package ginkeycloak
import (
"github.com/gin-gonic/gin"
)
type AccessCheckFunction func(tc *TokenContainer, ctx *gin.Context) bool
type AccessTuple struct {
Service string
Role string
Uid string
}
func GroupCheck(at []AccessTuple) func(tc *TokenContainer, ctx *gin.Context) bool {
ats := at
return func(tc *TokenContainer, ctx *gin.Context) bool {
addTokenToContext(tc, ctx)
for idx := range ats {
at := ats[idx]
if tc.KeyCloakToken.ResourceAccess != nil {
serviceRoles := tc.KeyCloakToken.ResourceAccess[at.Service]
for _, role := range serviceRoles.Roles {
if role == at.Role {
return true
}
}
}
}
return false
}
}
func RealmCheck(allowedRoles []string) func(tc *TokenContainer, ctx *gin.Context) bool {
return func(tc *TokenContainer, ctx *gin.Context) bool {
addTokenToContext(tc, ctx)
for _, allowedRole := range allowedRoles {
for _, role := range tc.KeyCloakToken.RealmAccess.Roles {
if role == allowedRole {
return true
}
}
}
return false
}
}
func addTokenToContext(tc *TokenContainer, ctx *gin.Context) {
ctx.Set("token", *tc.KeyCloakToken)
ctx.Set("uid", tc.KeyCloakToken.PreferredUsername)
}
func UidCheck(at []AccessTuple) func(tc *TokenContainer, ctx *gin.Context) bool {
ats := at
return func(tc *TokenContainer, ctx *gin.Context) bool {
addTokenToContext(tc, ctx)
uid := tc.KeyCloakToken.PreferredUsername
for idx := range ats {
at := ats[idx]
if at.Uid == uid {
return true
}
}
return false
}
}
func AuthCheck() func(tc *TokenContainer, ctx *gin.Context) bool {
return func(tc *TokenContainer, ctx *gin.Context) bool {
addTokenToContext(tc, ctx)
return true
}
}