@@ -122,15 +122,27 @@ function AuthStatus() {
122122async function loginAction ( { request } : LoaderFunctionArgs ) {
123123 let formData = await request . formData ( ) ;
124124 let username = formData . get ( "username" ) as string | null ;
125- let redirectTo = formData . get ( "redirectTo" ) as string | null ;
126125
126+ // Validate our form inputs and return validation errors via useActionData()
127127 if ( ! username ) {
128128 return {
129129 error : "You must provide a username to log in" ,
130130 } ;
131131 }
132132
133- await fakeAuthProvider . signin ( username ) ;
133+ // Sign in and redirect to the proper destination if successful.
134+ try {
135+ await fakeAuthProvider . signin ( username ) ;
136+ } catch ( error ) {
137+ // Unused as of now but this is how you would handle invalid
138+ // username/password combinations - just like validating the inputs
139+ // above
140+ return {
141+ error : "Invalid login attempt" ,
142+ } ;
143+ }
144+
145+ let redirectTo = formData . get ( "redirectTo" ) as string | null ;
134146 return redirect ( redirectTo || "/" ) ;
135147}
136148
@@ -176,6 +188,9 @@ function PublicPage() {
176188}
177189
178190function protectedLoader ( { request } : LoaderFunctionArgs ) {
191+ // If the user is not logged in and tries to access `/protected`, we redirect
192+ // them to `/login` with a `from` parameter that allows login to redirect back
193+ // to this page upon successful authentication
179194 if ( ! fakeAuthProvider . isAuthenticated ) {
180195 let params = new URLSearchParams ( ) ;
181196 params . set ( "from" , new URL ( request . url ) . pathname ) ;
0 commit comments