11/* eslint-disable perfectionist/sort-objects */
22
3+ import { asyncResultify } from '@douglasneuroinformatics/libjs' ;
34import { Dialog , Form } from '@douglasneuroinformatics/libui/components' ;
45import { useNotificationsStore } from '@douglasneuroinformatics/libui/hooks' ;
6+ import type { $LoginCredentials } from '@opendatacapture/schemas/auth' ;
7+ import axios from 'axios' ;
8+ import { err , ok } from 'neverthrow' ;
9+ import type { ResultAsync } from 'neverthrow' ;
510import { z } from 'zod/v4' ;
611
712import { useAppStore } from '@/store' ;
@@ -24,8 +29,33 @@ export const LoginDialog = ({ isOpen, setIsOpen }: LoginDialogProps) => {
2429
2530 const addNotification = useNotificationsStore ( ( store ) => store . addNotification ) ;
2631
27- const handleSubmit = ( { apiBaseUrl } : $LoginData ) => {
32+ const login = ( credentials : $LoginCredentials ) : ResultAsync < { accessToken : string } , string > => {
33+ return asyncResultify ( async ( ) => {
34+ try {
35+ const response = await axios . post ( `${ apiBaseUrl } /v1/auth/login` , credentials , {
36+ headers : {
37+ Accept : 'application/json'
38+ } ,
39+ validateStatus : ( ) => true
40+ } ) ;
41+ if ( response . status !== 200 ) {
42+ return err ( `${ response . status } : ${ response . statusText } ` ) ;
43+ }
44+ return ok ( await z . object ( { accessToken : z . jwt ( ) } ) . parseAsync ( response . data ) ) ;
45+ } catch ( error ) {
46+ console . error ( error ) ;
47+ return err ( 'Login Failed: Unknown Error' ) ;
48+ }
49+ } ) ;
50+ } ;
51+
52+ const handleSubmit = async ( { apiBaseUrl, ...credentials } : $LoginData ) => {
2853 updateSettings ( { apiBaseUrl } ) ;
54+ const loginResult = await login ( credentials ) ;
55+ if ( loginResult . isErr ( ) ) {
56+ addNotification ( { type : 'error' , message : loginResult . error } ) ;
57+ }
58+
2959 addNotification ( { type : 'success' } ) ;
3060 } ;
3161
@@ -72,8 +102,8 @@ export const LoginDialog = ({ isOpen, setIsOpen }: LoginDialogProps) => {
72102 ] }
73103 initialValues = { { apiBaseUrl } }
74104 validationSchema = { $LoginData }
75- onSubmit = { ( data ) => {
76- void handleSubmit ( data ) ;
105+ onSubmit = { async ( data ) => {
106+ await handleSubmit ( data ) ;
77107 setIsOpen ( false ) ;
78108 } }
79109 />
0 commit comments