Skip to content

Commit

Permalink
feat: add user login handler
Browse files Browse the repository at this point in the history
  • Loading branch information
akmalhisyammm committed Dec 1, 2021
1 parent 8e0b29e commit 5efc920
Show file tree
Hide file tree
Showing 6 changed files with 235 additions and 69 deletions.
42 changes: 33 additions & 9 deletions src/components/SideMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,24 @@ import {
IonIcon,
IonLabel,
} from '@ionic/react';
import { informationCircle, logIn, personAdd } from 'ionicons/icons';
import { useContext } from 'react';
import { useHistory } from 'react-router-dom';
import { AuthContext } from 'contexts/auth';
import { informationCircle, logIn, logOut, personAdd } from 'ionicons/icons';

const SideMenu: React.FC = () => {
const { currentUser, logout } = useContext(AuthContext);
const history = useHistory();

const handleLogout = async () => {
try {
await logout();
history.replace('/');
} catch (error) {
console.error(error);
}
};

return (
<IonMenu contentId="main">
<IonHeader>
Expand All @@ -24,14 +39,23 @@ const SideMenu: React.FC = () => {
<IonContent>
<IonList>
<IonMenuToggle autoHide={false}>
<IonItem button routerLink="/login">
<IonIcon slot="start" color="primary" icon={logIn} />
<IonLabel>Masuk</IonLabel>
</IonItem>
<IonItem button routerLink="/register">
<IonIcon slot="start" color="primary" icon={personAdd} />
<IonLabel>Daftar</IonLabel>
</IonItem>
{!currentUser ? (
<>
<IonItem button routerLink="/login">
<IonIcon slot="start" color="primary" icon={logIn} />
<IonLabel>Masuk</IonLabel>
</IonItem>
<IonItem button routerLink="/register">
<IonIcon slot="start" color="primary" icon={personAdd} />
<IonLabel>Daftar</IonLabel>
</IonItem>
</>
) : (
<IonItem button onClick={handleLogout}>
<IonIcon slot="start" color="primary" icon={logOut} />
<IonLabel>Keluar</IonLabel>
</IonItem>
)}
<IonItem button routerLink="/about">
<IonIcon slot="start" color="primary" icon={informationCircle} />
<IonLabel>Tentang</IonLabel>
Expand Down
47 changes: 37 additions & 10 deletions src/contexts/auth/AuthProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,45 @@
import { useState, useEffect } from 'react';
import { UserData } from 'types/userData';
import { AuthContext } from './auth.context';
import { firebaseAuth, registerUser, loginUser } from 'services/firebase';
import {
firebaseAuth,
registerUser,
loginUser,
logoutUser,
} from 'services/firebase';

export const AuthProvider: React.FC = ({ children }) => {
const [currentUser, setCurrentUser] = useState<UserData | null>(null);

useEffect(() => {
const unsubscribe = firebaseAuth.onAuthStateChanged((user: any) => {
setCurrentUser(user);
console.log("onAuthStateChanged", currentUser);
console.log('onAuthStateChanged', currentUser);
});

return unsubscribe;
}, []);
}, [currentUser]);

const register = async (email: string, password: string, fullName: string, phoneNumber: string, address: string, gender: 'male' | 'female') => {
const register = async (
email: string,
password: string,
fullName: string,
phoneNumber: string,
address: string,
gender: 'male' | 'female'
) => {
try {
await registerUser(email, password, fullName, phoneNumber, address, gender);
await registerUser(
email,
password,
fullName,
phoneNumber,
address,
gender
);
} catch (error) {
console.error(error);
throw new Error("Oops! Something went wrong.");
throw new Error('Oops! Something went wrong.');
}
};

Expand All @@ -29,24 +48,32 @@ export const AuthProvider: React.FC = ({ children }) => {
const result = await loginUser(email, password);

if (!result.status && result.message === 'email_not_verified') {
throw new Error("email_not_verified");
throw new Error('email_not_verified');
}
} catch (error) {
console.error(error);

if (error instanceof Error) {
if (error.message === 'email_not_verified') {
throw new Error("email_not_verified");
throw new Error('email_not_verified');
}
return;
}

throw new Error("Oops! Something went wrong.");
throw new Error('Oops! Something went wrong.');
}
};

const logout = async () => {
try {
await logoutUser();
} catch (error) {
console.error(error);
}
};

return (
<AuthContext.Provider value={{ currentUser, register, login }}>
<AuthContext.Provider value={{ currentUser, register, login, logout }}>
{children}
</AuthContext.Provider>
);
Expand Down
11 changes: 10 additions & 1 deletion src/contexts/auth/auth.context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,21 @@ import { UserData } from 'types/userData';

interface Context {
currentUser: UserData | null;
register: (email: string, password: string, fullName: string, phoneNumber: string, address: string, gender: 'male' | 'female') => void;
register: (
email: string,
password: string,
fullName: string,
phoneNumber: string,
address: string,
gender: 'male' | 'female'
) => void;
login: (email: string, password: string) => void;
logout: () => void;
}

export const AuthContext = createContext<Context>({
currentUser: null,
register: () => {},
login: () => {},
logout: () => {},
});
34 changes: 22 additions & 12 deletions src/pages/auth/Login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,12 @@ import {
import { klikDarurat } from 'assets';
import { mailOutline, lockClosedOutline } from 'ionicons/icons';

import { AuthContext } from '../../contexts/auth';
import { AuthContext } from 'contexts/auth';

import Layout from 'components/layout';

const Login: React.FC = () => {
const [toastMessage, setToastMessage] = useState<string>("");
const [toastMessage, setToastMessage] = useState<string>('');
const [loading, setLoading] = useState<boolean>(false);
const emailRef = useRef<HTMLIonInputElement>(null);
const passwordRef = useRef<HTMLIonInputElement>(null);
Expand All @@ -39,34 +39,33 @@ const Login: React.FC = () => {
}

if (email.toString().trim().length === 0) {
setToastMessage("Email wajib diisi");
setToastMessage('Email wajib diisi');
return;
}

if (password.toString().length === 0) {
setToastMessage("Kata sandi wajib diisi");
setToastMessage('Kata sandi wajib diisi');
return;
}

try {
setToastMessage("");
setToastMessage('');
setLoading(true);

await authCtx.login(email.toString(), password.toString());

//setLoading(false);
history.length > 0 ? history.goBack() : history.replace('/main');

history.replace('/main');
} catch (error) {
if (error instanceof Error) {
if (error.message === 'email_not_verified') {
setLoading(false);
setToastMessage("Harap verifikasi email anda");
console.log("Harap verifikasi email anda");
setToastMessage('Harap verifikasi email anda');
console.log('Harap verifikasi email anda');
}
return;
} else {
setToastMessage("Gagal untuk login");
setToastMessage('Gagal untuk login');
}
}

Expand Down Expand Up @@ -136,15 +135,26 @@ const Login: React.FC = () => {
color="primary"
slot="start"
/>
<IonInput type="email" inputMode="email" placeholder="Email" ref={emailRef} required />
<IonInput
type="email"
inputMode="email"
placeholder="Email"
ref={emailRef}
required
/>
</IonItem>
<IonItem style={{ '--background': 'inherit' }}>
<IonIcon
icon={lockClosedOutline}
color="primary"
slot="start"
/>
<IonInput type="password" placeholder="Kata Sandi" ref={passwordRef} required />
<IonInput
type="password"
placeholder="Kata Sandi"
ref={passwordRef}
required
/>
</IonItem>
</IonList>
</IonCol>
Expand Down
Loading

0 comments on commit 5efc920

Please sign in to comment.