Skip to content

Commit d8e3180

Browse files
committedSep 19, 2017
init
0 parents  commit d8e3180

28 files changed

+11157
-0
lines changed
 

‎.gitignore

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# See https://help.github.com/ignore-files/ for more about ignoring files.
2+
3+
# dependencies
4+
/node_modules
5+
6+
# testing
7+
/coverage
8+
9+
# production
10+
/build
11+
12+
# misc
13+
.DS_Store
14+
.env.local
15+
.env.development.local
16+
.env.test.local
17+
.env.production.local
18+
19+
npm-debug.log*
20+
yarn-debug.log*
21+
yarn-error.log*

‎README.md

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# react-redux-firebase-authentication
2+
3+
* Found in [Taming the State in React](https://roadtoreact.com/course-details?courseId=TAMING_THE_STATE)
4+
* [Live](https://react-firebase-authentication.wieruch.com/)
5+
6+
## Features
7+
8+
* uses:
9+
* React (create-react-app)
10+
* firebase 4.3.1
11+
* react-router 4.2.0
12+
* redux
13+
* features:
14+
* Sign In
15+
* Sign Up
16+
* Sign Out
17+
* Password Forget
18+
* Password Change
19+
* Protected Routes with Authorization
20+
* Database: Users
21+
22+
## Installation
23+
24+
* `git clone git@github.com:rwieruch/react-redux-firebase-authentication.git`
25+
* `cd react-redux-firebase-authentication`
26+
* `npm install`
27+
* `npm start`
28+
* visit http://localhost:3000/
29+
* Use your own Firebase Credentials
30+
31+
### Use your own Firebase Credentials
32+
33+
* visit https://firebase.google.com/ and create a Firebase App
34+
* copy and paste your Credentials from your Firebase App into src/firebase/firebase.js
35+
* activate Email/Password Sign-In Method in your Firebase App

‎package-lock.json

+10,215
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎package.json

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
{
2+
"name": "react-redux-firebase-authentication",
3+
"version": "0.1.0",
4+
"private": true,
5+
"dependencies": {
6+
"firebase": "^4.3.1",
7+
"prop-types": "^15.5.10",
8+
"react": "^15.6.1",
9+
"react-dom": "^15.6.1",
10+
"react-router-dom": "^4.2.2",
11+
"react-scripts": "1.0.13"
12+
},
13+
"scripts": {
14+
"start": "react-scripts start",
15+
"build": "react-scripts build",
16+
"test": "react-scripts test --env=jsdom",
17+
"eject": "react-scripts eject"
18+
}
19+
}

‎public/favicon.ico

3.78 KB
Binary file not shown.

‎public/index.html

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<!doctype html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="utf-8">
5+
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
6+
<meta name="theme-color" content="#000000">
7+
<!--
8+
manifest.json provides metadata used when your web app is added to the
9+
homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
10+
-->
11+
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
12+
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
13+
<!--
14+
Notice the use of %PUBLIC_URL% in the tags above.
15+
It will be replaced with the URL of the `public` folder during the build.
16+
Only files inside the `public` folder can be referenced from the HTML.
17+
18+
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
19+
work correctly both with client-side routing and a non-root public URL.
20+
Learn how to configure a non-root public URL by running `npm run build`.
21+
-->
22+
<title>React App</title>
23+
</head>
24+
<body>
25+
<noscript>
26+
You need to enable JavaScript to run this app.
27+
</noscript>
28+
<div id="root"></div>
29+
<!--
30+
This HTML file is a template.
31+
If you open it directly in the browser, you will see an empty page.
32+
33+
You can add webfonts, meta tags, or analytics to this file.
34+
The build step will place the bundled scripts into the <body> tag.
35+
36+
To begin the development, run `npm start` or `yarn start`.
37+
To create a production bundle, use `npm run build` or `yarn build`.
38+
-->
39+
</body>
40+
</html>

‎public/manifest.json

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
{
2+
"short_name": "React App",
3+
"name": "Create React App Sample",
4+
"icons": [
5+
{
6+
"src": "favicon.ico",
7+
"sizes": "192x192",
8+
"type": "image/png"
9+
}
10+
],
11+
"start_url": "./index.html",
12+
"display": "standalone",
13+
"theme_color": "#000000",
14+
"background_color": "#ffffff"
15+
}

‎src/components/Account/index.js

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import React from 'react';
2+
import PropTypes from 'prop-types';
3+
4+
import { PasswordForgetForm } from '../PasswordForget';
5+
import PasswordChangeForm from '../PasswordChange';
6+
import withAuthorization from '../Session/withAuthorization';
7+
8+
const AccountPage = (props, { authUser }) =>
9+
<div>
10+
<h1>Account: {authUser.email}</h1>
11+
<PasswordForgetForm />
12+
<PasswordChangeForm />
13+
</div>
14+
15+
AccountPage.contextTypes = {
16+
authUser: PropTypes.object,
17+
};
18+
19+
export default withAuthorization(true)(AccountPage);

‎src/components/App/index.css

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
.app {
2+
margin: 20px;
3+
}

‎src/components/App/index.js

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import React from 'react';
2+
import {
3+
BrowserRouter as Router,
4+
Route,
5+
} from 'react-router-dom';
6+
7+
import Navigation from '../Navigation';
8+
import LandingPage from '../Landing';
9+
import SignUpPage from '../SignUp';
10+
import SignInPage from '../SignIn';
11+
import PasswordForgetPage from '../PasswordForget';
12+
import HomePage from '../Home';
13+
import AccountPage from '../Account';
14+
import withAuthentication from '../Session/withAuthentication';
15+
import * as routes from '../../constants/routes';
16+
17+
import './index.css';
18+
19+
const App = () =>
20+
<Router>
21+
<div className="app">
22+
<Navigation />
23+
24+
<hr/>
25+
26+
<Route exact path={routes.LANDING} component={LandingPage} />
27+
<Route exact path={routes.SIGN_UP} component={SignUpPage} />
28+
<Route exact path={routes.SIGN_IN} component={SignInPage} />
29+
<Route exact path={routes.PASSWORD_FORGET} component={PasswordForgetPage} />
30+
<Route exact path={routes.HOME} component={HomePage} />
31+
<Route exact path={routes.ACCOUNT} component={AccountPage} />
32+
33+
<hr/>
34+
35+
<span>Found in <a href="https://roadtoreact.com/course-details?courseId=TAMING_THE_STATE">Taming the State in React</a></span> | <span>Star the <a href="https://github.com/rwieruch/react-firebase-authentication">Repository</a></span> | <span>Receive a <a href="https://www.getrevue.co/profile/rwieruch">Developer's Newsletter</a></span>
36+
</div>
37+
</Router>
38+
39+
export default withAuthentication(App);

‎src/components/Home/index.js

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import React, { Component } from 'react';
2+
3+
import withAuthorization from '../Session/withAuthorization';
4+
import { db } from '../../firebase';
5+
6+
const fromObjectToList = (object) =>
7+
object
8+
? Object.keys(object).map(key => ({ ...object[key], index: key }))
9+
: [];
10+
11+
class HomePage extends Component {
12+
constructor(props) {
13+
super(props);
14+
15+
this.state = {
16+
users: []
17+
};
18+
}
19+
20+
componentDidMount() {
21+
db.onceGetUsers().then(snapshot =>
22+
this.setState(() => ({ users: fromObjectToList(snapshot.val()) }))
23+
);
24+
}
25+
26+
render() {
27+
return (
28+
<div>
29+
<h1>Home</h1>
30+
<p>The Home Page is accessible by every signed in user.</p>
31+
32+
{ !!this.state.users.length && <UserList users={this.state.users} /> }
33+
</div>
34+
);
35+
}
36+
}
37+
38+
const UserList = ({ users }) =>
39+
<div>
40+
<h2>List of App Users (Saved on Sign Up)</h2>
41+
{users.map(user =>
42+
<div key={user.index}>{user.username} ({user.index})</div>
43+
)}
44+
</div>
45+
46+
export default withAuthorization(true)(HomePage);

‎src/components/Landing/index.js

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import React from 'react';
2+
3+
const LandingPage = () =>
4+
<div>
5+
<h1>Landing</h1>
6+
<p>The Landing Page is open to everyone, even though the user isn't signed in.</p>
7+
</div>
8+
9+
export default LandingPage;

‎src/components/Navigation/index.js

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import React from 'react';
2+
import PropTypes from 'prop-types';
3+
import { Link } from 'react-router-dom';
4+
5+
import SignOutButton from '../SignOut';
6+
7+
const Navigation = (props, { authUser }) =>
8+
<div>
9+
{ authUser
10+
? <NavigationAuth />
11+
: <NavigationNonAuth />
12+
}
13+
</div>
14+
15+
Navigation.contextTypes = {
16+
authUser: PropTypes.object,
17+
};
18+
19+
const NavigationAuth = () =>
20+
<ul>
21+
<li><Link to="/">Landing</Link></li>
22+
<li><Link to="/home">Home</Link></li>
23+
<li><Link to="/account">Account</Link></li>
24+
<li><SignOutButton /></li>
25+
</ul>
26+
27+
const NavigationNonAuth = () =>
28+
<ul>
29+
<li><Link to="/">Landing</Link></li>
30+
<li><Link to="/signin">Sign In</Link></li>
31+
</ul>
32+
33+
export default Navigation;
+71
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
import React, { Component } from 'react';
2+
3+
import { auth } from '../../firebase';
4+
5+
const updateByPropertyName = (propertyName, value) => () => ({
6+
[propertyName]: value,
7+
});
8+
9+
const INITIAL_STATE = {
10+
passwordOne: '',
11+
passwordTwo: '',
12+
error: null,
13+
};
14+
15+
class PasswordChangeForm extends Component {
16+
constructor(props) {
17+
super(props);
18+
19+
this.state = { ...INITIAL_STATE };
20+
}
21+
22+
onSubmit = (event) => {
23+
const { passwordOne } = this.state;
24+
25+
auth.doPasswordUpdate(passwordOne)
26+
.then(() => {
27+
this.setState(() => ({ ...INITIAL_STATE }));
28+
})
29+
.catch(error => {
30+
this.setState(updateByPropertyName('error', error));
31+
});
32+
33+
event.preventDefault();
34+
}
35+
36+
render() {
37+
const {
38+
passwordOne,
39+
passwordTwo,
40+
error,
41+
} = this.state;
42+
43+
const isInvalid =
44+
passwordOne !== passwordTwo ||
45+
passwordOne === '';
46+
47+
return (
48+
<form onSubmit={this.onSubmit}>
49+
<input
50+
value={passwordOne}
51+
onChange={event => this.setState(updateByPropertyName('passwordOne', event.target.value))}
52+
type="password"
53+
placeholder="New Password"
54+
/>
55+
<input
56+
value={passwordTwo}
57+
onChange={event => this.setState(updateByPropertyName('passwordTwo', event.target.value))}
58+
type="password"
59+
placeholder="Confirm New Password"
60+
/>
61+
<button disabled={isInvalid} type="submit">
62+
Reset My Password
63+
</button>
64+
65+
{ error && <p>{error.message}</p> }
66+
</form>
67+
);
68+
}
69+
}
70+
71+
export default PasswordChangeForm;
+78
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
import React, { Component } from 'react';
2+
import { Link } from 'react-router-dom';
3+
4+
import { auth } from '../../firebase';
5+
6+
const PasswordForgetPage = () =>
7+
<div>
8+
<h1>PasswordForget</h1>
9+
<PasswordForgetForm />
10+
</div>
11+
12+
const updateByPropertyName = (propertyName, value) => () => ({
13+
[propertyName]: value,
14+
});
15+
16+
const INITIAL_STATE = {
17+
email: '',
18+
error: null,
19+
};
20+
21+
class PasswordForgetForm extends Component {
22+
constructor(props) {
23+
super(props);
24+
25+
this.state = { ...INITIAL_STATE };
26+
}
27+
28+
onSubmit = (event) => {
29+
const { email } = this.state;
30+
31+
auth.doPasswordReset(email)
32+
.then(() => {
33+
this.setState(() => ({ ...INITIAL_STATE }));
34+
})
35+
.catch(error => {
36+
this.setState(updateByPropertyName('error', error));
37+
});
38+
39+
event.preventDefault();
40+
}
41+
42+
render() {
43+
const {
44+
email,
45+
error,
46+
} = this.state;
47+
48+
const isInvalid = email === '';
49+
50+
return (
51+
<form onSubmit={this.onSubmit}>
52+
<input
53+
value={this.state.email}
54+
onChange={event => this.setState(updateByPropertyName('email', event.target.value))}
55+
type="text"
56+
placeholder="Email Address"
57+
/>
58+
<button disabled={isInvalid} type="submit">
59+
Reset My Password
60+
</button>
61+
62+
{ error && <p>{error.message}</p> }
63+
</form>
64+
);
65+
}
66+
}
67+
68+
const PasswordForgetLink = () =>
69+
<p>
70+
<Link to="/pw-forget">Forgot Password?</Link>
71+
</p>
72+
73+
export default PasswordForgetPage;
74+
75+
export {
76+
PasswordForgetForm,
77+
PasswordForgetLink,
78+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import React from 'react';
2+
import PropTypes from 'prop-types';
3+
4+
import { firebase } from '../../firebase';
5+
6+
const withAuthentication = (Component) => {
7+
class WithAuthentication extends React.Component {
8+
constructor(props) {
9+
super(props);
10+
11+
this.state = {
12+
authUser: null,
13+
};
14+
}
15+
16+
getChildContext() {
17+
return {
18+
authUser: this.state.authUser,
19+
};
20+
}
21+
22+
componentDidMount() {
23+
firebase.auth.onAuthStateChanged(authUser => {
24+
authUser
25+
? this.setState(() => ({ authUser }))
26+
: this.setState(() => ({ authUser: null }));
27+
});
28+
}
29+
30+
render() {
31+
return (
32+
<Component />
33+
);
34+
}
35+
}
36+
37+
WithAuthentication.childContextTypes = {
38+
authUser: PropTypes.object,
39+
};
40+
41+
return WithAuthentication;
42+
}
43+
44+
export default withAuthentication;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import React from 'react';
2+
import { withRouter } from 'react-router-dom';
3+
4+
import { firebase } from '../../firebase';
5+
import * as routes from '../../constants/routes';
6+
7+
const withAuthorization = (needsAuthorization) => (Component) => {
8+
class WithAuthorization extends React.Component {
9+
componentDidMount() {
10+
firebase.auth.onAuthStateChanged(authUser => {
11+
if (!authUser && needsAuthorization) {
12+
this.props.history.push(routes.SIGN_IN)
13+
}
14+
});
15+
}
16+
17+
render() {
18+
return (
19+
<Component />
20+
);
21+
}
22+
}
23+
24+
return withRouter(WithAuthorization);
25+
}
26+
27+
export default withAuthorization;

‎src/components/SignIn/index.js

+95
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
import React, { Component } from 'react';
2+
import { withRouter } from 'react-router-dom';
3+
4+
import { SignUpLink } from '../SignUp';
5+
import { PasswordForgetLink } from '../PasswordForget';
6+
import { auth } from '../../firebase';
7+
import * as routes from '../../constants/routes';
8+
9+
const SignInPage = ({ history }) =>
10+
<div>
11+
<h1>SignIn</h1>
12+
<SignInForm history={history} />
13+
<PasswordForgetLink />
14+
<SignUpLink />
15+
</div>
16+
17+
const updateByPropertyName = (propertyName, value) => () => ({
18+
[propertyName]: value,
19+
});
20+
21+
const INITIAL_STATE = {
22+
email: '',
23+
password: '',
24+
error: null,
25+
};
26+
27+
class SignInForm extends Component {
28+
constructor(props) {
29+
super(props);
30+
31+
this.state = { ...INITIAL_STATE };
32+
}
33+
34+
onSubmit = (event) => {
35+
const {
36+
email,
37+
password,
38+
} = this.state;
39+
40+
const {
41+
history,
42+
} = this.props;
43+
44+
auth.doSignInWithEmailAndPassword(email, password)
45+
.then(() => {
46+
this.setState(() => ({ ...INITIAL_STATE }));
47+
history.push(routes.HOME);
48+
})
49+
.catch(error => {
50+
this.setState(updateByPropertyName('error', error));
51+
});
52+
53+
event.preventDefault();
54+
}
55+
56+
render() {
57+
const {
58+
email,
59+
password,
60+
error,
61+
} = this.state;
62+
63+
const isInvalid =
64+
password === '' ||
65+
email === '';
66+
67+
return (
68+
<form onSubmit={this.onSubmit}>
69+
<input
70+
value={email}
71+
onChange={event => this.setState(updateByPropertyName('email', event.target.value))}
72+
type="text"
73+
placeholder="Email Address"
74+
/>
75+
<input
76+
value={password}
77+
onChange={event => this.setState(updateByPropertyName('password', event.target.value))}
78+
type="password"
79+
placeholder="Password"
80+
/>
81+
<button disabled={isInvalid} type="submit">
82+
Sign In
83+
</button>
84+
85+
{ error && <p>{error.message}</p> }
86+
</form>
87+
);
88+
}
89+
}
90+
91+
export default withRouter(SignInPage);
92+
93+
export {
94+
SignInForm,
95+
};

‎src/components/SignOut/index.js

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import React from 'react';
2+
3+
import { auth } from '../../firebase';
4+
5+
const SignOutButton = () =>
6+
<button
7+
type="button"
8+
onClick={auth.doSignOut}
9+
>
10+
Sign Out
11+
</button>
12+
13+
export default SignOutButton;

‎src/components/SignUp/index.js

+129
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
import React, { Component } from 'react';
2+
import {
3+
Link,
4+
withRouter,
5+
} from 'react-router-dom';
6+
7+
import { auth, db } from '../../firebase';
8+
import * as routes from '../../constants/routes';
9+
10+
const SignUpPage = ({ history }) =>
11+
<div>
12+
<h1>SignUp</h1>
13+
<SignUpForm history={history} />
14+
</div>
15+
16+
const updateByPropertyName = (propertyName, value) => () => ({
17+
[propertyName]: value,
18+
});
19+
20+
const INITIAL_STATE = {
21+
username: '',
22+
email: '',
23+
passwordOne: '',
24+
passwordTwo: '',
25+
error: null,
26+
};
27+
28+
class SignUpForm extends Component {
29+
constructor(props) {
30+
super(props);
31+
32+
this.state = { ...INITIAL_STATE };
33+
}
34+
35+
onSubmit = (event) => {
36+
const {
37+
username,
38+
email,
39+
passwordOne,
40+
} = this.state;
41+
42+
const {
43+
history,
44+
} = this.props;
45+
46+
auth.doCreateUserWithEmailAndPassword(email, passwordOne)
47+
.then(authUser => {
48+
49+
// Create a user in your own accessible Firebase Database too
50+
db.doCreateUser(authUser.uid, username, email)
51+
.then(() => {
52+
this.setState(() => ({ ...INITIAL_STATE }));
53+
history.push(routes.HOME);
54+
})
55+
.catch(error => {
56+
this.setState(updateByPropertyName('error', error));
57+
});
58+
59+
})
60+
.catch(error => {
61+
this.setState(updateByPropertyName('error', error));
62+
});
63+
64+
event.preventDefault();
65+
}
66+
67+
render() {
68+
const {
69+
username,
70+
email,
71+
passwordOne,
72+
passwordTwo,
73+
error,
74+
} = this.state;
75+
76+
const isInvalid =
77+
passwordOne !== passwordTwo ||
78+
passwordOne === '' ||
79+
username === '';
80+
81+
return (
82+
<form onSubmit={this.onSubmit}>
83+
<input
84+
value={username}
85+
onChange={event => this.setState(updateByPropertyName('username', event.target.value))}
86+
type="text"
87+
placeholder="Full Name"
88+
/>
89+
<input
90+
value={email}
91+
onChange={event => this.setState(updateByPropertyName('email', event.target.value))}
92+
type="text"
93+
placeholder="Email Address"
94+
/>
95+
<input
96+
value={passwordOne}
97+
onChange={event => this.setState(updateByPropertyName('passwordOne', event.target.value))}
98+
type="password"
99+
placeholder="Password"
100+
/>
101+
<input
102+
value={passwordTwo}
103+
onChange={event => this.setState(updateByPropertyName('passwordTwo', event.target.value))}
104+
type="password"
105+
placeholder="Confirm Password"
106+
/>
107+
<button disabled={isInvalid} type="submit">
108+
Sign Up
109+
</button>
110+
111+
{ error && <p>{error.message}</p> }
112+
</form>
113+
);
114+
}
115+
}
116+
117+
const SignUpLink = () =>
118+
<p>
119+
Don't have an account?
120+
{' '}
121+
<Link to="/signup">Sign Up</Link>
122+
</p>
123+
124+
export default withRouter(SignUpPage);
125+
126+
export {
127+
SignUpForm,
128+
SignUpLink,
129+
};

‎src/constants/routes.js

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
export const LANDING = '/';
2+
export const SIGN_UP = '/signup';
3+
export const SIGN_IN = '/signin';
4+
export const PASSWORD_FORGET = '/pw-forget';
5+
export const HOME = '/home';
6+
export const ACCOUNT = '/account';

‎src/firebase/auth.js

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import { auth } from './firebase';
2+
3+
// Sign Up
4+
export const doCreateUserWithEmailAndPassword = (email, password) =>
5+
auth.createUserWithEmailAndPassword(email, password);
6+
7+
// Sign In
8+
export const doSignInWithEmailAndPassword = (email, password) =>
9+
auth.signInWithEmailAndPassword(email, password);
10+
11+
// Sign out
12+
export const doSignOut = () =>
13+
auth.signOut();
14+
15+
// Password Reset
16+
export const doPasswordReset = (email) =>
17+
auth.sendPasswordResetEmail(email);
18+
19+
// Password Change
20+
export const doPasswordUpdate = (password) =>
21+
auth.currentUser.updatePassword(password);

‎src/firebase/db.js

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import { db } from './firebase';
2+
3+
// User API
4+
5+
export const doCreateUser = (id, username, email) =>
6+
db.ref(`users/${id}`).set({
7+
username,
8+
email,
9+
});
10+
11+
export const onceGetUsers = () =>
12+
db.ref('users').once('value');
13+
14+
// Other db APIs ...

‎src/firebase/firebase.js

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import * as firebase from 'firebase';
2+
3+
const prodConfig = {
4+
apiKey: YOUR_API_KEY,
5+
authDomain: YOUR_AUTH_DOMAIN,
6+
databaseURL: YOUR_DATABASE_URL,
7+
projectId: YOUR_PROJECT_ID,
8+
storageBucket: '',
9+
messagingSenderId: YOUR_MESSAGING_SENDER_ID,
10+
};
11+
12+
const devConfig = {
13+
apiKey: YOUR_API_KEY,
14+
authDomain: YOUR_AUTH_DOMAIN,
15+
databaseURL: YOUR_DATABASE_URL,
16+
projectId: YOUR_PROJECT_ID,
17+
storageBucket: '',
18+
messagingSenderId: YOUR_MESSAGING_SENDER_ID,
19+
};
20+
21+
const config = process.env.NODE_ENV === 'production'
22+
? prodConfig
23+
: devConfig;
24+
25+
if (!firebase.apps.length) {
26+
firebase.initializeApp(config);
27+
}
28+
29+
const db = firebase.database();
30+
const auth = firebase.auth();
31+
32+
export {
33+
db,
34+
auth,
35+
};

‎src/firebase/index.js

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import * as auth from './auth';
2+
import * as db from './db';
3+
import * as firebase from './firebase';
4+
5+
export {
6+
auth,
7+
db,
8+
firebase,
9+
};

‎src/index.css

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
body {
2+
margin: 0;
3+
padding: 0;
4+
font-family: sans-serif;
5+
}

‎src/index.js

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import React from 'react';
2+
import ReactDOM from 'react-dom';
3+
import './index.css';
4+
import App from './components/App';
5+
import registerServiceWorker from './registerServiceWorker';
6+
7+
ReactDOM.render(<App />, document.getElementById('root'));
8+
registerServiceWorker();

‎src/registerServiceWorker.js

+108
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
// In production, we register a service worker to serve assets from local cache.
2+
3+
// This lets the app load faster on subsequent visits in production, and gives
4+
// it offline capabilities. However, it also means that developers (and users)
5+
// will only see deployed updates on the "N+1" visit to a page, since previously
6+
// cached resources are updated in the background.
7+
8+
// To learn more about the benefits of this model, read https://goo.gl/KwvDNy.
9+
// This link also includes instructions on opting out of this behavior.
10+
11+
const isLocalhost = Boolean(
12+
window.location.hostname === 'localhost' ||
13+
// [::1] is the IPv6 localhost address.
14+
window.location.hostname === '[::1]' ||
15+
// 127.0.0.1/8 is considered localhost for IPv4.
16+
window.location.hostname.match(
17+
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
18+
)
19+
);
20+
21+
export default function register() {
22+
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
23+
// The URL constructor is available in all browsers that support SW.
24+
const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
25+
if (publicUrl.origin !== window.location.origin) {
26+
// Our service worker won't work if PUBLIC_URL is on a different origin
27+
// from what our page is served on. This might happen if a CDN is used to
28+
// serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374
29+
return;
30+
}
31+
32+
window.addEventListener('load', () => {
33+
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
34+
35+
if (!isLocalhost) {
36+
// Is not local host. Just register service worker
37+
registerValidSW(swUrl);
38+
} else {
39+
// This is running on localhost. Lets check if a service worker still exists or not.
40+
checkValidServiceWorker(swUrl);
41+
}
42+
});
43+
}
44+
}
45+
46+
function registerValidSW(swUrl) {
47+
navigator.serviceWorker
48+
.register(swUrl)
49+
.then(registration => {
50+
registration.onupdatefound = () => {
51+
const installingWorker = registration.installing;
52+
installingWorker.onstatechange = () => {
53+
if (installingWorker.state === 'installed') {
54+
if (navigator.serviceWorker.controller) {
55+
// At this point, the old content will have been purged and
56+
// the fresh content will have been added to the cache.
57+
// It's the perfect time to display a "New content is
58+
// available; please refresh." message in your web app.
59+
console.log('New content is available; please refresh.');
60+
} else {
61+
// At this point, everything has been precached.
62+
// It's the perfect time to display a
63+
// "Content is cached for offline use." message.
64+
console.log('Content is cached for offline use.');
65+
}
66+
}
67+
};
68+
};
69+
})
70+
.catch(error => {
71+
console.error('Error during service worker registration:', error);
72+
});
73+
}
74+
75+
function checkValidServiceWorker(swUrl) {
76+
// Check if the service worker can be found. If it can't reload the page.
77+
fetch(swUrl)
78+
.then(response => {
79+
// Ensure service worker exists, and that we really are getting a JS file.
80+
if (
81+
response.status === 404 ||
82+
response.headers.get('content-type').indexOf('javascript') === -1
83+
) {
84+
// No service worker found. Probably a different app. Reload the page.
85+
navigator.serviceWorker.ready.then(registration => {
86+
registration.unregister().then(() => {
87+
window.location.reload();
88+
});
89+
});
90+
} else {
91+
// Service worker found. Proceed as normal.
92+
registerValidSW(swUrl);
93+
}
94+
})
95+
.catch(() => {
96+
console.log(
97+
'No internet connection found. App is running in offline mode.'
98+
);
99+
});
100+
}
101+
102+
export function unregister() {
103+
if ('serviceWorker' in navigator) {
104+
navigator.serviceWorker.ready.then(registration => {
105+
registration.unregister();
106+
});
107+
}
108+
}

0 commit comments

Comments
 (0)
Please sign in to comment.