go_import_excel_pg/internal/jwt.go

64 lines
1.5 KiB
Go
Raw Permalink Normal View History

2024-02-22 10:43:39 +07:00
package internal
import (
"context"
"log"
"os"
"github.com/golang-jwt/jwt/v5"
)
type JwtPayload struct {
UserId float64 `json:"id"`
NamaLengkap string `json:"nama_lengkap"`
NotesId string `json:"notes_id"`
FasyankesId float64 `json:"fasyankes_id"`
Email string `json:"email"`
UserType float64 `json:"user_type"`
PPKPelayanan interface{} `json:"ppk_pelayanan"`
AlamatFasyankes interface{} `json:"alamat_fasyankes"`
}
func GetPayloadFromContext(ctx context.Context) *JwtPayload {
payload, ok := ctx.Value(UserContext).(JwtPayload)
if !ok {
return nil
}
return &payload
}
func ParseJWT(s string) JwtPayload {
salt := os.Getenv("JWT_SALT")
mySecretKey := []byte(salt)
// Parse the token
token, err := jwt.Parse(s, func(token *jwt.Token) (interface{}, error) {
return mySecretKey, nil
})
if err != nil {
log.Fatal(err)
}
claims, valid := token.Claims.(jwt.MapClaims)
if !valid && !token.Valid {
log.Fatal("Invalid token")
}
data := claims["user"].(map[string]interface{})
parsedToken := JwtPayload{
UserId: data["id"].(float64),
NamaLengkap: data["namaLengkap"].(string),
NotesId: data["notesId"].(string),
FasyankesId: data["fasyankesId"].(float64),
Email: data["email"].(string),
UserType: data["userType"].(float64),
PPKPelayanan: data["ppkPelayanan"],
AlamatFasyankes: data["alamatFasyankes"],
}
return parsedToken
}