-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
71 lines (60 loc) 路 1.5 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 middlewares
import (
"errors"
"fmt"
"net/http"
"os"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
"github.com/hackfeed/remrratality/backend/internal/server/models"
log "github.com/sirupsen/logrus"
)
type signedDetails struct {
Email string
UserID string
jwt.StandardClaims
}
func Auth() gin.HandlerFunc {
return func(c *gin.Context) {
clientToken := c.Request.Header.Get("token")
if clientToken == "" {
log.Errorf("failed to get authorization header")
c.AbortWithStatusJSON(http.StatusUnauthorized, models.Response{
Message: "No Authorization header provided",
})
return
}
claims, err := validateToken(clientToken)
if err != nil {
log.Errorf("failed to validate %s token", clientToken)
c.AbortWithStatusJSON(http.StatusInternalServerError, models.Response{
Message: "Token validation failed",
})
return
}
c.Set("email", claims.Email)
c.Set("user_id", claims.UserID)
c.Next()
}
}
func validateToken(signedToken string) (*signedDetails, error) {
token, err := jwt.ParseWithClaims(
signedToken,
&signedDetails{},
func(token *jwt.Token) (interface{}, error) {
return []byte(os.Getenv("SECRET_KEY")), nil
},
)
if err != nil {
return nil, fmt.Errorf("failed to obtain token, error is: %s", err)
}
claims, ok := token.Claims.(*signedDetails)
if !ok {
return nil, errors.New("token is invalid")
}
if claims.ExpiresAt < time.Now().Local().Unix() {
return nil, errors.New("token is expired")
}
return claims, nil
}