feat: import Sea vHost single-server testing release
This commit is contained in:
commit
248badd33e
441 files changed
+63221
No files matched your search
@@ -0,0 +1,148 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"sea-vhost/internal/auth"
|
||||
"sea-vhost/internal/store"
|
||||
)
|
||||
|
||||
func (s *Server) login(w http.ResponseWriter, r *http.Request) {
|
||||
started := time.Now()
|
||||
var input struct {
|
||||
Identifier string `json:"identifier"`
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
TOTPCode string `json:"totpCode"`
|
||||
}
|
||||
if err := decodeJSON(r, &input); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "请求格式错误")
|
||||
return
|
||||
}
|
||||
identifier := strings.TrimSpace(input.Identifier)
|
||||
if identifier == "" {
|
||||
identifier = strings.TrimSpace(input.Email)
|
||||
}
|
||||
identifier = strings.ToLower(identifier)
|
||||
clientIP := requestClientIP(r)
|
||||
ipKey := "ip:" + clientIP
|
||||
now := time.Now()
|
||||
if allowed, retryAfter := s.loginLimiter.allow(ipKey, now, loginIPBurst); !allowed {
|
||||
writeLoginRateLimit(w, retryAfter)
|
||||
return
|
||||
}
|
||||
validInput := len(identifier) >= 3 && len(identifier) <= 254 && len(input.Password) >= 1 && len(input.Password) <= 128
|
||||
identifierKey := ""
|
||||
if validInput {
|
||||
digest := sha256.Sum256([]byte(identifier))
|
||||
identifierKey = "identifier:" + clientIP + ":" + fmt.Sprintf("%x", digest[:12])
|
||||
if allowed, retryAfter := s.loginLimiter.allow(identifierKey, now, loginIdentifierBurst); !allowed {
|
||||
writeLoginRateLimit(w, retryAfter)
|
||||
return
|
||||
}
|
||||
}
|
||||
user, err := s.store.UserByLogin(r.Context(), identifier)
|
||||
validPassword := validInput && err == nil && auth.VerifyPasswordConstantWork(user.PasswordHash, input.Password)
|
||||
if err != nil || !validInput {
|
||||
validPassword = auth.VerifyPasswordConstantWork("", input.Password) && validPassword
|
||||
}
|
||||
if !validPassword {
|
||||
s.auditLoginFailure(r, user, identifier, "invalid_credentials")
|
||||
minimumLoginDelay(started)
|
||||
writeError(w, http.StatusUnauthorized, "账号、主机名或密码不正确")
|
||||
return
|
||||
}
|
||||
if !oidcPasswordAllowed(s.readServiceConfig(r, "oidc_config"), user.Role) {
|
||||
s.auditLoginFailure(r, user, identifier, "password_login_disabled")
|
||||
minimumLoginDelay(started)
|
||||
writeCodedError(w, 403, "password_login_disabled", "该类账号已关闭密码登录,请使用 SSO 登录")
|
||||
return
|
||||
}
|
||||
if user.MFAEnabled {
|
||||
security, securityErr := s.store.UserSecurity(r.Context(), user.ID)
|
||||
if securityErr != nil {
|
||||
writeError(w, http.StatusInternalServerError, "无法验证双重认证")
|
||||
return
|
||||
}
|
||||
secret, openErr := s.secretBox.Open(mfaSecretLabel(user.ID), security.TOTPSecretCiphertext)
|
||||
validSecondFactor := openErr == nil && auth.VerifyTOTP(secret, input.TOTPCode, time.Now())
|
||||
if !validSecondFactor && strings.TrimSpace(input.TOTPCode) != "" {
|
||||
validSecondFactor, securityErr = s.store.ConsumeRecoveryCode(r.Context(), user.ID, auth.RecoveryCodeHash(input.TOTPCode))
|
||||
}
|
||||
if securityErr != nil {
|
||||
writeError(w, http.StatusInternalServerError, "无法验证双重认证")
|
||||
return
|
||||
}
|
||||
if !validSecondFactor {
|
||||
s.auditLoginFailure(r, user, identifier, "mfa_required")
|
||||
minimumLoginDelay(started)
|
||||
writeCodedError(w, http.StatusUnauthorized, "mfa_required", "请输入动态验证码或恢复码")
|
||||
return
|
||||
}
|
||||
}
|
||||
if err = s.issueSession(w, r, user); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "无法创建会话")
|
||||
return
|
||||
}
|
||||
s.clearImpersonation(w)
|
||||
s.loginLimiter.reset(ipKey, identifierKey)
|
||||
s.store.Log(r.Context(), user.TenantID, user.ID, "login", "session", "", clientIP, true, "登录 Sea vHost")
|
||||
writeJSON(w, http.StatusOK, map[string]any{"user": user})
|
||||
}
|
||||
|
||||
func (s *Server) issueSession(w http.ResponseWriter, r *http.Request, user store.User) error {
|
||||
token, err := auth.NewSessionToken(s.cfg.SessionSecret)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
expires := time.Now().Add(s.cfg.SessionTTL)
|
||||
if err = s.store.CreateSession(r.Context(), user.ID, token, expires); err != nil {
|
||||
return err
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{Name: "sea_session", Value: token, Path: "/", HttpOnly: true, Secure: s.cfg.CookieSecure, SameSite: http.SameSiteStrictMode, Expires: expires, MaxAge: int(s.cfg.SessionTTL.Seconds())})
|
||||
return nil
|
||||
}
|
||||
|
||||
func minimumLoginDelay(started time.Time) {
|
||||
if remaining := 350*time.Millisecond - time.Since(started); remaining > 0 {
|
||||
time.Sleep(remaining)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) auditLoginFailure(r *http.Request, user store.User, identifier, reason string) {
|
||||
digest := sha256.Sum256([]byte(strings.ToLower(strings.TrimSpace(identifier))))
|
||||
resourceID := fmt.Sprintf("%x", digest[:12])
|
||||
var userID *uint64
|
||||
if user.ID != 0 {
|
||||
userID = &user.ID
|
||||
}
|
||||
s.store.LogEvent(r.Context(), user.TenantID, userID, "login", "session", resourceID, requestClientIP(r), false, reason)
|
||||
}
|
||||
|
||||
func writeLoginRateLimit(w http.ResponseWriter, retryAfter time.Duration) {
|
||||
seconds := (retryAfter + time.Second - 1) / time.Second
|
||||
if seconds < 1 {
|
||||
seconds = 1
|
||||
}
|
||||
w.Header().Set("Retry-After", strconv.FormatInt(int64(seconds), 10))
|
||||
writeError(w, http.StatusTooManyRequests, "登录尝试过于频繁,请稍后再试")
|
||||
}
|
||||
|
||||
func (s *Server) logout(w http.ResponseWriter, r *http.Request) {
|
||||
user := currentUser(r)
|
||||
s.store.Log(r.Context(), user.TenantID, user.ID, "logout", "session", "", requestClientIP(r), true, "退出 Sea vHost")
|
||||
if cookie, err := r.Cookie("sea_session"); err == nil {
|
||||
_ = s.store.DeleteSession(r.Context(), cookie.Value)
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{Name: "sea_session", Value: "", Path: "/", HttpOnly: true, Secure: s.cfg.CookieSecure, SameSite: http.SameSiteStrictMode, MaxAge: -1})
|
||||
s.clearImpersonation(w)
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
func (s *Server) me(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"user": currentUser(r)})
|
||||
}
|
||||
Reference in new issue
Block a user