Skip to content

Commit

Permalink
Merge pull request #232 from flickmatch/firebase-login-new-branch
Browse files Browse the repository at this point in the history
old google login method added
  • Loading branch information
abhimanyu-fm authored May 19, 2024
2 parents ac04c54 + f6abb96 commit fee40d6
Show file tree
Hide file tree
Showing 8 changed files with 1,709 additions and 71 deletions.
1,566 changes: 1,525 additions & 41 deletions react-fm/package-lock.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions react-fm/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"@react-oauth/google": "^0.12.1",
"@types/gapi.client": "^1.0.8",
"axios": "^1.6.8",
"firebase": "^10.12.0",
"gapi-client": "^0.0.3",
"is-mobile": "^3.1.1",
"lodash": "^4.17.21",
Expand Down
20 changes: 20 additions & 0 deletions react-fm/src/Root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,31 @@ import { createRoot } from 'react-dom/client';
import { HelmetProvider } from 'react-helmet-async';
import { RecoilRoot } from 'recoil';

import { getAnalytics } from 'firebase/analytics';
import { initializeApp } from 'firebase/app';

import ThemeProvider from '@/theme/Provider';

// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: import.meta.env.VITE_FIREBASE_API_KEY,
authDomain: 'flickmatch-6e505.firebaseapp.com',
projectId: 'flickmatch-6e505',
storageBucket: 'flickmatch-6e505.appspot.com',
messagingSenderId: import.meta.env.VITE_MESSAGING_SENDER_ID,
appId: import.meta.env.VITE_FIREBASE_APP_ID,
measurementId: import.meta.env.VITE_FIREBASE_MEASUREMENT_ID,
};

const container = document.getElementById('root') as HTMLElement;
const root = createRoot(container);

// Initialize Firebase
const app = initializeApp(firebaseConfig);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const analytics = getAnalytics(app);

