Skip to content

Commit

Permalink
feat: add auth functions
Browse files Browse the repository at this point in the history
  • Loading branch information
Ramin Rezaei committed May 28, 2024
1 parent 69aa3cc commit cccf93d
Show file tree
Hide file tree
Showing 12 changed files with 706 additions and 12 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"dependencies": {
"@reduxjs/toolkit": "^2.2.5",
"clsx": "^2.1.1",
"firebase": "^10.12.2",
"localforage": "^1.10.0",
"lottie-react": "^2.4.0",
"match-sorter": "^6.3.4",
Expand Down
16 changes: 7 additions & 9 deletions src/domains/home/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { notify } from "../../shared/utils/notify";
import { animator } from "../../shared/utils/animator";
import { ROUTES } from "../../shared/constants/routes";
import { classnames } from "../../shared/utils/classnames";
import { LoginRequest } from "../../shared/firebase/requests/auth";
import { userLoginAction } from "../../shared/redux/user/user-slice";

import LOVE_ANIMATION from '../../shared/assets/love-animation.json';
Expand All @@ -24,17 +25,14 @@ export function HomePage(){

const onSubmit = (e: FormEvent<HTMLButtonElement>) => {
e.preventDefault();
if (isCodeValid(code) && code === 'ramin') {
// TODO: Login
notify.success({ message: 'Welcome! 😍' });
dispatch(userLoginAction({
id: 1,
name: 'Ramin',
}));
navigate(ROUTES.COUNTER);
if (isCodeValid(code)) {
LoginRequest(code, (user: GUser) => {
dispatch(userLoginAction(user));
navigate(ROUTES.COUNTER);
});
return;
}
notify.error({ message: 'Oops, Your Code Is Wrong!' });
notify.error({ message: 'Oops, Your Code Pattern Is Not Correct!' });
};

return (
Expand Down
3 changes: 3 additions & 0 deletions src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
createBrowserRouter,
} from "react-router-dom";
import { Provider } from 'react-redux';
import { initFirebase } from "./shared/firebase";
import { PersistGate } from 'redux-persist/integration/react';

import { ROUTES } from "./shared/constants/routes";
Expand All @@ -19,6 +20,8 @@ import { CounterPage } from './domains/counter';
// Styles
import './styles/main.scss';

initFirebase();

const router = createBrowserRouter([
{
path: ROUTES.HOME,
Expand Down
6 changes: 6 additions & 0 deletions src/shared/firebase/constants/database.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { getDatabase } from "firebase/database";

export const DATABASE_USERS_TABLE_NAME = 'USERS';
export const DATABASE_MESSAGES_TABLE_NAME = 'MESSAGES';

export const DB = getDatabase();
9 changes: 9 additions & 0 deletions src/shared/firebase/constants/firebase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export const FIREBASE_CONFIGS = {
projectId: "memories-counter",
messagingSenderId: "295192400416",
storageBucket: "memories-counter.appspot.com",
authDomain: "memories-counter.firebaseapp.com",
apiKey: "AIzaSyBdnKbIQ7a4Kv_7Nf74ZqX1VmpgJykiR80",
appId: "1:295192400416:web:61c08e58c814a39197a245",
databaseURL: "https://memories-counter-default-rtdb.europe-west1.firebasedatabase.app",
};
18 changes: 18 additions & 0 deletions src/shared/firebase/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { notify } from '../utils/notify';
import { initializeApp } from 'firebase/app';
import { FIREBASE_CONFIGS } from './constants/firebase';
import { getAuth, signInAnonymously } from 'firebase/auth';

const FIREBASE_APP = initializeApp(FIREBASE_CONFIGS);

const AUTH = getAuth(FIREBASE_APP);

export const initFirebase = () => {
signInAnonymously(AUTH)
.then(() => {
console.log('%cDB - SUCCESS!', 'color: green');
})
.catch(() => {
notify.error({ message: "Error: We couldn't connect to the Database!" });
});
}
53 changes: 53 additions & 0 deletions src/shared/firebase/requests/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { notify } from '../../utils/notify';
import { ref, set, get, child, push } from 'firebase/database';
import { DB, DATABASE_USERS_TABLE_NAME } from '../constants/database';

type UserDataType = GUser;
type LoginCallbackType = (user: GUser) => void;

export const LoginRequest = (code: string, callback: LoginCallbackType = () => {}) => {
get(child(ref(DB), `${DATABASE_USERS_TABLE_NAME}/`))
.then((snapshot) => {
if (snapshot.exists()) {
const users = Object.entries(snapshot.val()).map(([key, value]) => ({
id: key,
...value || {},
isAuthenticated: true
})) as GUser[];
const user = users.filter((item) => item.code === code);

if (user.length) {
notify.success({ message: 'Welcome! 😍' });
callback(user[0]);
} else {
notify.error({ message: 'Oops, Your Code Is Wrong!' });
}
}
})
.catch(() => notify.error({ message: 'Oops, Server Error!' }));
};

export const RegisterRequest = (userData: UserDataType, callback: LoginCallbackType = () => {}) => {
const userId = push(child(ref(DB), DATABASE_USERS_TABLE_NAME)).key;
set(ref(DB, `${DATABASE_USERS_TABLE_NAME}/${userId}`), userData)
.then(() => {
notify.success({ message: 'Your account created successful.' });
LoginRequest(userData.code, callback);
})
.catch(() => notify.error({ message: 'Oops, You cannot create account now!' }));
};

export const GetUsersRequest = (callback: (users: GUser[]) => void = () => {}) => {
get(child(ref(DB), `${DATABASE_USERS_TABLE_NAME}/`))
.then((snapshot) => {
if (snapshot.exists()) {
const users = Object.entries(snapshot.val()).map(([key, value]) => ({
id: key,
...value || {},
isAuthenticated: true
})) as GUser[];
callback(users);
}
})
.catch(() => notify.error({ message: 'Oops, Server Error!' }));
};
16 changes: 16 additions & 0 deletions src/shared/firebase/requests/get-messages.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { notify } from '../../utils/notify';
import { ref, get, child } from 'firebase/database';
import { DB, DATABASE_MESSAGES_TABLE_NAME } from '../constants/database';

type GetMessagesRequestProps = (messages?: GMessage[]) => void;

export const GetMessagesRequest = (callback: GetMessagesRequestProps = () => {}) => {
get(child(ref(DB), `${DATABASE_MESSAGES_TABLE_NAME}/`))
.then((snapshot) => {
if (snapshot.exists()) {
console.log('>>> Messages Updated');
callback(Object.values(snapshot.val()) as GMessage[]);
}
})
.catch(() => notify.error({ message: "Error: Messages couldn't be updated." }));
};
9 changes: 9 additions & 0 deletions src/shared/firebase/requests/post-message.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { notify } from '../../utils/notify';
import { ref, set } from 'firebase/database';
import { DB, DATABASE_MESSAGES_TABLE_NAME } from '../constants/database';

export const PostMessageRequest = (userId: string, data: any, callback = () => {}) => {
set(ref(DB, `${DATABASE_MESSAGES_TABLE_NAME}/${userId}`), data)
.then(callback)
.catch(() => notify.error({ message: "Error: Your messages couldn't be saved." }));
};
8 changes: 8 additions & 0 deletions src/shared/redux/user/user-slice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ import { REDUCERS } from "../../constants/reducers";
const initialState: GUser = {
id: null,
name: '',
code: '',
email: '',
birthday: '',
isMale: false,
isAuthenticated: false
};

Expand All @@ -22,6 +26,10 @@ const userSlice = createSlice({
return {
id: null,
name: '',
code: '',
email: '',
birthday: '',
isMale: false,
isAuthenticated: false
};
}
Expand Down
6 changes: 5 additions & 1 deletion src/types/user.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@ export {};
declare global {
interface GUser {
name: string;
id: null | number;
code: string;
email: string;
isMale: boolean;
birthday: stringl;
id: null | string;
isAuthenticated: boolean;
}
}
Loading

0 comments on commit cccf93d

Please sign in to comment.