90 lines
2.7 KiB
TypeScript
90 lines
2.7 KiB
TypeScript
import { request, CLIENT_ID } from '@/utils/request'
|
||
import type { LoginResult as AuthLoginResult, RegisterResult } from '@/types/business/auth'
|
||
import type {
|
||
LoginBySmsParams,
|
||
LoginResult,
|
||
ResetPasswordParams,
|
||
User,
|
||
} from '@/types/business/user'
|
||
import { isPhone, isValidPassword } from '@/utils/validate'
|
||
|
||
export const PC_CLIENT_ID = CLIENT_ID
|
||
|
||
export function loginByAccountApi(data: { username: string; password: string }): Promise<AuthLoginResult> {
|
||
return request<AuthLoginResult>({
|
||
url: '/auth/login',
|
||
method: 'post',
|
||
data: {
|
||
username: data.username,
|
||
password: data.password,
|
||
clientId: PC_CLIENT_ID,
|
||
grantType: 'password',
|
||
},
|
||
})
|
||
}
|
||
|
||
export function registerByAccountApi(data: { username: string; password: string }): Promise<RegisterResult> {
|
||
return request<RegisterResult>({
|
||
url: '/auth/register',
|
||
method: 'post',
|
||
data: {
|
||
username: data.username,
|
||
password: data.password,
|
||
userType: 'sys_user',
|
||
clientId: PC_CLIENT_ID,
|
||
grantType: 'password',
|
||
},
|
||
})
|
||
}
|
||
|
||
// TODO(api): 以下为原 mock 逻辑(保留,待后端对应接口就绪后替换)
|
||
|
||
const SIX_DIGIT_CODE = /^\d{6}$/
|
||
|
||
export function sendSmsCode(phone: string): Promise<void> {
|
||
if (!isPhone(phone)) return Promise.reject(new Error('手机号格式不正确'))
|
||
return Promise.resolve()
|
||
}
|
||
|
||
export function loginBySms(params: LoginBySmsParams): Promise<LoginResult> {
|
||
const { phone, code } = params
|
||
if (!isPhone(phone)) return Promise.reject(new Error('手机号格式不正确'))
|
||
if (!SIX_DIGIT_CODE.test(code)) return Promise.reject(new Error('验证码格式不正确,应为6位数字'))
|
||
const user: User = {
|
||
id: 'u1',
|
||
nickname: '王永志',
|
||
avatar: '',
|
||
phone: '186****618',
|
||
email: 'yongzh******4@163.com',
|
||
passwordModifiedAt: '',
|
||
}
|
||
return Promise.resolve({ token: `mock-token-${Date.now()}`, user })
|
||
}
|
||
|
||
function validateAuthForm(
|
||
phone: string,
|
||
code: string,
|
||
password: string,
|
||
confirmPassword: string,
|
||
agree: boolean,
|
||
): string | null {
|
||
if (!isPhone(phone)) return '手机号格式不正确'
|
||
if (!SIX_DIGIT_CODE.test(code)) return '验证码格式不正确,应为6位数字'
|
||
if (!isValidPassword(password)) return '密码长度应为6-20位'
|
||
if (password !== confirmPassword) return '两次输入的密码不一致'
|
||
if (!agree) return '请先阅读并同意《用户协议》和《隐私政策》'
|
||
return null
|
||
}
|
||
|
||
export function resetPassword(params: ResetPasswordParams): Promise<void> {
|
||
const message = validateAuthForm(
|
||
params.phone,
|
||
params.code,
|
||
params.password,
|
||
params.confirmPassword,
|
||
params.agree,
|
||
)
|
||
if (message) return Promise.reject(new Error(message))
|
||
return Promise.resolve()
|
||
}
|