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

Don/WFJB2-108: Route login/signup #74

Merged
merged 6 commits into from
Oct 7, 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
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')
}
72 changes: 46 additions & 26 deletions web/src/app/components/AuthForms/LoginForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,39 +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');
// 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 @@ -52,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
3 changes: 3 additions & 0 deletions web/src/app/components/AuthForms/SignupForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { NavLink } from 'react-router-dom';
import { Role } from '../../type/role';
import {toast} from "react-toastify";
import {createFSAEUserDto, register_alumni, register_member, register_sponsor} from "@/api/register";
import { useNavigate } from 'react-router-dom';

interface Field {
label: string;
Expand Down Expand Up @@ -108,6 +109,7 @@ const FormComponent: React.FC<FormComponentProps> = ({ fields, onSubmit }) => (
);

const SignupForm = ({ role }: { role: Role }) => {
const navigate = useNavigate();
const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
const formData = new FormData(event.target as HTMLFormElement);
Expand Down Expand Up @@ -135,6 +137,7 @@ const SignupForm = ({ role }: { role: Role }) => {
} else {
toast.error('Registering Unknown Role');
}
navigate('/', { replace: true });
};

return (
Expand Down
4 changes: 4 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1


Loading