2024-02-10 16:23:50 +00:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"crypto/sha256"
|
|
|
|
"encoding/base64"
|
|
|
|
"github.com/1f349/mjwt"
|
|
|
|
"github.com/1f349/mjwt/auth"
|
|
|
|
"github.com/go-oauth2/oauth2/v4"
|
|
|
|
"github.com/golang-jwt/jwt/v4"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
type JWTAccessGenerate struct {
|
2024-07-27 21:46:58 +01:00
|
|
|
signer *mjwt.Issuer
|
2024-09-13 15:31:40 +01:00
|
|
|
db mjwtGetUserRoles
|
2024-02-10 16:23:50 +00:00
|
|
|
}
|
|
|
|
|
2024-09-13 15:31:40 +01:00
|
|
|
func NewMJWTAccessGenerate(signer *mjwt.Issuer, db mjwtGetUserRoles) *JWTAccessGenerate {
|
2024-02-10 16:23:50 +00:00
|
|
|
return &JWTAccessGenerate{signer, db}
|
|
|
|
}
|
|
|
|
|
|
|
|
var _ oauth2.AccessGenerate = &JWTAccessGenerate{}
|
|
|
|
|
2024-09-13 15:31:40 +01:00
|
|
|
type mjwtGetUserRoles interface {
|
|
|
|
GetUserRoles(ctx context.Context, subject string) ([]string, error)
|
|
|
|
}
|
|
|
|
|
2024-02-10 16:23:50 +00:00
|
|
|
func (j *JWTAccessGenerate) Token(ctx context.Context, data *oauth2.GenerateBasic, isGenRefresh bool) (access, refresh string, err error) {
|
2024-05-17 21:40:31 +01:00
|
|
|
roles, err := j.db.GetUserRoles(ctx, data.UserID)
|
2024-02-10 16:23:50 +00:00
|
|
|
if err != nil {
|
|
|
|
return "", "", err
|
|
|
|
}
|
|
|
|
|
2024-09-02 22:54:03 +01:00
|
|
|
ps := auth.NewPermStorage()
|
|
|
|
for _, role := range roles {
|
|
|
|
ps.Set(role)
|
|
|
|
}
|
2024-07-27 21:46:58 +01:00
|
|
|
out := auth.NewPermStorage()
|
2024-09-02 22:54:03 +01:00
|
|
|
ForEachRole(data.Client.(interface{ UsePerms() []string }).UsePerms(), func(role string) {
|
2024-02-14 21:35:50 +00:00
|
|
|
for _, i := range ps.Filter(strings.Split(role, " ")).Dump() {
|
|
|
|
out.Set(i)
|
|
|
|
}
|
2024-02-10 16:23:50 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
access, err = j.signer.GenerateJwt(data.UserID, "", jwt.ClaimStrings{data.TokenInfo.GetClientID()}, data.TokenInfo.GetAccessExpiresIn(), auth.AccessTokenClaims{
|
2024-02-14 21:04:52 +00:00
|
|
|
Perms: out,
|
2024-02-10 16:23:50 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
if isGenRefresh {
|
|
|
|
t := uuid.NewHash(sha256.New(), uuid.New(), []byte(access), 5).String()
|
|
|
|
refresh = base64.URLEncoding.EncodeToString([]byte(t))
|
|
|
|
refresh = strings.ToUpper(strings.TrimRight(refresh, "="))
|
|
|
|
}
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|