feat: 管理后台登录
Some checks failed
Backend Deploy (Go + Docker) / deploy (push) Successful in 1m4s
Extension Build & Release / build (push) Failing after 46s

This commit is contained in:
zs
2026-03-02 23:54:59 +08:00
parent 4e5147fb13
commit d2b330c0c9
7 changed files with 115 additions and 5 deletions

View File

@@ -0,0 +1,53 @@
package service
import (
"errors"
"os"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/zs/InsightReply/internal/repository"
"golang.org/x/crypto/bcrypt"
)
type AuthService struct {
userRepo *repository.UserRepository
}
func NewAuthService(userRepo *repository.UserRepository) *AuthService {
return &AuthService{userRepo: userRepo}
}
func (s *AuthService) Login(email, password string) (string, error) {
// 1. Fetch user by email
user, err := s.userRepo.GetByEmail(email)
if err != nil {
return "", errors.New("invalid email or password")
}
// 2. Compare password hash
err = bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(password))
if err != nil {
return "", errors.New("invalid email or password")
}
// 3. Generate JWT Token
secret := os.Getenv("JWT_SECRET")
if secret == "" {
secret = "fallback_secret_key_change_in_production"
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"sub": user.ID.String(),
"email": user.Email,
"exp": time.Now().Add(time.Hour * 72).Unix(), // 3 days expiration
"iat": time.Now().Unix(),
})
tokenString, err := token.SignedString([]byte(secret))
if err != nil {
return "", err
}
return tokenString, nil
}