79 lines
2.4 KiB
Go
79 lines
2.4 KiB
Go
package jwt
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"time"
|
|
|
|
"com.sismedika.com.absensi/pkg/config"
|
|
"github.com/dgrijalva/jwt-go"
|
|
)
|
|
|
|
// var conf = config.Data
|
|
|
|
// GenerateToken generates a jwt token and assign a username to it's claims and return it
|
|
func GenerateToken(user_id int, username string, staff_id int) (string, int64, error) {
|
|
token := jwt.New(jwt.SigningMethodHS256)
|
|
/* Create a map to store our claims */
|
|
claims := token.Claims.(jwt.MapClaims)
|
|
/* Set token claims */
|
|
expired := time.Now().Add(time.Minute * time.Duration(config.Data.GetInt("tokenExpiration"))).Unix()
|
|
claims["user_id"] = user_id
|
|
claims["user_name"] = username
|
|
claims["staff_id"] = staff_id
|
|
claims["exp"] = expired
|
|
tokenString, err := token.SignedString([]byte(config.Data.Get("secretkey")))
|
|
if err != nil {
|
|
return "", 0, fmt.Errorf("GENERATE_TOKEN_FAILED")
|
|
}
|
|
return tokenString, expired, nil
|
|
}
|
|
|
|
// ParseToken parses a jwt token and returns the username in it's claims
|
|
func ParseToken(tokenStr string) (int, string, int, error) {
|
|
claims := jwt.MapClaims{}
|
|
|
|
token, err := jwt.ParseWithClaims(tokenStr, claims, func(token *jwt.Token) (interface{}, error) {
|
|
return []byte(config.Data.Get("secretkey")), nil
|
|
})
|
|
if err != nil {
|
|
v, _ := err.(*jwt.ValidationError)
|
|
|
|
if v.Errors == jwt.ValidationErrorExpired {
|
|
log.Printf("parse token 1: %v\n", err)
|
|
return 0, "", 0, fmt.Errorf("TOKEN_EXPIRED")
|
|
}
|
|
|
|
log.Printf("parse token 2: %v\n", err)
|
|
return 0, "", 0, fmt.Errorf("TOKEN_INVALID")
|
|
}
|
|
|
|
if !token.Valid {
|
|
log.Printf("token invalid: %v\n", err)
|
|
return 0, "", 0, fmt.Errorf(("TOKEN_INVALID"))
|
|
}
|
|
|
|
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
|
|
if !ok {
|
|
return 0, "", 0, fmt.Errorf(("TOKEN_INVALID"))
|
|
}
|
|
// type of user_id is float64: https://stackoverflow.com/questions/70705673/panic-interface-conversion-interface-is-float64-not-int64
|
|
if claims["user_id"] == nil {
|
|
return 0, "", 0, fmt.Errorf(("TOKEN_INVALID"))
|
|
}
|
|
if claims["user_name"] == nil {
|
|
return 0, "", 0, fmt.Errorf(("TOKEN_INVALID"))
|
|
}
|
|
if claims["staff_id"] == nil {
|
|
return 0, "", 0, fmt.Errorf(("TOKEN_INVALID"))
|
|
}
|
|
user_id := int(claims["user_id"].(float64))
|
|
user_name := claims["user_name"].(string)
|
|
staff_id := int(claims["practitioner_id"].(float64))
|
|
return user_id, user_name, staff_id, nil
|
|
} else {
|
|
log.Printf("token claims: %v\n", err)
|
|
return 0, "", 0, fmt.Errorf(("TOKEN_INVALID"))
|
|
}
|
|
}
|