feat: Add Login Page
This commit is contained in:
@@ -0,0 +1,154 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrUserNotFound = errors.New("user not found")
|
||||
ErrUserAlreadyExists = errors.New("user already exists")
|
||||
ErrTokenNotFound = errors.New("token not found")
|
||||
)
|
||||
|
||||
// userRepository implements user repository interface
|
||||
type userRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewUserRepository creates a new user repository
|
||||
func NewUserRepository(db *gorm.DB) interfaces.UserRepository {
|
||||
return &userRepository{db: db}
|
||||
}
|
||||
|
||||
// CreateUser creates a user
|
||||
func (r *userRepository) CreateUser(ctx context.Context, user *types.User) error {
|
||||
logger.Infof(ctx, "Creating user in database: %s", user.Email)
|
||||
return r.db.WithContext(ctx).Create(user).Error
|
||||
}
|
||||
|
||||
// GetUserByID gets a user by ID
|
||||
func (r *userRepository) GetUserByID(ctx context.Context, id string) (*types.User, error) {
|
||||
var user types.User
|
||||
if err := r.db.WithContext(ctx).Where("id = ?", id).First(&user).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrUserNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// GetUserByEmail gets a user by email
|
||||
func (r *userRepository) GetUserByEmail(ctx context.Context, email string) (*types.User, error) {
|
||||
var user types.User
|
||||
if err := r.db.WithContext(ctx).Where("email = ?", email).First(&user).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrUserNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// GetUserByUsername gets a user by username
|
||||
func (r *userRepository) GetUserByUsername(ctx context.Context, username string) (*types.User, error) {
|
||||
var user types.User
|
||||
if err := r.db.WithContext(ctx).Where("username = ?", username).First(&user).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrUserNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// UpdateUser updates a user
|
||||
func (r *userRepository) UpdateUser(ctx context.Context, user *types.User) error {
|
||||
return r.db.WithContext(ctx).Save(user).Error
|
||||
}
|
||||
|
||||
// DeleteUser deletes a user
|
||||
func (r *userRepository) DeleteUser(ctx context.Context, id string) error {
|
||||
return r.db.WithContext(ctx).Where("id = ?", id).Delete(&types.User{}).Error
|
||||
}
|
||||
|
||||
// ListUsers lists users with pagination
|
||||
func (r *userRepository) ListUsers(ctx context.Context, offset, limit int) ([]*types.User, error) {
|
||||
var users []*types.User
|
||||
query := r.db.WithContext(ctx).Order("created_at DESC")
|
||||
|
||||
if limit > 0 {
|
||||
query = query.Limit(limit)
|
||||
}
|
||||
|
||||
if offset > 0 {
|
||||
query = query.Offset(offset)
|
||||
}
|
||||
|
||||
if err := query.Find(&users).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return users, nil
|
||||
}
|
||||
|
||||
// authTokenRepository implements auth token repository interface
|
||||
type authTokenRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewAuthTokenRepository creates a new auth token repository
|
||||
func NewAuthTokenRepository(db *gorm.DB) interfaces.AuthTokenRepository {
|
||||
return &authTokenRepository{db: db}
|
||||
}
|
||||
|
||||
// CreateToken creates an auth token
|
||||
func (r *authTokenRepository) CreateToken(ctx context.Context, token *types.AuthToken) error {
|
||||
return r.db.WithContext(ctx).Create(token).Error
|
||||
}
|
||||
|
||||
// GetTokenByValue gets a token by its value
|
||||
func (r *authTokenRepository) GetTokenByValue(ctx context.Context, tokenValue string) (*types.AuthToken, error) {
|
||||
var token types.AuthToken
|
||||
if err := r.db.WithContext(ctx).Where("token = ?", tokenValue).First(&token).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrTokenNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &token, nil
|
||||
}
|
||||
|
||||
// GetTokensByUserID gets all tokens for a user
|
||||
func (r *authTokenRepository) GetTokensByUserID(ctx context.Context, userID string) ([]*types.AuthToken, error) {
|
||||
var tokens []*types.AuthToken
|
||||
if err := r.db.WithContext(ctx).Where("user_id = ?", userID).Find(&tokens).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return tokens, nil
|
||||
}
|
||||
|
||||
// UpdateToken updates a token
|
||||
func (r *authTokenRepository) UpdateToken(ctx context.Context, token *types.AuthToken) error {
|
||||
return r.db.WithContext(ctx).Save(token).Error
|
||||
}
|
||||
|
||||
// DeleteToken deletes a token
|
||||
func (r *authTokenRepository) DeleteToken(ctx context.Context, id string) error {
|
||||
return r.db.WithContext(ctx).Where("id = ?", id).Delete(&types.AuthToken{}).Error
|
||||
}
|
||||
|
||||
// DeleteExpiredTokens deletes all expired tokens
|
||||
func (r *authTokenRepository) DeleteExpiredTokens(ctx context.Context) error {
|
||||
return r.db.WithContext(ctx).Where("expires_at < NOW()").Delete(&types.AuthToken{}).Error
|
||||
}
|
||||
|
||||
// RevokeTokensByUserID revokes all tokens for a user
|
||||
func (r *authTokenRepository) RevokeTokensByUserID(ctx context.Context, userID string) error {
|
||||
return r.db.WithContext(ctx).Model(&types.AuthToken{}).Where("user_id = ?", userID).Update("is_revoked", true).Error
|
||||
}
|
||||
@@ -18,7 +18,9 @@ import (
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
var apiKeySecret = []byte(os.Getenv("TENANT_AES_KEY"))
|
||||
var apiKeySecret = func() []byte {
|
||||
return []byte(os.Getenv("TENANT_AES_KEY"))
|
||||
}
|
||||
|
||||
// ListTenantsParams defines parameters for listing tenants with filtering and pagination
|
||||
type ListTenantsParams struct {
|
||||
@@ -221,7 +223,7 @@ func (r *tenantService) generateApiKey(tenantID uint) string {
|
||||
binary.LittleEndian.PutUint64(idBytes, uint64(tenantID))
|
||||
|
||||
// 2. Encrypt tenant_id using AES-GCM
|
||||
block, err := aes.NewCipher(apiKeySecret)
|
||||
block, err := aes.NewCipher(apiKeySecret())
|
||||
if err != nil {
|
||||
panic("Failed to create AES cipher: " + err.Error())
|
||||
}
|
||||
@@ -267,7 +269,7 @@ func (r *tenantService) ExtractTenantIDFromAPIKey(apiKey string) (uint, error) {
|
||||
nonce, ciphertext := encryptedData[:12], encryptedData[12:]
|
||||
|
||||
// 4. Decrypt
|
||||
block, err := aes.NewCipher(apiKeySecret)
|
||||
block, err := aes.NewCipher(apiKeySecret())
|
||||
if err != nil {
|
||||
return 0, errors.New("decryption error")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,408 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/google/uuid"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// JWT secret key - in production this should be from environment variable
|
||||
var jwtSecret = []byte("your-secret-key")
|
||||
|
||||
// userService implements the UserService interface
|
||||
type userService struct {
|
||||
userRepo interfaces.UserRepository
|
||||
tokenRepo interfaces.AuthTokenRepository
|
||||
tenantService interfaces.TenantService
|
||||
}
|
||||
|
||||
// NewUserService creates a new user service instance
|
||||
func NewUserService(userRepo interfaces.UserRepository, tokenRepo interfaces.AuthTokenRepository, tenantService interfaces.TenantService) interfaces.UserService {
|
||||
return &userService{
|
||||
userRepo: userRepo,
|
||||
tokenRepo: tokenRepo,
|
||||
tenantService: tenantService,
|
||||
}
|
||||
}
|
||||
|
||||
// Register creates a new user account
|
||||
func (s *userService) Register(ctx context.Context, req *types.RegisterRequest) (*types.User, error) {
|
||||
logger.Info(ctx, "Start user registration")
|
||||
|
||||
// Validate input
|
||||
if req.Username == "" || req.Email == "" || req.Password == "" {
|
||||
return nil, errors.New("username, email and password are required")
|
||||
}
|
||||
|
||||
// Check if user already exists
|
||||
existingUser, _ := s.userRepo.GetUserByEmail(ctx, req.Email)
|
||||
if existingUser != nil {
|
||||
return nil, errors.New("user with this email already exists")
|
||||
}
|
||||
|
||||
existingUser, _ = s.userRepo.GetUserByUsername(ctx, req.Username)
|
||||
if existingUser != nil {
|
||||
return nil, errors.New("user with this username already exists")
|
||||
}
|
||||
|
||||
// Hash password
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to hash password: %v", err)
|
||||
return nil, errors.New("failed to process password")
|
||||
}
|
||||
|
||||
// Create default tenant for the user
|
||||
tenant := &types.Tenant{
|
||||
Name: fmt.Sprintf("%s's Workspace", req.Username),
|
||||
Description: "Default workspace",
|
||||
Status: "active",
|
||||
RetrieverEngines: types.RetrieverEngines{
|
||||
Engines: []types.RetrieverEngineParams{
|
||||
{
|
||||
RetrieverType: types.KeywordsRetrieverType,
|
||||
RetrieverEngineType: types.PostgresRetrieverEngineType,
|
||||
},
|
||||
{
|
||||
RetrieverType: types.VectorRetrieverType,
|
||||
RetrieverEngineType: types.PostgresRetrieverEngineType,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
createdTenant, err := s.tenantService.CreateTenant(ctx, tenant)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to create tenant: %v", err)
|
||||
return nil, errors.New("failed to create workspace")
|
||||
}
|
||||
|
||||
// Create user
|
||||
user := &types.User{
|
||||
ID: uuid.New().String(),
|
||||
Username: req.Username,
|
||||
Email: req.Email,
|
||||
PasswordHash: string(hashedPassword),
|
||||
TenantID: createdTenant.ID,
|
||||
IsActive: true,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
err = s.userRepo.CreateUser(ctx, user)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to create user: %v", err)
|
||||
return nil, errors.New("failed to create user")
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "User registered successfully: %s", user.Email)
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// Login authenticates a user and returns tokens
|
||||
func (s *userService) Login(ctx context.Context, req *types.LoginRequest) (*types.LoginResponse, error) {
|
||||
logger.Infof(ctx, "Start user login for email: %s", req.Email)
|
||||
|
||||
// Get user by email
|
||||
user, err := s.userRepo.GetUserByEmail(ctx, req.Email)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to get user by email %s: %v", req.Email, err)
|
||||
return &types.LoginResponse{
|
||||
Success: false,
|
||||
Message: "Invalid email or password",
|
||||
}, nil
|
||||
}
|
||||
if user == nil {
|
||||
logger.Warnf(ctx, "User not found for email: %s", req.Email)
|
||||
return &types.LoginResponse{
|
||||
Success: false,
|
||||
Message: "Invalid email or password",
|
||||
}, nil
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Found user: ID=%s, Email=%s, IsActive=%t", user.ID, user.Email, user.IsActive)
|
||||
|
||||
// Check if user is active
|
||||
if !user.IsActive {
|
||||
logger.Warnf(ctx, "User account is disabled for email: %s", req.Email)
|
||||
return &types.LoginResponse{
|
||||
Success: false,
|
||||
Message: "Account is disabled",
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Verify password
|
||||
logger.Infof(ctx, "Verifying password for user: %s", user.Email)
|
||||
err = bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(req.Password))
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Password verification failed for user %s: %v", user.Email, err)
|
||||
return &types.LoginResponse{
|
||||
Success: false,
|
||||
Message: "Invalid email or password",
|
||||
}, nil
|
||||
}
|
||||
logger.Infof(ctx, "Password verification successful for user: %s", user.Email)
|
||||
|
||||
// Generate tokens
|
||||
logger.Infof(ctx, "Generating tokens for user: %s", user.Email)
|
||||
accessToken, refreshToken, err := s.GenerateTokens(ctx, user)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to generate tokens for user %s: %v", user.Email, err)
|
||||
return &types.LoginResponse{
|
||||
Success: false,
|
||||
Message: "Login failed",
|
||||
}, nil
|
||||
}
|
||||
logger.Infof(ctx, "Tokens generated successfully for user: %s", user.Email)
|
||||
|
||||
// Get tenant information
|
||||
logger.Infof(ctx, "Getting tenant information for user %s, tenant ID: %s", user.Email, user.TenantID)
|
||||
tenant, err := s.tenantService.GetTenantByID(ctx, user.TenantID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to get tenant info for user %s, tenant ID %s: %v", user.Email, user.TenantID, err)
|
||||
} else {
|
||||
logger.Infof(ctx, "Tenant information retrieved successfully for user: %s", user.Email)
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "User logged in successfully: %s", user.Email)
|
||||
return &types.LoginResponse{
|
||||
Success: true,
|
||||
Message: "Login successful",
|
||||
User: user,
|
||||
Tenant: tenant,
|
||||
Token: accessToken,
|
||||
RefreshToken: refreshToken,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// GetUserByID gets a user by ID
|
||||
func (s *userService) GetUserByID(ctx context.Context, id string) (*types.User, error) {
|
||||
return s.userRepo.GetUserByID(ctx, id)
|
||||
}
|
||||
|
||||
// GetUserByEmail gets a user by email
|
||||
func (s *userService) GetUserByEmail(ctx context.Context, email string) (*types.User, error) {
|
||||
return s.userRepo.GetUserByEmail(ctx, email)
|
||||
}
|
||||
|
||||
// GetUserByUsername gets a user by username
|
||||
func (s *userService) GetUserByUsername(ctx context.Context, username string) (*types.User, error) {
|
||||
return s.userRepo.GetUserByUsername(ctx, username)
|
||||
}
|
||||
|
||||
// UpdateUser updates user information
|
||||
func (s *userService) UpdateUser(ctx context.Context, user *types.User) error {
|
||||
user.UpdatedAt = time.Now()
|
||||
return s.userRepo.UpdateUser(ctx, user)
|
||||
}
|
||||
|
||||
// DeleteUser deletes a user
|
||||
func (s *userService) DeleteUser(ctx context.Context, id string) error {
|
||||
return s.userRepo.DeleteUser(ctx, id)
|
||||
}
|
||||
|
||||
// ChangePassword changes user password
|
||||
func (s *userService) ChangePassword(ctx context.Context, userID string, oldPassword, newPassword string) error {
|
||||
user, err := s.userRepo.GetUserByID(ctx, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Verify old password
|
||||
err = bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(oldPassword))
|
||||
if err != nil {
|
||||
return errors.New("invalid old password")
|
||||
}
|
||||
|
||||
// Hash new password
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
user.PasswordHash = string(hashedPassword)
|
||||
user.UpdatedAt = time.Now()
|
||||
|
||||
return s.userRepo.UpdateUser(ctx, user)
|
||||
}
|
||||
|
||||
// ValidatePassword validates user password
|
||||
func (s *userService) ValidatePassword(ctx context.Context, userID string, password string) error {
|
||||
user, err := s.userRepo.GetUserByID(ctx, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(password))
|
||||
}
|
||||
|
||||
// GenerateTokens generates access and refresh tokens for user
|
||||
func (s *userService) GenerateTokens(ctx context.Context, user *types.User) (accessToken, refreshToken string, err error) {
|
||||
// Generate access token (expires in 24 hours)
|
||||
accessClaims := jwt.MapClaims{
|
||||
"user_id": user.ID,
|
||||
"email": user.Email,
|
||||
"tenant_id": user.TenantID,
|
||||
"exp": time.Now().Add(24 * time.Hour).Unix(),
|
||||
"iat": time.Now().Unix(),
|
||||
"type": "access",
|
||||
}
|
||||
|
||||
accessTokenObj := jwt.NewWithClaims(jwt.SigningMethodHS256, accessClaims)
|
||||
accessToken, err = accessTokenObj.SignedString(jwtSecret)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
|
||||
// Generate refresh token (expires in 7 days)
|
||||
refreshClaims := jwt.MapClaims{
|
||||
"user_id": user.ID,
|
||||
"exp": time.Now().Add(7 * 24 * time.Hour).Unix(),
|
||||
"iat": time.Now().Unix(),
|
||||
"type": "refresh",
|
||||
}
|
||||
|
||||
refreshTokenObj := jwt.NewWithClaims(jwt.SigningMethodHS256, refreshClaims)
|
||||
refreshToken, err = refreshTokenObj.SignedString(jwtSecret)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
|
||||
// Store tokens in database
|
||||
accessTokenRecord := &types.AuthToken{
|
||||
ID: uuid.New().String(),
|
||||
UserID: user.ID,
|
||||
Token: accessToken,
|
||||
TokenType: "access_token",
|
||||
ExpiresAt: time.Now().Add(24 * time.Hour),
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
refreshTokenRecord := &types.AuthToken{
|
||||
ID: uuid.New().String(),
|
||||
UserID: user.ID,
|
||||
Token: refreshToken,
|
||||
TokenType: "refresh_token",
|
||||
ExpiresAt: time.Now().Add(7 * 24 * time.Hour),
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
_ = s.tokenRepo.CreateToken(ctx, accessTokenRecord)
|
||||
_ = s.tokenRepo.CreateToken(ctx, refreshTokenRecord)
|
||||
|
||||
return accessToken, refreshToken, nil
|
||||
}
|
||||
|
||||
// ValidateToken validates an access token
|
||||
func (s *userService) ValidateToken(ctx context.Context, tokenString string) (*types.User, error) {
|
||||
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
return jwtSecret, nil
|
||||
})
|
||||
|
||||
if err != nil || !token.Valid {
|
||||
return nil, errors.New("invalid token")
|
||||
}
|
||||
|
||||
claims, ok := token.Claims.(jwt.MapClaims)
|
||||
if !ok {
|
||||
return nil, errors.New("invalid token claims")
|
||||
}
|
||||
|
||||
userID, ok := claims["user_id"].(string)
|
||||
if !ok {
|
||||
return nil, errors.New("invalid user ID in token")
|
||||
}
|
||||
|
||||
// Check if token is revoked
|
||||
tokenRecord, err := s.tokenRepo.GetTokenByValue(ctx, tokenString)
|
||||
if err != nil || tokenRecord == nil || tokenRecord.IsRevoked {
|
||||
return nil, errors.New("token is revoked")
|
||||
}
|
||||
|
||||
return s.userRepo.GetUserByID(ctx, userID)
|
||||
}
|
||||
|
||||
// RefreshToken refreshes access token using refresh token
|
||||
func (s *userService) RefreshToken(ctx context.Context, refreshTokenString string) (accessToken, newRefreshToken string, err error) {
|
||||
token, err := jwt.Parse(refreshTokenString, func(token *jwt.Token) (interface{}, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
return jwtSecret, nil
|
||||
})
|
||||
|
||||
if err != nil || !token.Valid {
|
||||
return "", "", errors.New("invalid refresh token")
|
||||
}
|
||||
|
||||
claims, ok := token.Claims.(jwt.MapClaims)
|
||||
if !ok {
|
||||
return "", "", errors.New("invalid token claims")
|
||||
}
|
||||
|
||||
tokenType, ok := claims["type"].(string)
|
||||
if !ok || tokenType != "refresh" {
|
||||
return "", "", errors.New("not a refresh token")
|
||||
}
|
||||
|
||||
userID, ok := claims["user_id"].(string)
|
||||
if !ok {
|
||||
return "", "", errors.New("invalid user ID in token")
|
||||
}
|
||||
|
||||
// Check if token is revoked
|
||||
tokenRecord, err := s.tokenRepo.GetTokenByValue(ctx, refreshTokenString)
|
||||
if err != nil || tokenRecord == nil || tokenRecord.IsRevoked {
|
||||
return "", "", errors.New("refresh token is revoked")
|
||||
}
|
||||
|
||||
// Get user
|
||||
user, err := s.userRepo.GetUserByID(ctx, userID)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
|
||||
// Revoke old refresh token
|
||||
tokenRecord.IsRevoked = true
|
||||
_ = s.tokenRepo.UpdateToken(ctx, tokenRecord)
|
||||
|
||||
// Generate new tokens
|
||||
return s.GenerateTokens(ctx, user)
|
||||
}
|
||||
|
||||
// RevokeToken revokes a token
|
||||
func (s *userService) RevokeToken(ctx context.Context, tokenString string) error {
|
||||
tokenRecord, err := s.tokenRepo.GetTokenByValue(ctx, tokenString)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
tokenRecord.IsRevoked = true
|
||||
tokenRecord.UpdatedAt = time.Now()
|
||||
|
||||
return s.tokenRepo.UpdateToken(ctx, tokenRecord)
|
||||
}
|
||||
|
||||
// GetCurrentUser gets current user from context
|
||||
func (s *userService) GetCurrentUser(ctx context.Context) (*types.User, error) {
|
||||
userID, ok := ctx.Value("user_id").(string)
|
||||
if !ok {
|
||||
return nil, errors.New("user not found in context")
|
||||
}
|
||||
|
||||
return s.userRepo.GetUserByID(ctx, userID)
|
||||
}
|
||||
@@ -78,6 +78,8 @@ func BuildContainer(container *dig.Container) *dig.Container {
|
||||
must(container.Provide(repository.NewSessionRepository))
|
||||
must(container.Provide(repository.NewMessageRepository))
|
||||
must(container.Provide(repository.NewModelRepository))
|
||||
must(container.Provide(repository.NewUserRepository))
|
||||
must(container.Provide(repository.NewAuthTokenRepository))
|
||||
|
||||
// Business service layer
|
||||
must(container.Provide(service.NewTenantService))
|
||||
@@ -91,6 +93,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
|
||||
must(container.Provide(service.NewModelService))
|
||||
must(container.Provide(service.NewDatasetService))
|
||||
must(container.Provide(service.NewEvaluationService))
|
||||
must(container.Provide(service.NewUserService))
|
||||
|
||||
// Chat pipeline components for processing chat requests
|
||||
must(container.Provide(chatpipline.NewEventManager))
|
||||
@@ -117,6 +120,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
|
||||
must(container.Provide(handler.NewModelHandler))
|
||||
must(container.Provide(handler.NewEvaluationHandler))
|
||||
must(container.Provide(handler.NewInitializationHandler))
|
||||
must(container.Provide(handler.NewAuthHandler))
|
||||
|
||||
// Router configuration
|
||||
must(container.Provide(router.NewRouter))
|
||||
@@ -177,6 +181,15 @@ func initDatabase(cfg *config.Config) (*gorm.DB, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Auto-migrate database tables
|
||||
err = db.AutoMigrate(
|
||||
&types.User{},
|
||||
&types.AuthToken{},
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to auto-migrate database tables: %v", err)
|
||||
}
|
||||
|
||||
// Get underlying SQL DB object
|
||||
sqlDB, err := db.DB()
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/errors"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// AuthHandler implements HTTP request handlers for user authentication
|
||||
// Provides functionality for user registration, login, logout, and token management
|
||||
// through the REST API endpoints
|
||||
type AuthHandler struct {
|
||||
userService interfaces.UserService
|
||||
}
|
||||
|
||||
// NewAuthHandler creates a new auth handler instance with the provided service
|
||||
// Parameters:
|
||||
// - userService: An implementation of the UserService interface for business logic
|
||||
//
|
||||
// Returns a pointer to the newly created AuthHandler
|
||||
func NewAuthHandler(userService interfaces.UserService) *AuthHandler {
|
||||
return &AuthHandler{
|
||||
userService: userService,
|
||||
}
|
||||
}
|
||||
|
||||
// Register handles the HTTP request for user registration
|
||||
// It deserializes the request body into a registration request object, validates it,
|
||||
// calls the service to create the user, and returns the result
|
||||
// Parameters:
|
||||
// - c: Gin context for the HTTP request
|
||||
func (h *AuthHandler) Register(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
logger.Info(ctx, "Start user registration")
|
||||
|
||||
var req types.RegisterRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.Error(ctx, "Failed to parse registration request parameters", err)
|
||||
appErr := errors.NewValidationError("Invalid registration parameters").WithDetails(err.Error())
|
||||
c.Error(appErr)
|
||||
return
|
||||
}
|
||||
|
||||
// Validate required fields
|
||||
if req.Username == "" || req.Email == "" || req.Password == "" {
|
||||
logger.Error(ctx, "Missing required registration fields")
|
||||
appErr := errors.NewValidationError("Username, email and password are required")
|
||||
c.Error(appErr)
|
||||
return
|
||||
}
|
||||
|
||||
// Call service to register user
|
||||
user, err := h.userService.Register(ctx, &req)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to register user: %v", err)
|
||||
appErr := errors.NewBadRequestError("Registration failed").WithDetails(err.Error())
|
||||
c.Error(appErr)
|
||||
return
|
||||
}
|
||||
|
||||
// Return success response
|
||||
response := &types.RegisterResponse{
|
||||
Success: true,
|
||||
Message: "Registration successful",
|
||||
User: user,
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "User registered successfully: %s", user.Email)
|
||||
c.JSON(http.StatusCreated, response)
|
||||
}
|
||||
|
||||
// Login handles the HTTP request for user login
|
||||
// It deserializes the request body into a login request object, validates it,
|
||||
// calls the service to authenticate the user, and returns tokens
|
||||
// Parameters:
|
||||
// - c: Gin context for the HTTP request
|
||||
func (h *AuthHandler) Login(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
logger.Info(ctx, "Start user login")
|
||||
|
||||
var req types.LoginRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.Error(ctx, "Failed to parse login request parameters", err)
|
||||
appErr := errors.NewValidationError("Invalid login parameters").WithDetails(err.Error())
|
||||
c.Error(appErr)
|
||||
return
|
||||
}
|
||||
|
||||
// Validate required fields
|
||||
if req.Email == "" || req.Password == "" {
|
||||
logger.Error(ctx, "Missing required login fields")
|
||||
appErr := errors.NewValidationError("Email and password are required")
|
||||
c.Error(appErr)
|
||||
return
|
||||
}
|
||||
|
||||
// Call service to authenticate user
|
||||
response, err := h.userService.Login(ctx, &req)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to login user: %v", err)
|
||||
appErr := errors.NewUnauthorizedError("Login failed").WithDetails(err.Error())
|
||||
c.Error(appErr)
|
||||
return
|
||||
}
|
||||
|
||||
// Check if login was successful
|
||||
if !response.Success {
|
||||
logger.Warnf(ctx, "Login failed: %s", response.Message)
|
||||
c.JSON(http.StatusUnauthorized, response)
|
||||
return
|
||||
}
|
||||
|
||||
// User is already in the correct format from service
|
||||
|
||||
logger.Infof(ctx, "User logged in successfully: %s", req.Email)
|
||||
c.JSON(http.StatusOK, response)
|
||||
}
|
||||
|
||||
// Logout handles the HTTP request for user logout
|
||||
// It extracts the token from the Authorization header and revokes it
|
||||
// Parameters:
|
||||
// - c: Gin context for the HTTP request
|
||||
func (h *AuthHandler) Logout(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
logger.Info(ctx, "Start user logout")
|
||||
|
||||
// Extract token from Authorization header
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader == "" {
|
||||
logger.Error(ctx, "Missing Authorization header")
|
||||
appErr := errors.NewValidationError("Authorization header is required")
|
||||
c.Error(appErr)
|
||||
return
|
||||
}
|
||||
|
||||
// Parse Bearer token
|
||||
tokenParts := strings.Split(authHeader, " ")
|
||||
if len(tokenParts) != 2 || tokenParts[0] != "Bearer" {
|
||||
logger.Error(ctx, "Invalid Authorization header format")
|
||||
appErr := errors.NewValidationError("Invalid Authorization header format")
|
||||
c.Error(appErr)
|
||||
return
|
||||
}
|
||||
|
||||
token := tokenParts[1]
|
||||
|
||||
// Revoke token
|
||||
err := h.userService.RevokeToken(ctx, token)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to revoke token: %v", err)
|
||||
appErr := errors.NewInternalServerError("Logout failed").WithDetails(err.Error())
|
||||
c.Error(appErr)
|
||||
return
|
||||
}
|
||||
|
||||
logger.Info(ctx, "User logged out successfully")
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": "Logout successful",
|
||||
})
|
||||
}
|
||||
|
||||
// RefreshToken handles the HTTP request for refreshing access tokens
|
||||
// It extracts the refresh token from the request body and generates new tokens
|
||||
// Parameters:
|
||||
// - c: Gin context for the HTTP request
|
||||
func (h *AuthHandler) RefreshToken(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
logger.Info(ctx, "Start token refresh")
|
||||
|
||||
var req struct {
|
||||
RefreshToken string `json:"refreshToken" binding:"required"`
|
||||
}
|
||||
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.Error(ctx, "Failed to parse refresh token request", err)
|
||||
appErr := errors.NewValidationError("Invalid refresh token request").WithDetails(err.Error())
|
||||
c.Error(appErr)
|
||||
return
|
||||
}
|
||||
|
||||
// Call service to refresh token
|
||||
accessToken, newRefreshToken, err := h.userService.RefreshToken(ctx, req.RefreshToken)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to refresh token: %v", err)
|
||||
appErr := errors.NewUnauthorizedError("Token refresh failed").WithDetails(err.Error())
|
||||
c.Error(appErr)
|
||||
return
|
||||
}
|
||||
|
||||
logger.Info(ctx, "Token refreshed successfully")
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": "Token refreshed successfully",
|
||||
"access_token": accessToken,
|
||||
"refresh_token": newRefreshToken,
|
||||
})
|
||||
}
|
||||
|
||||
// GetCurrentUser handles the HTTP request for getting current user information
|
||||
// It extracts the user from the context (set by auth middleware) and returns user info
|
||||
// Parameters:
|
||||
// - c: Gin context for the HTTP request
|
||||
func (h *AuthHandler) GetCurrentUser(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
logger.Info(ctx, "Get current user info")
|
||||
|
||||
// Get current user from service (which extracts from context)
|
||||
user, err := h.userService.GetCurrentUser(ctx)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to get current user: %v", err)
|
||||
appErr := errors.NewUnauthorizedError("Failed to get user information").WithDetails(err.Error())
|
||||
c.Error(appErr)
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Retrieved current user info: %s", user.Email)
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"user": user.ToUserInfo(),
|
||||
})
|
||||
}
|
||||
|
||||
// ChangePassword handles the HTTP request for changing user password
|
||||
// It extracts the current user and validates the old password before setting new one
|
||||
// Parameters:
|
||||
// - c: Gin context for the HTTP request
|
||||
func (h *AuthHandler) ChangePassword(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
logger.Info(ctx, "Start password change")
|
||||
|
||||
var req struct {
|
||||
OldPassword string `json:"old_password" binding:"required"`
|
||||
NewPassword string `json:"new_password" binding:"required,min=6"`
|
||||
}
|
||||
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.Error(ctx, "Failed to parse password change request", err)
|
||||
appErr := errors.NewValidationError("Invalid password change request").WithDetails(err.Error())
|
||||
c.Error(appErr)
|
||||
return
|
||||
}
|
||||
|
||||
// Get current user
|
||||
user, err := h.userService.GetCurrentUser(ctx)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to get current user: %v", err)
|
||||
appErr := errors.NewUnauthorizedError("Failed to get user information").WithDetails(err.Error())
|
||||
c.Error(appErr)
|
||||
return
|
||||
}
|
||||
|
||||
// Change password
|
||||
err = h.userService.ChangePassword(ctx, user.ID, req.OldPassword, req.NewPassword)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to change password: %v", err)
|
||||
appErr := errors.NewBadRequestError("Password change failed").WithDetails(err.Error())
|
||||
c.Error(appErr)
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Password changed successfully for user: %s", user.Email)
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": "Password changed successfully",
|
||||
})
|
||||
}
|
||||
|
||||
// ValidateToken handles the HTTP request for validating access tokens
|
||||
// It extracts the token from the Authorization header and validates it
|
||||
// Parameters:
|
||||
// - c: Gin context for the HTTP request
|
||||
func (h *AuthHandler) ValidateToken(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
logger.Info(ctx, "Start token validation")
|
||||
|
||||
// Extract token from Authorization header
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader == "" {
|
||||
logger.Error(ctx, "Missing Authorization header")
|
||||
appErr := errors.NewValidationError("Authorization header is required")
|
||||
c.Error(appErr)
|
||||
return
|
||||
}
|
||||
|
||||
// Parse Bearer token
|
||||
tokenParts := strings.Split(authHeader, " ")
|
||||
if len(tokenParts) != 2 || tokenParts[0] != "Bearer" {
|
||||
logger.Error(ctx, "Invalid Authorization header format")
|
||||
appErr := errors.NewValidationError("Invalid Authorization header format")
|
||||
c.Error(appErr)
|
||||
return
|
||||
}
|
||||
|
||||
token := tokenParts[1]
|
||||
|
||||
// Validate token
|
||||
user, err := h.userService.ValidateToken(ctx, token)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to validate token: %v", err)
|
||||
appErr := errors.NewUnauthorizedError("Token validation failed").WithDetails(err.Error())
|
||||
c.Error(appErr)
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Token validated successfully for user: %s", user.Email)
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": "Token is valid",
|
||||
"user": user.ToUserInfo(),
|
||||
})
|
||||
}
|
||||
@@ -141,8 +141,10 @@ func (h *InitializationHandler) CheckStatus(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
logger.Info(ctx, "Checking system initialization status")
|
||||
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
|
||||
|
||||
// 检查是否存在租户
|
||||
tenant, err := h.tenantService.GetTenantByID(ctx, types.InitDefaultTenantID)
|
||||
tenant, err := h.tenantService.GetTenantByID(ctx, tenantID)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
@@ -165,7 +167,6 @@ func (h *InitializationHandler) CheckStatus(c *gin.Context) {
|
||||
})
|
||||
return
|
||||
}
|
||||
ctx = context.WithValue(ctx, types.TenantIDContextKey, types.InitDefaultTenantID)
|
||||
|
||||
// 检查是否存在模型
|
||||
models, err := h.modelService.ListModels(ctx)
|
||||
@@ -194,6 +195,7 @@ func (h *InitializationHandler) Initialize(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
logger.Info(ctx, "Starting system initialization")
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
|
||||
|
||||
var req InitializationRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
@@ -259,63 +261,16 @@ func (h *InitializationHandler) Initialize(c *gin.Context) {
|
||||
}
|
||||
var err error
|
||||
// 1. 处理租户 - 检查是否存在,不存在则创建
|
||||
tenant, _ := h.tenantService.GetTenantByID(ctx, types.InitDefaultTenantID)
|
||||
tenant, _ := h.tenantService.GetTenantByID(ctx, tenantID)
|
||||
if tenant == nil {
|
||||
logger.Info(ctx, "Tenant not found, creating tenant")
|
||||
// 创建默认租户
|
||||
tenant = &types.Tenant{
|
||||
ID: types.InitDefaultTenantID,
|
||||
Name: "Default Tenant",
|
||||
Description: "System Default Tenant",
|
||||
RetrieverEngines: types.RetrieverEngines{
|
||||
Engines: []types.RetrieverEngineParams{
|
||||
{
|
||||
RetrieverType: types.KeywordsRetrieverType,
|
||||
RetrieverEngineType: types.PostgresRetrieverEngineType,
|
||||
},
|
||||
{
|
||||
RetrieverType: types.VectorRetrieverType,
|
||||
RetrieverEngineType: types.PostgresRetrieverEngineType,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
logger.Info(ctx, "Creating default tenant")
|
||||
tenant, err = h.tenantService.CreateTenant(ctx, tenant)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError("创建租户失败: " + err.Error()))
|
||||
return
|
||||
}
|
||||
} else {
|
||||
logger.Info(ctx, "Tenant exists, updating if needed")
|
||||
// 更新租户信息(如果需要)
|
||||
updated := false
|
||||
if tenant.Name != "Default Tenant" {
|
||||
tenant.Name = "Default Tenant"
|
||||
updated = true
|
||||
}
|
||||
if tenant.Description != "System Default Tenant" {
|
||||
tenant.Description = "System Default Tenant"
|
||||
updated = true
|
||||
}
|
||||
|
||||
if updated {
|
||||
_, err = h.tenantService.UpdateTenant(ctx, tenant)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError("更新租户失败: " + err.Error()))
|
||||
return
|
||||
}
|
||||
logger.Info(ctx, "Tenant updated successfully")
|
||||
}
|
||||
err = errors.NewInternalServerError("Failed to get tenant")
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
// 创建带有租户ID的新上下文
|
||||
newCtx := context.WithValue(ctx, types.TenantIDContextKey, types.InitDefaultTenantID)
|
||||
|
||||
// 2. 处理模型 - 检查现有模型并更新或创建
|
||||
existingModels, err := h.modelService.ListModels(newCtx)
|
||||
existingModels, err := h.modelService.ListModels(ctx)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
// 如果获取失败,继续执行创建流程
|
||||
@@ -420,7 +375,7 @@ func (h *InitializationHandler) Initialize(c *gin.Context) {
|
||||
existingModel.IsDefault = true
|
||||
existingModel.Status = types.ModelStatusActive
|
||||
|
||||
err := h.modelService.UpdateModel(newCtx, existingModel)
|
||||
err := h.modelService.UpdateModel(ctx, existingModel)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"model_name": modelConfig.name,
|
||||
@@ -437,7 +392,7 @@ func (h *InitializationHandler) Initialize(c *gin.Context) {
|
||||
modelConfig.name, modelConfig.modelType,
|
||||
)
|
||||
newModel := &types.Model{
|
||||
TenantID: types.InitDefaultTenantID,
|
||||
TenantID: tenantID,
|
||||
Name: modelConfig.name,
|
||||
Type: modelConfig.modelType,
|
||||
Source: modelConfig.source,
|
||||
@@ -453,7 +408,7 @@ func (h *InitializationHandler) Initialize(c *gin.Context) {
|
||||
Status: types.ModelStatusActive,
|
||||
}
|
||||
|
||||
err := h.modelService.CreateModel(newCtx, newModel)
|
||||
err := h.modelService.CreateModel(ctx, newModel)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"model_name": modelConfig.name,
|
||||
@@ -470,7 +425,7 @@ func (h *InitializationHandler) Initialize(c *gin.Context) {
|
||||
if !req.Multimodal.Enabled {
|
||||
if existingVLM, exists := modelMap[types.ModelTypeVLLM]; exists {
|
||||
logger.Info(ctx, "Deleting VLM model as multimodal is disabled")
|
||||
err := h.modelService.DeleteModel(newCtx, existingVLM.ID)
|
||||
err := h.modelService.DeleteModel(ctx, existingVLM.ID)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"model_id": existingVLM.ID,
|
||||
@@ -485,7 +440,7 @@ func (h *InitializationHandler) Initialize(c *gin.Context) {
|
||||
if !req.Rerank.Enabled {
|
||||
if existingRerank, exists := modelMap[types.ModelTypeRerank]; exists {
|
||||
logger.Info(ctx, "Deleting Rerank model as rerank is disabled")
|
||||
err := h.modelService.DeleteModel(newCtx, existingRerank.ID)
|
||||
err := h.modelService.DeleteModel(ctx, existingRerank.ID)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"model_id": existingRerank.ID,
|
||||
@@ -497,7 +452,7 @@ func (h *InitializationHandler) Initialize(c *gin.Context) {
|
||||
}
|
||||
|
||||
// 3. 处理知识库 - 检查是否存在,不存在则创建,存在则更新
|
||||
kb, err := h.kbService.GetKnowledgeBaseByID(newCtx, types.InitDefaultKnowledgeBaseID)
|
||||
kbs, err := h.kbService.ListKnowledgeBases(ctx)
|
||||
|
||||
// 找到embedding模型ID和LLM模型ID
|
||||
var embeddingModelID, llmModelID, rerankModelID, vlmModelID string
|
||||
@@ -516,14 +471,16 @@ func (h *InitializationHandler) Initialize(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
if kb == nil {
|
||||
var kb *types.KnowledgeBase
|
||||
|
||||
if len(kbs) == 0 {
|
||||
// 创建新知识库
|
||||
logger.Info(ctx, "Creating default knowledge base")
|
||||
kb = &types.KnowledgeBase{
|
||||
ID: types.InitDefaultKnowledgeBaseID,
|
||||
ID: uuid.New().String(),
|
||||
Name: "Default Knowledge Base",
|
||||
Description: "System Default Knowledge Base",
|
||||
TenantID: types.InitDefaultTenantID,
|
||||
TenantID: tenantID,
|
||||
ChunkingConfig: types.ChunkingConfig{
|
||||
ChunkSize: req.DocumentSplitting.ChunkSize,
|
||||
ChunkOverlap: req.DocumentSplitting.ChunkOverlap,
|
||||
@@ -566,7 +523,7 @@ func (h *InitializationHandler) Initialize(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
_, err = h.kbService.CreateKnowledgeBase(newCtx, kb)
|
||||
_, err = h.kbService.CreateKnowledgeBase(ctx, kb)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError("创建知识库失败: " + err.Error()))
|
||||
@@ -575,10 +532,11 @@ func (h *InitializationHandler) Initialize(c *gin.Context) {
|
||||
} else {
|
||||
// 更新现有知识库
|
||||
logger.Info(ctx, "Updating existing knowledge base")
|
||||
kb = kbs[0]
|
||||
|
||||
// 检查是否有文件,如果有文件则不允许修改Embedding模型
|
||||
knowledgeList, err := h.knowledgeService.ListKnowledgeByKnowledgeBaseID(
|
||||
newCtx, types.InitDefaultKnowledgeBaseID,
|
||||
ctx, kb.ID,
|
||||
)
|
||||
hasFiles := err == nil && len(knowledgeList) > 0
|
||||
|
||||
@@ -639,7 +597,7 @@ func (h *InitializationHandler) Initialize(c *gin.Context) {
|
||||
}
|
||||
|
||||
// 更新基本信息和配置
|
||||
err = h.kbRepository.UpdateKnowledgeBase(newCtx, kb)
|
||||
err = h.kbRepository.UpdateKnowledgeBase(ctx, kb)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError("更新知识库配置失败: " + err.Error()))
|
||||
@@ -649,7 +607,7 @@ func (h *InitializationHandler) Initialize(c *gin.Context) {
|
||||
// 如果需要更新模型ID,使用repository直接更新
|
||||
if !hasFiles || kb.SummaryModelID != llmModelID {
|
||||
// 刷新知识库对象以获取最新信息
|
||||
kb, err = h.kbService.GetKnowledgeBaseByID(newCtx, types.InitDefaultKnowledgeBaseID)
|
||||
kb, err = h.kbService.GetKnowledgeBaseByID(ctx, kb.ID)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError("获取更新后的知识库失败: " + err.Error()))
|
||||
@@ -665,7 +623,7 @@ func (h *InitializationHandler) Initialize(c *gin.Context) {
|
||||
}
|
||||
|
||||
// 使用repository直接更新模型ID
|
||||
err = h.kbRepository.UpdateKnowledgeBase(newCtx, kb)
|
||||
err = h.kbRepository.UpdateKnowledgeBase(ctx, kb)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError("更新知识库模型ID失败: " + err.Error()))
|
||||
@@ -1074,11 +1032,8 @@ func (h *InitializationHandler) GetCurrentConfig(c *gin.Context) {
|
||||
|
||||
logger.Info(ctx, "Getting current system configuration")
|
||||
|
||||
// 设置租户上下文
|
||||
newCtx := context.WithValue(ctx, types.TenantIDContextKey, types.InitDefaultTenantID)
|
||||
|
||||
// 获取模型信息
|
||||
models, err := h.modelService.ListModels(newCtx)
|
||||
models, err := h.modelService.ListModels(ctx)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError("获取模型列表失败: " + err.Error()))
|
||||
@@ -1086,16 +1041,24 @@ func (h *InitializationHandler) GetCurrentConfig(c *gin.Context) {
|
||||
}
|
||||
|
||||
// 获取知识库信息
|
||||
kb, err := h.kbService.GetKnowledgeBaseByID(newCtx, types.InitDefaultKnowledgeBaseID)
|
||||
kbs, err := h.kbService.ListKnowledgeBases(ctx)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError("获取知识库信息失败: " + err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
if len(kbs) == 0 {
|
||||
logger.Error(ctx, "No knowledge bases found")
|
||||
c.Error(errors.NewInternalServerError("获取知识库信息失败"))
|
||||
return
|
||||
}
|
||||
|
||||
kb := kbs[0]
|
||||
|
||||
// 检查知识库是否有文件
|
||||
knowledgeList, err := h.knowledgeService.ListPagedKnowledgeByKnowledgeBaseID(newCtx,
|
||||
types.InitDefaultKnowledgeBaseID, &types.Pagination{
|
||||
knowledgeList, err := h.knowledgeService.ListPagedKnowledgeByKnowledgeBaseID(ctx,
|
||||
kb.ID, &types.Pagination{
|
||||
Page: 1,
|
||||
PageSize: 1,
|
||||
})
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/errors"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
@@ -48,7 +49,7 @@ func (h *TestDataHandler) GetTestData(c *gin.Context) {
|
||||
|
||||
logger.Info(ctx, "Start retrieving test data")
|
||||
|
||||
tenantID := uint(types.InitDefaultTenantID)
|
||||
tenantID := c.GetUint(types.TenantIDContextKey.String())
|
||||
logger.Debugf(ctx, "Test tenant ID environment variable: %d", tenantID)
|
||||
|
||||
// Retrieve the test tenant data
|
||||
@@ -60,24 +61,26 @@ func (h *TestDataHandler) GetTestData(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
knowledgeBaseID := types.InitDefaultKnowledgeBaseID
|
||||
logger.Debugf(ctx, "Test knowledge base ID environment variable: %s", knowledgeBaseID)
|
||||
|
||||
// Retrieve the test knowledge base data
|
||||
logger.Infof(ctx, "Retrieving test knowledge base, ID: %s", knowledgeBaseID)
|
||||
knowledgeBase, err := h.kbService.GetKnowledgeBaseByID(ctx, knowledgeBaseID)
|
||||
kbs, err := h.kbService.ListKnowledgeBases(ctx)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
if len(kbs) == 0 {
|
||||
logger.Error(ctx, "No knowledge bases found")
|
||||
c.Error(errors.NewInternalServerError("获取知识库信息失败"))
|
||||
return
|
||||
}
|
||||
|
||||
logger.Info(ctx, "Test data retrieved successfully")
|
||||
// Return the test data in the response
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"data": gin.H{
|
||||
"tenant": tenant,
|
||||
"knowledge_bases": []types.KnowledgeBase{*knowledgeBase},
|
||||
"knowledge_bases": kbs,
|
||||
},
|
||||
"success": true,
|
||||
})
|
||||
|
||||
+85
-48
@@ -16,10 +16,10 @@ import (
|
||||
|
||||
// 无需认证的API列表
|
||||
var noAuthAPI = map[string][]string{
|
||||
"/api/v1/test-data": {"GET"},
|
||||
"/api/v1/tenants": {"POST"},
|
||||
"/api/v1/initialization/*": {"GET", "POST"},
|
||||
"/health": {"GET"},
|
||||
"/health": {"GET"},
|
||||
"/api/v1/auth/register": {"POST"},
|
||||
"/api/v1/auth/login": {"POST"},
|
||||
"/api/v1/auth/refresh": {"POST"},
|
||||
}
|
||||
|
||||
// 检查请求是否在无需认证的API列表中
|
||||
@@ -38,7 +38,7 @@ func isNoAuthAPI(path string, method string) bool {
|
||||
}
|
||||
|
||||
// Auth 认证中间件
|
||||
func Auth(tenantService interfaces.TenantService, cfg *config.Config) gin.HandlerFunc {
|
||||
func Auth(tenantService interfaces.TenantService, userService interfaces.UserService, cfg *config.Config) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
// ignore OPTIONS request
|
||||
if c.Request.Method == "OPTIONS" {
|
||||
@@ -52,53 +52,90 @@ func Auth(tenantService interfaces.TenantService, cfg *config.Config) gin.Handle
|
||||
return
|
||||
}
|
||||
|
||||
// Get API Key from request header
|
||||
// 尝试JWT Token认证
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader != "" && strings.HasPrefix(authHeader, "Bearer ") {
|
||||
token := strings.TrimPrefix(authHeader, "Bearer ")
|
||||
user, err := userService.ValidateToken(c.Request.Context(), token)
|
||||
if err == nil && user != nil {
|
||||
// JWT Token认证成功
|
||||
// 获取租户信息
|
||||
tenant, err := tenantService.GetTenantByID(c.Request.Context(), user.TenantID)
|
||||
if err != nil {
|
||||
log.Printf("Error getting tenant by ID: %v, tenantID: %d, userID: %s", err, user.TenantID, user.ID)
|
||||
c.JSON(http.StatusUnauthorized, gin.H{
|
||||
"error": "Unauthorized: invalid tenant",
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// 存储用户和租户信息到上下文
|
||||
c.Set(types.TenantIDContextKey.String(), user.TenantID)
|
||||
c.Set(types.TenantInfoContextKey.String(), tenant)
|
||||
c.Set("user", user)
|
||||
c.Request = c.Request.WithContext(
|
||||
context.WithValue(
|
||||
context.WithValue(
|
||||
context.WithValue(c.Request.Context(), types.TenantIDContextKey, user.TenantID),
|
||||
types.TenantInfoContextKey, tenant,
|
||||
),
|
||||
"user", user,
|
||||
),
|
||||
)
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 尝试X-API-Key认证(兼容模式)
|
||||
apiKey := c.GetHeader("X-API-Key")
|
||||
if apiKey == "" {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
|
||||
c.Abort()
|
||||
if apiKey != "" {
|
||||
// Get tenant information
|
||||
tenantID, err := tenantService.ExtractTenantIDFromAPIKey(apiKey)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{
|
||||
"error": "Unauthorized: invalid API key format",
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// Verify API key validity (matches the one in database)
|
||||
t, err := tenantService.GetTenantByID(c.Request.Context(), tenantID)
|
||||
if err != nil {
|
||||
log.Printf("Error getting tenant by ID: %v, tenantID: %d, apiKey: %s", err, tenantID, apiKey)
|
||||
c.JSON(http.StatusUnauthorized, gin.H{
|
||||
"error": "Unauthorized: invalid API key",
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
if t == nil || t.APIKey != apiKey {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{
|
||||
"error": "Unauthorized: invalid API key",
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// Store tenant ID in context
|
||||
c.Set(types.TenantIDContextKey.String(), tenantID)
|
||||
c.Set(types.TenantInfoContextKey.String(), t)
|
||||
c.Request = c.Request.WithContext(
|
||||
context.WithValue(
|
||||
context.WithValue(c.Request.Context(), types.TenantIDContextKey, tenantID),
|
||||
types.TenantInfoContextKey, t,
|
||||
),
|
||||
)
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
// Get tenant information
|
||||
tenantID, err := tenantService.ExtractTenantIDFromAPIKey(apiKey)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{
|
||||
"error": "Unauthorized: invalid API key format",
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// Verify API key validity (matches the one in database)
|
||||
t, err := tenantService.GetTenantByID(c.Request.Context(), tenantID)
|
||||
if err != nil {
|
||||
log.Printf("Error getting tenant by ID: %v, tenantID: %d, apiKey: %s", err, tenantID, apiKey)
|
||||
c.JSON(http.StatusUnauthorized, gin.H{
|
||||
"error": "Unauthorized: invalid API key",
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
if t == nil || t.APIKey != apiKey {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{
|
||||
"error": "Unauthorized: invalid API key",
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// Store tenant ID in context
|
||||
c.Set(types.TenantIDContextKey.String(), tenantID)
|
||||
c.Set(types.TenantInfoContextKey.String(), t)
|
||||
c.Request = c.Request.WithContext(
|
||||
context.WithValue(
|
||||
context.WithValue(c.Request.Context(), types.TenantIDContextKey, tenantID),
|
||||
types.TenantInfoContextKey, t,
|
||||
),
|
||||
)
|
||||
c.Next()
|
||||
// 没有提供任何认证信息
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized: missing authentication"})
|
||||
c.Abort()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+49
-23
@@ -18,6 +18,14 @@ type RouterParams struct {
|
||||
dig.In
|
||||
|
||||
Config *config.Config
|
||||
UserService interfaces.UserService
|
||||
KBService interfaces.KnowledgeBaseService
|
||||
KnowledgeService interfaces.KnowledgeService
|
||||
ChunkService interfaces.ChunkService
|
||||
SessionService interfaces.SessionService
|
||||
MessageService interfaces.MessageService
|
||||
ModelService interfaces.ModelService
|
||||
EvaluationService interfaces.EvaluationService
|
||||
KBHandler *handler.KnowledgeBaseHandler
|
||||
KnowledgeHandler *handler.KnowledgeHandler
|
||||
TenantHandler *handler.TenantHandler
|
||||
@@ -28,6 +36,7 @@ type RouterParams struct {
|
||||
TestDataHandler *handler.TestDataHandler
|
||||
ModelHandler *handler.ModelHandler
|
||||
EvaluationHandler *handler.EvaluationHandler
|
||||
AuthHandler *handler.AuthHandler
|
||||
InitializationHandler *handler.InitializationHandler
|
||||
}
|
||||
|
||||
@@ -50,7 +59,7 @@ func NewRouter(params RouterParams) *gin.Engine {
|
||||
r.Use(middleware.Logger())
|
||||
r.Use(middleware.Recovery())
|
||||
r.Use(middleware.ErrorHandler())
|
||||
r.Use(middleware.Auth(params.TenantService, params.Config))
|
||||
r.Use(middleware.Auth(params.TenantService, params.UserService, params.Config))
|
||||
|
||||
// 添加OpenTelemetry追踪中间件
|
||||
r.Use(middleware.TracingMiddleware())
|
||||
@@ -60,31 +69,10 @@ func NewRouter(params RouterParams) *gin.Engine {
|
||||
c.JSON(200, gin.H{"status": "ok"})
|
||||
})
|
||||
|
||||
// 测试数据接口(不需要认证)
|
||||
r.GET("/api/v1/test-data", params.TestDataHandler.GetTestData)
|
||||
|
||||
// 初始化接口(不需要认证)
|
||||
r.GET("/api/v1/initialization/status", params.InitializationHandler.CheckStatus)
|
||||
r.GET("/api/v1/initialization/config", params.InitializationHandler.GetCurrentConfig)
|
||||
r.POST("/api/v1/initialization/initialize", params.InitializationHandler.Initialize)
|
||||
|
||||
// Ollama相关接口(不需要认证)
|
||||
r.GET("/api/v1/initialization/ollama/status", params.InitializationHandler.CheckOllamaStatus)
|
||||
r.GET("/api/v1/initialization/ollama/models", params.InitializationHandler.ListOllamaModels)
|
||||
r.POST("/api/v1/initialization/ollama/models/check", params.InitializationHandler.CheckOllamaModels)
|
||||
r.POST("/api/v1/initialization/ollama/models/download", params.InitializationHandler.DownloadOllamaModel)
|
||||
r.GET("/api/v1/initialization/ollama/download/progress/:taskId", params.InitializationHandler.GetDownloadProgress)
|
||||
r.GET("/api/v1/initialization/ollama/download/tasks", params.InitializationHandler.ListDownloadTasks)
|
||||
|
||||
// 远程API相关接口(不需要认证)
|
||||
r.POST("/api/v1/initialization/remote/check", params.InitializationHandler.CheckRemoteModel)
|
||||
r.POST("/api/v1/initialization/embedding/test", params.InitializationHandler.TestEmbeddingModel)
|
||||
r.POST("/api/v1/initialization/rerank/check", params.InitializationHandler.CheckRerankModel)
|
||||
r.POST("/api/v1/initialization/multimodal/test", params.InitializationHandler.TestMultimodalFunction)
|
||||
|
||||
// 需要认证的API路由
|
||||
v1 := r.Group("/api/v1")
|
||||
{
|
||||
RegisterAuthRoutes(v1, params.AuthHandler)
|
||||
RegisterTenantRoutes(v1, params.TenantHandler)
|
||||
RegisterKnowledgeBaseRoutes(v1, params.KBHandler)
|
||||
RegisterKnowledgeRoutes(v1, params.KnowledgeHandler)
|
||||
@@ -94,6 +82,8 @@ func NewRouter(params RouterParams) *gin.Engine {
|
||||
RegisterMessageRoutes(v1, params.MessageHandler)
|
||||
RegisterModelRoutes(v1, params.ModelHandler)
|
||||
RegisterEvaluationRoutes(v1, params.EvaluationHandler)
|
||||
RegisterInitializationRoutes(v1, params.InitializationHandler)
|
||||
RegisterTestDataRoutes(v1, params.TestDataHandler)
|
||||
}
|
||||
|
||||
return r
|
||||
@@ -247,3 +237,39 @@ func RegisterEvaluationRoutes(r *gin.RouterGroup, handler *handler.EvaluationHan
|
||||
evaluationRoutes.GET("/", handler.GetEvaluationResult)
|
||||
}
|
||||
}
|
||||
|
||||
func RegisterTestDataRoutes(r *gin.RouterGroup, handler *handler.TestDataHandler) {
|
||||
r.GET("/test-data", handler.GetTestData)
|
||||
}
|
||||
|
||||
// RegisterAuthRoutes registers authentication routes
|
||||
func RegisterAuthRoutes(r *gin.RouterGroup, handler *handler.AuthHandler) {
|
||||
r.POST("/auth/register", handler.Register)
|
||||
r.POST("/auth/login", handler.Login)
|
||||
r.POST("/auth/refresh", handler.RefreshToken)
|
||||
r.GET("/auth/validate", handler.ValidateToken)
|
||||
r.POST("/auth/logout", handler.Logout)
|
||||
r.GET("/auth/me", handler.GetCurrentUser)
|
||||
r.POST("/auth/change-password", handler.ChangePassword)
|
||||
}
|
||||
|
||||
func RegisterInitializationRoutes(r *gin.RouterGroup, handler *handler.InitializationHandler) {
|
||||
// 初始化接口
|
||||
r.GET("/initialization/status", handler.CheckStatus)
|
||||
r.GET("/initialization/config", handler.GetCurrentConfig)
|
||||
r.POST("/initialization/initialize", handler.Initialize)
|
||||
|
||||
// Ollama相关接口
|
||||
r.GET("/initialization/ollama/status", handler.CheckOllamaStatus)
|
||||
r.GET("/initialization/ollama/models", handler.ListOllamaModels)
|
||||
r.POST("/initialization/ollama/models/check", handler.CheckOllamaModels)
|
||||
r.POST("/initialization/ollama/models/download", handler.DownloadOllamaModel)
|
||||
r.GET("/initialization/ollama/download/progress/:taskId", handler.GetDownloadProgress)
|
||||
r.GET("/initialization/ollama/download/tasks", handler.ListDownloadTasks)
|
||||
|
||||
// 远程API相关接口
|
||||
r.POST("/initialization/remote/check", handler.CheckRemoteModel)
|
||||
r.POST("/initialization/embedding/test", handler.TestEmbeddingModel)
|
||||
r.POST("/initialization/rerank/check", handler.CheckRerankModel)
|
||||
r.POST("/initialization/multimodal/test", handler.TestMultimodalFunction)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
package interfaces
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// UserService defines the user service interface
|
||||
type UserService interface {
|
||||
// Register creates a new user account
|
||||
Register(ctx context.Context, req *types.RegisterRequest) (*types.User, error)
|
||||
// Login authenticates a user and returns tokens
|
||||
Login(ctx context.Context, req *types.LoginRequest) (*types.LoginResponse, error)
|
||||
// GetUserByID gets a user by ID
|
||||
GetUserByID(ctx context.Context, id string) (*types.User, error)
|
||||
// GetUserByEmail gets a user by email
|
||||
GetUserByEmail(ctx context.Context, email string) (*types.User, error)
|
||||
// GetUserByUsername gets a user by username
|
||||
GetUserByUsername(ctx context.Context, username string) (*types.User, error)
|
||||
// UpdateUser updates user information
|
||||
UpdateUser(ctx context.Context, user *types.User) error
|
||||
// DeleteUser deletes a user
|
||||
DeleteUser(ctx context.Context, id string) error
|
||||
// ChangePassword changes user password
|
||||
ChangePassword(ctx context.Context, userID string, oldPassword, newPassword string) error
|
||||
// ValidatePassword validates user password
|
||||
ValidatePassword(ctx context.Context, userID string, password string) error
|
||||
// GenerateTokens generates access and refresh tokens for user
|
||||
GenerateTokens(ctx context.Context, user *types.User) (accessToken, refreshToken string, err error)
|
||||
// ValidateToken validates an access token
|
||||
ValidateToken(ctx context.Context, token string) (*types.User, error)
|
||||
// RefreshToken refreshes access token using refresh token
|
||||
RefreshToken(ctx context.Context, refreshToken string) (accessToken, newRefreshToken string, err error)
|
||||
// RevokeToken revokes a token
|
||||
RevokeToken(ctx context.Context, token string) error
|
||||
// GetCurrentUser gets current user from context
|
||||
GetCurrentUser(ctx context.Context) (*types.User, error)
|
||||
}
|
||||
|
||||
// UserRepository defines the user repository interface
|
||||
type UserRepository interface {
|
||||
// CreateUser creates a user
|
||||
CreateUser(ctx context.Context, user *types.User) error
|
||||
// GetUserByID gets a user by ID
|
||||
GetUserByID(ctx context.Context, id string) (*types.User, error)
|
||||
// GetUserByEmail gets a user by email
|
||||
GetUserByEmail(ctx context.Context, email string) (*types.User, error)
|
||||
// GetUserByUsername gets a user by username
|
||||
GetUserByUsername(ctx context.Context, username string) (*types.User, error)
|
||||
// UpdateUser updates a user
|
||||
UpdateUser(ctx context.Context, user *types.User) error
|
||||
// DeleteUser deletes a user
|
||||
DeleteUser(ctx context.Context, id string) error
|
||||
// ListUsers lists users with pagination
|
||||
ListUsers(ctx context.Context, offset, limit int) ([]*types.User, error)
|
||||
}
|
||||
|
||||
// AuthTokenRepository defines the auth token repository interface
|
||||
type AuthTokenRepository interface {
|
||||
// CreateToken creates an auth token
|
||||
CreateToken(ctx context.Context, token *types.AuthToken) error
|
||||
// GetTokenByValue gets a token by its value
|
||||
GetTokenByValue(ctx context.Context, tokenValue string) (*types.AuthToken, error)
|
||||
// GetTokensByUserID gets all tokens for a user
|
||||
GetTokensByUserID(ctx context.Context, userID string) ([]*types.AuthToken, error)
|
||||
// UpdateToken updates a token
|
||||
UpdateToken(ctx context.Context, token *types.AuthToken) error
|
||||
// DeleteToken deletes a token
|
||||
DeleteToken(ctx context.Context, id string) error
|
||||
// DeleteExpiredTokens deletes all expired tokens
|
||||
DeleteExpiredTokens(ctx context.Context) error
|
||||
// RevokeTokensByUserID revokes all tokens for a user
|
||||
RevokeTokensByUserID(ctx context.Context, userID string) error
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// User represents a user in the system
|
||||
type User struct {
|
||||
// Unique identifier of the user
|
||||
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
|
||||
// Username of the user
|
||||
Username string `json:"username" gorm:"type:varchar(100);uniqueIndex;not null"`
|
||||
// Email address of the user
|
||||
Email string `json:"email" gorm:"type:varchar(255);uniqueIndex;not null"`
|
||||
// Hashed password of the user
|
||||
PasswordHash string `json:"-" gorm:"type:varchar(255);not null"`
|
||||
// Avatar URL of the user
|
||||
Avatar string `json:"avatar" gorm:"type:varchar(500)"`
|
||||
// Tenant ID that the user belongs to
|
||||
TenantID uint `json:"tenant_id" gorm:"index"`
|
||||
// Whether the user is active
|
||||
IsActive bool `json:"is_active" gorm:"default:true"`
|
||||
// Creation time of the user
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
// Last updated time of the user
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
// Deletion time of the user
|
||||
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`
|
||||
|
||||
// Association relationship, not stored in the database
|
||||
Tenant *Tenant `json:"tenant,omitempty" gorm:"foreignKey:TenantID"`
|
||||
}
|
||||
|
||||
// AuthToken represents an authentication token
|
||||
type AuthToken struct {
|
||||
// Unique identifier of the token
|
||||
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
|
||||
// User ID that owns this token
|
||||
UserID string `json:"user_id" gorm:"type:varchar(36);index;not null"`
|
||||
// Token value (JWT or other format)
|
||||
Token string `json:"token" gorm:"type:text;not null"`
|
||||
// Token type (access_token, refresh_token)
|
||||
TokenType string `json:"token_type" gorm:"type:varchar(50);not null"`
|
||||
// Token expiration time
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
// Whether the token is revoked
|
||||
IsRevoked bool `json:"is_revoked" gorm:"default:false"`
|
||||
// Creation time of the token
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
// Last updated time of the token
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
|
||||
// Association relationship
|
||||
User *User `json:"user,omitempty" gorm:"foreignKey:UserID"`
|
||||
}
|
||||
|
||||
// LoginRequest represents a login request
|
||||
type LoginRequest struct {
|
||||
Email string `json:"email" binding:"required,email"`
|
||||
Password string `json:"password" binding:"required,min=6"`
|
||||
}
|
||||
|
||||
// RegisterRequest represents a registration request
|
||||
type RegisterRequest struct {
|
||||
Username string `json:"username" binding:"required,min=3,max=50"`
|
||||
Email string `json:"email" binding:"required,email"`
|
||||
Password string `json:"password" binding:"required,min=6"`
|
||||
}
|
||||
|
||||
// LoginResponse represents a login response
|
||||
type LoginResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Message string `json:"message,omitempty"`
|
||||
User *User `json:"user,omitempty"`
|
||||
Tenant *Tenant `json:"tenant,omitempty"`
|
||||
Token string `json:"token,omitempty"`
|
||||
RefreshToken string `json:"refresh_token,omitempty"`
|
||||
}
|
||||
|
||||
// RegisterResponse represents a registration response
|
||||
type RegisterResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Message string `json:"message,omitempty"`
|
||||
User *User `json:"user,omitempty"`
|
||||
Tenant *Tenant `json:"tenant,omitempty"`
|
||||
}
|
||||
|
||||
// UserInfo represents user information for API responses
|
||||
type UserInfo struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
Email string `json:"email"`
|
||||
Avatar string `json:"avatar"`
|
||||
TenantID uint `json:"tenant_id"`
|
||||
IsActive bool `json:"is_active"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// ToUserInfo converts User to UserInfo (without sensitive data)
|
||||
func (u *User) ToUserInfo() *UserInfo {
|
||||
return &UserInfo{
|
||||
ID: u.ID,
|
||||
Username: u.Username,
|
||||
Email: u.Email,
|
||||
Avatar: u.Avatar,
|
||||
TenantID: u.TenantID,
|
||||
IsActive: u.IsActive,
|
||||
CreatedAt: u.CreatedAt,
|
||||
UpdatedAt: u.UpdatedAt,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user