add auth window
This commit is contained in:
54
src/hooks/useAuth.js
Normal file
54
src/hooks/useAuth.js
Normal file
@@ -0,0 +1,54 @@
|
||||
import { useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { API_URL } from "../config/constants";
|
||||
|
||||
export function useAuth() {
|
||||
const navigate = useNavigate();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
const login = async (email, password) => {
|
||||
if (!email || !password) { setError("Введи email и пароль"); return; }
|
||||
setLoading(true); setError("");
|
||||
|
||||
try {
|
||||
const res = await fetch(`${API_URL}/api/auth/login`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ email, password }),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
throw new Error(data.message || "Неверный email или пароль");
|
||||
}
|
||||
|
||||
const { token, user } = await res.json();
|
||||
localStorage.setItem("token", token);
|
||||
localStorage.setItem("user", JSON.stringify(user));
|
||||
navigate("/dashboard");
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const loginGoogle = () => { /* TODO: @react-oauth/google */ };
|
||||
|
||||
const loginYandex = () => {
|
||||
const clientId = process.env.REACT_APP_YANDEX_CLIENT_ID;
|
||||
const redirect = encodeURIComponent(`${window.location.origin}/auth/yandex`);
|
||||
window.location.href =
|
||||
`https://oauth.yandex.ru/authorize?response_type=code&client_id=${clientId}&redirect_uri=${redirect}`;
|
||||
};
|
||||
|
||||
const loginVK = () => {
|
||||
const appId = process.env.REACT_APP_VK_APP_ID;
|
||||
const redirect = encodeURIComponent(`${window.location.origin}/auth/vk`);
|
||||
window.location.href =
|
||||
`https://oauth.vk.com/authorize?client_id=${appId}&redirect_uri=${redirect}&response_type=code&scope=email`;
|
||||
};
|
||||
|
||||
return { login, loginGoogle, loginYandex, loginVK, loading, error };
|
||||
}
|
||||
Reference in New Issue
Block a user