initial commit
This commit is contained in:
@@ -0,0 +1,135 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/dusiburg/kotosoft-id/internal/models"
|
||||
"github.com/google/uuid"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
type TokenInfo struct {
|
||||
UserID uuid.UUID
|
||||
Scopes []string
|
||||
ClientID uuid.UUID
|
||||
}
|
||||
|
||||
func (s *Service) GetUserByID(ctx context.Context, id uuid.UUID) (*models.User, error) {
|
||||
return s.users.GetUserByID(ctx, id)
|
||||
}
|
||||
|
||||
func (s *Service) Register(ctx context.Context, input models.UserRegisterInput) (*models.User, error) {
|
||||
if s.users.IsUserExistsByEmail(ctx, input.Email) {
|
||||
return nil, models.ErrAlreadyExists
|
||||
}
|
||||
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return nil, models.ErrInternal
|
||||
}
|
||||
|
||||
return s.users.CreateUser(ctx, models.User{
|
||||
Email: input.Email,
|
||||
PasswordHash: string(hash),
|
||||
FirstName: input.FirstName,
|
||||
SecondName: input.SecondName,
|
||||
BirthDate: input.BirthDate,
|
||||
Sex: input.Sex,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) RefreshTokens(ctx context.Context, rawToken string) (*TokenPair, error) {
|
||||
row, err := s.oauth.GetRefreshTokenByHash(ctx, sha256Hex(rawToken))
|
||||
if err != nil {
|
||||
return nil, models.ErrUnauthorized
|
||||
}
|
||||
|
||||
if time.Now().After(row.ExpiresAt) {
|
||||
return nil, models.ErrUnauthorized
|
||||
}
|
||||
|
||||
client, err := s.oauth.GetOAuthClientByID(ctx, row.ClientID)
|
||||
if err != nil {
|
||||
return nil, models.ErrInternal
|
||||
}
|
||||
|
||||
scopes := scopesFromJSON(row.Scopes)
|
||||
if !ScopesAllowed(client.Scopes, scopes) {
|
||||
return nil, ErrInvalidGrant
|
||||
}
|
||||
|
||||
if err := s.oauth.DeleteRefreshTokenByID(ctx, row.ID); err != nil {
|
||||
return nil, models.ErrInternal
|
||||
}
|
||||
|
||||
user, err := s.users.GetUserByID(ctx, row.UserID)
|
||||
if err != nil {
|
||||
return nil, models.ErrUnauthorized
|
||||
}
|
||||
|
||||
return s.issuePair(ctx, user, client.ID, scopes)
|
||||
}
|
||||
|
||||
func (s *Service) ValidateAccessToken(ctx context.Context, token string) (*TokenInfo, error) {
|
||||
token = strings.TrimSpace(token)
|
||||
if token == "" {
|
||||
return nil, models.ErrUnauthorized
|
||||
}
|
||||
|
||||
data, err := s.redis.Get(ctx, accessTokenPrefix+token).Bytes()
|
||||
if err != nil {
|
||||
return nil, models.ErrUnauthorized
|
||||
}
|
||||
|
||||
var info struct {
|
||||
UserID uuid.UUID `json:"user_id"`
|
||||
Scopes []string `json:"scopes"`
|
||||
ClientID uuid.UUID `json:"client_id"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &info); err != nil {
|
||||
return nil, models.ErrUnauthorized
|
||||
}
|
||||
|
||||
return &TokenInfo{UserID: info.UserID, Scopes: info.Scopes, ClientID: info.ClientID}, nil
|
||||
}
|
||||
|
||||
func (s *Service) UpdateProfile(ctx context.Context, userID uuid.UUID, input models.UserUpdateInput) (*models.User, error) {
|
||||
user, err := s.users.GetUserByID(ctx, userID)
|
||||
if err != nil {
|
||||
return nil, models.ErrNotFound
|
||||
}
|
||||
|
||||
if input.FirstName != "" {
|
||||
user.FirstName = input.FirstName
|
||||
}
|
||||
if input.SecondName != "" {
|
||||
user.SecondName = input.SecondName
|
||||
}
|
||||
if input.BirthDate != nil {
|
||||
user.BirthDate = input.BirthDate
|
||||
}
|
||||
if input.Sex != "" {
|
||||
user.Sex = input.Sex
|
||||
}
|
||||
if input.Password != "" {
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return nil, models.ErrInternal
|
||||
}
|
||||
user.PasswordHash = string(hash)
|
||||
}
|
||||
user.UpdatedAt = time.Now()
|
||||
|
||||
return s.users.UpdateUser(ctx, *user)
|
||||
}
|
||||
|
||||
func (s *Service) DeleteProfile(ctx context.Context, userID uuid.UUID, accessToken string) error {
|
||||
if err := s.users.DeleteUser(ctx, userID); err != nil {
|
||||
return models.ErrInternal
|
||||
}
|
||||
_ = s.redis.Del(ctx, accessTokenPrefix+accessToken)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/dusiburg/kotosoft-id/internal/models"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func (s *Service) GetUserConsents(ctx context.Context, userID uuid.UUID) ([]models.UserConsent, error) {
|
||||
return s.oauth.GetUserConsents(ctx, userID)
|
||||
}
|
||||
|
||||
func (s *Service) HasUserConsent(ctx context.Context, userId uuid.UUID, clientId uuid.UUID, scopes []string) bool {
|
||||
allConsents, err := s.oauth.GetUserConsentsByClientID(ctx, userId, clientId)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
consents := make(map[string]bool)
|
||||
for _, scopes := range allConsents {
|
||||
for _, scope := range scopes.Scopes {
|
||||
consents[scope] = true
|
||||
}
|
||||
}
|
||||
|
||||
for _, scope := range scopes {
|
||||
if !consents[scope] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Service) RevokeConsent(ctx context.Context, userID uuid.UUID, clientID string) error {
|
||||
client, err := s.oauth.GetOAuthClientByClientID(ctx, clientID)
|
||||
if err != nil {
|
||||
return models.ErrNotFound
|
||||
}
|
||||
|
||||
if err := s.oauth.RevokeConsent(ctx, userID, client.ID, &userID); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
tokens, _ := s.redis.SMembers(ctx, fmt.Sprintf("user_client_tokens:%s:%s", userID, client.ID)).Result()
|
||||
for _, token := range tokens {
|
||||
s.redis.Del(ctx, accessTokenPrefix+token)
|
||||
}
|
||||
s.redis.Del(ctx, fmt.Sprintf("user_client_tokens:%s:%s", userID, client.ID))
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func newOpaqueToken(nBytes int) (string, error) {
|
||||
b := make([]byte, nBytes)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(b), nil
|
||||
}
|
||||
|
||||
func sha256Hex(v string) string {
|
||||
h := sha256.Sum256([]byte(v))
|
||||
return hex.EncodeToString(h[:])
|
||||
}
|
||||
|
||||
func pkceVerifyS256(verifier, challenge string) bool {
|
||||
sum := sha256.Sum256([]byte(verifier))
|
||||
got := base64.RawURLEncoding.EncodeToString(sum[:])
|
||||
return subtle.ConstantTimeCompare([]byte(got), []byte(challenge)) == 1
|
||||
}
|
||||
|
||||
func parseScopes(scope string) []string {
|
||||
scope = strings.TrimSpace(scope)
|
||||
if scope == "" {
|
||||
return nil
|
||||
}
|
||||
seen := make(map[string]struct{})
|
||||
var out []string
|
||||
for _, p := range strings.Fields(scope) {
|
||||
if _, dup := seen[p]; !dup {
|
||||
seen[p] = struct{}{}
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func ScopesAllowed(clientScopesJSON json.RawMessage, requested []string) bool {
|
||||
if len(requested) == 0 {
|
||||
return true
|
||||
}
|
||||
allowed := scopesFromJSON(clientScopesJSON)
|
||||
set := make(map[string]struct{}, len(allowed))
|
||||
for _, a := range allowed {
|
||||
set[a] = struct{}{}
|
||||
}
|
||||
for _, r := range requested {
|
||||
if _, ok := set[r]; !ok {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func scopesFromJSON(b json.RawMessage) []string {
|
||||
if len(b) == 0 {
|
||||
return nil
|
||||
}
|
||||
var out []string
|
||||
_ = json.Unmarshal(b, &out)
|
||||
return out
|
||||
}
|
||||
|
||||
func redirectURIMatches(redirectURIsJSON json.RawMessage, redirectURI string) bool {
|
||||
var uris []string
|
||||
if err := json.Unmarshal(redirectURIsJSON, &uris); err != nil {
|
||||
return false
|
||||
}
|
||||
for _, u := range uris {
|
||||
if u == redirectURI {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func verifyClientSecret(stored, provided string) bool {
|
||||
if stored == "" {
|
||||
return true
|
||||
}
|
||||
if provided == "" {
|
||||
return false
|
||||
}
|
||||
if strings.HasPrefix(stored, "$2") {
|
||||
return bcrypt.CompareHashAndPassword([]byte(stored), []byte(provided)) == nil
|
||||
}
|
||||
return subtle.ConstantTimeCompare([]byte(stored), []byte(provided)) == 1
|
||||
}
|
||||
|
||||
func HashClientSecret(secret string) (string, error) {
|
||||
if secret == "" {
|
||||
return "", nil
|
||||
}
|
||||
b, err := bcrypt.GenerateFromPassword([]byte(secret), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("hash client secret: %w", err)
|
||||
}
|
||||
return string(b), nil
|
||||
}
|
||||
|
||||
func bcryptCompare(hash, password string) error {
|
||||
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
|
||||
}
|
||||
|
||||
func ScopesContain(tokenScopes []string, required []string) bool {
|
||||
if len(required) == 0 {
|
||||
return true
|
||||
}
|
||||
set := make(map[string]struct{}, len(tokenScopes))
|
||||
for _, s := range tokenScopes {
|
||||
set[s] = struct{}{}
|
||||
}
|
||||
for _, r := range required {
|
||||
if _, ok := set[r]; !ok {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/dusiburg/kotosoft-id/internal/models"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type OAuthSession struct {
|
||||
ClientID string `json:"client_id"`
|
||||
ClientName string `json:"client_name"`
|
||||
RedirectURI string `json:"redirect_uri"`
|
||||
Scopes []string `json:"scopes"`
|
||||
State string `json:"state"`
|
||||
CodeChallenge string `json:"code_challenge"`
|
||||
CodeChallengeMethod string `json:"code_challenge_method"`
|
||||
UserID uuid.UUID `json:"user_id,omitempty"`
|
||||
}
|
||||
|
||||
type TokenPair struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
RefreshToken string `json:"refresh_token,omitempty"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresIn int64 `json:"expires_in"`
|
||||
Scope string `json:"scope,omitempty"`
|
||||
User *models.User `json:"user,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Service) CreateOAuthSession(
|
||||
ctx context.Context,
|
||||
clientID, redirectURI, scope, state, codeChallenge, codeChallengeMethod string,
|
||||
) (string, error) {
|
||||
if clientID == "" || redirectURI == "" || codeChallenge == "" {
|
||||
return "", ErrInvalidRequest
|
||||
}
|
||||
if codeChallengeMethod != "" && codeChallengeMethod != "S256" {
|
||||
return "", ErrInvalidRequest
|
||||
}
|
||||
|
||||
client, err := s.oauth.GetOAuthClientByClientID(ctx, clientID)
|
||||
if err != nil {
|
||||
return "", ErrUnauthorizedClient
|
||||
}
|
||||
if !redirectURIMatches(client.RedirectURIs, redirectURI) {
|
||||
return "", ErrInvalidRequest
|
||||
}
|
||||
|
||||
scopes := parseScopes(scope)
|
||||
if len(scopes) > 0 && !ScopesAllowed(client.Scopes, scopes) {
|
||||
return "", ErrInvalidRequest
|
||||
}
|
||||
|
||||
token, err := newOpaqueToken(24)
|
||||
if err != nil {
|
||||
return "", models.ErrInternal
|
||||
}
|
||||
|
||||
sess := OAuthSession{
|
||||
ClientID: client.ClientID,
|
||||
ClientName: client.Name,
|
||||
RedirectURI: redirectURI,
|
||||
Scopes: scopes,
|
||||
State: state,
|
||||
CodeChallenge: codeChallenge,
|
||||
CodeChallengeMethod: "S256",
|
||||
}
|
||||
|
||||
if err := s.saveSession(ctx, token, &sess); err != nil {
|
||||
return "", models.ErrInternal
|
||||
}
|
||||
return token, nil
|
||||
}
|
||||
|
||||
func (s *Service) GetOAuthSession(ctx context.Context, token string) (*OAuthSession, error) {
|
||||
data, err := s.redis.Get(ctx, oauthSessionPrefix+token).Bytes()
|
||||
if err != nil {
|
||||
return nil, ErrInvalidGrant
|
||||
}
|
||||
var sess OAuthSession
|
||||
if err := json.Unmarshal(data, &sess); err != nil {
|
||||
return nil, ErrInvalidGrant
|
||||
}
|
||||
return &sess, nil
|
||||
}
|
||||
|
||||
func (s *Service) saveSession(ctx context.Context, token string, sess *OAuthSession) error {
|
||||
data, _ := json.Marshal(sess)
|
||||
return s.redis.Set(ctx, oauthSessionPrefix+token, data, oauthSessionTTL).Err()
|
||||
}
|
||||
|
||||
func (s *Service) SessionLogin(ctx context.Context, token, email, password string) (string, error) {
|
||||
sess, err := s.GetOAuthSession(ctx, token)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
user, err := s.users.GetUserByEmail(ctx, email)
|
||||
if err != nil || bcryptCompare(user.PasswordHash, password) != nil {
|
||||
return "", models.ErrUnauthorized
|
||||
}
|
||||
|
||||
sess.UserID = user.ID
|
||||
if err := s.saveSession(ctx, token, sess); err != nil {
|
||||
return "", models.ErrInternal
|
||||
}
|
||||
|
||||
client, err := s.oauth.GetOAuthClientByClientID(ctx, sess.ClientID)
|
||||
if err != nil {
|
||||
return "", ErrInvalidClient
|
||||
}
|
||||
|
||||
if client.Trusted {
|
||||
return s.SessionApprove(ctx, token)
|
||||
}
|
||||
|
||||
hasUserConsents := s.HasUserConsent(ctx, sess.UserID, client.ID, sess.Scopes)
|
||||
if hasUserConsents {
|
||||
return s.SessionApprove(ctx, token)
|
||||
}
|
||||
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func (s *Service) SessionAttach(ctx context.Context, sessionToken, accessToken string) (string, error) {
|
||||
info, err := s.ValidateAccessToken(ctx, accessToken)
|
||||
if err != nil {
|
||||
return "", models.ErrUnauthorized
|
||||
}
|
||||
|
||||
sess, err := s.GetOAuthSession(ctx, sessionToken)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
sess.UserID = info.UserID
|
||||
if err := s.saveSession(ctx, sessionToken, sess); err != nil {
|
||||
return "", models.ErrInternal
|
||||
}
|
||||
|
||||
client, err := s.oauth.GetOAuthClientByClientID(ctx, sess.ClientID)
|
||||
if err != nil {
|
||||
return "", ErrInvalidClient
|
||||
}
|
||||
if client.Trusted {
|
||||
return s.SessionApprove(ctx, sessionToken)
|
||||
}
|
||||
|
||||
hasUserConsents := s.HasUserConsent(ctx, sess.UserID, client.ID, sess.Scopes)
|
||||
if hasUserConsents {
|
||||
return s.SessionApprove(ctx, sessionToken)
|
||||
}
|
||||
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func (s *Service) SessionApprove(ctx context.Context, token string) (string, error) {
|
||||
sess, err := s.GetOAuthSession(ctx, token)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if sess.UserID == uuid.Nil {
|
||||
return "", ErrInvalidGrant
|
||||
}
|
||||
|
||||
client, err := s.oauth.GetOAuthClientByClientID(ctx, sess.ClientID)
|
||||
if err != nil {
|
||||
return "", ErrInvalidClient
|
||||
}
|
||||
|
||||
code, err := s.createAuthCode(ctx, sess.UserID, client.ID, sess.RedirectURI, sess.Scopes, sess.CodeChallenge)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
_ = s.redis.Del(ctx, oauthSessionPrefix+token)
|
||||
s.oauth.RecordUserConsent(ctx, sess.UserID, client.ID, sess.Scopes)
|
||||
|
||||
redirectURL, _ := url.Parse(sess.RedirectURI)
|
||||
q := redirectURL.Query()
|
||||
q.Set("code", code)
|
||||
if sess.State != "" {
|
||||
q.Set("state", sess.State)
|
||||
}
|
||||
redirectURL.RawQuery = q.Encode()
|
||||
|
||||
return redirectURL.String(), nil
|
||||
}
|
||||
|
||||
func (s *Service) ExchangeCode(ctx context.Context, auth ClientAuth, code, redirectURI, codeVerifier string) (*TokenPair, error) {
|
||||
if auth.ClientID == "" || code == "" || redirectURI == "" || codeVerifier == "" {
|
||||
return nil, ErrInvalidRequest
|
||||
}
|
||||
|
||||
client, err := s.AuthenticateClient(ctx, auth)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
row, err := s.oauth.GetAuthorizationCodeByHash(ctx, sha256Hex(code))
|
||||
if err != nil || row.ConsumedAt != nil || time.Now().After(row.ExpiresAt) {
|
||||
return nil, ErrInvalidGrant
|
||||
}
|
||||
if row.ClientID != client.ID || row.RedirectURI != redirectURI {
|
||||
return nil, ErrInvalidGrant
|
||||
}
|
||||
if !pkceVerifyS256(codeVerifier, row.CodeChallenge) {
|
||||
return nil, ErrInvalidGrant
|
||||
}
|
||||
|
||||
if err := s.oauth.ConsumeAuthorizationCodeByID(ctx, row.ID); err != nil {
|
||||
return nil, models.ErrInternal
|
||||
}
|
||||
|
||||
user, err := s.users.GetUserByID(ctx, row.UserID)
|
||||
if err != nil {
|
||||
return nil, models.ErrInternal
|
||||
}
|
||||
|
||||
s.oauth.UpdateConsentLastUsed(ctx, row.UserID, client.ID)
|
||||
|
||||
return s.issuePair(ctx, user, client.ID, scopesFromJSON(row.Scopes))
|
||||
}
|
||||
|
||||
func (s *Service) ExchangeRefreshToken(ctx context.Context, auth ClientAuth, rawToken string) (*TokenPair, error) {
|
||||
if auth.ClientID == "" || rawToken == "" {
|
||||
return nil, ErrInvalidRequest
|
||||
}
|
||||
|
||||
client, err := s.AuthenticateClient(ctx, auth)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
row, err := s.oauth.GetRefreshTokenByHash(ctx, sha256Hex(rawToken))
|
||||
if err != nil || time.Now().After(row.ExpiresAt) || row.ClientID != client.ID {
|
||||
return nil, ErrInvalidGrant
|
||||
}
|
||||
|
||||
if err := s.oauth.DeleteRefreshTokenByID(ctx, row.ID); err != nil {
|
||||
return nil, models.ErrInternal
|
||||
}
|
||||
|
||||
s.oauth.UpdateConsentLastUsed(ctx, row.UserID, client.ID)
|
||||
|
||||
user, err := s.users.GetUserByID(ctx, row.UserID)
|
||||
if err != nil {
|
||||
return nil, models.ErrInternal
|
||||
}
|
||||
|
||||
scopes := scopesFromJSON(row.Scopes)
|
||||
if !ScopesAllowed(client.Scopes, scopes) {
|
||||
return nil, ErrInvalidGrant
|
||||
}
|
||||
|
||||
return s.issuePair(ctx, user, client.ID, scopes)
|
||||
}
|
||||
|
||||
func (s *Service) RevokeToken(ctx context.Context, auth ClientAuth, rawToken string) error {
|
||||
client, err := s.AuthenticateClient(ctx, auth)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
row, err := s.oauth.GetRefreshTokenByHash(ctx, sha256Hex(rawToken))
|
||||
if err != nil || row.ClientID != client.ID {
|
||||
return nil
|
||||
}
|
||||
|
||||
_ = s.oauth.DeleteRefreshTokenByID(ctx, row.ID)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) createAuthCode(
|
||||
ctx context.Context,
|
||||
userID, clientID uuid.UUID,
|
||||
redirectURI string,
|
||||
scopes []string,
|
||||
codeChallenge string,
|
||||
) (string, error) {
|
||||
rawCode, err := newOpaqueToken(32)
|
||||
if err != nil {
|
||||
return "", models.ErrInternal
|
||||
}
|
||||
|
||||
scopeJSON, _ := json.Marshal(scopes)
|
||||
now := time.Now()
|
||||
|
||||
_, err = s.oauth.CreateAuthorizationCode(ctx, models.AuthorizationCodeRow{
|
||||
CodeHash: sha256Hex(rawCode),
|
||||
UserID: userID,
|
||||
ClientID: clientID,
|
||||
RedirectURI: redirectURI,
|
||||
Scopes: scopeJSON,
|
||||
CodeChallenge: codeChallenge,
|
||||
CodeChallengeMethod: "S256",
|
||||
ExpiresAt: now.Add(5 * time.Minute),
|
||||
CreatedAt: now,
|
||||
})
|
||||
if err != nil {
|
||||
return "", models.ErrInternal
|
||||
}
|
||||
|
||||
return rawCode, nil
|
||||
}
|
||||
|
||||
func (s *Service) issuePair(ctx context.Context, user *models.User, clientID uuid.UUID, scopes []string) (*TokenPair, error) {
|
||||
accessToken, err := newOpaqueToken(32)
|
||||
if err != nil {
|
||||
return nil, models.ErrInternal
|
||||
}
|
||||
rawRefresh, err := newOpaqueToken(32)
|
||||
if err != nil {
|
||||
return nil, models.ErrInternal
|
||||
}
|
||||
|
||||
scopeJSON, _ := json.Marshal(scopes)
|
||||
now := time.Now()
|
||||
|
||||
accessData := struct {
|
||||
UserID uuid.UUID `json:"user_id"`
|
||||
Scopes []string `json:"scopes"`
|
||||
ClientID uuid.UUID `json:"client_id"`
|
||||
}{
|
||||
UserID: user.ID,
|
||||
Scopes: scopes,
|
||||
ClientID: clientID,
|
||||
}
|
||||
data, _ := json.Marshal(accessData)
|
||||
if err := s.redis.Set(ctx, accessTokenPrefix+accessToken, data, s.tokens.AccessTTL).Err(); err != nil {
|
||||
return nil, models.ErrInternal
|
||||
}
|
||||
|
||||
_, err = s.oauth.CreateRefreshToken(ctx, models.RefreshTokenRow{
|
||||
TokenHash: sha256Hex(rawRefresh),
|
||||
UserID: user.ID,
|
||||
ClientID: clientID,
|
||||
Scopes: scopeJSON,
|
||||
ExpiresAt: now.Add(s.tokens.RefreshTTL),
|
||||
CreatedAt: now,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, models.ErrInternal
|
||||
}
|
||||
|
||||
return &TokenPair{
|
||||
AccessToken: accessToken,
|
||||
RefreshToken: rawRefresh,
|
||||
TokenType: "Bearer",
|
||||
ExpiresIn: int64(s.tokens.AccessTTL.Seconds()),
|
||||
Scope: strings.Join(scopes, " "),
|
||||
User: user,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/dusiburg/kotosoft-id/internal/models"
|
||||
"github.com/google/uuid"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalidRequest = errors.New("invalid_request")
|
||||
ErrUnauthorizedClient = errors.New("unauthorized_client")
|
||||
ErrInvalidClient = errors.New("invalid_client")
|
||||
ErrInvalidGrant = errors.New("invalid_grant")
|
||||
ErrUnsupportedGrantType = errors.New("unsupported_grant_type")
|
||||
ErrAccessDenied = errors.New("access_denied")
|
||||
)
|
||||
|
||||
type UserRepo interface {
|
||||
CreateUser(ctx context.Context, user models.User) (*models.User, error)
|
||||
UpdateUser(ctx context.Context, user models.User) (*models.User, error)
|
||||
DeleteUser(ctx context.Context, id uuid.UUID) error
|
||||
GetUserByEmail(ctx context.Context, email string) (*models.User, error)
|
||||
GetUserByID(ctx context.Context, id uuid.UUID) (*models.User, error)
|
||||
IsUserExistsByEmail(ctx context.Context, email string) bool
|
||||
}
|
||||
|
||||
type OAuthRepo interface {
|
||||
GetOAuthClientByClientID(ctx context.Context, clientID string) (*models.OAuthClient, error)
|
||||
GetOAuthClientByID(ctx context.Context, id uuid.UUID) (*models.OAuthClient, error)
|
||||
CreateAuthorizationCode(ctx context.Context, row models.AuthorizationCodeRow) (*models.AuthorizationCodeRow, error)
|
||||
GetAuthorizationCodeByHash(ctx context.Context, codeHash string) (*models.AuthorizationCodeRow, error)
|
||||
ConsumeAuthorizationCodeByID(ctx context.Context, id uuid.UUID) error
|
||||
CreateRefreshToken(ctx context.Context, row models.RefreshTokenRow) (*models.RefreshTokenRow, error)
|
||||
GetRefreshTokenByHash(ctx context.Context, tokenHash string) (*models.RefreshTokenRow, error)
|
||||
DeleteRefreshTokenByID(ctx context.Context, id uuid.UUID) error
|
||||
RecordUserConsent(ctx context.Context, userID, clientID uuid.UUID, scopes []string) error
|
||||
GetUserConsents(ctx context.Context, userID uuid.UUID) ([]models.UserConsent, error)
|
||||
UpdateConsentLastUsed(ctx context.Context, userID, clientID uuid.UUID) error
|
||||
GetUserConsentsByClientID(ctx context.Context, userID uuid.UUID, clientID uuid.UUID) ([]models.UserConsent, error)
|
||||
RevokeConsent(ctx context.Context, userID, clientID uuid.UUID, revokedBy *uuid.UUID) error
|
||||
}
|
||||
|
||||
type TokenConfig struct {
|
||||
AccessTTL time.Duration
|
||||
RefreshTTL time.Duration
|
||||
}
|
||||
|
||||
type ClientAuth struct {
|
||||
ClientID string
|
||||
ClientSecret string
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
users UserRepo
|
||||
oauth OAuthRepo
|
||||
redis *redis.Client
|
||||
tokens TokenConfig
|
||||
basicClient *models.OAuthClient
|
||||
}
|
||||
|
||||
func New(
|
||||
users UserRepo,
|
||||
oauth OAuthRepo,
|
||||
rdb *redis.Client,
|
||||
tokenCfg TokenConfig,
|
||||
basicClient *models.OAuthClient,
|
||||
) *Service {
|
||||
return &Service{
|
||||
users: users,
|
||||
oauth: oauth,
|
||||
redis: rdb,
|
||||
tokens: tokenCfg,
|
||||
basicClient: basicClient,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) AuthenticateClient(ctx context.Context, auth ClientAuth) (*models.OAuthClient, error) {
|
||||
client, err := s.oauth.GetOAuthClientByClientID(ctx, auth.ClientID)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidClient
|
||||
}
|
||||
if !verifyClientSecret(client.ClientSecret, auth.ClientSecret) {
|
||||
return nil, ErrInvalidClient
|
||||
}
|
||||
return client, nil
|
||||
}
|
||||
|
||||
const (
|
||||
oauthSessionPrefix = "oauth_session:"
|
||||
accessTokenPrefix = "access_token:"
|
||||
oauthSessionTTL = 10 * time.Minute
|
||||
)
|
||||
Reference in New Issue
Block a user