Skip to content

Commit

Permalink
Redirect user to profile depending on userType
Browse files Browse the repository at this point in the history
  • Loading branch information
Kinzi-c committed Oct 7, 2024
1 parent 40d28f7 commit ad0f6bb
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 52 deletions.
44 changes: 19 additions & 25 deletions web/src/api/login.ts
Original file line number Diff line number Diff line change
@@ -1,47 +1,41 @@
import {apiInstance} from "@/api/ApiInstance";

import { apiInstance } from '@/api/ApiInstance';
export async function login(email: string, password: string) {
let userRole;
try {
const res = await apiInstance.get(`user/${email}/role`)
userRole = res.data
const res = await apiInstance.get(`user/${email}/role`);
userRole = res.data;

if (userRole == null) {
throw Error("Invalid credentials");
if (!userRole) {
throw Error('Invalid credentials');
}
} catch (e) {
throw Error("Invalid credentials")
throw Error('Invalid credentials');
}

let loginUrl;
console.log(userRole)
if (userRole === 'admin') {
loginUrl = 'login-admin'
loginUrl = 'login-admin';
} else if (userRole === 'alumni') {
loginUrl = 'login-alumni'
loginUrl = 'login-alumni';
} else if (userRole === 'member') {
loginUrl = 'login-member'
loginUrl = 'login-member';
} else if (userRole === 'sponsor') {
loginUrl = 'login-sponsor'
loginUrl = 'login-sponsor';
} else {
throw Error("Unknown login type")
throw Error('Unknown login type');
}

try {
const res = await apiInstance.post(loginUrl, {
"email": email,
"password": password
})
const {userId, token} = res.data;
localStorage.setItem('accessToken', token)
console.log(`Successfully logged in as UserID ${userId}`)
email,
password,
});
const { userId, token } = res.data;
localStorage.setItem('accessToken', token);
console.log(`Successfully logged in as UserID ${userId}`);

// Todo: After successful login. Create endpoint to get whoami() and link that to redux state.
return { userType: userRole }; // Return userType
} catch (e) {
throw Error("Invalid credentials")
throw Error('Invalid credentials');
}
}

export async function logout() {
localStorage.removeItem('accessToken')
}
73 changes: 46 additions & 27 deletions web/src/app/components/AuthForms/LoginForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,40 +4,47 @@ import { NavLink } from 'react-router-dom';
import { useNavigate } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import { toast } from 'react-toastify';
import { login } from "@/api/login";
import { useState } from "react";
import { login } from '@/api/login';
import { useState } from 'react';

export function LoginForm() {
const dispatch = useDispatch();
const navigate = useNavigate();

const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
// const handleLoginAs = (userType: 'student' | 'sponsor' | 'alumni' | 'admin') => {
//
//
// // dispatch(setUserType(userType)); Todo: Move this to API folder
// // const profilePath = {
// // student: '/profile/student',
// // sponsor: '/profile/sponsor',
// // alumni: '/profile/alumni',
// // admin: '/profile/admin',
// // }[userType];
// // toast.success('Logged in as ' + userType);
// // navigate(profilePath, { replace: true });
// };

async function onLogin() {
await login(email, password)
.then((response) => {
toast.success('Login Successful');
navigate('/profile', { replace: true });
// Todo: Do something afterwards.
// handleLoginAs(response.data.userType);
}).catch((error) => {
console.log(error)
toast.error(error.toString());
})
try {
const { userType } = await login(email, password);
toast.success('Login Successful');

// Redirect based on user type
switch (userType) {
case 'admin':
navigate('/profile/admin', { replace: true });
break;
case 'alumni':
navigate('/profile/alumni', { replace: true });
break;
case 'member':
navigate('/profile/student', { replace: true });
break;
case 'sponsor':
navigate('/profile/sponsor', { replace: true });
break;
default:
navigate('/'); // Default fallback
}
} catch (error) {
if (error instanceof Error) {
toast.error(error.message);
console.error(error);
} else {
toast.error('An unknown error occurred');
console.error('Unknown error:', error);
}
}
}

return (
Expand All @@ -53,8 +60,20 @@ export function LoginForm() {
Login
</Title>

<TextInput placeholder="Enter email" size="lg" mb="lg" value={email} onChange={(event) => setEmail(event.target.value)} />
<PasswordInput placeholder="Enter password" mt="xl" size="lg" value={password} onChange={(event) => setPassword(event.target.value)} />
<TextInput
placeholder="Enter email"
size="lg"
mb="lg"
value={email}
onChange={(event) => setEmail(event.target.value)}
/>
<PasswordInput
placeholder="Enter password"
mt="xl"
size="lg"
value={password}
onChange={(event) => setPassword(event.target.value)}
/>
<Checkbox label="Remember Me" mt="xl" size="md" />
<Button fullWidth mt="xl" mb="md" size="lg" onClick={onLogin}>
Login
Expand Down

0 comments on commit ad0f6bb

Please sign in to comment.