refactor: simplify setup flow — eliminate redundant DB calls and login round-trips
- Add AdminExists() to UserRepository (EXISTS query, not full table scan) - SetupInitialAdmin returns tokens directly (skip separate Login call) - Add SetupRequest DTO to auth_dto.go (replace inline struct) - Extract defaultEmail() helper (removes duplicated email logic) - AuthPage uses setup tokens directly (skip redundant apiLogin call) - Use customAxiosInstance for auth API calls (consistent with codebase)
This commit is contained in:
@ -50,6 +50,13 @@ type LoginRequest struct {
|
||||
Password string `json:"password" binding:"required"`
|
||||
}
|
||||
|
||||
// SetupRequest 初始管理员注册请求
|
||||
type SetupRequest struct {
|
||||
Username string `json:"username" binding:"required"`
|
||||
Password string `json:"password" binding:"required"`
|
||||
Email string `json:"email,omitempty"`
|
||||
}
|
||||
|
||||
// RefreshTokenRequest 刷新 Token 请求
|
||||
type RefreshTokenRequest struct {
|
||||
RefreshToken string `json:"refreshToken" binding:"required"`
|
||||
|
||||
@ -265,11 +265,7 @@ func (h *AuthHandler) AuthStatus(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// Setup creates the first admin user. Only works when no admin exists.
|
||||
func (h *AuthHandler) Setup(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
Email string `json:"email"`
|
||||
}
|
||||
var req dto.SetupRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
respondError(w, http.StatusBadRequest, "Invalid request body", err.Error())
|
||||
return
|
||||
@ -279,19 +275,12 @@ func (h *AuthHandler) Setup(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
_, err := h.authService.SetupInitialAdmin(r.Context(), req.Username, req.Password, req.Email)
|
||||
_, accessToken, refreshToken, err := h.authService.SetupInitialAdmin(r.Context(), req.Username, req.Password, req.Email)
|
||||
if err != nil {
|
||||
respondServiceError(w, err, "Failed to create initial admin")
|
||||
return
|
||||
}
|
||||
|
||||
// Generate access token immediately
|
||||
accessToken, refreshToken, _, err := h.authService.Login(r.Context(), req.Username, req.Password)
|
||||
if err != nil {
|
||||
respondServiceError(w, err, "Admin created but login failed")
|
||||
return
|
||||
}
|
||||
|
||||
respondJSON(w, http.StatusCreated, map[string]string{
|
||||
"accessToken": accessToken,
|
||||
"refreshToken": refreshToken,
|
||||
|
||||
Reference in New Issue
Block a user