init
This commit is contained in:
36
lib/api.ts
Normal file
36
lib/api.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://127.0.0.1:8000';
|
||||
|
||||
const apiRequest = async (endpoint, options = {}) => {
|
||||
const { method = 'GET', body = null, token = null } = options;
|
||||
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
'Accept': 'application/json',
|
||||
};
|
||||
|
||||
if (token) {
|
||||
headers['Authorization'] = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
const config = {
|
||||
method,
|
||||
headers,
|
||||
};
|
||||
|
||||
if (body) {
|
||||
config.body = JSON.stringify(body);
|
||||
}
|
||||
|
||||
const response = await fetch(`${API_URL}${endpoint}`, config);
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({ detail: 'An unknown error occurred' }));
|
||||
throw new Error(errorData.detail || `HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
if (response.headers.get("content-type")?.includes("application/json")) {
|
||||
return response.json();
|
||||
}
|
||||
|
||||
return response; // For non-json responses like video streams
|
||||
};
|
||||
45
lib/auth.tsx
Normal file
45
lib/auth.tsx
Normal file
@@ -0,0 +1,45 @@
|
||||
import React, { createContext, useContext, useState, useEffect } from 'react';
|
||||
|
||||
const AuthContext = createContext(null);
|
||||
|
||||
export const AuthProvider = ({ children }) => {
|
||||
const [token, setToken] = useState(null);
|
||||
const [user, setUser] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
const storedToken = localStorage.getItem('authToken');
|
||||
const storedUser = localStorage.getItem('authUser');
|
||||
if (storedToken && storedUser) {
|
||||
setToken(storedToken);
|
||||
setUser(JSON.parse(storedUser));
|
||||
}
|
||||
setLoading(false);
|
||||
}, []);
|
||||
|
||||
const login = (newToken, newUser) => {
|
||||
setToken(newToken);
|
||||
setUser(newUser);
|
||||
localStorage.setItem('authToken', newToken);
|
||||
localStorage.setItem('authUser', JSON.stringify(newUser));
|
||||
};
|
||||
|
||||
const logout = () => {
|
||||
setToken(null);
|
||||
setUser(null);
|
||||
localStorage.removeItem('authToken');
|
||||
localStorage.removeItem('authUser');
|
||||
};
|
||||
|
||||
const value = { token, user, login, logout, isAuthenticated: !!token };
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={value}>
|
||||
{!loading && children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export const useAuth = () => {
|
||||
return useContext(AuthContext);
|
||||
};
|
||||
Reference in New Issue
Block a user