Skip to content

Commit

Permalink
[fix] fixes routing bugs (#83)
Browse files Browse the repository at this point in the history
* fix: corrects CONFIG.lca path

* fix bug where login always redirects to onboarding

* remove redundant auth check

---------

Co-authored-by: jinkang-0 <[email protected]>
  • Loading branch information
varortz and jinkang-0 authored May 15, 2024
1 parent 86c4d15 commit cc19672
Show file tree
Hide file tree
Showing 5 changed files with 64 additions and 43 deletions.
42 changes: 22 additions & 20 deletions src/app/(auth)/login/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,53 +15,55 @@ import { ProfileContext } from '@/utils/ProfileProvider';
export default function Login() {
const auth = useAuth();
const profile = useContext(ProfileContext);
if (!auth || !profile) {
throw new Error('Page must have auth and profile context defined');
}

const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [errorMessage, setErrorMessage] = useState('');
const [emailError, setEmailError] = useState('');
const [passwordError, setPasswordError] = useState('');
const [finishLogin, setFinishLogin] = useState(false);
const [isLoggingIn, setIsLoggingIn] = useState(false);

const { push } = useRouter();
const validEmail = (e: string) => e !== '' && isEmail(e);

useEffect(() => {
if (!auth) throw new Error('Auth must be defined');
if (auth.userId && !finishLogin) push(CONFIG.settings);
}, [auth, profile, push]);
if (auth.userId && !isLoggingIn) push(CONFIG.settings);
}, [auth, profile, push, isLoggingIn]);

const handleSignIn = async () => {
if (!auth) {
setErrorMessage('');
return;
}

setEmailError(validEmail(email) ? '' : 'Invalid Email');
setPasswordError(password !== '' ? '' : 'Invalid Password');
if (!validEmail(email) || password === '') {
setErrorMessage('');
return;
}

const { error } = await auth.signIn(email, password);
setIsLoggingIn(true);
const { error, data } = await auth.signIn(email, password);

if (error) {
setErrorMessage(error.message);
// TODO: use error.status to check if it's an email-specific or password-specific error
// then, raise the error in the TextInput component.
} else {
profile?.loadProfile();
setErrorMessage('');
setFinishLogin(true);
const loadedProfile = await profile.loadProfile(data.user?.id);

// conditional routing after logging in
if (profile?.profileReady) {
if (!profile?.profileData) push(CONFIG.onboardingHome);
else if (profile.roles.map(r => r.role).includes('ATTORNEY'))
push(CONFIG.cases);
else if (profile.roles.map(r => r.role).includes('LEGAL_FELLOW'))
push(CONFIG.lca);
else push(CONFIG.languageSupport);
if (!loadedProfile) {
push(CONFIG.onboardingHome);
return;
}

// conditional routing after logging in
if (!loadedProfile.profileData) push(CONFIG.onboardingHome);
else if (loadedProfile.roles.find(role => role.role === 'ATTORNEY'))
push(CONFIG.cases);
else if (loadedProfile.roles.find(role => role.role === 'LEGAL_FELLOW'))
push(CONFIG.lca);
else push(CONFIG.languageSupport);
}
};

Expand Down
4 changes: 2 additions & 2 deletions src/components/ProfileMatch/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -152,12 +152,12 @@ export default function ProfileMatch({
<P>No information available about languages</P>
</Flex>
)}
<P>
<P $color={COLORS.greyMid}>
Go to{' '}
<LinkColored $color={COLORS.blueMid} href={CONFIG.settings}>
Profile
</LinkColored>{' '}
to update any information.
to update any information
</P>
</Flex>
);
Expand Down
2 changes: 1 addition & 1 deletion src/lib/configs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const CONFIG = {
pageSize: 20,
settings: '/settings',
cases: '/cases',
lca: '/limited-case-assistance',
lca: '/limited-case-assignments',
languageSupport: '/language-support',
};

Expand Down
10 changes: 4 additions & 6 deletions src/utils/AuthProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,10 @@ export default function AuthProvider({
const setAll = useCallback((newSession: Session | null) => {
if (!newSession) return;
setSession(newSession);
if (newSession?.user?.id) {
const sessionUserId = newSession.user.id as UUID;
const sessionUserEmail = newSession.user.email;
setUserId(sessionUserId);
setUserEmail(sessionUserEmail);
}
const sessionUserId = (newSession.user.id as UUID) ?? undefined;
const sessionUserEmail = newSession.user.email ?? undefined;
setUserId(sessionUserId);
setUserEmail(sessionUserEmail);
}, []);

// on page load, check if there's a session and set it
Expand Down
49 changes: 35 additions & 14 deletions src/utils/ProfileProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
useMemo,
useState,
} from 'react';
import { UUID } from 'crypto';
import {
deleteLanguages,
deleteRoles,
Expand All @@ -30,6 +31,12 @@ import {
} from '@/types/schema';
import { useAuth } from '@/utils/AuthProvider';

interface LoadedProfileData {
profileData: Profile | null;
languages: ProfileLanguage[];
roles: ProfileRole[];
}

interface ProfileContextType {
profileData: Profile | null;
languages: ProfileLanguage[];
Expand All @@ -43,7 +50,7 @@ interface ProfileContextType {
languages: ProfileLanguage[],
roles: ProfileRole[],
) => Promise<void>;
loadProfile: () => Promise<void>;
loadProfile: (id?: string) => Promise<LoadedProfileData | null>;
}

export const ProfileContext = createContext<ProfileContextType | undefined>(
Expand All @@ -63,22 +70,36 @@ export default function ProfileProvider({ children }: { children: ReactNode }) {
const [profileRoles, setProfileRoles] = useState<ProfileRole[]>([]);
const { userId } = auth;

const loadProfile = useCallback(async () => {
setProfileReady(false);
const loadProfile = useCallback(
async (id?: string) => {
setProfileReady(false);

if (!userId) {
setProfileReady(true);
return;
}
if (!userId && !id) {
setProfileReady(true);
return null;
}

await Promise.all([
fetchProfileById(userId).then(data => setProfileData(data)),
fetchLanguagesById(userId).then(data => setProfileLangs(data)),
fetchRolesById(userId).then(data => setProfileRoles(data)),
]);
const fetchId = (id || userId) as UUID;

setProfileReady(true);
}, [userId]);
const [fetchedProfileData, languagesData, rolesData] = await Promise.all([
fetchProfileById(fetchId),
fetchLanguagesById(fetchId),
fetchRolesById(fetchId),
]);

setProfileData(fetchedProfileData);
setProfileLangs(languagesData);
setProfileRoles(rolesData);
setProfileReady(true);

return {
profileData: fetchedProfileData,
languages: languagesData,
roles: rolesData,
};
},
[userId],
);

useEffect(() => {
loadProfile();
Expand Down

0 comments on commit cc19672

Please sign in to comment.