1
+ package middlewares
2
+
3
+ import (
4
+ "net/http"
5
+ "strings"
6
+ helper "github.com/Asrez/GoAPIBlog/api/helpers"
7
+ "github.com/Asrez/GoAPIBlog/config"
8
+ "github.com/Asrez/GoAPIBlog/constants"
9
+ "github.com/Asrez/GoAPIBlog/pkg/service_errors"
10
+ "github.com/Asrez/GoAPIBlog/services"
11
+ "github.com/gin-gonic/gin"
12
+ "github.com/golang-jwt/jwt"
13
+ )
14
+
15
+ func Authentication (cfg * config.Config ) gin.HandlerFunc {
16
+ var tokenService = services .NewTokenService (cfg )
17
+
18
+ return func (c * gin.Context ) {
19
+ var err error
20
+ claimMap := map [string ]interface {}{}
21
+ auth := c .GetHeader (constants .AuthorizationHeaderKey )
22
+ token := strings .Split (auth , " " )
23
+ if auth == "" {
24
+ err = & service_errors.ServiceError {EndUserMessage : service_errors .TokenRequired }
25
+ } else {
26
+ claimMap , err = tokenService .GetClaims (token [1 ])
27
+ if err != nil {
28
+ switch err .(* jwt.ValidationError ).Errors {
29
+ case jwt .ValidationErrorExpired :
30
+ err = & service_errors.ServiceError {EndUserMessage : service_errors .TokenExpired }
31
+ default :
32
+ err = & service_errors.ServiceError {EndUserMessage : service_errors .TokenInvalid }
33
+ }
34
+ }
35
+ }
36
+ if err != nil {
37
+ c .AbortWithStatusJSON (http .StatusUnauthorized , helper .GenerateBaseResponseWithError (
38
+ nil , false , helper .AuthError , err ,
39
+ ))
40
+ return
41
+ }
42
+
43
+ c .Set (constants .UserIdKey , claimMap [constants .UserIdKey ])
44
+ c .Set (constants .FirstNameKey , claimMap [constants .FirstNameKey ])
45
+ c .Set (constants .LastNameKey , claimMap [constants .LastNameKey ])
46
+ c .Set (constants .UsernameKey , claimMap [constants .UsernameKey ])
47
+ c .Set (constants .EmailKey , claimMap [constants .EmailKey ])
48
+ c .Set (constants .ExpireTimeKey , claimMap [constants .ExpireTimeKey ])
49
+
50
+ c .Next ()
51
+ }
52
+ }
0 commit comments