first commit
This commit is contained in:
134
services/auth/jwt.go
Normal file
134
services/auth/jwt.go
Normal file
@@ -0,0 +1,134 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"sismedika.com/sas/westone/configs"
|
||||
"sismedika.com/sas/westone/types"
|
||||
"sismedika.com/sas/westone/utils"
|
||||
)
|
||||
|
||||
type ContextKey string
|
||||
|
||||
const UserContextKey ContextKey = "mk1S2sKM12KASd02dp1"
|
||||
|
||||
// func WithJWTAuth(handlerFunc http.HandlerFunc, store types.UserStore) http.HandlerFunc {
|
||||
// return func(w http.ResponseWriter, r *http.Request) {
|
||||
// tokenString := utils.GetTokenFromRequest(r)
|
||||
// token, err := validateJWT(tokenString)
|
||||
// if err != nil {
|
||||
// log.Printf("failed to validate token: %v", err)
|
||||
// permissionDenied(w)
|
||||
// return
|
||||
// }
|
||||
|
||||
// if !token.Valid {
|
||||
// log.Println("invalid token")
|
||||
// permissionDenied(w)
|
||||
// return
|
||||
// }
|
||||
|
||||
// claims := token.Claims.(jwt.MapClaims)
|
||||
// str := claims["userID"].(string)
|
||||
|
||||
// userID, err := strconv.Atoi(str)
|
||||
// if err != nil {
|
||||
// log.Printf("failed to convert userID to int: %v", err)
|
||||
// permissionDenied(w)
|
||||
// return
|
||||
// }
|
||||
|
||||
// u, err := store.GetUserByID(userID)
|
||||
// if err != nil {
|
||||
// log.Printf("failed to get user by id: %v", err)
|
||||
// permissionDenied(w)
|
||||
// return
|
||||
// }
|
||||
|
||||
// // Add the user to the context
|
||||
// ctx := r.Context()
|
||||
// ctx = context.WithValue(ctx, UserKey, u.MUserID)
|
||||
// r = r.WithContext(ctx)
|
||||
|
||||
// // Call the function if the token is valid
|
||||
// handlerFunc(w, r)
|
||||
// }
|
||||
// }
|
||||
|
||||
func CreateJWT(data types.DataJWT) (string, error) {
|
||||
secret := []byte(configs.Envs.JWTSecret)
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
||||
"M_UserID": data.M_UserID,
|
||||
"M_UserEmail": data.M_UserEmail,
|
||||
"M_UserUsername": data.M_UserUsername,
|
||||
"M_UserGroupDashboard": data.M_UserGroupDashboard,
|
||||
"M_UserDefaultTSampleStationID": data.M_UserDefaultTSampleStationID,
|
||||
"M_StaffName": data.M_StaffName,
|
||||
"Is_Courier": data.Is_Courier,
|
||||
"Time_Autologout": data.Time_Autologout,
|
||||
"Type_Akun": data.Type_Akun,
|
||||
"IP": data.Ip,
|
||||
"Agent": data.Agent,
|
||||
"Version": data.Version,
|
||||
"LastLogin": data.LastLogin,
|
||||
})
|
||||
|
||||
tokenString, err := token.SignedString(secret)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return tokenString, err
|
||||
}
|
||||
|
||||
func validateJWT(tokenString string) (*jwt.Token, error) {
|
||||
return jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
|
||||
return []byte(configs.Envs.JWTSecret), nil
|
||||
})
|
||||
}
|
||||
|
||||
func permissionDenied(w http.ResponseWriter) {
|
||||
utils.WriteError(w, http.StatusForbidden, fmt.Errorf("PERMISSION DENIED"))
|
||||
}
|
||||
|
||||
func GetUserIDFromContext(ctx context.Context) int {
|
||||
userID, ok := ctx.Value(UserContextKey).(int)
|
||||
if !ok {
|
||||
return -1
|
||||
}
|
||||
|
||||
return userID
|
||||
}
|
||||
|
||||
func AuthMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
tokenstr := utils.GetTokenFromRequest(r)
|
||||
token, err := validateJWT(tokenstr)
|
||||
if err != nil {
|
||||
log.Printf("[ERROR] Failed to validate jwt token: %v", err)
|
||||
permissionDenied(w)
|
||||
return
|
||||
}
|
||||
|
||||
if !token.Valid {
|
||||
log.Println("[ERROR] Invalid token")
|
||||
permissionDenied(w)
|
||||
return
|
||||
}
|
||||
|
||||
claims := token.Claims.(jwt.MapClaims)
|
||||
ctx := r.Context()
|
||||
ctx = context.WithValue(ctx, UserContextKey, claims)
|
||||
r = r.WithContext(ctx)
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user