1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
|
'use client';
import React, { createContext, useState, useContext, useEffect } from 'react';
export type User = {
id: number;
username: string;
email: string;
has_password: boolean;
google_id?: string | null;
avatar?: string;
banner_file?: string;
description?: string;
premium?: boolean;
is_banned?: boolean;
is_moderator?: boolean;
token_version?: number;
profile?: {
id: number;
user_id: number;
avatar_file?: string;
banner_file?: string;
description?: string;
publications_count?: number;
collections_count?: number;
subscriptions_count?: number;
followers_count?: number;
following_count?: number;
};
integrations?: {
facebook?: string | null;
pinterest?: string | null;
discord?: string | null;
artstation?: string | null;
x?: string | null; // Twitter/X
behance?: string | null;
instagram?: string | null;
};
};
interface AuthContextType {
user: User | null;
setUser: (user: User | null) => void;
logout: () => void;
}
const AuthContext = createContext<AuthContextType | null>(null);
const API_URL = process.env.NEXT_PUBLIC_API_URL;
export const AuthContextProvider = ({ children }: React.PropsWithChildren) => {
const [user, setUser] = useState<User | null>(null);
useEffect(() => {
const fetchUser = async () => {
try {
const res = await fetch(`${API_URL}/api/me`, {
credentials: 'include',
});
if (!res.ok) {
setUser(null);
return;
}
const data = await res.json();
setUser(data.authenticated ? data.user : null);
} catch (err) {
console.error('Error fetching user:', err);
setUser(null);
}
};
fetchUser();
}, []);
const logout = async () => {
await fetch(`${API_URL}/api/auth/logout`, {
method: 'POST',
credentials: 'include',
});
setUser(null);
};
return (
<AuthContext.Provider value={{ user, setUser, logout }}>
{children}
</AuthContext.Provider>
);
};
export const useAuthContext = () => {
const context = useContext(AuthContext);
if (!context)
throw new Error(
'useAuthContext must be used within AuthContextProvider',
);
return context;
};
export const useUser = () => useAuthContext().user;
export const useLogout = () => useAuthContext().logout;
|