wire frontend password login

This commit is contained in:
Yisroel Baum 2026-07-31 11:44:19 +03:00
parent 1dff3f6976
commit 3da9c586c3
Signed by: yisroelbaum
GPG key ID: 0FA60884F75520A9
4 changed files with 239 additions and 3 deletions

View file

@ -13,7 +13,27 @@ const meResponseSchema = z.object({
user: authUserSchema,
})
const invalidCredentialsResponseSchema = z.object({
error: z.literal('invalid_credentials'),
})
const loginValidationResponseSchema = z.object({
errors: z.object({
email: z.array(z.string()).optional(),
password: z.array(z.string()).optional(),
}),
})
export type AuthUser = z.infer<typeof authUserSchema>
export type LoginFieldErrors = Partial<Record<'email' | 'password', string>>
export type LoginResult =
| {
success: true
}
| {
success: false
fieldErrors: LoginFieldErrors
}
export const useAuthStore = defineStore('auth', () => {
const user = ref<AuthUser | null>(null)
@ -57,11 +77,90 @@ export const useAuthStore = defineStore('auth', () => {
}
}
async function login(email: string, password: string): Promise<LoginResult> {
loading.value = true
error.value = null
try {
const response = await fetch(`${API_BASE}/api/login`, {
method: 'POST',
credentials: 'include',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({ email, password }),
})
const responseBody: unknown = await response.json()
if (response.status === 200) {
user.value = meResponseSchema.parse(responseBody).user
return { success: true }
}
user.value = null
if (
response.status === 401 &&
invalidCredentialsResponseSchema.safeParse(responseBody).success
) {
error.value = 'Email or password is incorrect.'
return { success: false, fieldErrors: {} }
}
if (response.status === 422) {
const validationResponse = loginValidationResponseSchema.safeParse(responseBody)
if (validationResponse.success) {
return {
success: false,
fieldErrors: firstLoginFieldErrors(validationResponse.data.errors),
}
}
}
if (response.status === 429) {
error.value = 'Too many login attempts. Try again in a minute.'
return { success: false, fieldErrors: {} }
}
error.value = 'Unable to log in. Please try again.'
return { success: false, fieldErrors: {} }
} catch {
user.value = null
error.value = 'Unable to log in. Please try again.'
return { success: false, fieldErrors: {} }
} finally {
loading.value = false
}
}
return {
user,
loading,
error,
isAuthenticated,
fetchMe,
login,
}
})
function firstLoginFieldErrors(
errors: Partial<Record<'email' | 'password', string[]>>,
): LoginFieldErrors {
const fieldErrors: LoginFieldErrors = {}
const emailError = errors.email?.[0]
const passwordError = errors.password?.[0]
if (emailError !== undefined) {
fieldErrors.email = emailError
}
if (passwordError !== undefined) {
fieldErrors.password = passwordError
}
return fieldErrors
}