c091ad7aed
Stand up an internal ops-api service with operator account, auth, and audit log subsystems backed by a dedicated migrations_ops migration set. Wire Makefile targets and the migrate Dockerfile stage so the new schema ships alongside the existing tenant + monitoring databases. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
189 lines
4.9 KiB
Go
189 lines
4.9 KiB
Go
package app
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/golang-jwt/jwt/v5"
|
|
"github.com/google/uuid"
|
|
"golang.org/x/crypto/bcrypt"
|
|
|
|
"github.com/geo-platform/tenant-api/internal/ops/domain"
|
|
"github.com/geo-platform/tenant-api/internal/ops/repository"
|
|
"github.com/geo-platform/tenant-api/internal/shared/response"
|
|
)
|
|
|
|
type OperatorClaims struct {
|
|
OperatorID int64 `json:"operator_id"`
|
|
Username string `json:"username"`
|
|
DisplayName string `json:"display_name"`
|
|
Role string `json:"role"`
|
|
jwt.RegisteredClaims
|
|
}
|
|
|
|
type TokenIssuer struct {
|
|
secret []byte
|
|
accessTTL time.Duration
|
|
}
|
|
|
|
func NewTokenIssuer(secret string, accessTTL time.Duration) *TokenIssuer {
|
|
return &TokenIssuer{secret: []byte(secret), accessTTL: accessTTL}
|
|
}
|
|
|
|
func (t *TokenIssuer) AccessTTL() time.Duration { return t.accessTTL }
|
|
|
|
type IssuedToken struct {
|
|
AccessToken string
|
|
ExpiresAt int64
|
|
}
|
|
|
|
func (t *TokenIssuer) Issue(operator *domain.OperatorAccount) (*IssuedToken, error) {
|
|
now := time.Now()
|
|
exp := now.Add(t.accessTTL)
|
|
claims := OperatorClaims{
|
|
OperatorID: operator.ID,
|
|
Username: operator.Username,
|
|
DisplayName: operator.DisplayName,
|
|
Role: operator.Role,
|
|
RegisteredClaims: jwt.RegisteredClaims{
|
|
ID: uuid.New().String(),
|
|
Subject: "ops-access",
|
|
IssuedAt: jwt.NewNumericDate(now),
|
|
ExpiresAt: jwt.NewNumericDate(exp),
|
|
},
|
|
}
|
|
signed, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(t.secret)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("sign ops token: %w", err)
|
|
}
|
|
return &IssuedToken{AccessToken: signed, ExpiresAt: exp.Unix()}, nil
|
|
}
|
|
|
|
func (t *TokenIssuer) Parse(raw string) (*OperatorClaims, error) {
|
|
token, err := jwt.ParseWithClaims(raw, &OperatorClaims{}, func(tok *jwt.Token) (any, error) {
|
|
if _, ok := tok.Method.(*jwt.SigningMethodHMAC); !ok {
|
|
return nil, fmt.Errorf("unexpected signing method: %v", tok.Header["alg"])
|
|
}
|
|
return t.secret, nil
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
claims, ok := token.Claims.(*OperatorClaims)
|
|
if !ok || !token.Valid {
|
|
return nil, errors.New("invalid ops token")
|
|
}
|
|
if claims.Subject != "ops-access" {
|
|
return nil, errors.New("wrong token subject")
|
|
}
|
|
return claims, nil
|
|
}
|
|
|
|
type AuthService struct {
|
|
accounts *repository.AccountRepository
|
|
audits *AuditService
|
|
issuer *TokenIssuer
|
|
}
|
|
|
|
func NewAuthService(accounts *repository.AccountRepository, audits *AuditService, issuer *TokenIssuer) *AuthService {
|
|
return &AuthService{accounts: accounts, audits: audits, issuer: issuer}
|
|
}
|
|
|
|
type LoginInput struct {
|
|
Username string
|
|
Password string
|
|
IP string
|
|
UserAgent string
|
|
RequestID string
|
|
}
|
|
|
|
type LoginResult struct {
|
|
AccessToken string
|
|
ExpiresAt int64
|
|
Operator OperatorView
|
|
}
|
|
|
|
type OperatorView struct {
|
|
ID int64 `json:"id"`
|
|
Username string `json:"username"`
|
|
DisplayName string `json:"display_name"`
|
|
Email *string `json:"email"`
|
|
Role string `json:"role"`
|
|
Status string `json:"status"`
|
|
}
|
|
|
|
func ToOperatorView(a *domain.OperatorAccount) OperatorView {
|
|
return OperatorView{
|
|
ID: a.ID,
|
|
Username: a.Username,
|
|
DisplayName: a.DisplayName,
|
|
Email: a.Email,
|
|
Role: a.Role,
|
|
Status: a.Status,
|
|
}
|
|
}
|
|
|
|
const (
|
|
ActionLoginSuccess = "auth.login.success"
|
|
ActionLoginFailed = "auth.login.failure"
|
|
)
|
|
|
|
func (s *AuthService) Login(ctx context.Context, in LoginInput) (*LoginResult, error) {
|
|
account, err := s.accounts.GetByUsername(ctx, in.Username)
|
|
if err != nil {
|
|
s.recordLoginFailure(ctx, in, "account_not_found")
|
|
return nil, response.ErrUnauthorized(40110, "invalid_credentials", "账号或密码错误")
|
|
}
|
|
|
|
if !account.IsActive() {
|
|
s.recordLoginFailure(ctx, in, "account_disabled")
|
|
return nil, response.ErrForbidden(40310, "account_disabled", "账号已停用")
|
|
}
|
|
|
|
if err := bcrypt.CompareHashAndPassword([]byte(account.PasswordHash), []byte(in.Password)); err != nil {
|
|
s.recordLoginFailure(ctx, in, "wrong_password")
|
|
return nil, response.ErrUnauthorized(40110, "invalid_credentials", "账号或密码错误")
|
|
}
|
|
|
|
token, err := s.issuer.Issue(account)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("issue token: %w", err)
|
|
}
|
|
|
|
if err := s.accounts.MarkLogin(ctx, account.ID); err != nil {
|
|
// non-fatal — login already succeeded
|
|
_ = err
|
|
}
|
|
|
|
id := account.ID
|
|
_ = s.audits.Append(ctx, domain.AuditEvent{
|
|
OperatorID: &id,
|
|
OperatorName: account.DisplayName,
|
|
Action: ActionLoginSuccess,
|
|
IP: in.IP,
|
|
UserAgent: in.UserAgent,
|
|
RequestID: in.RequestID,
|
|
})
|
|
|
|
return &LoginResult{
|
|
AccessToken: token.AccessToken,
|
|
ExpiresAt: token.ExpiresAt,
|
|
Operator: ToOperatorView(account),
|
|
}, nil
|
|
}
|
|
|
|
func (s *AuthService) recordLoginFailure(ctx context.Context, in LoginInput, reason string) {
|
|
_ = s.audits.Append(ctx, domain.AuditEvent{
|
|
Action: ActionLoginFailed,
|
|
IP: in.IP,
|
|
UserAgent: in.UserAgent,
|
|
RequestID: in.RequestID,
|
|
Metadata: map[string]any{
|
|
"username": in.Username,
|
|
"reason": reason,
|
|
},
|
|
})
|
|
}
|