forked from ebhomengo/niki
1
0
Fork 0
niki/service/auth/create.go

40 lines
1.1 KiB
Go
Raw Normal View History

package auth
import (
"git.gocasts.ir/ebhomengo/niki/entity"
"github.com/golang-jwt/jwt/v4"
"time"
)
func (s Service) CreateAccessToken(user entity.Authenticable) (string, error) {
return s.createToken(user.ID, user.Role, s.Config.AccessSubject, s.Config.AccessExpirationTime)
}
func (s Service) CreateRefreshToken(user entity.Authenticable) (string, error) {
return s.createToken(user.ID, user.Role, s.Config.RefreshSubject, s.Config.RefreshExpirationTime)
}
func (s Service) createToken(userID uint, role, 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
}