Skip to content
Open
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: 9 additions & 35 deletions frontend/src/Register.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import React, { useState } from "react";
import { setAuthState } from "./external/bcanSatchel/actions";
import { observer } from "mobx-react-lite";
import { useNavigate } from "react-router-dom";
import logo from "./images/bcan_logo.svg";
import { api } from "./api";
import { useAuthContext } from "./context/auth/authContext";

/**
* Register a new BCAN user
Expand All @@ -14,41 +13,15 @@ const Register = observer(() => {
const [password, setPassword] = useState("");
const navigate = useNavigate();

const { register } = useAuthContext();

const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();

try {
const response = await api("/auth/register", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password, email }),
});

const data = await response.json();

if (!response.ok) {
alert(data.message || "Registration failed.");
return;
}

// If registration succeeded, automatically log in the user
const loginResponse = await api("/auth/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password }),
});

const loginData = await loginResponse.json();

if (loginResponse.ok && loginData.access_token) {
setAuthState(true, loginData.user, loginData.access_token);
navigate("/grant-info");
} else {
alert(loginData.message || "Login after registration failed.");
}
} catch (error) {
console.error("Error during registration:", error);
alert("An error occurred while registering. Please try again later.");
const success = await register(username, password, email);
if (success) {
navigate("/login");
} else {
console.warn("Registration failed");
}
};

Expand Down Expand Up @@ -80,6 +53,7 @@ const Register = observer(() => {
>
← Back to Sign In
</button>


{/* Username field */}
<label htmlFor="username" style={styles.label}>
Expand Down
47 changes: 32 additions & 15 deletions frontend/src/context/auth/authContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { api } from '../../api';
interface AuthContextProps {
isAuthenticated: boolean;
login: (username: string, password: string) => Promise<boolean>;
register: (username: string, password: string, email: string) => Promise<void>;
register: (username: string, password: string, email: string) => Promise<boolean>;
logout: () => void;
user: User | null;
}
Expand Down Expand Up @@ -57,24 +57,41 @@ export const AuthProvider = observer(({ children }: { children: ReactNode }) =>
/**
* Register a new user and automatically log them in
*/
const register = async (username: string, password: string, email: string) => {

const response = await api('/auth/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password, email }),
});

const data = await response.json();
if (response.ok) {
// log the user in after registration
await login(username, password);
} else {
alert(data.message || 'Registration failed');
const register = async (username: string, password: string, email: string): Promise<boolean> => {
try {
const response = await api('/auth/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password, email }),
});

const data = await response.json();

if (response.ok) {
const loggedIn = await login(username, password);
if (loggedIn) return true;
console.warn('User registered but auto-login failed');
return false;
}

if (response.status === 409 || data.message?.includes('exists')) {
alert('An account with this username or email already exists.');
} else if (response.status === 400) {
alert(data.message || 'Invalid registration details.');
} else {
alert('Registration failed. Please try again later.');
}

return false;
} catch (error) {
console.error('Error during registration:', error);
alert('An unexpected error occurred. Please try again later.');
return false;
}
};



/** Log out the user */
const logout = () => {
api('/auth/logout', { method: 'POST' });
Expand Down