good spot withh auth

This commit is contained in:
Arjun Patel
2022-01-12 23:52:58 -08:00
parent a83e319c78
commit 3e37774238
8 changed files with 167 additions and 65 deletions
+83
View File
@@ -0,0 +1,83 @@
import { getAuth, GoogleAuthProvider, onAuthStateChanged, signInWithPopup, User } from "firebase/auth";
import React, { useContext, useEffect, useState } from "react";
import { useRouter } from 'next/router'
import firebase from '../services/firebase'
const AuthContext = React.createContext(null);
const googleProvider = new GoogleAuthProvider()
const auth = getAuth();
export function AuthProvider({ children }) {
const [currUser, setCurrUser] = useState(null);
const [loading, setLoading] = useState(true)
const router = useRouter()
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, user => {
setLoading(false)
console.log(user)
// will be null or the firebase logged in user
setCurrUser(user)
});
return unsubscribe
}, [])
const signInGoogle = () => {
signInWithPopup(auth, googleProvider).then((res) => {
// This gives you a Google Access Token. You can use it to access the Google API.
const credential = GoogleAuthProvider.credentialFromResult(result);
const token = credential.accessToken;
// The signed-in user info.
const user = result.user;
setCurrUser(user)
console.log(user)
}).catch((error) => {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error.message;
// The email of the user's account used.
const email = error.email;
// The AuthCredential type that was used.
const credential = GoogleAuthProvider.credentialFromError(error);
console.log(error)
})
}
const signOut = () => {
console.log('logging user out')
signOut(auth).then(() => {
// Sign-out successful.
console.log("signed out fine, redirecting to proper place")
router.push('/')
}).catch((error) => {
// An error happened.
console.log(error)
});
}
const value = {
currUser,
signInGoogle,
signOut
}
return (
<AuthContext.Provider value={value}>
{!loading && children}
</AuthContext.Provider>
)
}
// custom hook to use the authUserContext and access currUser
export function useAuth() {
return useContext(AuthContext)
}
-37
View File
@@ -1,37 +0,0 @@
import { getAuth, onAuthStateChanged, User } from "firebase/auth";
import React, { useContext, useEffect, useState } from "react";
const AuthContext = React.createContext(null);
export function useAuth() {
return useContext(AuthContext)
}
export function AuthProvider({ children }) {
const [currUser, setCurrUser] = useState<null | User>(null);
function loginSignup() {
return
}
useEffect(() => {
const unsubscribe = getAuth().onAuthStateChanged(user => {
// will be null or the firebase logged in user
setCurrUser(user)
});
return unsubscribe
}, [])
const value = {
currUser
}
return (
<AuthContext.Provider value={value}>
{children}
</AuthContext.Provider>
)
}
-25
View File
@@ -1,25 +0,0 @@
// Import the functions you need from the SDKs you need
import firebase from "firebase/app";
import { getAnalytics } from "firebase/analytics";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_APIKEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_MESSAGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_APPID,
measurementId: process.env.NEXT_PUBLIC_MEASUREMENT_ID
};
// Initialize Firebase
const app = firebase.initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
export default app;
+4 -1
View File
@@ -1,6 +1,7 @@
import '../styles/globals.css'
import 'antd/dist/antd.css';
import Head from 'next/head'
import { AuthProvider } from '../contexts/authContext'
function MyApp({ Component, pageProps }) {
return <>
@@ -32,7 +33,9 @@ function MyApp({ Component, pageProps }) {
</Head>
<main>
<Component {...pageProps} />
<AuthProvider>
<Component {...pageProps} />
</AuthProvider>
</main>
</>
}
+25
View File
@@ -0,0 +1,25 @@
import { useRouter } from 'next/router'
import { useEffect } from 'react'
import { useAuth } from '../../contexts/authContext'
export default function Dashboard() {
const { currUser, signOut } = useAuth()
const router = useRouter()
useEffect(() => {
// if not authed, go to home
if (!currUser) {
console.log('routing from dashboard to teams home')
router.push('/teams')
}
}, [])
return (
<div>
<h1 className='text-white'>This is the dashboard</h1>
<button onClick={signOut} className='mt-10 text-sm text-orange-500 font-semibold py-1 px-4 bg-orange-200 rounded'>👋 Logout</button>
</div>
)
}
+5
View File
@@ -1,6 +1,7 @@
import Head from 'next/head';
import Image from 'next/image';
import styles from '/styles/Home.module.css';
import Link from 'next/link';
export default function Home() {
return (
@@ -70,6 +71,10 @@ export default function Home() {
<p id="side-note">
why? we live in a distracted world. let&apos;s fix it, because less is more.
</p>
<Link exact href='/teams/login' className='text-3xl text-white'>
<button className='mt-10 text-sm text-emerald-500 font-semibold py-1 px-4 bg-gray-200 rounded'>👋 Login</button>
</Link>
</main>
</div>
);
+17 -2
View File
@@ -1,13 +1,28 @@
import { useRouter } from 'next/router'
import { useEffect } from 'react';
import {FaGoogle} from "react-icons/fa";
import { useAuth } from '../../contexts/authContext'
export default function Login() {
const { currUser, signInGoogle } = useAuth()
const router = useRouter()
useEffect(() => {
// if auth, go to dashboard
if (currUser) {
console.log('already logged in, redirecting to the dashboard')
router.push('/teams/dashboard')
}
}, [currUser])
return (
<div className="container mx-auto max-w-screen-sm bg-white bg-opacity-80 mt-20 p-10 rounded-lg shadow-lg flex flex-col items-start">
<button className='mx-auto text-md text-sky-500 py-2 px-5 bg-gray-200 rounded flex flex-row items-center space-x-2 shadow-lg'>
<button onClick={signInGoogle} className='mx-auto text-md text-sky-500 py-2 px-5 bg-gray-200 rounded flex flex-row items-center space-x-2 shadow-lg'>
<FaGoogle />
<span>Continue with Google</span>
</button>
{JSON.stringify(currUser?.email)}
</div>
)
}
+33
View File
@@ -0,0 +1,33 @@
// const firebaseConfig = {
// apiKey: process.env.NEXT_PUBLIC_FIREBASE_APIKEY,
// authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
// projectId: process.env.NEXT_PUBLIC_PROJECT_ID,
// storageBucket: process.env.NEXT_PUBLIC_STORAGE_BUCKET,
// messagingSenderId: process.env.NEXT_PUBLIC_MESSAGING_SENDER_ID,
// appId: process.env.NEXT_PUBLIC_APPID,
// measurementId: process.env.NEXT_PUBLIC_MEASUREMENT_ID
// };
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "AIzaSyAr3iEcoduqDv0IW9czwmt3Yqp5StZED0w",
authDomain: "nirvana-for-business.firebaseapp.com",
projectId: "nirvana-for-business",
storageBucket: "nirvana-for-business.appspot.com",
messagingSenderId: "825654222284",
appId: "1:825654222284:web:0778c8883de21917b51169",
measurementId: "G-MB5G7G09MR"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);