admin/services/auth.ts
alisaza e1eaf5eff5 feat: initial ghabilee-admin backoffice app
Extract admin dashboard from ghabilee-frontend2 into a dedicated Next.js
app for backoffice.ghabilee.ir (no SEO indexing / Clarity).
2026-09-05 13:12:59 +03:30

102 lines
2.8 KiB
TypeScript

import type { AuthTokensDto, OtpRequestResponseDto } from '@/api/generated/models'
import { texts } from '@/texts'
import {
createServiceError,
errorResult,
handleServiceError,
type ServiceCallOptions,
type ServiceResult,
shouldBubbleErrorToParent,
successResult,
} from '@/services/errorHandler'
import { unwrapApiData } from '@/services/apiResponse'
import { getAuth } from '@/api/generated/auth/auth'
import { convertPersianToEnglish } from '@/helpers'
export type RequestOtpResult = OtpRequestResponseDto
export type AuthTokensResult = AuthTokensDto
const authApi = getAuth()
/** Request OTP — POST /auth/request-otp */
export const REQUEST_OTP = async (data: { mobile: string }, options?: ServiceCallOptions): Promise<ServiceResult<RequestOtpResult>> => {
try {
const res = await authApi.authControllerRequestOtp({
mobile: convertPersianToEnglish(data.mobile).trim(),
})
const payload = res.data
if (!payload.success) {
throw createServiceError(payload.message || texts.auth.sendOtpFailedFallback)
}
const body = unwrapApiData(payload)
if (!body?.purpose || body.expiresIn == null) {
throw createServiceError(texts.common.invalidServerResponse)
}
return successResult(body)
} catch (error) {
const normalizedError = handleServiceError(error, options)
if (shouldBubbleErrorToParent(options)) {
throw normalizedError
}
return errorResult(normalizedError)
}
}
/** Verify OTP — POST /auth/verify-otp */
export const VERIFY_OTP = async (
data: { mobile: string; code: string; termsAccepted?: boolean },
options?: ServiceCallOptions
): Promise<ServiceResult<AuthTokensResult>> => {
try {
const body = {
mobile: convertPersianToEnglish(data.mobile).trim(),
code: convertPersianToEnglish(data.code).trim(),
termsAccepted: data.termsAccepted,
}
const res = await authApi.authControllerVerifyOtp(body)
const payload = res.data
if (!payload.success) {
throw createServiceError(payload.message || texts.auth.otpInvalidFallback)
}
const tokens = unwrapApiData(payload)
if (!tokens?.accessToken || !tokens?.status) {
throw createServiceError(texts.auth.invalidLoginResponse)
}
return successResult(tokens)
} catch (error) {
const normalizedError = handleServiceError(error, options)
if (shouldBubbleErrorToParent(options)) {
throw normalizedError
}
return errorResult(normalizedError)
}
}
export const LOGOUT = async (options?: ServiceCallOptions): Promise<ServiceResult<unknown>> => {
try {
const response = await authApi.authControllerLogout()
return successResult(response.data)
} catch (error) {
const normalizedError = handleServiceError(error, options)
if (shouldBubbleErrorToParent(options)) {
throw normalizedError
}
return errorResult(normalizedError)
}
}