├── .gitignore
├── .prettierrc
├── README.md
├── package.json
├── public
├── favicon.ico
├── index.html
├── logo192.png
├── logo512.png
├── manifest.json
└── robots.txt
├── src
├── App.js
├── App.test.js
├── components
│ ├── auth
│ │ ├── ConfirmForm.js
│ │ └── LoginForm.js
│ ├── dashboard
│ │ └── Dashboard.js
│ ├── layout
│ │ ├── ColorModeSwitcher.js
│ │ ├── Layout.js
│ │ ├── Nav.js
│ │ └── NotFound.js
│ └── route
│ │ └── PrivateRoute.js
├── hooks
│ └── useAuth.js
├── index.js
├── reportWebVitals.js
├── serviceWorker.js
├── setupTests.js
└── test-utils.js
└── yarn.lock
/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | /node_modules
5 | /.pnp
6 | .pnp.js
7 |
8 | # testing
9 | /coverage
10 |
11 | # production
12 | /build
13 |
14 | # misc
15 | .DS_Store
16 | .env.local
17 | .env.development.local
18 | .env.test.local
19 | .env.production.local
20 |
21 | npm-debug.log*
22 | yarn-debug.log*
23 | yarn-error.log*
24 |
--------------------------------------------------------------------------------
/.prettierrc:
--------------------------------------------------------------------------------
1 | {
2 | "arrowParens": "avoid",
3 | "trailingComma": "es5",
4 | "singleQuote": true,
5 | "semi": true
6 | }
7 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Passwordless login with Firebase and React
2 |
3 | This repo is from a complete step-by-step tutorial by [Skillthrive](https://youtu.be/8Xnpipa2k2M).
4 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "firebase-auth-video",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "@chakra-ui/react": "^1.0.0",
7 | "@emotion/react": "^11.0.0",
8 | "@emotion/styled": "^11.0.0",
9 | "@testing-library/jest-dom": "^5.9.0",
10 | "@testing-library/react": "^10.2.1",
11 | "@testing-library/user-event": "^12.0.2",
12 | "firebase": "^8.2.9",
13 | "framer-motion": ">=3.0.0",
14 | "react": "^17.0.1",
15 | "react-dom": "^17.0.1",
16 | "react-hook-form": "^6.15.4",
17 | "react-icons": "^3.0.0",
18 | "react-router-dom": "^5.2.0",
19 | "react-scripts": "4.0.3",
20 | "web-vitals": "^0.2.2"
21 | },
22 | "scripts": {
23 | "start": "react-scripts start",
24 | "build": "react-scripts build",
25 | "test": "react-scripts test",
26 | "eject": "react-scripts eject"
27 | },
28 | "eslintConfig": {
29 | "extends": "react-app"
30 | },
31 | "browserslist": {
32 | "production": [
33 | ">0.2%",
34 | "not dead",
35 | "not op_mini all"
36 | ],
37 | "development": [
38 | "last 1 chrome version",
39 | "last 1 firefox version",
40 | "last 1 safari version"
41 | ]
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hunterbecton/react-firebase-passwordless/ca39b6c11bda4e22ee4c92959c5a13bf6e207133/public/favicon.ico
--------------------------------------------------------------------------------
/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
12 |
13 |
17 |
18 |
27 | React App
28 |
29 |
30 |
31 |
32 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/public/logo192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hunterbecton/react-firebase-passwordless/ca39b6c11bda4e22ee4c92959c5a13bf6e207133/public/logo192.png
--------------------------------------------------------------------------------
/public/logo512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hunterbecton/react-firebase-passwordless/ca39b6c11bda4e22ee4c92959c5a13bf6e207133/public/logo512.png
--------------------------------------------------------------------------------
/public/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "short_name": "React App",
3 | "name": "Create React App Sample",
4 | "icons": [
5 | {
6 | "src": "favicon.ico",
7 | "sizes": "64x64 32x32 24x24 16x16",
8 | "type": "image/x-icon"
9 | },
10 | {
11 | "src": "logo192.png",
12 | "type": "image/png",
13 | "sizes": "192x192"
14 | },
15 | {
16 | "src": "logo512.png",
17 | "type": "image/png",
18 | "sizes": "512x512"
19 | }
20 | ],
21 | "start_url": ".",
22 | "display": "standalone",
23 | "theme_color": "#000000",
24 | "background_color": "#ffffff"
25 | }
26 |
--------------------------------------------------------------------------------
/public/robots.txt:
--------------------------------------------------------------------------------
1 | # https://www.robotstxt.org/robotstxt.html
2 | User-agent: *
3 | Disallow:
4 |
--------------------------------------------------------------------------------
/src/App.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
3 |
4 | import Layout from './components/layout/Layout';
5 | import LoginForm from './components/auth/LoginForm';
6 | import ConfirmForm from './components/auth/ConfirmForm';
7 | import PrivateRoute from './components/route/PrivateRoute';
8 | import Dashboard from './components/dashboard/Dashboard';
9 | import NotFound from './components/layout/NotFound';
10 |
11 | function App() {
12 | return (
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 | );
32 | }
33 |
34 | export default App;
35 |
--------------------------------------------------------------------------------
/src/App.test.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { screen } from '@testing-library/react';
3 | import { render } from './test-utils';
4 | import App from './App';
5 |
6 | test('renders learn react link', () => {
7 | render();
8 | const linkElement = screen.getByText(/learn chakra/i);
9 | expect(linkElement).toBeInTheDocument();
10 | });
11 |
--------------------------------------------------------------------------------
/src/components/auth/ConfirmForm.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { useForm } from 'react-hook-form';
3 | import {
4 | Heading,
5 | GridItem,
6 | Alert,
7 | AlertIcon,
8 | FormLabel,
9 | FormControl,
10 | Input,
11 | Button,
12 | } from '@chakra-ui/react';
13 | import { useHistory, useLocation } from 'react-router-dom';
14 |
15 | import { useAuth } from '../../hooks/useAuth';
16 |
17 | const ConfirmForm = () => {
18 | const { handleSubmit, register, errors, setError, formState } = useForm();
19 |
20 | const { signInWithEmailLink } = useAuth();
21 |
22 | const history = useHistory();
23 |
24 | const location = useLocation();
25 |
26 | const onSubmit = async data => {
27 | try {
28 | await signInWithEmailLink(data.email, location.search);
29 | history.push('/');
30 | } catch (error) {
31 | setError('email', {
32 | type: 'manual',
33 | message: error.message,
34 | });
35 | }
36 | };
37 |
38 | return (
39 |
44 |
45 | Confirm Email
46 |
47 | {errors.email && (
48 |
49 |
50 | {errors.email.message}
51 |
52 | )}
53 |
67 |
68 | );
69 | };
70 |
71 | export default ConfirmForm;
72 |
--------------------------------------------------------------------------------
/src/components/auth/LoginForm.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { useForm } from 'react-hook-form';
3 | import {
4 | Heading,
5 | GridItem,
6 | Alert,
7 | AlertIcon,
8 | FormLabel,
9 | FormControl,
10 | Input,
11 | Button,
12 | } from '@chakra-ui/react';
13 |
14 | import { useAuth } from '../../hooks/useAuth';
15 |
16 | const LoginForm = () => {
17 | const { handleSubmit, register, errors, setError, formState } = useForm();
18 |
19 | const { sendSignInLinkToEmail } = useAuth();
20 |
21 | const onSubmit = async data => {
22 | try {
23 | await sendSignInLinkToEmail(data.email);
24 | } catch (error) {
25 | setError('email', {
26 | type: 'manual',
27 | message: error.message,
28 | });
29 | }
30 | };
31 |
32 | return (
33 |
38 |
39 | Login
40 |
41 | {errors.email && (
42 |
43 |
44 | {errors.email.message}
45 |
46 | )}
47 | {formState.isSubmitSuccessful && (
48 |
49 |
50 | Check your email to complete login!
51 |
52 | )}
53 |
67 |
68 | );
69 | };
70 |
71 | export default LoginForm;
72 |
--------------------------------------------------------------------------------
/src/components/dashboard/Dashboard.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { Heading, GridItem, Text } from '@chakra-ui/react';
3 |
4 | import { useAuth } from '../../hooks/useAuth';
5 |
6 | const Dashboard = () => {
7 | const { user } = useAuth();
8 |
9 | return (
10 |
15 |
16 | Dashboard
17 |
18 | Welcome, {user.email}!
19 |
20 | );
21 | };
22 |
23 | export default Dashboard;
24 |
--------------------------------------------------------------------------------
/src/components/layout/ColorModeSwitcher.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { useColorMode, useColorModeValue, IconButton } from '@chakra-ui/react';
3 | import { FaMoon, FaSun } from 'react-icons/fa';
4 |
5 | export const ColorModeSwitcher = props => {
6 | const { toggleColorMode } = useColorMode();
7 | const text = useColorModeValue('dark', 'light');
8 | const SwitchIcon = useColorModeValue(FaMoon, FaSun);
9 |
10 | return (
11 | }
20 | {...props}
21 | />
22 | );
23 | };
24 |
--------------------------------------------------------------------------------
/src/components/layout/Layout.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { Grid } from '@chakra-ui/react';
3 |
4 | import { ColorModeSwitcher } from './ColorModeSwitcher';
5 | import Nav from './Nav';
6 |
7 | const Layout = ({ children }) => {
8 | return (
9 |
16 |
17 |
18 | {children}
19 |
20 | );
21 | };
22 |
23 | export default Layout;
24 |
--------------------------------------------------------------------------------
/src/components/layout/Nav.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { GridItem, Box, Flex, Text } from '@chakra-ui/react';
3 | import { Link } from 'react-router-dom';
4 |
5 | import { useAuth } from '../../hooks/useAuth';
6 |
7 | const Nav = () => {
8 | const { user, logout } = useAuth();
9 |
10 | return (
11 |
12 |
13 | {user && (
14 | <>
15 |
16 |
17 | Dashboard
18 |
19 |
20 |
21 |
22 | Logout
23 |
24 |
25 | >
26 | )}
27 | {!user && (
28 |
29 |
30 | Login
31 |
32 |
33 | )}
34 |
35 |
36 | );
37 | };
38 |
39 | export default Nav;
40 |
--------------------------------------------------------------------------------
/src/components/layout/NotFound.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { Heading, GridItem } from '@chakra-ui/react';
3 |
4 | const NotFound = () => {
5 | return (
6 |
11 |
12 | 404: Page not found
13 |
14 |
15 | );
16 | };
17 |
18 | export default NotFound;
19 |
--------------------------------------------------------------------------------
/src/components/route/PrivateRoute.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { Route, Redirect } from 'react-router-dom';
3 |
4 | import { useAuth } from '../../hooks/useAuth';
5 |
6 | const PrivateRoute = ({ children, ...rest }) => {
7 | const { user } = useAuth();
8 |
9 | return (
10 | (user ? children : )}
13 | >
14 | );
15 | };
16 |
17 | export default PrivateRoute;
18 |
--------------------------------------------------------------------------------
/src/hooks/useAuth.js:
--------------------------------------------------------------------------------
1 | import React, { useState, useEffect, useContext, createContext } from 'react';
2 | import firebase from 'firebase/app';
3 | import 'firebase/auth';
4 |
5 | // Initialize Firebase
6 | firebase.initializeApp({
7 | apiKey: process.env.REACT_APP_FB_API,
8 | authDomain: process.env.REACT_APP_FB_DOMAIN,
9 | projectId: process.env.REACT_APP_FB_PROJECT,
10 | storageBucket: process.env.REACT_APP_FB_BUCKET,
11 | messagingSenderId: process.env.REACT_APP_FB_SENDER,
12 | appID: process.env.REACT_APP_FB_APP,
13 | });
14 |
15 | const AuthContext = createContext();
16 |
17 | // Hook for child components to get the auth object ...
18 | // ... and re-render when it changes.
19 | export const useAuth = () => {
20 | return useContext(AuthContext);
21 | };
22 |
23 | // Provider hook that creates auth object and handles state
24 | export const AuthProvider = ({ children }) => {
25 | const [user, setUser] = useState(null);
26 | const [isAuthenticating, setIsAuthenticating] = useState(true);
27 |
28 | // Wrap any Firebase methods we want to use making sure ...
29 | // ... to save the user to state.
30 | const sendSignInLinkToEmail = email => {
31 | return firebase
32 | .auth()
33 | .sendSignInLinkToEmail(email, {
34 | url: 'https://react-firebase-passwordless.vercel.app/confirm',
35 | handleCodeInApp: true,
36 | })
37 | .then(() => {
38 | return true;
39 | });
40 | };
41 |
42 | const signInWithEmailLink = (email, code) => {
43 | return firebase
44 | .auth()
45 | .signInWithEmailLink(email, code)
46 | .then(result => {
47 | setUser(result.user);
48 | return true;
49 | });
50 | };
51 |
52 | const logout = () => {
53 | return firebase
54 | .auth()
55 | .signOut()
56 | .then(() => {
57 | setUser(null);
58 | });
59 | };
60 |
61 | // Subscribe to user on mount
62 | // Because this sets state in the callback it will cause any ...
63 | // ... component that utilizes this hook to re-render with the ...
64 | // ... latest auth object.
65 | useEffect(() => {
66 | const unsubscribe = firebase.auth().onAuthStateChanged(user => {
67 | setUser(user);
68 | setIsAuthenticating(false);
69 | });
70 |
71 | // Cleanup subscription on unmount
72 | return () => unsubscribe();
73 | }, []);
74 |
75 | const values = {
76 | user,
77 | isAuthenticating,
78 | sendSignInLinkToEmail,
79 | signInWithEmailLink,
80 | logout,
81 | };
82 |
83 | return (
84 |
85 | {!isAuthenticating && children}
86 |
87 | );
88 | };
89 |
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | import { ColorModeScript } from '@chakra-ui/react';
2 | import React, { StrictMode } from 'react';
3 | import ReactDOM from 'react-dom';
4 | import { ChakraProvider, theme } from '@chakra-ui/react';
5 |
6 | import App from './App';
7 | import reportWebVitals from './reportWebVitals';
8 | import * as serviceWorker from './serviceWorker';
9 | import { AuthProvider } from './hooks/useAuth';
10 |
11 | ReactDOM.render(
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 | ,
20 | document.getElementById('root')
21 | );
22 |
23 | // If you want your app to work offline and load faster, you can change
24 | // unregister() to register() below. Note this comes with some pitfalls.
25 | // Learn more about service workers: https://cra.link/PWA
26 | serviceWorker.unregister();
27 |
28 | // If you want to start measuring performance in your app, pass a function
29 | // to log results (for example: reportWebVitals(console.log))
30 | // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
31 | reportWebVitals();
32 |
--------------------------------------------------------------------------------
/src/reportWebVitals.js:
--------------------------------------------------------------------------------
1 | const reportWebVitals = onPerfEntry => {
2 | if (onPerfEntry && onPerfEntry instanceof Function) {
3 | import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
4 | getCLS(onPerfEntry);
5 | getFID(onPerfEntry);
6 | getFCP(onPerfEntry);
7 | getLCP(onPerfEntry);
8 | getTTFB(onPerfEntry);
9 | });
10 | }
11 | };
12 |
13 | export default reportWebVitals;
14 |
--------------------------------------------------------------------------------
/src/serviceWorker.js:
--------------------------------------------------------------------------------
1 | // This optional code is used to register a service worker.
2 | // register() is not called by default.
3 |
4 | // This lets the app load faster on subsequent visits in production, and gives
5 | // it offline capabilities. However, it also means that developers (and users)
6 | // will only see deployed updates on subsequent visits to a page, after all the
7 | // existing tabs open on the page have been closed, since previously cached
8 | // resources are updated in the background.
9 |
10 | // To learn more about the benefits of this model and instructions on how to
11 | // opt-in, read https://cra.link/PWA
12 |
13 | const isLocalhost = Boolean(
14 | window.location.hostname === 'localhost' ||
15 | // [::1] is the IPv6 localhost address.
16 | window.location.hostname === '[::1]' ||
17 | // 127.0.0.0/8 are considered localhost for IPv4.
18 | window.location.hostname.match(
19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
20 | )
21 | );
22 |
23 | export function register(config) {
24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
25 | // The URL constructor is available in all browsers that support SW.
26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
27 | if (publicUrl.origin !== window.location.origin) {
28 | // Our service worker won't work if PUBLIC_URL is on a different origin
29 | // from what our page is served on. This might happen if a CDN is used to
30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374
31 | return;
32 | }
33 |
34 | window.addEventListener('load', () => {
35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
36 |
37 | if (isLocalhost) {
38 | // This is running on localhost. Let's check if a service worker still exists or not.
39 | checkValidServiceWorker(swUrl, config);
40 |
41 | // Add some additional logging to localhost, pointing developers to the
42 | // service worker/PWA documentation.
43 | navigator.serviceWorker.ready.then(() => {
44 | console.log(
45 | 'This web app is being served cache-first by a service ' +
46 | 'worker. To learn more, visit https://cra.link/PWA'
47 | );
48 | });
49 | } else {
50 | // Is not localhost. Just register service worker
51 | registerValidSW(swUrl, config);
52 | }
53 | });
54 | }
55 | }
56 |
57 | function registerValidSW(swUrl, config) {
58 | navigator.serviceWorker
59 | .register(swUrl)
60 | .then(registration => {
61 | registration.onupdatefound = () => {
62 | const installingWorker = registration.installing;
63 | if (installingWorker == null) {
64 | return;
65 | }
66 | installingWorker.onstatechange = () => {
67 | if (installingWorker.state === 'installed') {
68 | if (navigator.serviceWorker.controller) {
69 | // At this point, the updated precached content has been fetched,
70 | // but the previous service worker will still serve the older
71 | // content until all client tabs are closed.
72 | console.log(
73 | 'New content is available and will be used when all ' +
74 | 'tabs for this page are closed. See https://cra.link/PWA.'
75 | );
76 |
77 | // Execute callback
78 | if (config && config.onUpdate) {
79 | config.onUpdate(registration);
80 | }
81 | } else {
82 | // At this point, everything has been precached.
83 | // It is the perfect time to display a
84 | // "Content is cached for offline use." message.
85 | console.log('Content is cached for offline use.');
86 |
87 | // Execute callback
88 | if (config && config.onSuccess) {
89 | config.onSuccess(registration);
90 | }
91 | }
92 | }
93 | };
94 | };
95 | })
96 | .catch(error => {
97 | console.error('Error during service worker registration:', error);
98 | });
99 | }
100 |
101 | function checkValidServiceWorker(swUrl, config) {
102 | // Check if the service worker can be found. If it can't reload the page.
103 | fetch(swUrl, {
104 | headers: { 'Service-Worker': 'script' },
105 | })
106 | .then(response => {
107 | // Ensure service worker exists, and that we really are getting a JS file.
108 | const contentType = response.headers.get('content-type');
109 | if (
110 | response.status === 404 ||
111 | (contentType != null && contentType.indexOf('javascript') === -1)
112 | ) {
113 | // No service worker found. Probably a different app. Reload the page.
114 | navigator.serviceWorker.ready.then(registration => {
115 | registration.unregister().then(() => {
116 | window.location.reload();
117 | });
118 | });
119 | } else {
120 | // Service worker found. Proceed as normal.
121 | registerValidSW(swUrl, config);
122 | }
123 | })
124 | .catch(() => {
125 | console.log(
126 | 'No internet connection found. App is running in offline mode.'
127 | );
128 | });
129 | }
130 |
131 | export function unregister() {
132 | if ('serviceWorker' in navigator) {
133 | navigator.serviceWorker.ready
134 | .then(registration => {
135 | registration.unregister();
136 | })
137 | .catch(error => {
138 | console.error(error.message);
139 | });
140 | }
141 | }
142 |
--------------------------------------------------------------------------------
/src/setupTests.js:
--------------------------------------------------------------------------------
1 | // jest-dom adds custom jest matchers for asserting on DOM nodes.
2 | // allows you to do things like:
3 | // expect(element).toHaveTextContent(/react/i)
4 | // learn more: https://github.com/testing-library/jest-dom
5 | import '@testing-library/jest-dom';
6 |
--------------------------------------------------------------------------------
/src/test-utils.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { render } from '@testing-library/react';
3 | import { ChakraProvider, theme } from '@chakra-ui/react';
4 |
5 | const AllProviders = ({ children }) => (
6 | {children}
7 | );
8 |
9 | const customRender = (ui, options) =>
10 | render(ui, { wrapper: AllProviders, ...options });
11 |
12 | export { customRender as render };
13 |
--------------------------------------------------------------------------------