forked from takuya152005/go-gin-xorm-starter
-
Notifications
You must be signed in to change notification settings - Fork 1
/
auth_middleware.go
126 lines (108 loc) · 3.13 KB
/
auth_middleware.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package server
import (
"fmt"
"net/http"
"strings"
"github.com/itomofumi/go-gin-xorm-starter/model"
"github.com/itomofumi/go-gin-xorm-starter/util"
"github.com/itomofumi/gognito/auth"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
)
var authContextKey = "auth"
// SetAuth passes an authenticator.
func SetAuth(authenticator auth.Authenticator) gin.HandlerFunc {
return func(c *gin.Context) {
c.Set(authContextKey, authenticator)
c.Next()
}
}
// AuthMiddleware verifies JWT with authenticator.
func AuthMiddleware() gin.HandlerFunc {
logger := util.GetLogger()
return func(c *gin.Context) {
authenticator := c.MustGet(authContextKey).(auth.Authenticator)
err := authHandler(c, authenticator)
if err != nil {
er := model.NewErrorResponse("401", model.ErrorAuth, err.Error())
logger.Debugln(er)
c.AbortWithStatusJSON(http.StatusUnauthorized, er)
}
c.Next()
}
}
// OptionalAuthMiddleware does optional JWT verification.
func OptionalAuthMiddleware() gin.HandlerFunc {
logger := util.GetLogger()
return func(c *gin.Context) {
if _, ok := GetBearer(c.Request.Header["Authorization"]); ok {
authenticator := c.MustGet(authContextKey).(auth.Authenticator)
err := authHandler(c, authenticator)
if err != nil {
er := model.NewErrorResponse("401", model.ErrorAuth, err.Error())
logger.Debugln(er)
c.AbortWithStatusJSON(http.StatusUnauthorized, er)
}
} else {
c.Next()
}
}
}
func authHandler(c *gin.Context, authenticator auth.Authenticator) error {
tokenString, ok := GetBearer(c.Request.Header["Authorization"])
if !ok {
return fmt.Errorf("Bearer token was not found in Authorization header")
}
authedUser, err := authenticateUser(tokenString, authenticator)
if err != nil {
return err
}
// set user information to Gin's context.
c.Set("email", authedUser.Email)
c.Set("sub", authedUser.Sub)
c.Set("token", authedUser.Token)
return nil
}
// AuthenticatedUser verified user information
type AuthenticatedUser struct {
Email string
Sub string
Token *jwt.Token
}
// authenticateUser performs authentication to the given JWT token.
func authenticateUser(tokenString string, authenticator auth.Authenticator) (*AuthenticatedUser, error) {
token, err := authenticator.ValidateToken(tokenString)
if err != nil {
return nil, fmt.Errorf("token is not valid. [Reason] %v", err)
}
// "token == nil" may happen when 'NoVerification Mode' is enabled.
if token == nil || token.Claims == nil {
return nil, fmt.Errorf("wrong format token")
}
// よく使うユーザー情報も渡す
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
return nil, fmt.Errorf("wrong format token")
}
email, ok := claims["email"].(string)
if !ok {
return nil, fmt.Errorf("token must contain email")
}
sub := claims["sub"].(string)
authedUser := AuthenticatedUser{
Email: email,
Sub: sub,
Token: token,
}
return &authedUser, nil
}
// GetBearer gets a bearer token from Authorization header
func GetBearer(auth []string) (jwt string, ok bool) {
for _, v := range auth {
ret := strings.Split(v, " ")
if len(ret) == 2 && ret[0] == "Bearer" {
return ret[1], true
}
}
return "", false
}