├── .env.example
├── .gitignore
├── README.md
├── package-lock.json
├── package.json
├── public
├── favicon.ico
├── index.html
├── logo192.png
├── logo512.png
├── manifest.json
└── robots.txt
├── src
├── App.css
├── App.test.tsx
├── App.tsx
├── AuthProvider.tsx
├── PrivateRoute.jsx
├── config
│ ├── ApplicationRoutes.tsx
│ └── firebase.ts
├── firebase.ts
├── index.css
├── index.tsx
├── logo.svg
├── react-app-env.d.ts
├── serviceWorker.ts
├── setupTests.ts
└── views
│ ├── Auth
│ ├── components
│ │ ├── index.ts
│ │ ├── login.tsx
│ │ └── signup.tsx
│ ├── config
│ │ └── AuthRoutes.tsx
│ └── index.ts
│ └── Dashboard
│ ├── components
│ ├── dashboard.tsx
│ └── index.ts
│ ├── config
│ └── DashboardRoutes.tsx
│ └── index.ts
├── tsconfig.json
└── yarn.lock
/.env.example:
--------------------------------------------------------------------------------
1 | REACT_APP_API_KEY=ABCDKDKDKKDLDLLSMDFKSDMFKDSFSDFSDMFKSD
2 | REACT_APP_AUTH_DOMAIN=fir-authentication-firehizekin.firebaseapp.com
3 | REACT_APP_DATABASE_URL=https://fir-authentication-firehizekin.firebaseio.com
4 | REACT_APP_PROJECT_ID=fir-authentication-firehizekin
5 | REACT_APP_STORAGE_BUCKET=fir-authentication-firehizekin.appspot.com
6 | REACT_APP_MESSAGING_SENDER_ID=433323234
7 | REACT_APP_ID=1:719405984917:web:jdfdkfsjd4kk4k4544
8 | REACT_APP_MEASUREMENT_ID=H-fdsfsmjds433
--------------------------------------------------------------------------------
/.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 |
25 | .env
26 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
2 |
3 | ## Available Scripts
4 |
5 | In the project directory, you can run:
6 | ### `npm install`
7 | Installs project dependencies
8 |
9 | ### `npm start`
10 |
11 | Runs the app in the development mode.
12 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
13 |
14 | The page will reload if you make edits.
15 | You will also see any lint errors in the console.
16 |
17 |
18 | ## Configuring environment and firebase
19 | Refer to the .env.example file to know about how you have to enter firebase keys and configuration. Create .env file and put your own configuration there. The file .env.example consists fake credentials.
20 |
21 | ## Learn More
22 |
23 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
24 |
25 | To learn React, check out the [React documentation](https://reactjs.org/).
26 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-authentication",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "@testing-library/jest-dom": "^4.2.4",
7 | "@testing-library/react": "^9.3.2",
8 | "@testing-library/user-event": "^7.1.2",
9 | "@types/jest": "^24.9.1",
10 | "@types/node": "^12.12.28",
11 | "@types/react": "^16.9.22",
12 | "@types/react-dom": "^16.9.5",
13 | "@types/react-router-dom": "^5.1.3",
14 | "firebase": "^7.9.1",
15 | "react": "^16.12.0",
16 | "react-dom": "^16.12.0",
17 | "react-firebase": "^2.2.8",
18 | "react-router-dom": "^5.1.2",
19 | "react-scripts": "3.4.0",
20 | "typescript": "^3.7.5"
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/SudeepTimalsina/firebase-react-authentication/ab72f0b1230885c59c391b4a0233d9ab10dad5d0/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/SudeepTimalsina/firebase-react-authentication/ab72f0b1230885c59c391b4a0233d9ab10dad5d0/public/logo192.png
--------------------------------------------------------------------------------
/public/logo512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SudeepTimalsina/firebase-react-authentication/ab72f0b1230885c59c391b4a0233d9ab10dad5d0/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.css:
--------------------------------------------------------------------------------
1 | .App {
2 | text-align: center;
3 | }
4 |
5 | .App-logo {
6 | height: 40vmin;
7 | pointer-events: none;
8 | }
9 |
10 | @media (prefers-reduced-motion: no-preference) {
11 | .App-logo {
12 | animation: App-logo-spin infinite 20s linear;
13 | }
14 | }
15 |
16 | .App-header {
17 | background-color: #282c34;
18 | min-height: 100vh;
19 | display: flex;
20 | flex-direction: column;
21 | align-items: center;
22 | justify-content: center;
23 | font-size: calc(10px + 2vmin);
24 | color: white;
25 | }
26 |
27 | .App-link {
28 | color: #61dafb;
29 | }
30 |
31 | @keyframes App-logo-spin {
32 | from {
33 | transform: rotate(0deg);
34 | }
35 | to {
36 | transform: rotate(360deg);
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/App.test.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { render } from '@testing-library/react';
3 | import App from './App';
4 |
5 | test('renders learn react link', () => {
6 | const { getByText } = render();
7 | const linkElement = getByText(/learn react/i);
8 | expect(linkElement).toBeInTheDocument();
9 | });
10 |
--------------------------------------------------------------------------------
/src/App.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import './App.css';
3 | import ApplicationRoutes from './config/ApplicationRoutes';
4 |
5 | function App() {
6 | return (
7 |
8 | );
9 | }
10 |
11 | export default App;
12 |
--------------------------------------------------------------------------------
/src/AuthProvider.tsx:
--------------------------------------------------------------------------------
1 | import React, { useEffect, useState } from "react";
2 | import firebase from "./firebase";
3 |
4 | type ContextProps = {
5 | user: firebase.User | null;
6 | authenticated: boolean;
7 | setUser: any;
8 | loadingAuthState: boolean;
9 | };
10 |
11 | export const AuthContext = React.createContext>({});
12 |
13 | export const AuthProvider = ({ children }: any) => {
14 | const [user, setUser] = useState(null as firebase.User | null);
15 | const [loadingAuthState, setLoadingAuthState] = useState(true);
16 |
17 | useEffect(() => {
18 | firebase.auth().onAuthStateChanged((user: any) => {
19 | setUser(user);
20 | setLoadingAuthState(false);
21 | console.log(user, 'ap user');
22 | console.log(user !== null, 'ap authenticated');
23 | });
24 | }, []);
25 |
26 | return (
27 |
34 | {children}
35 |
36 | );
37 | }
--------------------------------------------------------------------------------
/src/PrivateRoute.jsx:
--------------------------------------------------------------------------------
1 | import React, { useContext } from "react";
2 | import { Route, Redirect } from "react-router-dom";
3 | import { AuthContext } from "./AuthProvider";
4 |
5 | const PrivateRoute = ({ component: RouteComponent, ...rest}) => {
6 | const {authenticated, loadingAuthState} = useContext(AuthContext);
7 |
8 | if (loadingAuthState) {
9 | return (
10 |
11 |
Loading...
12 |
13 | );
14 | }
15 |
16 | return (
17 |
20 | authenticated ? (
21 |
22 | ) : (
23 |
24 | )
25 | }
26 | />
27 | );
28 | }
29 |
30 | export default PrivateRoute
--------------------------------------------------------------------------------
/src/config/ApplicationRoutes.tsx:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import { BrowserRouter as Router, Route, Switch, Redirect } from "react-router-dom";
3 | import { AuthRoutes } from "../views/Auth";
4 | import PrivateRoute from "../PrivateRoute";
5 | import { DashboardRoutes } from "../views/Dashboard";
6 | // import { Dashboard } from "../views/Dashboard/components";
7 |
8 | const ApplicationRoutes = () => {
9 | return (
10 |
11 |
12 |
13 |
14 |
15 | {/* */}
16 |
17 |
18 | );
19 | }
20 |
21 | export default ApplicationRoutes;
--------------------------------------------------------------------------------
/src/config/firebase.ts:
--------------------------------------------------------------------------------
1 | let firebaseConfig = {
2 | apiKey: process.env.REACT_APP_API_KEY,
3 | authDomain: process.env.REACT_APP_AUTH_DOMAIN,
4 | databaseURL: process.env.REACT_APP_DATABASE_URL,
5 | projectId: process.env.REACT_APP_PROJECT_ID,
6 | storageBucket: process.env.REACT_APP_STORAGE_BUCKET,
7 | messagingSenderId: process.env.REACT_APP_MESSAGING_SENDER_ID,
8 | appId: process.env.REAT_APP_ID,
9 | measurementId: process.env.REACT_APP_MEASUREMENT_ID
10 | };
11 |
12 | export default firebaseConfig;
--------------------------------------------------------------------------------
/src/firebase.ts:
--------------------------------------------------------------------------------
1 | import firebase from "firebase/app";
2 | import firebaseConfig from "./config/firebase";
3 |
4 | firebase.initializeApp(firebaseConfig);
5 |
6 | export default firebase;
--------------------------------------------------------------------------------
/src/index.css:
--------------------------------------------------------------------------------
1 | body {
2 | margin: 0;
3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
5 | sans-serif;
6 | -webkit-font-smoothing: antialiased;
7 | -moz-osx-font-smoothing: grayscale;
8 | }
9 |
10 | code {
11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
12 | monospace;
13 | }
14 |
--------------------------------------------------------------------------------
/src/index.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import './index.css';
4 | import App from './App';
5 | import * as serviceWorker from './serviceWorker';
6 | import {AuthProvider} from './AuthProvider';
7 |
8 | ReactDOM.render( , document.getElementById('root'));
9 |
10 | // If you want your app to work offline and load faster, you can change
11 | // unregister() to register() below. Note this comes with some pitfalls.
12 | // Learn more about service workers: https://bit.ly/CRA-PWA
13 | serviceWorker.unregister();
14 |
--------------------------------------------------------------------------------
/src/logo.svg:
--------------------------------------------------------------------------------
1 |
8 |
--------------------------------------------------------------------------------
/src/react-app-env.d.ts:
--------------------------------------------------------------------------------
1 | ///
2 |
--------------------------------------------------------------------------------
/src/serviceWorker.ts:
--------------------------------------------------------------------------------
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://bit.ly/CRA-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 | type Config = {
24 | onSuccess?: (registration: ServiceWorkerRegistration) => void;
25 | onUpdate?: (registration: ServiceWorkerRegistration) => void;
26 | };
27 |
28 | export function register(config?: Config) {
29 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
30 | // The URL constructor is available in all browsers that support SW.
31 | const publicUrl = new URL(
32 | process.env.PUBLIC_URL,
33 | window.location.href
34 | );
35 | if (publicUrl.origin !== window.location.origin) {
36 | // Our service worker won't work if PUBLIC_URL is on a different origin
37 | // from what our page is served on. This might happen if a CDN is used to
38 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374
39 | return;
40 | }
41 |
42 | window.addEventListener('load', () => {
43 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
44 |
45 | if (isLocalhost) {
46 | // This is running on localhost. Let's check if a service worker still exists or not.
47 | checkValidServiceWorker(swUrl, config);
48 |
49 | // Add some additional logging to localhost, pointing developers to the
50 | // service worker/PWA documentation.
51 | navigator.serviceWorker.ready.then(() => {
52 | console.log(
53 | 'This web app is being served cache-first by a service ' +
54 | 'worker. To learn more, visit https://bit.ly/CRA-PWA'
55 | );
56 | });
57 | } else {
58 | // Is not localhost. Just register service worker
59 | registerValidSW(swUrl, config);
60 | }
61 | });
62 | }
63 | }
64 |
65 | function registerValidSW(swUrl: string, config?: Config) {
66 | navigator.serviceWorker
67 | .register(swUrl)
68 | .then(registration => {
69 | registration.onupdatefound = () => {
70 | const installingWorker = registration.installing;
71 | if (installingWorker == null) {
72 | return;
73 | }
74 | installingWorker.onstatechange = () => {
75 | if (installingWorker.state === 'installed') {
76 | if (navigator.serviceWorker.controller) {
77 | // At this point, the updated precached content has been fetched,
78 | // but the previous service worker will still serve the older
79 | // content until all client tabs are closed.
80 | console.log(
81 | 'New content is available and will be used when all ' +
82 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
83 | );
84 |
85 | // Execute callback
86 | if (config && config.onUpdate) {
87 | config.onUpdate(registration);
88 | }
89 | } else {
90 | // At this point, everything has been precached.
91 | // It's the perfect time to display a
92 | // "Content is cached for offline use." message.
93 | console.log('Content is cached for offline use.');
94 |
95 | // Execute callback
96 | if (config && config.onSuccess) {
97 | config.onSuccess(registration);
98 | }
99 | }
100 | }
101 | };
102 | };
103 | })
104 | .catch(error => {
105 | console.error('Error during service worker registration:', error);
106 | });
107 | }
108 |
109 | function checkValidServiceWorker(swUrl: string, config?: Config) {
110 | // Check if the service worker can be found. If it can't reload the page.
111 | fetch(swUrl, {
112 | headers: { 'Service-Worker': 'script' }
113 | })
114 | .then(response => {
115 | // Ensure service worker exists, and that we really are getting a JS file.
116 | const contentType = response.headers.get('content-type');
117 | if (
118 | response.status === 404 ||
119 | (contentType != null && contentType.indexOf('javascript') === -1)
120 | ) {
121 | // No service worker found. Probably a different app. Reload the page.
122 | navigator.serviceWorker.ready.then(registration => {
123 | registration.unregister().then(() => {
124 | window.location.reload();
125 | });
126 | });
127 | } else {
128 | // Service worker found. Proceed as normal.
129 | registerValidSW(swUrl, config);
130 | }
131 | })
132 | .catch(() => {
133 | console.log(
134 | 'No internet connection found. App is running in offline mode.'
135 | );
136 | });
137 | }
138 |
139 | export function unregister() {
140 | if ('serviceWorker' in navigator) {
141 | navigator.serviceWorker.ready
142 | .then(registration => {
143 | registration.unregister();
144 | })
145 | .catch(error => {
146 | console.error(error.message);
147 | });
148 | }
149 | }
150 |
--------------------------------------------------------------------------------
/src/setupTests.ts:
--------------------------------------------------------------------------------
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/extend-expect';
6 |
--------------------------------------------------------------------------------
/src/views/Auth/components/index.ts:
--------------------------------------------------------------------------------
1 | import SignUp from "./signup";
2 | import Login from "./login";
3 |
4 | export { SignUp, Login };
--------------------------------------------------------------------------------
/src/views/Auth/components/login.tsx:
--------------------------------------------------------------------------------
1 | import React, { useState, useContext, useEffect } from "react";
2 | import { useHistory } from "react-router-dom";
3 | import firebase from "../../../firebase";
4 | import "firebase/auth";
5 | import "firebase/firestore";
6 | import { AuthContext } from "../../../AuthProvider";
7 |
8 | interface UserData {
9 | email: string;
10 | password: string;
11 | }
12 |
13 | const Login = () => {
14 | const authContext = useContext(AuthContext);
15 | const {loadingAuthState} = useContext(AuthContext);
16 | const history = useHistory();
17 | const [values, setValues] = useState({
18 | email: "",
19 | password: ""
20 | } as UserData);
21 |
22 | const db = firebase.firestore();
23 |
24 | useEffect(() => {
25 | firebase
26 | .auth()
27 | .getRedirectResult()
28 | .then(result => {
29 | if (!result || !result.user || !firebase.auth().currentUser) {
30 | return;
31 | }
32 |
33 | return setUserProfile().then(() => {
34 | redirectToTargetPage();
35 | });
36 | })
37 | .catch(error => {
38 | console.log(error, 'error');
39 | });
40 |
41 | }, []);
42 |
43 | const setUserProfile = async () => {
44 | if (await isUserExists()) {
45 | return;
46 | }
47 |
48 | const currentUser = firebase.auth().currentUser!;
49 | db
50 | .collection("Users")
51 | .doc(currentUser.uid)
52 | .set({
53 | username: currentUser.displayName
54 | })
55 | .then(() => {
56 | console.log('Saved');
57 | return;
58 | })
59 | .catch(error => {
60 | console.log(error.message);
61 | alert(error.message);
62 | })
63 | }
64 |
65 | const isUserExists = async () => {
66 | const doc = await db
67 | .collection("users")
68 | .doc(firebase.auth().currentUser!.uid)
69 | .get()
70 | return doc.exists;
71 | }
72 |
73 | const redirectToTargetPage = () => {
74 | history.push("/dashboard");
75 | }
76 |
77 | const handleClick = () => {
78 | history.push("/auth/signup")
79 | }
80 |
81 | const handleChange = (event: any) => {
82 | event.persist();
83 | setValues(values => ({
84 | ...values,
85 | [event.target.name]: event.target.value
86 | }));
87 | }
88 |
89 | const handleSubmit = (event: any) => {
90 | event.preventDefault();
91 |
92 | firebase
93 | .auth()
94 | .signInWithEmailAndPassword(values.email, values.password)
95 | .then(res => {
96 | authContext.setUser(res);
97 | console.log(res, 'res')
98 | history.push("/dashboard");
99 | })
100 | .catch(error => {
101 | console.log(error.message);
102 | alert(error.message);
103 | });
104 | }
105 |
106 | const handleSocialClick = (sns: any) => {
107 | console.log(sns, 'sns');
108 |
109 | let provider: firebase.auth.AuthProvider;
110 | switch (sns) {
111 | case "Facebook":
112 | provider = new firebase.auth.FacebookAuthProvider();
113 | console.log(provider, 'fbprovider');
114 | break;
115 |
116 | case "Google":
117 | provider = new firebase.auth.GoogleAuthProvider();
118 | console.log(provider, 'gprovider');
119 | break;
120 |
121 | case "Twitter":
122 | provider = new firebase.auth.TwitterAuthProvider();
123 | break;
124 |
125 | default:
126 | throw new Error("Unsupported SNS" + sns)
127 | }
128 |
129 | firebase
130 | .auth()
131 | .signInWithRedirect(provider)
132 | .catch(handleAuthError);
133 | }
134 |
135 | const handleAuthError = (error: firebase.auth.Error) => {
136 | console.log(error)
137 | }
138 |
139 | if (loadingAuthState) {
140 | return (
141 |
142 |
Loading...
143 |
144 | );
145 | }
146 |
147 | return (
148 |
149 |
Login
150 |
157 |
158 |
Social SignUp
159 |
160 |
161 |
162 |
163 | );
164 | }
165 |
166 | export default Login;
--------------------------------------------------------------------------------
/src/views/Auth/components/signup.tsx:
--------------------------------------------------------------------------------
1 | import React, { useState, useContext } from "react";
2 | import { useHistory } from "react-router-dom";
3 | import firebase from "../../../firebase";
4 | import "firebase/auth";
5 | import "firebase/firestore";
6 | import { AuthContext } from "../../../AuthProvider";
7 |
8 | interface FormItems {
9 | username: string;
10 | phone: string;
11 | email: string;
12 | password: string;
13 | }
14 |
15 | const SignUp = () => {
16 | const authContext = useContext(AuthContext);
17 | const [values, setValues] = useState({
18 | username: "",
19 | email: "",
20 | password: "",
21 | phone: ""
22 | } as FormItems);
23 |
24 | const history = useHistory();
25 |
26 | const handleClick = () => {
27 | history.push("/auth/login")
28 | }
29 |
30 | const handleChange = (event: any) => {
31 | event.persist();
32 | setValues(values => ({
33 | ...values,
34 | [event.target.name]: event.target.value
35 | }));
36 |
37 | }
38 |
39 | const handleSubmit = (event: any) => {
40 | event?.preventDefault();
41 | console.log(values, 'values');
42 | firebase
43 | .auth()
44 | .createUserWithEmailAndPassword(values.email, values.password)
45 | .then((userCredential : firebase.auth.UserCredential) => {
46 | authContext.setUser(userCredential);
47 | const db = firebase.firestore();
48 | db.collection("Users")
49 | .doc(userCredential.user!.uid)
50 | .set({
51 | email: values.email,
52 | username: values.username,
53 | phone: values.phone
54 | })
55 | .then(() => {
56 | console.log('ok');
57 | history.push("/dashboard");
58 | })
59 | .catch(error => {
60 | console.log(error.message);
61 | alert(error.message);
62 | });
63 | })
64 |
65 | }
66 | return (
67 |
79 | );
80 | }
81 |
82 | export default SignUp;
--------------------------------------------------------------------------------
/src/views/Auth/config/AuthRoutes.tsx:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import { Route, Switch, Redirect } from "react-router-dom";
3 | import { SignUp, Login } from "../../Auth/components";
4 |
5 | export const AuthRoutes = () => {
6 | return (
7 |
8 |
9 |
10 |
11 |
12 | );
13 | };
--------------------------------------------------------------------------------
/src/views/Auth/index.ts:
--------------------------------------------------------------------------------
1 | export { AuthRoutes } from "../Auth/config/AuthRoutes";
--------------------------------------------------------------------------------
/src/views/Dashboard/components/dashboard.tsx:
--------------------------------------------------------------------------------
1 | import React, {useState, useEffect} from "react";
2 | import { useHistory } from "react-router-dom";
3 | import firebase from "../../../firebase";
4 | import "firebase/firestore";
5 |
6 | const Dashboard = () => {
7 | const [userName, setUserName] = useState();
8 | const history = useHistory();
9 |
10 | const handleClick = (event: any) => {
11 | event.preventDefault();
12 |
13 | firebase
14 | .auth()
15 | .signOut()
16 | .then(res => {
17 | history.push("/auth/login");
18 | })
19 | }
20 |
21 | useEffect(() => {
22 | const db = firebase.firestore();
23 | db
24 | .collection("Users")
25 | .doc(firebase.auth().currentUser!.uid)
26 | .get()
27 | .then(res => {
28 | const user = res.data();
29 | if (user) {
30 | setUserName(user['username'])
31 | }
32 | })
33 | }, []);
34 |
35 | return (
36 |
37 |
Dashboard
38 | Welcome to Dashboard!
39 | {userName}
40 |
41 |
42 | );
43 | }
44 |
45 | export default Dashboard;
--------------------------------------------------------------------------------
/src/views/Dashboard/components/index.ts:
--------------------------------------------------------------------------------
1 | import Dashboard from "./dashboard";
2 |
3 | export {Dashboard};
--------------------------------------------------------------------------------
/src/views/Dashboard/config/DashboardRoutes.tsx:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import {Route, Switch } from "react-router-dom";
3 | import { Dashboard } from "../components";
4 |
5 | export const DashboardRoutes = () => {
6 | return (
7 |
8 |
9 |
10 | );
11 | }
--------------------------------------------------------------------------------
/src/views/Dashboard/index.ts:
--------------------------------------------------------------------------------
1 | export { DashboardRoutes } from "../Dashboard/config/DashboardRoutes";
2 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "es5",
4 | "lib": [
5 | "dom",
6 | "dom.iterable",
7 | "esnext"
8 | ],
9 | "allowJs": true,
10 | "skipLibCheck": true,
11 | "esModuleInterop": true,
12 | "allowSyntheticDefaultImports": true,
13 | "strict": true,
14 | "forceConsistentCasingInFileNames": true,
15 | "module": "esnext",
16 | "moduleResolution": "node",
17 | "resolveJsonModule": true,
18 | "isolatedModules": true,
19 | "noEmit": true,
20 | "jsx": "react"
21 | },
22 | "include": [
23 | "src"
24 | ]
25 | }
26 |
--------------------------------------------------------------------------------