-
Notifications
You must be signed in to change notification settings - Fork 3
/
auth.go
71 lines (65 loc) · 1.84 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
package ensweb
import (
"net/http"
"github.com/golang-jwt/jwt/v5"
)
func (s *Server) BasicAuthHandle(claims jwt.Claims, hf HandlerFunc, af AuthFunc, ef HandlerFunc) HandlerFunc {
return HandlerFunc(func(req *Request) *Result {
err := s.ValidateJWTToken(req.ClientToken.Token, claims)
if err != nil {
if ef != nil {
return ef(req)
} else {
return s.RenderJSONError(req, http.StatusUnauthorized, err.Error(), err.Error())
}
}
req.ClientToken.Model = claims
req.ClientToken.Verified = true
if af != nil {
if !af(req) {
if ef != nil {
return ef(req)
} else {
return s.RenderJSONError(req, http.StatusUnauthorized, "Access denined", "Access denied")
}
}
}
return hf(req)
})
}
func (s *Server) APIKeyAuthHandle(hf HandlerFunc, ef HandlerFunc) HandlerFunc {
return HandlerFunc(func(req *Request) *Result {
if s.apiKey != s.GetReqHeader(req, APIKeyHeader) {
if ef != nil {
return ef(req)
} else {
return s.RenderJSONError(req, http.StatusUnauthorized, "API Key is not matched", "API Key is not matched")
}
}
req.ClientToken.APIKeyVerified = true
return hf(req)
})
}
func (s *Server) SessionAuthHandle(claims jwt.Claims, sessionName string, sessionKey string, hf HandlerFunc, ef HandlerFunc) HandlerFunc {
return HandlerFunc(func(req *Request) *Result {
token := s.GetSessionCookies(req, sessionName, sessionKey)
if token == nil {
if ef != nil {
return ef(req)
} else {
return s.RenderJSONError(req, http.StatusUnauthorized, "invalid session", "invalid session")
}
}
err := s.ValidateJWTToken(token.(string), claims)
if err != nil {
if ef != nil {
return ef(req)
} else {
return s.RenderJSONError(req, http.StatusUnauthorized, err.Error(), err.Error())
}
}
req.ClientToken.Model = claims
req.ClientToken.Verified = true
return hf(req)
})
}