e045e00fbf
Add self-service password change that re-hashes the credential and bumps a per-user session version so all existing access/refresh tokens are rejected. Session version is tracked in Redis with an in-memory fallback and enforced in middleware and refresh. Scope prompt rules and rule groups to a brand: new brand_id column (migrated to a "未归属" fallback brand for existing rows), brand-filtered queries/indexes, and brand-aware admin-web tabs. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
142 lines
3.6 KiB
Go
142 lines
3.6 KiB
Go
package auth
|
|
|
|
import (
|
|
"crypto/sha256"
|
|
"fmt"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/golang-jwt/jwt/v5"
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
type Manager struct {
|
|
mu sync.RWMutex
|
|
secret []byte
|
|
accessTTL time.Duration
|
|
refreshTTL time.Duration
|
|
}
|
|
|
|
func NewManager(secret string, accessTTL, refreshTTL time.Duration) *Manager {
|
|
m := &Manager{}
|
|
m.Update(secret, accessTTL, refreshTTL)
|
|
return m
|
|
}
|
|
|
|
func (m *Manager) Update(secret string, accessTTL, refreshTTL time.Duration) {
|
|
if m == nil {
|
|
return
|
|
}
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
m.secret = []byte(secret)
|
|
m.accessTTL = accessTTL
|
|
m.refreshTTL = refreshTTL
|
|
}
|
|
|
|
type TokenPair struct {
|
|
AccessToken string `json:"access_token"`
|
|
RefreshToken string `json:"refresh_token"`
|
|
AccessJTI string `json:"-"`
|
|
RefreshJTI string `json:"-"`
|
|
ExpiresAt int64 `json:"expires_at"`
|
|
}
|
|
|
|
func (m *Manager) Issue(userID, tenantID, primaryWorkspaceID int64, role string) (*TokenPair, error) {
|
|
return m.IssueWithSessionVersion(userID, tenantID, primaryWorkspaceID, role, 0)
|
|
}
|
|
|
|
func (m *Manager) IssueWithSessionVersion(userID, tenantID, primaryWorkspaceID int64, role string, sessionVersion int64) (*TokenPair, error) {
|
|
secret, accessTTL, refreshTTL := m.snapshot()
|
|
now := time.Now()
|
|
accessJTI := uuid.New().String()
|
|
refreshJTI := uuid.New().String()
|
|
|
|
accessClaims := Claims{
|
|
UserID: userID,
|
|
TenantID: tenantID,
|
|
PrimaryWorkspaceID: primaryWorkspaceID,
|
|
Role: role,
|
|
SessionVersion: sessionVersion,
|
|
RegisteredClaims: jwt.RegisteredClaims{
|
|
ID: accessJTI,
|
|
Subject: "access",
|
|
IssuedAt: jwt.NewNumericDate(now),
|
|
ExpiresAt: jwt.NewNumericDate(now.Add(accessTTL)),
|
|
},
|
|
}
|
|
accessToken, err := jwt.NewWithClaims(jwt.SigningMethodHS256, accessClaims).SignedString(secret)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("sign access token: %w", err)
|
|
}
|
|
|
|
refreshClaims := Claims{
|
|
UserID: userID,
|
|
TenantID: tenantID,
|
|
PrimaryWorkspaceID: primaryWorkspaceID,
|
|
Role: role,
|
|
SessionVersion: sessionVersion,
|
|
RegisteredClaims: jwt.RegisteredClaims{
|
|
ID: refreshJTI,
|
|
Subject: "refresh",
|
|
IssuedAt: jwt.NewNumericDate(now),
|
|
ExpiresAt: jwt.NewNumericDate(now.Add(refreshTTL)),
|
|
},
|
|
}
|
|
refreshToken, err := jwt.NewWithClaims(jwt.SigningMethodHS256, refreshClaims).SignedString(secret)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("sign refresh token: %w", err)
|
|
}
|
|
|
|
return &TokenPair{
|
|
AccessToken: accessToken,
|
|
RefreshToken: refreshToken,
|
|
AccessJTI: accessJTI,
|
|
RefreshJTI: refreshJTI,
|
|
ExpiresAt: now.Add(accessTTL).Unix(),
|
|
}, nil
|
|
}
|
|
|
|
func (m *Manager) Parse(tokenStr string) (*Claims, error) {
|
|
secret, _, _ := m.snapshot()
|
|
token, err := jwt.ParseWithClaims(tokenStr, &Claims{}, func(t *jwt.Token) (interface{}, error) {
|
|
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
|
return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
|
|
}
|
|
return secret, nil
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
claims, ok := token.Claims.(*Claims)
|
|
if !ok || !token.Valid {
|
|
return nil, fmt.Errorf("invalid token claims")
|
|
}
|
|
return claims, nil
|
|
}
|
|
|
|
func (m *Manager) AccessTTL() time.Duration {
|
|
_, ttl, _ := m.snapshot()
|
|
return ttl
|
|
}
|
|
|
|
func (m *Manager) RefreshTTL() time.Duration {
|
|
_, _, ttl := m.snapshot()
|
|
return ttl
|
|
}
|
|
|
|
func (m *Manager) snapshot() ([]byte, time.Duration, time.Duration) {
|
|
if m == nil {
|
|
return nil, 0, 0
|
|
}
|
|
m.mu.RLock()
|
|
defer m.mu.RUnlock()
|
|
secret := append([]byte(nil), m.secret...)
|
|
return secret, m.accessTTL, m.refreshTTL
|
|
}
|
|
|
|
func HashToken(raw string) string {
|
|
h := sha256.Sum256([]byte(raw))
|
|
return fmt.Sprintf("%x", h)
|
|
}
|