forked from ebhomengo/niki
78 lines
2.2 KiB
Go
78 lines
2.2 KiB
Go
|
package benefactorauthservice
|
||
|
|
||
|
import (
|
||
|
"git.gocasts.ir/ebhomengo/niki/entity"
|
||
|
"github.com/golang-jwt/jwt/v4"
|
||
|
"strings"
|
||
|
"time"
|
||
|
)
|
||
|
|
||
|
type Config struct {
|
||
|
SignKey string `koanf:"sign_key"`
|
||
|
AccessExpirationTime time.Duration `koanf:"access_expiration_time"`
|
||
|
RefreshExpirationTime time.Duration `koanf:"refresh_expiration_time"`
|
||
|
AccessSubject string `koanf:"access_subject"`
|
||
|
RefreshSubject string `koanf:"refresh_subject"`
|
||
|
}
|
||
|
|
||
|
type Service struct {
|
||
|
config Config
|
||
|
}
|
||
|
|
||
|
func New(cfg Config) Service {
|
||
|
return Service{
|
||
|
config: cfg,
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (s Service) CreateAccessToken(benefactor entity.Benefactor) (string, error) {
|
||
|
return s.createToken(benefactor.ID, benefactor.Role, s.config.AccessSubject, s.config.AccessExpirationTime)
|
||
|
}
|
||
|
|
||
|
func (s Service) CreateRefreshToken(benefactor entity.Benefactor) (string, error) {
|
||
|
return s.createToken(benefactor.ID, benefactor.Role, s.config.RefreshSubject, s.config.RefreshExpirationTime)
|
||
|
}
|
||
|
|
||
|
func (s Service) ParseToken(bearerToken string) (*Claims, error) {
|
||
|
//https://pkg.go.dev/github.com/golang-jwt/jwt/v5#example-ParseWithClaims-CustomClaimsType
|
||
|
|
||
|
tokenStr := strings.Replace(bearerToken, "Bearer ", "", 1)
|
||
|
|
||
|
token, err := jwt.ParseWithClaims(tokenStr, &Claims{}, func(token *jwt.Token) (interface{}, error) {
|
||
|
return []byte(s.config.SignKey), nil
|
||
|
})
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
if claims, ok := token.Claims.(*Claims); ok && token.Valid {
|
||
|
return claims, nil
|
||
|
} else {
|
||
|
return nil, err
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (s Service) createToken(userID uint, role entity.UserRole, subject string, expireDuration time.Duration) (string, error) {
|
||
|
// create a signer for rsa 256
|
||
|
// TODO - replace with rsa 256 RS256 - https://github.com/golang-jwt/jwt/blob/main/http_example_test.go
|
||
|
|
||
|
// set our claims
|
||
|
claims := Claims{
|
||
|
RegisteredClaims: jwt.RegisteredClaims{
|
||
|
Subject: subject,
|
||
|
ExpiresAt: jwt.NewNumericDate(time.Now().Add(expireDuration)),
|
||
|
},
|
||
|
UserID: userID,
|
||
|
Role: role,
|
||
|
}
|
||
|
|
||
|
// TODO - add sign method to config
|
||
|
accessToken := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||
|
tokenString, err := accessToken.SignedString([]byte(s.config.SignKey))
|
||
|
if err != nil {
|
||
|
return "", err
|
||
|
}
|
||
|
|
||
|
return tokenString, nil
|
||
|
}
|