2026-05-02 13:02:38 +08:00

54 lines
2.2 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package auth
import (
"context"
"database/sql"
"hyapp/pkg/appcode"
"hyapp/pkg/xerr"
authdomain "hyapp/services/user-service/internal/domain/auth"
identitystorage "hyapp/services/user-service/internal/storage/mysql/identity"
)
func (r *Repository) SetPassword(ctx context.Context, account authdomain.PasswordAccount) error {
// password_accounts 以 user_id 唯一v1 只允许首次设置密码。
_, err := r.db.ExecContext(ctx, `
INSERT INTO password_accounts (app_code, user_id, password_hash, hash_alg, created_at_ms, updated_at_ms)
VALUES (?, ?, ?, ?, ?, ?)
`, appcode.Normalize(account.AppCode), account.UserID, account.PasswordHash, account.HashAlg, account.CreatedAtMs, account.UpdatedAtMs)
if err != nil {
// 唯一键冲突映射为 PASSWORD_ALREADY_SET。
return mapAuthDuplicateError(err)
}
return nil
}
// FindPasswordByDisplayUserID 通过当前 active display_user_id 查找用户密码身份。
func (r *Repository) FindPasswordByDisplayUserID(ctx context.Context, displayUserID string, nowMs int64) (authdomain.PasswordAccount, error) {
// 密码登录前先按输入短号触发靓号懒过期。
if err := identitystorage.ExpirePrettyByDisplayUserID(ctx, r.db, displayUserID, nowMs, "lazy_password_login"); err != nil {
return authdomain.PasswordAccount{}, err
}
var account authdomain.PasswordAccount
err := r.db.QueryRowContext(ctx, `
SELECT pa.app_code, pa.user_id, u.current_display_user_id, pa.password_hash, pa.hash_alg, pa.created_at_ms, pa.updated_at_ms
FROM users u
INNER JOIN password_accounts pa ON pa.app_code = u.app_code AND pa.user_id = u.user_id
WHERE u.app_code = ? AND u.current_display_user_id = ?
`, appcode.FromContext(ctx), displayUserID).Scan(&account.AppCode, &account.UserID, &account.DisplayUserID, &account.PasswordHash, &account.HashAlg, &account.CreatedAtMs, &account.UpdatedAtMs)
if err == sql.ErrNoRows {
// 短号不存在或未设置密码都返回 not found由 service 统一映射 AUTH_FAILED。
return authdomain.PasswordAccount{}, xerr.New(xerr.NotFound, "password account not found")
}
if err != nil {
return authdomain.PasswordAccount{}, err
}
return account, nil
}
// CreateSession 创建新的 refresh session。