@@ -11,7 +11,7 @@ import { api } from '../../api';
1111interface 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