forked from baron/baron-sso
린트 적용
This commit is contained in:
@@ -8,10 +8,10 @@ import (
|
|||||||
// BrokerUser is the standard user model used within Baron SSO business logic.
|
// BrokerUser is the standard user model used within Baron SSO business logic.
|
||||||
// It defines the canonical set of fields that must be supported by any underlying IDP.
|
// It defines the canonical set of fields that must be supported by any underlying IDP.
|
||||||
type BrokerUser struct {
|
type BrokerUser struct {
|
||||||
ID string `json:"id" required:"true"`
|
ID string `json:"id" required:"true"`
|
||||||
Email string `json:"email" required:"true"`
|
Email string `json:"email" required:"true"`
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
PhoneNumber string `json:"phone_number"`
|
PhoneNumber string `json:"phone_number"`
|
||||||
// Attributes stores custom user attributes.
|
// Attributes stores custom user attributes.
|
||||||
// The "required_keys" tag specifies which keys MUST be present in the IDP's schema support.
|
// The "required_keys" tag specifies which keys MUST be present in the IDP's schema support.
|
||||||
Attributes map[string]interface{} `json:"attributes" required_keys:"grade,department"`
|
Attributes map[string]interface{} `json:"attributes" required_keys:"grade,department"`
|
||||||
|
|||||||
@@ -55,4 +55,4 @@ func (h *AdminHandler) CheckAuth(c *fiber.Ctx) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{"status": "ok"})
|
return c.Status(fiber.StatusOK).JSON(fiber.Map{"status": "ok"})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -35,14 +35,14 @@ const (
|
|||||||
statusSuccess = "success"
|
statusSuccess = "success"
|
||||||
|
|
||||||
// Durations
|
// Durations
|
||||||
defaultExpiration = 5 * time.Minute
|
defaultExpiration = 5 * time.Minute
|
||||||
signupStateExpiration = 10 * time.Minute
|
signupStateExpiration = 10 * time.Minute
|
||||||
signupBlockDuration = 10 * time.Minute
|
signupBlockDuration = 10 * time.Minute
|
||||||
maxSignupFailures = 5
|
maxSignupFailures = 5
|
||||||
emailCodeTTL = 5 * time.Minute
|
emailCodeTTL = 5 * time.Minute
|
||||||
smsCodeTTL = 3 * time.Minute
|
smsCodeTTL = 3 * time.Minute
|
||||||
prefixPwdResetToken = "pwdreset_token:"
|
prefixPwdResetToken = "pwdreset_token:"
|
||||||
pwdResetExpiration = 15 * time.Minute
|
pwdResetExpiration = 15 * time.Minute
|
||||||
)
|
)
|
||||||
|
|
||||||
type AuthHandler struct {
|
type AuthHandler struct {
|
||||||
@@ -125,12 +125,12 @@ func (h *AuthHandler) CheckEmail(c *fiber.Ctx) error {
|
|||||||
// Note: Descope doesn't have a direct "exists" check, we use Load or Search.
|
// Note: Descope doesn't have a direct "exists" check, we use Load or Search.
|
||||||
// Since we are checking availability for signup, we want "User not found".
|
// Since we are checking availability for signup, we want "User not found".
|
||||||
exists, err := h.DescopeClient.Management.User().Load(context.Background(), req.Email)
|
exists, err := h.DescopeClient.Management.User().Load(context.Background(), req.Email)
|
||||||
|
|
||||||
// If err is nil and exists is not nil, user exists.
|
// If err is nil and exists is not nil, user exists.
|
||||||
if err == nil && exists != nil {
|
if err == nil && exists != nil {
|
||||||
return c.JSON(fiber.Map{"available": false, "message": "Email already registered"})
|
return c.JSON(fiber.Map{"available": false, "message": "Email already registered"})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if specific error is "not found" or just assume if Load fails it might be free.
|
// Check if specific error is "not found" or just assume if Load fails it might be free.
|
||||||
// Typically Descope Load returns error if not found? Let's assume so or check error message.
|
// Typically Descope Load returns error if not found? Let's assume so or check error message.
|
||||||
// Actually, strictly speaking, we should handle specific errors, but for MVP:
|
// Actually, strictly speaking, we should handle specific errors, but for MVP:
|
||||||
@@ -146,7 +146,7 @@ func (h *AuthHandler) SendSignupEmailCode(c *fiber.Ctx) error {
|
|||||||
req.Type = "email" // Enforce type
|
req.Type = "email" // Enforce type
|
||||||
|
|
||||||
key := prefixSignupEmail + req.Target
|
key := prefixSignupEmail + req.Target
|
||||||
|
|
||||||
// 1. Check existing state (Rate Limit / Block)
|
// 1. Check existing state (Rate Limit / Block)
|
||||||
state, _ := h.getSignupState(key)
|
state, _ := h.getSignupState(key)
|
||||||
if state != nil && state.FailCount > maxSignupFailures {
|
if state != nil && state.FailCount > maxSignupFailures {
|
||||||
@@ -164,26 +164,26 @@ func (h *AuthHandler) SendSignupEmailCode(c *fiber.Ctx) error {
|
|||||||
newState := &signupState{
|
newState := &signupState{
|
||||||
Code: code,
|
Code: code,
|
||||||
Verified: false,
|
Verified: false,
|
||||||
FailCount: 0, // Reset fail count on new code generation? Or keep it?
|
FailCount: 0, // Reset fail count on new code generation? Or keep it?
|
||||||
// Requirement says "Auth fail > 5 -> block". New code usually resets or continues?
|
// Requirement says "Auth fail > 5 -> block". New code usually resets or continues?
|
||||||
// Usually getting a new code doesn't reset verify failure count if we want strict blocking.
|
// Usually getting a new code doesn't reset verify failure count if we want strict blocking.
|
||||||
// But for simplicity let's say "fail count" applies to verification attempts.
|
// But for simplicity let's say "fail count" applies to verification attempts.
|
||||||
// If we are issuing a new code, it's a new attempt cycle usually.
|
// If we are issuing a new code, it's a new attempt cycle usually.
|
||||||
// However, spamming "send code" is also an attack.
|
// However, spamming "send code" is also an attack.
|
||||||
// Let's keep FailCount if exists, or 0.
|
// Let's keep FailCount if exists, or 0.
|
||||||
ExpiresAt: time.Now().Add(emailCodeTTL).Unix(),
|
ExpiresAt: time.Now().Add(emailCodeTTL).Unix(),
|
||||||
}
|
}
|
||||||
if state != nil {
|
if state != nil {
|
||||||
newState.FailCount = state.FailCount
|
newState.FailCount = state.FailCount
|
||||||
}
|
}
|
||||||
|
|
||||||
h.saveSignupState(key, newState, signupStateExpiration)
|
h.saveSignupState(key, newState, signupStateExpiration)
|
||||||
|
|
||||||
// 4. Send Email
|
// 4. Send Email
|
||||||
if h.EmailService == nil {
|
if h.EmailService == nil {
|
||||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "Email service not configured"})
|
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "Email service not configured"})
|
||||||
}
|
}
|
||||||
|
|
||||||
subject := "[Baron SSO] 회원가입 인증코드"
|
subject := "[Baron SSO] 회원가입 인증코드"
|
||||||
body := fmt.Sprintf(`
|
body := fmt.Sprintf(`
|
||||||
<div style="padding: 20px; font-family: sans-serif;">
|
<div style="padding: 20px; font-family: sans-serif;">
|
||||||
@@ -193,7 +193,7 @@ func (h *AuthHandler) SendSignupEmailCode(c *fiber.Ctx) error {
|
|||||||
<p>이 코드는 5분간 유효합니다.</p>
|
<p>이 코드는 5분간 유효합니다.</p>
|
||||||
</div>
|
</div>
|
||||||
`, code)
|
`, code)
|
||||||
|
|
||||||
go h.EmailService.SendEmail(req.Target, subject, body)
|
go h.EmailService.SendEmail(req.Target, subject, body)
|
||||||
|
|
||||||
return c.JSON(fiber.Map{"message": "Verification code sent"})
|
return c.JSON(fiber.Map{"message": "Verification code sent"})
|
||||||
@@ -312,10 +312,18 @@ func (h *AuthHandler) Signup(c *fiber.Ctx) error {
|
|||||||
}
|
}
|
||||||
// Check complexity (at least 2 types: lower, upper, digit, special)
|
// Check complexity (at least 2 types: lower, upper, digit, special)
|
||||||
types := 0
|
types := 0
|
||||||
if strings.ContainsAny(req.Password, "abcdefghijklmnopqrstuvwxyz") { types++ }
|
if strings.ContainsAny(req.Password, "abcdefghijklmnopqrstuvwxyz") {
|
||||||
if strings.ContainsAny(req.Password, "ABCDEFGHIJKLMNOPQRSTUVWXYZ") { types++ }
|
types++
|
||||||
if strings.ContainsAny(req.Password, "0123456789") { types++ }
|
}
|
||||||
if strings.ContainsAny(req.Password, "!@#$%^&*()_+-=[]{}|;:,.<>?") { types++ }
|
if strings.ContainsAny(req.Password, "ABCDEFGHIJKLMNOPQRSTUVWXYZ") {
|
||||||
|
types++
|
||||||
|
}
|
||||||
|
if strings.ContainsAny(req.Password, "0123456789") {
|
||||||
|
types++
|
||||||
|
}
|
||||||
|
if strings.ContainsAny(req.Password, "!@#$%^&*()_+-=[]{}|;:,.<>?") {
|
||||||
|
types++
|
||||||
|
}
|
||||||
if types < 2 {
|
if types < 2 {
|
||||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "Password must contain at least 2 types of characters (letters, numbers, symbols)"})
|
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "Password must contain at least 2 types of characters (letters, numbers, symbols)"})
|
||||||
}
|
}
|
||||||
@@ -359,14 +367,14 @@ func (h *AuthHandler) Signup(c *fiber.Ctx) error {
|
|||||||
"termsAccepted": req.TermsAccepted,
|
"termsAccepted": req.TermsAccepted,
|
||||||
"createdAt": time.Now().Format(time.RFC3339),
|
"createdAt": time.Now().Format(time.RFC3339),
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create user
|
// Create user
|
||||||
// Note: Descope `Create` does not set password. We usually need `Create` then `Password().Update`
|
// Note: Descope `Create` does not set password. We usually need `Create` then `Password().Update`
|
||||||
// or use a specialized signup flow.
|
// or use a specialized signup flow.
|
||||||
// `Management.User().Create` creates a user but doesn't set a password credential immediately unless specified?
|
// `Management.User().Create` creates a user but doesn't set a password credential immediately unless specified?
|
||||||
// Actually `User().Create` creates the identity.
|
// Actually `User().Create` creates the identity.
|
||||||
// To set password, we use `h.DescopeClient.Management.User().SetPassword(...)`
|
// To set password, we use `h.DescopeClient.Management.User().SetPassword(...)`
|
||||||
|
|
||||||
// Check if user exists (Double check)
|
// Check if user exists (Double check)
|
||||||
exists, _ := h.DescopeClient.Management.User().Load(context.Background(), req.Email)
|
exists, _ := h.DescopeClient.Management.User().Load(context.Background(), req.Email)
|
||||||
if exists != nil {
|
if exists != nil {
|
||||||
@@ -1305,8 +1313,6 @@ func (h *AuthHandler) HandleDescopeEmailRelay(c *fiber.Ctx) error {
|
|||||||
return c.Status(501).JSON(fiber.Map{"error": "Real email sending not implemented"})
|
return c.Status(501).JSON(fiber.Map{"error": "Real email sending not implemented"})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// --- User Profile Handlers ---
|
// --- User Profile Handlers ---
|
||||||
|
|
||||||
func (h *AuthHandler) formatPhoneForDisplay(phone string) string {
|
func (h *AuthHandler) formatPhoneForDisplay(phone string) string {
|
||||||
@@ -1409,7 +1415,7 @@ func (h *AuthHandler) UpdateMe(c *fiber.Ctx) error {
|
|||||||
// Normalize for comparison
|
// Normalize for comparison
|
||||||
normID := strings.ReplaceAll(loginID, "+82", "0")
|
normID := strings.ReplaceAll(loginID, "+82", "0")
|
||||||
normOld := strings.ReplaceAll(oldPhoneStorage, "+82", "0")
|
normOld := strings.ReplaceAll(oldPhoneStorage, "+82", "0")
|
||||||
|
|
||||||
if loginID == oldPhoneStorage || (normOld != "" && normID == normOld) {
|
if loginID == oldPhoneStorage || (normOld != "" && normID == normOld) {
|
||||||
slog.Info("[UpdateMe] Updating LoginID", "old", loginID, "new", newPhoneStorage)
|
slog.Info("[UpdateMe] Updating LoginID", "old", loginID, "new", newPhoneStorage)
|
||||||
_, err = h.DescopeClient.Management.User().UpdateLoginID(c.Context(), loginID, newPhoneStorage)
|
_, err = h.DescopeClient.Management.User().UpdateLoginID(c.Context(), loginID, newPhoneStorage)
|
||||||
@@ -1456,7 +1462,7 @@ func (h *AuthHandler) SendUpdateCode(c *fiber.Ctx) error {
|
|||||||
if token == "" {
|
if token == "" {
|
||||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "Unauthorized"})
|
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "Unauthorized"})
|
||||||
}
|
}
|
||||||
|
|
||||||
authorized, userToken, err := h.DescopeClient.Auth.ValidateSessionWithToken(c.Context(), token)
|
authorized, userToken, err := h.DescopeClient.Auth.ValidateSessionWithToken(c.Context(), token)
|
||||||
if err != nil || !authorized {
|
if err != nil || !authorized {
|
||||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "Invalid session"})
|
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "Invalid session"})
|
||||||
@@ -1471,7 +1477,7 @@ func (h *AuthHandler) SendUpdateCode(c *fiber.Ctx) error {
|
|||||||
|
|
||||||
phone := h.formatPhoneForStorage(req.Phone)
|
phone := h.formatPhoneForStorage(req.Phone)
|
||||||
code := fmt.Sprintf("%06d", rand.Intn(1000000))
|
code := fmt.Sprintf("%06d", rand.Intn(1000000))
|
||||||
|
|
||||||
// Store code in Redis
|
// Store code in Redis
|
||||||
key := "otp_update_phone:" + userToken.ID + ":" + phone
|
key := "otp_update_phone:" + userToken.ID + ":" + phone
|
||||||
h.RedisService.Set(key, code, 5*time.Minute)
|
h.RedisService.Set(key, code, 5*time.Minute)
|
||||||
|
|||||||
@@ -28,8 +28,8 @@ type AuditLogEntry struct {
|
|||||||
LoginIDs map[string]string // loginId and loginId_normalized
|
LoginIDs map[string]string // loginId and loginId_normalized
|
||||||
Token string // For reset tokens, magic link tokens
|
Token string // For reset tokens, magic link tokens
|
||||||
DescopeError string
|
DescopeError string
|
||||||
DescopeStatus int // Descope HTTP status
|
DescopeStatus int // Descope HTTP status
|
||||||
DescopeBody string // Descope response body (full raw)
|
DescopeBody string // Descope response body (full raw)
|
||||||
RefreshToken string
|
RefreshToken string
|
||||||
SessionJwt string
|
SessionJwt string
|
||||||
AccessJwt string
|
AccessJwt string
|
||||||
@@ -68,7 +68,6 @@ func NewAuditLogEntry(c *fiber.Ctx, stage string) *AuditLogEntry {
|
|||||||
headers["Origin"] = c.Get("Origin")
|
headers["Origin"] = c.Get("Origin")
|
||||||
headers["Referer"] = c.Get("Referer")
|
headers["Referer"] = c.Get("Referer")
|
||||||
|
|
||||||
|
|
||||||
return &AuditLogEntry{
|
return &AuditLogEntry{
|
||||||
RequestID: reqID,
|
RequestID: reqID,
|
||||||
Stage: stage,
|
Stage: stage,
|
||||||
@@ -85,7 +84,6 @@ func NewAuditLogEntry(c *fiber.Ctx, stage string) *AuditLogEntry {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Log emits an audit log entry using slog.
|
// Log emits an audit log entry using slog.
|
||||||
// It includes common fields and allows for additional custom fields.
|
// It includes common fields and allows for additional custom fields.
|
||||||
func (ale *AuditLogEntry) Log(level slog.Level, msg string, args ...any) {
|
func (ale *AuditLogEntry) Log(level slog.Level, msg string, args ...any) {
|
||||||
@@ -213,4 +211,4 @@ func (ale *AuditLogEntry) Log(level slog.Level, msg string, args ...any) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
slog.Default().LogAttrs(context.Background(), level, msg, attrs...)
|
slog.Default().LogAttrs(context.Background(), level, msg, attrs...)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -70,28 +70,28 @@ func (d *DescopeProvider) GetMetadata() (*domain.IDPMetadata, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (d *DescopeProvider) InitiatePasswordReset(loginID, redirectUrl string) error {
|
func (d *DescopeProvider) InitiatePasswordReset(loginID, redirectUrl string) error {
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
err := d.Client.Auth.Password().SendPasswordReset(ctx, loginID, redirectUrl, nil)
|
err := d.Client.Auth.Password().SendPasswordReset(ctx, loginID, redirectUrl, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
slog.Error("Descope SendPasswordReset failed (raw)",
|
slog.Error("Descope SendPasswordReset failed (raw)",
|
||||||
"loginID", loginID,
|
"loginID", loginID,
|
||||||
"redirectUrl", redirectUrl,
|
"redirectUrl", redirectUrl,
|
||||||
"err", err,
|
"err", err,
|
||||||
"err_type", fmt.Sprintf("%T", err),
|
"err_type", fmt.Sprintf("%T", err),
|
||||||
)
|
)
|
||||||
|
|
||||||
if de, ok := err.(*descope.Error); ok {
|
if de, ok := err.(*descope.Error); ok {
|
||||||
status := de.Info[descope.ErrorInfoKeys.HTTPResponseStatusCode] // "Status-Code"
|
status := de.Info[descope.ErrorInfoKeys.HTTPResponseStatusCode] // "Status-Code"
|
||||||
slog.Error("Descope error details",
|
slog.Error("Descope error details",
|
||||||
"code", de.Code,
|
"code", de.Code,
|
||||||
"description", de.Description,
|
"description", de.Description,
|
||||||
"message", de.Message,
|
"message", de.Message,
|
||||||
"status_code", status,
|
"status_code", status,
|
||||||
"info", de.Info,
|
"info", de.Info,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *DescopeProvider) VerifyPasswordResetToken(token string) (*domain.AuthInfo, error) {
|
func (d *DescopeProvider) VerifyPasswordResetToken(token string) (*domain.AuthInfo, error) {
|
||||||
|
|||||||
Reference in New Issue
Block a user