generated from fahricansecer/boilerplate-fe
Some checks failed
UI Deploy (Next-Auth Support) 🎨 / build-and-deploy (push) Has been cancelled
92 lines
2.0 KiB
TypeScript
92 lines
2.0 KiB
TypeScript
/**
|
||
* Auth Service — NextAuth CredentialsProvider için server-side auth çağrıları.
|
||
* `apiRequest` yerine doğrudan fetch kullanır (server-side, session gerektirmez).
|
||
*/
|
||
|
||
const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000/api';
|
||
|
||
interface LoginDto {
|
||
email: string;
|
||
password: string;
|
||
}
|
||
|
||
interface AuthUser {
|
||
id: string;
|
||
email: string;
|
||
firstName?: string;
|
||
lastName?: string;
|
||
roles?: string[];
|
||
}
|
||
|
||
interface AuthResponse {
|
||
accessToken: string;
|
||
refreshToken: string;
|
||
expiresIn?: number;
|
||
user: AuthUser;
|
||
}
|
||
|
||
interface ApiResponse<T> {
|
||
success: boolean;
|
||
data: T;
|
||
message?: string;
|
||
statusCode?: number;
|
||
}
|
||
|
||
async function authFetch<T>(url: string, body: unknown): Promise<ApiResponse<T>> {
|
||
try {
|
||
const res = await fetch(`${API_URL}${url}`, {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify(body),
|
||
});
|
||
|
||
const json = await res.json();
|
||
|
||
if (!res.ok) {
|
||
return {
|
||
success: false,
|
||
data: null as unknown as T,
|
||
message: json?.message || 'İstek başarısız',
|
||
statusCode: res.status,
|
||
};
|
||
}
|
||
|
||
return {
|
||
success: true,
|
||
data: json?.data ?? json,
|
||
message: json?.message,
|
||
statusCode: res.status,
|
||
};
|
||
} catch (error: unknown) {
|
||
const message = error instanceof Error ? error.message : 'Bağlantı hatası';
|
||
return {
|
||
success: false,
|
||
data: null as unknown as T,
|
||
message,
|
||
};
|
||
}
|
||
}
|
||
|
||
const login = (data: LoginDto) => {
|
||
return authFetch<AuthResponse>('/auth/login', data);
|
||
};
|
||
|
||
const register = (data: { email: string; password: string; firstName?: string; lastName?: string }) => {
|
||
return authFetch<AuthResponse>('/auth/register', data);
|
||
};
|
||
|
||
const refreshToken = (data: { refreshToken: string }) => {
|
||
return authFetch<AuthResponse>('/auth/refresh', data);
|
||
};
|
||
|
||
const logout = () => {
|
||
return authFetch<null>('/auth/logout', {});
|
||
};
|
||
|
||
export const authService = {
|
||
login,
|
||
register,
|
||
refreshToken,
|
||
logout,
|
||
};
|