-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
40 lines (35 loc) · 1.06 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
package middleware
import (
"fmt"
"net/http"
"strings"
"github.com/dgrijalva/jwt-go/v4"
"github.com/gin-gonic/gin"
"github.com/ahmadcahyana/arctic-fox/config"
"github.com/ahmadcahyana/arctic-fox/constants"
"github.com/ahmadcahyana/arctic-fox/datatransfers"
)
func AuthMiddleware(c *gin.Context) {
token := strings.TrimPrefix(c.GetHeader("Authorization"), "Bearer ")
if token == "" {
c.Set(constants.IsAuthenticatedKey, false)
c.Next()
return
}
claims, err := parseToken(token, config.AppConfig.JWTSecret)
if err != nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, datatransfers.Response{Error: err.Error()})
return
}
c.Set(constants.IsAuthenticatedKey, true)
c.Set(constants.UserIDKey, claims.ID)
c.Next()
}
func parseToken(tokenString, secret string) (claims datatransfers.JWTClaims, err error) {
if token, err := jwt.ParseWithClaims(tokenString, &claims, func(token *jwt.Token) (interface{}, error) {
return []byte(secret), nil
}); err != nil || !token.Valid {
return datatransfers.JWTClaims{}, fmt.Errorf("invalid token. %s", err)
}
return
}