chores: refactor struct and structure project
This commit is contained in:
@@ -1,138 +1,76 @@
|
||||
package authmiddleware
|
||||
|
||||
// import (
|
||||
// "context"
|
||||
// "fmt"
|
||||
// "net/http"
|
||||
// "strings"
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
// redisaccessor "legalgo-BE-go/internal/accessor/redis"
|
||||
// contextkeyenum "legalgo-BE-go/internal/enums/context_key"
|
||||
// jwtclaimenum "legalgo-BE-go/internal/enums/jwt"
|
||||
// resourceenum "legalgo-BE-go/internal/enums/resource"
|
||||
// "legalgo-BE-go/internal/services/auth"
|
||||
// "github.com/golang-jwt/jwt/v5"
|
||||
// )
|
||||
redisaccessor "legalgo-BE-go/internal/accessor/redis"
|
||||
"legalgo-BE-go/internal/utilities/response"
|
||||
"legalgo-BE-go/internal/utilities/utils"
|
||||
|
||||
// const SessionHeader = "Authorization"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
// func Authorization() func(next http.Handler) http.Handler {
|
||||
// return func(next http.Handler) http.Handler {
|
||||
// return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// ctx := r.Context()
|
||||
const SessionHeader = "Authorization"
|
||||
|
||||
// tokenString, err := GetToken(r)
|
||||
// if err != nil {
|
||||
// RespondWithError(w, r, err, "Invalid auth header")
|
||||
// return
|
||||
// }
|
||||
func Authorize() func(next http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
|
||||
// token, err := ValidateToken(ctx, tokenString)
|
||||
// if err != nil {
|
||||
// RespondWithError(w, r, err, err.Error())
|
||||
// return
|
||||
// }
|
||||
tokenString, err := utils.GetToken(r)
|
||||
if err != nil {
|
||||
response.RespondWithError(w, r, err, "Invalid auth header")
|
||||
return
|
||||
}
|
||||
|
||||
// if isAuthorized, ctx := VerifyClaims(ctx, token, nil); !isAuthorized {
|
||||
// RespondWithError(w, r, errorcode.ErrCodeUnauthorized, errorcode.ErrCodeUnauthorized.Message)
|
||||
// return
|
||||
// } else {
|
||||
// next.ServeHTTP(w, r.WithContext(ctx))
|
||||
// return
|
||||
// }
|
||||
// })
|
||||
// }
|
||||
// }
|
||||
spec, err := utils.GetTokenDetail(r)
|
||||
|
||||
// func GetToken(r *http.Request) (string, error) {
|
||||
// tokenString := GetTokenFromHeader(r)
|
||||
// if tokenString == "" {
|
||||
// tokenString = getTokenFromQuery(r)
|
||||
// }
|
||||
token, err := ValidateToken(ctx, spec.Email)
|
||||
if err != nil {
|
||||
response.RespondWithError(w, r, err, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// if tokenString == "" {
|
||||
// return "", fmt.Errorf("token not found")
|
||||
// }
|
||||
isValid := token == tokenString
|
||||
|
||||
// return tokenString, nil
|
||||
// }
|
||||
if !isValid {
|
||||
response.RespondWithError(w, r, err, "invalid token")
|
||||
return
|
||||
}
|
||||
|
||||
// func GetTokenFromHeader(r *http.Request) string {
|
||||
// session := r.Header.Get(SessionHeader)
|
||||
// arr := strings.Split(session, " ")
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// if len(arr) != 2 || strings.ToUpper(arr[0]) != "BEARER" {
|
||||
// return ""
|
||||
// }
|
||||
func ValidateToken(ctx context.Context, id string) (string, error) {
|
||||
redisClient := redisaccessor.Get()
|
||||
redisToken, err := utils.GetTokenRedis(ctx, redisClient, id)
|
||||
|
||||
// return arr[1]
|
||||
// }
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// func getTokenFromQuery(r *http.Request) string {
|
||||
// token := r.URL.Query().Get("token")
|
||||
// return token
|
||||
// }
|
||||
token, err := utils.ParseToken(redisToken)
|
||||
|
||||
// func VerifyClaims(ctx context.Context, token *jwt.Token,
|
||||
// requiredResources []resourceenum.Resource) (bool, context.Context) {
|
||||
// if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
|
||||
// rawResources := []interface{}{}
|
||||
// if claimValue, exist := claims[string(jwtclaimenum.RESOURCES)]; exist {
|
||||
// rawResources = claimValue.([]interface{})
|
||||
// }
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("invalid token: %w", err)
|
||||
}
|
||||
|
||||
// resources := []resourceenum.Resource{}
|
||||
// resourceMap := map[string]bool{}
|
||||
// Check if the token is valid
|
||||
if !token.Valid {
|
||||
return "", fmt.Errorf("invalid token: token is not valid")
|
||||
}
|
||||
|
||||
// for _, v := range rawResources {
|
||||
// value := v.(string)
|
||||
// resources = append(resources, resourceenum.Resource(value))
|
||||
// resourceMap[value] = true
|
||||
// }
|
||||
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
|
||||
expirationTime := claims["exp"].(float64) // Expiration time in Unix timestamp format
|
||||
if time.Unix(int64(expirationTime), 0).Before(time.Now()) {
|
||||
return "", fmt.Errorf("token has expired")
|
||||
}
|
||||
}
|
||||
|
||||
// ctx = context.WithValue(ctx, contextkeyenum.Authorization, UserAuthorization{
|
||||
// Type: claims[string(jwtclaimenum.TYPE)].(string),
|
||||
// UserId: claims[string(jwtclaimenum.AUDIENCE)].(string),
|
||||
// Username: claims[string(jwtclaimenum.USERNAME)].(string),
|
||||
// Resources: resources,
|
||||
// })
|
||||
|
||||
// isResourceFulfilled := false
|
||||
|
||||
// for _, v := range requiredResources {
|
||||
// if _, ok := resourceMap[string(v)]; ok {
|
||||
// isResourceFulfilled = true
|
||||
// ctx = context.WithValue(ctx, contextkeyenum.Resource, v)
|
||||
|
||||
// break
|
||||
// }
|
||||
// }
|
||||
|
||||
// if isResourceFulfilled || len(requiredResources) == 0 {
|
||||
// return true, ctx
|
||||
// }
|
||||
// }
|
||||
|
||||
// return false, nil
|
||||
// }
|
||||
|
||||
// func ValidateToken(ctx context.Context, tokenString string) (*jwt.Token, error) {
|
||||
// redisClient := redisaccessor.Get()
|
||||
// redisToken, err := redisClient.Exists(ctx, fmt.Sprintf("%s:%s", auth.BLACKLISTED_TOKEN_KEY, tokenString)).Result()
|
||||
|
||||
// if err != nil || redisToken > 0 {
|
||||
// return nil, fmt.Errorf("session already expired")
|
||||
// }
|
||||
|
||||
// token, err := jwt.Parse(tokenString, authsvc.VerifyToken(conf.JWTAccessToken))
|
||||
// if err != nil {
|
||||
// if ve, ok := err.(*jwt.ValidationError); ok {
|
||||
// if ve.Errors&jwt.ValidationErrorExpired != 0 {
|
||||
// err = errorcode.ErrCodeExpiredToken
|
||||
// }
|
||||
// }
|
||||
// return nil, err
|
||||
// }
|
||||
|
||||
// return token, nil
|
||||
// }
|
||||
return redisToken, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user