Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[#171] Protect route on client side #259

Merged
merged 1 commit into from
Mar 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 27 additions & 8 deletions ui/src/context/auth/auth-context.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
'use client';

import { usePathname } from 'next/navigation';
import { createContext, useContext, useEffect, useState, type ReactNode } from 'react';

import { fetchSignOut, getUserSelf, linkToSignIn } from '@/lib/apis/auth/client';
import { User } from '@/lib/definitions/auth';
import { ReactNode, createContext, useContext, useEffect, useState } from 'react';
import { protectedPaths } from '@/lib/constants/auth';
import type { User } from '@/lib/definitions/auth';

interface ContextShape {
user?: User;
Expand All @@ -15,23 +18,39 @@ const AuthContext = createContext<ContextShape | null>(null);
export function AuthProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<User>();

const handleGetUserSelf = async () => {
const user = await getUserSelf();
setUser(user);
};

useEffect(() => {
// why void?
// we don't handle getUserSelf error
// becuase failure to getUserSelf is just considered
// to be signed out.
void getUserSelf().then(setUser);
void handleGetUserSelf();
}, []);

const signOut = async () => {
await fetchSignOut();
void getUserSelf().then(setUser);
await handleGetUserSelf();
};

const signIn = () => {
linkToSignIn();
};

const pathname = usePathname();
useEffect(() => {
const protect = async () => {
const isLoggedIn = !!(await getUserSelf());
if (!isLoggedIn) {
// TODO: redirect to the sign-in page
signIn();
}
};

if (protectedPaths.includes(pathname)) {
void protect();
}
}, [pathname, user]);

return <AuthContext.Provider value={{ user, signOut, signIn }}>{children}</AuthContext.Provider>;
}

Expand Down
1 change: 1 addition & 0 deletions ui/src/lib/constants/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const protectedPaths = ['/review/write'];