forked from ebhomengo/niki
43 lines
1017 B
Go
43 lines
1017 B
Go
|
package auth
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
|
||
|
"github.com/golang-jwt/jwt/v4"
|
||
|
"strings"
|
||
|
)
|
||
|
|
||
|
func (s Service) ParseBearerToken(bearerToken string) (*Claims, error) {
|
||
|
tokenStr := strings.Replace(bearerToken, "Bearer ", "", 1)
|
||
|
|
||
|
return s.parseToken(tokenStr)
|
||
|
}
|
||
|
|
||
|
func (s Service) ParseRefreshToken(refreshToken string) (*Claims, error) {
|
||
|
claims, err := s.parseToken(refreshToken)
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
if claims.Subject != s.Config.RefreshSubject {
|
||
|
return nil, fmt.Errorf(errmsg.ErrorMsgInvalidRefreshToken)
|
||
|
}
|
||
|
|
||
|
return claims, nil
|
||
|
}
|
||
|
|
||
|
func (s Service) parseToken(token string) (*Claims, error) {
|
||
|
// https://pkg.go.dev/github.com/golang-jwt/jwt/v5#example-ParseWithClaims-CustomClaimsType
|
||
|
t, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) {
|
||
|
return []byte(s.Config.SignKey), nil
|
||
|
})
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
if claims, ok := t.Claims.(*Claims); ok && t.Valid {
|
||
|
return claims, nil
|
||
|
}
|
||
|
|
||
|
return nil, err
|
||
|
}
|