Skip to content

Commit 7693cd1

Browse files
committed
register changes
1 parent cbe8aa3 commit 7693cd1

File tree

2 files changed

+41
-48
lines changed

2 files changed

+41
-48
lines changed

frontend/src/Register.tsx

Lines changed: 9 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { observer } from "mobx-react-lite";
44
import { useNavigate } from "react-router-dom";
55
import logo from "./images/bcan_logo.svg";
66
import { api } from "./api";
7+
import { useAuthContext } from "./context/auth/authContext";
78

89
/**
910
* Register a new BCAN user
@@ -14,41 +15,15 @@ const Register = observer(() => {
1415
const [password, setPassword] = useState("");
1516
const navigate = useNavigate();
1617

18+
const { register } = useAuthContext();
19+
1720
const handleSubmit = async (e: React.FormEvent) => {
1821
e.preventDefault();
19-
20-
try {
21-
const response = await api("/auth/register", {
22-
method: "POST",
23-
headers: { "Content-Type": "application/json" },
24-
body: JSON.stringify({ username, password, email }),
25-
});
26-
27-
const data = await response.json();
28-
29-
if (!response.ok) {
30-
alert(data.message || "Registration failed.");
31-
return;
32-
}
33-
34-
// If registration succeeded, automatically log in the user
35-
const loginResponse = await api("/auth/login", {
36-
method: "POST",
37-
headers: { "Content-Type": "application/json" },
38-
body: JSON.stringify({ username, password }),
39-
});
40-
41-
const loginData = await loginResponse.json();
42-
43-
if (loginResponse.ok && loginData.access_token) {
44-
setAuthState(true, loginData.user, loginData.access_token);
45-
navigate("/grant-info");
46-
} else {
47-
alert(loginData.message || "Login after registration failed.");
48-
}
49-
} catch (error) {
50-
console.error("Error during registration:", error);
51-
alert("An error occurred while registering. Please try again later.");
22+
const success = await register(username, password, email);
23+
if (success) {
24+
navigate("/login");
25+
} else {
26+
console.warn("Registration failed");
5227
}
5328
};
5429

@@ -80,6 +55,7 @@ const Register = observer(() => {
8055
>
8156
← Back to Sign In
8257
</button>
58+
8359

8460
{/* Username field */}
8561
<label htmlFor="username" style={styles.label}>

frontend/src/context/auth/authContext.tsx

Lines changed: 32 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import { api } from '../../api';
1111
interface AuthContextProps {
1212
isAuthenticated: boolean;
1313
login: (username: string, password: string) => Promise<boolean>;
14-
register: (username: string, password: string, email: string) => Promise<void>;
14+
register: (username: string, password: string, email: string) => Promise<boolean>;
1515
logout: () => void;
1616
user: User | null;
1717
}
@@ -57,24 +57,41 @@ export const AuthProvider = observer(({ children }: { children: ReactNode }) =>
5757
/**
5858
* Register a new user and automatically log them in
5959
*/
60-
const register = async (username: string, password: string, email: string) => {
61-
62-
const response = await api('/auth/register', {
63-
method: 'POST',
64-
headers: { 'Content-Type': 'application/json' },
65-
body: JSON.stringify({ username, password, email }),
66-
});
67-
68-
const data = await response.json();
69-
if (response.ok) {
70-
// log the user in after registration
71-
await login(username, password);
72-
} else {
73-
alert(data.message || 'Registration failed');
60+
const register = async (username: string, password: string, email: string): Promise<boolean> => {
61+
try {
62+
const response = await api('/auth/register', {
63+
method: 'POST',
64+
headers: { 'Content-Type': 'application/json' },
65+
body: JSON.stringify({ username, password, email }),
66+
});
67+
68+
const data = await response.json();
69+
70+
if (response.ok) {
71+
const loggedIn = await login(username, password);
72+
if (loggedIn) return true;
73+
console.warn('User registered but auto-login failed');
74+
return false;
75+
}
76+
77+
if (response.status === 409 || data.message?.includes('exists')) {
78+
alert('An account with this username or email already exists.');
79+
} else if (response.status === 400) {
80+
alert(data.message || 'Invalid registration details.');
81+
} else {
82+
alert('Registration failed. Please try again later.');
83+
}
84+
85+
return false;
86+
} catch (error) {
87+
console.error('Error during registration:', error);
88+
alert('An unexpected error occurred. Please try again later.');
89+
return false;
7490
}
7591
};
7692

7793

94+
7895
/** Log out the user */
7996
const logout = () => {
8097
api('/auth/logout', { method: 'POST' });

0 commit comments

Comments
 (0)