feat: sign in sign up with all views
This commit is contained in:
6
kittyurl-frontend/src/context/AuthContext.tsx
Normal file
6
kittyurl-frontend/src/context/AuthContext.tsx
Normal file
@@ -0,0 +1,6 @@
|
||||
// src/context/AuthContext.ts
|
||||
import { createContext } from 'react';
|
||||
import type { AuthContextType } from '../types/auth';
|
||||
|
||||
// Eksportujemy tylko "pusty" kontekst
|
||||
export const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
||||
60
kittyurl-frontend/src/context/AuthProvider.tsx
Normal file
60
kittyurl-frontend/src/context/AuthProvider.tsx
Normal file
@@ -0,0 +1,60 @@
|
||||
// src/context/AuthProvider.tsx
|
||||
import { useState, useCallback, type ReactNode } from 'react';
|
||||
import { AuthContext } from './AuthContext'; // Importujemy stałą z pliku obok
|
||||
import { sha512 } from '../utils/crypto';
|
||||
import type { AuthResponse } from '../types/auth';
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [token, setToken] = useState<string | null>(sessionStorage.getItem('ktty_token'));
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const authRequest = useCallback(async (endpoint: 'signUp' | 'signIn', name: string, pass: string) => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const hashedPassword = await sha512(pass);
|
||||
const response = await fetch(`/api/v1/user/${endpoint}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'accept': 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ name, password: hashedPassword, ttl: 86400 }),
|
||||
});
|
||||
|
||||
const data: AuthResponse = await response.json();
|
||||
if (!response.ok) throw new Error(data.error || data.message || `Error ${response.status}`);
|
||||
|
||||
if (data.token) {
|
||||
sessionStorage.setItem('ktty_token', data.token);
|
||||
setToken(data.token); // To aktualizuje stan w całej aplikacji natychmiast!
|
||||
}
|
||||
return data;
|
||||
} catch (err: unknown) {
|
||||
setError(err instanceof Error ? err.message : 'Unknown error');
|
||||
return null;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const logout = useCallback(() => {
|
||||
sessionStorage.removeItem('ktty_token');
|
||||
setToken(null);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{
|
||||
isAuthenticated: !!token,
|
||||
token,
|
||||
loading,
|
||||
error,
|
||||
signIn: (n, p) => authRequest('signIn', n, p),
|
||||
signUp: (n, p) => authRequest('signUp', n, p),
|
||||
logout
|
||||
}}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user