feat: authorization

This commit is contained in:
moolcoov
2025-03-01 20:24:23 +03:00
parent f74b8df791
commit 535b0c39dc
22 changed files with 560 additions and 108 deletions
+23
View File
@@ -0,0 +1,23 @@
import { authFetch } from ".";
interface AuthResponse {
token: string;
}
export const signup = async (body: {
email: string;
username: string;
password: string;
}) => {
return await authFetch<AuthResponse>("/sign-up", {
method: "POST",
body,
});
};
export const login = async (body: { email: string; password: string }) => {
return await authFetch<AuthResponse>("/sign-in", {
method: "POST",
body,
});
};
+38
View File
@@ -0,0 +1,38 @@
import { ofetch } from "ofetch";
import { getToken, removeToken } from "../token";
const BASE_URL = import.meta.env.VITE_API_ENDPOINT;
export class ApiError extends Error {
response: Response;
status: number;
constructor(response: Response) {
super(response.statusText);
this.response = response;
this.status = response.status;
}
}
export const authFetch = ofetch.create({
baseURL: BASE_URL,
async onResponseError({ response }) {
throw new ApiError(response);
},
});
export const apiFetch = ofetch.create({
baseURL: BASE_URL,
headers: {
Authorization: "Bearer " + getToken(),
},
async onResponseError({ response }) {
if (response.status === 401) {
removeToken();
window.location.href = "/login";
return;
}
throw new ApiError(response);
},
});
+6
View File
@@ -0,0 +1,6 @@
import { apiFetch } from ".";
import { User } from "../types/user";
export const getCurrentUser = async () => {
return await apiFetch<User>("/me");
};
@@ -0,0 +1,23 @@
import { create } from "zustand";
import { User } from "../types/user";
import { getCurrentUser } from "../api/user";
interface UserState {
user: User | null;
loading: boolean;
fetchUser: () => Promise<void>;
}
const useUserStore = create<UserState>((set) => ({
user: null,
loading: true,
fetchUser: async () => {
set({ loading: true });
const user = await getCurrentUser();
set({ user, loading: false });
},
}));
export { useUserStore };
+17
View File
@@ -0,0 +1,17 @@
import Cookie from "js-cookie";
export const getToken = () => {
return Cookie.get("token");
};
export const saveToken = (token: string) => {
Cookie.set("token", token, {
secure: true,
sameSite: "Strict",
expires: 30,
});
};
export const removeToken = () => {
Cookie.remove("token");
};
@@ -0,0 +1,5 @@
export interface User {
id: string;
email: string;
username: string;
}