function render(App: ComponentType) {
root.render(
<GoogleOAuthProvider clientId="967689051729-u5kn73uscp0gp6s2itk6t4cs5fgkenkn.apps.googleusercontent.com">
Expand Down
2 changes: 1 addition & 1 deletion react-fm/src/pages/addGame/AddGame.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ function AddGame() {
options: {
content: (
<Alert severity="success">
<AlertTitle className={styles.alertTitle}>Turf Added Successfully</AlertTitle>
<AlertTitle className={styles.alertTitle}>Game Added Successfully</AlertTitle>
</Alert>
),
},
Expand Down
11 changes: 9 additions & 2 deletions react-fm/src/pages/googleLoginAuth/GoogleLogin.module.scss
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@
border-radius: 4px;
font-weight: 600;
height: 45px;
max-width: 80%;
max-width: 100%;
margin-bottom: 10px;
}

Expand Down Expand Up @@ -175,5 +175,12 @@

.emailLoginButton,
.portraitEmailLoginButton {
margin-left: 17.5%;
margin-left: 5px;
}

.signupText {
text-decoration: underline;
color: #606264;
font-weight: 500;
cursor: pointer;
}
172 changes: 147 additions & 25 deletions react-fm/src/pages/googleLoginAuth/GoogleLogin.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,31 +6,63 @@ import EmailIcon from '@mui/icons-material/Email';
import GoogleIcon from '@mui/icons-material/Google';
import SportsSoccerIcon from '@mui/icons-material/SportsSoccer';
import { Button } from '@mui/material';
import Alert from '@mui/material/Alert';
import AlertTitle from '@mui/material/AlertTitle';
import Box from '@mui/material/Box';
import TextField from '@mui/material/TextField';
import Typography from '@mui/material/Typography';

import axios from 'axios';
import {
createUserWithEmailAndPassword,
getAuth,
onAuthStateChanged,
sendEmailVerification,
signInWithEmailAndPassword,
} from 'firebase/auth';

import Meta from '@/components/Meta';
import useOrientation from '@/hooks/useOrientation';
import Footer from '@/sections/Footer';
import Header from '@/sections/Header';
import useNotifications from '@/store/notifications';

import styles from './GoogleLogin.module.scss';
import { apiUrl } from './constants';

function GoogleLogin() {
const isPortrait = useOrientation();
const navigate = useNavigate();
const auth = getAuth();

//----------------------------------------------------------------
const [, notificationsActions] = useNotifications();

const [isLoggedIn, setIsLoggedIn] = useState(false);
const [emailLogin, setEmailLogin] = useState(false);
const [showLogin, setShowLogin] = useState(false);
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [showSignup, setShowSignup] = useState(false);

const adminPassword = 'admin@flickmatch';
const onAuthStateChange = () => {
onAuthStateChanged(auth, (user) => {
if (user) {
const creationTime = user.metadata.creationTime;
const lastSignInTime = user.metadata.lastSignInTime;
if (creationTime === lastSignInTime) {
// eslint-disable-next-line no-console
console.log('User is logging in for the first time');
addUsers(user.email, user.displayName);
} else {
// eslint-disable-next-line no-console
console.log('User has logged in before');
}
}
});
};

const addUsers = (email: string, name: string) => {
const addUsers = (email: string | null, name: string | null) => {
fetch(apiUrl, {
method: 'POST',
headers: {
Expand All @@ -55,7 +87,6 @@ function GoogleLogin() {
throw new Error(result.errors[0].message);
// console.log(result.errors[0].message)
}
// console.log(result)
})
.catch((error) => {
// eslint-disable-next-line no-console
Expand Down Expand Up @@ -85,25 +116,79 @@ function GoogleLogin() {
});
};

const emailLoginFunc = () => {
if (password === adminPassword) {
const name = email.split('@')[0];
const emailData = { email: email, password: password, id: '344665', name: name };

localStorage.setItem('userData', JSON.stringify(emailData));
setIsLoggedIn(true);
navigate('/match-queues');
} else {
alert('Incorrect password');
}
};

const loginFunc = useGoogleLogin({
onSuccess: (credentialResponse) => getGoogleUserInfo(credentialResponse.access_token),
// eslint-disable-next-line no-console
onError: (error) => console.log('Login Failed ', error),
});

const errorNotification = (errorMessage: string) =>
notificationsActions.push({
options: {
content: (
<Alert severity="error">
<AlertTitle className={styles.alertTitle}>{errorMessage}</AlertTitle>
</Alert>
),
},
});

//email signup function
const emailSignUp = () => {
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
sendEmailVerification(userCredential.user).then(() => {
alert(
'Email verification link sent successfully! Please login after email verification successful',
);
});
setShowSignup(false);

auth.signOut();
})
.catch((error) => {
const errorMessage = error.message.slice(10);
if (errorMessage === 'Error (auth/email-already-in-use).') {
errorNotification('Email id already exists! Try logging in with google');
setShowSignup(false);
setEmailLogin(false);
} else {
errorNotification(errorMessage);
}
});
};

//email login function
const emailLogIn = () => {
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
const name = email.split('@')[0];

// Signed in
const user = userCredential.user;

if (user.emailVerified) {
const emailData = { email: user.email, id: user.uid, name: name };

localStorage.setItem('userData', JSON.stringify(emailData));
onAuthStateChange();
setIsLoggedIn(true);
navigate('/match-queues');
} else {
alert('Please verify your email before logging in');
}
})
.catch((error) => {
const errorMessage = error.message.slice(10);
errorNotification(errorMessage);
});
};

const emailLoginFunc = () => {
setShowLogin(true);
setEmailLogin(true);
};

return (
<>
<Meta title="Login/Signup" />
Expand All @@ -124,7 +209,13 @@ function GoogleLogin() {
<SportsSoccerIcon className={styles.sportsIcon} />
</Box>
<Box className={styles.loginSignupHeader}>
<Typography className={styles.loginSignupText}>Login / Signup</Typography>
{showSignup ? (
<Typography className={styles.loginSignupText}>Sign up</Typography>
) : showLogin ? (
<Typography className={styles.loginSignupText}>Login</Typography>
) : (
<Typography className={styles.loginSignupText}>Login / Sign up</Typography>
)}
<Typography className={styles.getStarted}>Let&#39;s get Started</Typography>
<Typography className={styles.signUpImmediately}>
Join our community and start your <br />
Expand Down Expand Up @@ -152,7 +243,7 @@ function GoogleLogin() {
className={
isPortrait ? styles.portraitGoogleLoginButton : styles.googleLoginButton
}
onClick={() => setEmailLogin(true)}
onClick={() => emailLoginFunc()}
startIcon={<EmailIcon />}
>
Log In / Sign Up with Email
Expand All @@ -175,13 +266,44 @@ function GoogleLogin() {
onChange={(e) => setPassword(e.target.value)}
className={styles.passwordField}
/>
<Button
variant="outlined"
className={isPortrait ? styles.portraitEmailLoginButton : styles.emailLoginButton}
onClick={() => emailLoginFunc()}
>
Sign In
</Button>
{showSignup ? (
<Button
variant="outlined"
className={
isPortrait ? styles.portraitEmailLoginButton : styles.emailLoginButton
}
onClick={() => emailSignUp()}
>
Sign up
</Button>
) : (
<Button
variant="outlined"
className={
isPortrait ? styles.portraitEmailLoginButton : styles.emailLoginButton
}
onClick={() => emailLogIn()}
>
Sign In
</Button>
)}
<Box>
{showSignup ? (
<Typography style={{ marginTop: 10 }}>
Already have an account?{' '}
<span onClick={() => setShowSignup(false)} className={styles.signupText}>
Sign in
</span>
</Typography>
) : (
<Typography style={{ marginTop: 10 }}>
Need an account?{' '}
<span onClick={() => setShowSignup(true)} className={styles.signupText}>
Sign up
</span>
</Typography>
)}
</Box>
</Box>
)}
</Box>
Expand Down
1 change: 1 addition & 0 deletions react-fm/src/sections/Footer/Footer.module.scss
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
.companyName {
font-weight: 600;
font-size: 20px;
margin-left: 9px;
}

.companyDetails {
Expand Down
7 changes: 5 additions & 2 deletions react-fm/src/sections/Footer/Footer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import { FlexBox } from '@/components/styled';
import useOrientation from '@/hooks/useOrientation';

import styles from './Footer.module.scss';
import mainlogo from '/logo.png';

function Footer() {
const isPortrait = useOrientation();
Expand Down Expand Up @@ -97,7 +96,11 @@ function Footer() {
<AppBar color="transparent" elevation={1} position="static" className={styles.container}>
<FlexBox className={isPortrait ? styles.mobileAppBar : styles.appBar}>
<FlexBox className={isPortrait ? styles.mobileCompanyDetails : styles.companyDetails}>
<img src={mainlogo} alt="logo" className={styles.logo} />
<img
src="https://firebasestorage.googleapis.com/v0/b/flickmatch-374a2.appspot.com/o/fm_rainbow.png?alt=media&token=1b06ae27-bf10-4974-9100-6bb5f2308314"
alt="logo"
className={styles.logo}
/>
<Typography className={styles.companyName}>Flickmatch Private Limited</Typography>
</FlexBox>
<FlexBox className={isPortrait ? styles.mobileMenuDetails : styles.menuDetails}>
Expand Down

0 comments on commit fee40d6

Please sign in to comment.