summaryrefslogtreecommitdiff
path: root/react/08-auth-with-context/src/contexts/AuthContext.jsx
blob: 9ac16b15c1ad5180e8047ce5706aa580f692b292 (plain)
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
import { createContext, useState, useEffect, use } from 'react';

// 1. Initialize Context
const AuthContext = createContext(null);

// 2. Create a Custom Provider Component
export function AuthProvider({ children }) {
    const [user, setUser] = useState(null);

    useEffect(() => {
        // Fetch user data from your backend API
        const fetchUser = async () => {
            const response = await fetch('/bff/api/security/user');
            const data = await response.json();
            setUser(data); // Data format: { username: "john", name: "John", roles: ["ADMIN", "MANAGER"] }
        };
        fetchUser();
    }, []);

    const login = () => {
        // TODO: Start single sign-on process (say using OAuth2, OpenID)

        // For testing
        setUser({ username: "john", name: "John", roles: ["ADMIN", "MANAGER"] })
    }

    const logout = async () => {
        const logoutUser = async () => {
            const response = await fetch('/bff/logout');
            const data = await response.json();
            setUser(null);
            // TODO: Send user to somewhere
        };
        logoutUser();

        // For testing
        setUser(null);
    };

    const isLoggedIn = () => {
        if (user) {
            return true;
        }

        return false;
    };

    const isAdmin = () => {
        return isInRole("ADMIN");
    }

    const isInRole = (role) => {
        if (user && role && user.roles) {
            return user.roles.includes(role);
        }

        return false;
    };

    const isInRoles = (roles) => {
        if (user && roles && user.roles) {
            return roles.some(value => user.roles.includes(value));
        }

        return false;
    }

    // Provide the state and the modifier function as a value object
    return (
        <AuthContext value={{ user, login, logout, isLoggedIn, isAdmin, isInRole, isInRoles }}>
            {children}
        </AuthContext>
    );
}

// 3. Create a clean Custom Hook to consume this specific context
export function useAuth() {
    const context = use(AuthContext);
    if (!context) {
        throw new Error('useAuth must be used within an AuthProvider');
    }
    return context;
}