Unverified Commit f0220e6a authored by Luis Alvarez D's avatar Luis Alvarez D Committed by GitHub

[Examples] Update firebase authentication (#12687)

parent 565e111c
# Example: Firebase authentication with a serverless API
## How to use
### Using `create-next-app`
Execute [`create-next-app`](https://github.com/zeit/next.js/tree/canary/packages/create-next-app) with [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) or [npx](https://github.com/zkat/npx#readme) to bootstrap the example:
```bash
npx create-next-app --example with-firebase-authentication-serverless with-firebase-authentication-serverless-app
# or
yarn create next-app --example with-firebase-authentication-serverless with-firebase-authentication-serverless-app
```
### Download manually
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-firebase-authentication-serverless
cd with-firebase-authentication-serverless
```
Set up Firebase:
- Create a project at the [Firebase console](https://console.firebase.google.com/).
- Get your account credentials from the Firebase console at _Project settings > Service accounts_, where you can click on _Generate new private key_ and download the credentials as a json file. It will contain keys such as `project_id`, `client_email` and `client_id`. Set them as environment variables in the `.env` file at the root of this project.
- Get your authentication credentials from the Firebase console under _Project settings > General> Your apps_ Add a new web app if you don't already have one. Under _Firebase SDK snippet_ choose _Config_ to get the configuration as JSON. It will include keys like `apiKey`, `authDomain` and `databaseUrl`. Set the appropriate environment variables in the `.env` file at the root of this project.
- Set the environment variables `SESSION_SECRET_CURRENT` and `SESSION_SECRET_PREVIOUS` in the `.env` file. (These are used by [`cookie-session`](https://github.com/expressjs/cookie-session/#secret).]
Install it and run:
```bash
npm install
npm run dev
# or
yarn
yarn dev
```
Deploy it to the cloud with [Vercel](https://vercel.com/import?filter=next.js&utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).
After deploying, copy the deployment URL and navigate to your Firebase project's Authentication tab. Scroll down in the page to "Authorized domains" and add that URL to the list.
## The idea behind the example
This example includes Firebase authentication and serverless [API routes](https://nextjs.org/docs/api-routes/introduction). On login, the app calls `/api/login`, which stores the user's info (their decoded Firebase token) in a cookie so that it's available server-side in `getInitialProps`. On logout, the app calls `/api/logout` to destroy the cookie.
This example has been moved to [with-firebase-authentication](/examples/with-firebase-authentication)
// Responsible for setting environment variables.
// Note: this isn't strictly required for this example – you can
// inline your Firebase config or set environment variables howevever
// else you wish – but it's a convenient way to make sure the private
// key doesn't end up in source control.
const fs = require('fs')
const { NODE_ENV } = process.env
if (!NODE_ENV) {
throw new Error(
'The NODE_ENV environment variable is required but was not specified.'
)
}
// Set env vars from appropiate `.env` files. We're following the
// file structure used in create-react-app and documented in the
// Ruby dotenv. See:
// https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use
const dotEnvPath = './.env'
const dotEnvFiles = [
`${dotEnvPath}.${NODE_ENV}.local`,
`${dotEnvPath}.${NODE_ENV}`,
// Don't include `.env.local` for the test environment.
NODE_ENV !== 'test' && `${dotEnvPath}.local`,
dotEnvPath,
].filter(Boolean)
dotEnvFiles.forEach(dotenvFile => {
if (fs.existsSync(dotenvFile)) {
// eslint-disable-next-line global-require
require('dotenv').config({
path: dotenvFile,
})
}
})
{
"name": "with-firebase-auth-serverless",
"version": "1.0.0",
"scripts": {
"dev": "cross-env NODE_ENV=development next dev",
"build": "cross-env NODE_ENV=production next build",
"start": "cross-env NODE_ENV=production next start"
},
"dependencies": {
"cookie-session": "1.4.0",
"dotenv": "8.2.0",
"firebase": "^7.6.1",
"firebase-admin": "^8.9.0",
"isomorphic-unfetch": "^3.0.0",
"lodash": "4.17.15",
"next": "latest",
"prop-types": "15.7.2",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-firebaseui": "4.0.0"
},
"devDependencies": {
"cross-env": "^7.0.2"
}
}
import React from 'react'
import PropTypes from 'prop-types'
import { get } from 'lodash/object'
import Link from 'next/link'
import Router from 'next/router'
import withAuthUser from '../utils/pageWrappers/withAuthUser'
import withAuthUserInfo from '../utils/pageWrappers/withAuthUserInfo'
import logout from '../utils/auth/logout'
const Index = props => {
const { AuthUserInfo, data } = props
const AuthUser = get(AuthUserInfo, 'AuthUser', null)
const { favoriteFood } = data
return (
<div>
<p>Hi there!</p>
{!AuthUser ? (
<p>
You are not signed in.{' '}
<Link href={'/auth'}>
<a>Sign in</a>
</Link>
</p>
) : (
<div>
<p>You're signed in. Email: {AuthUser.email}</p>
<p
style={{
display: 'inlinelock',
color: 'blue',
textDecoration: 'underline',
cursor: 'pointer',
}}
onClick={async () => {
try {
await logout()
Router.push('/auth')
} catch (e) {
console.error(e)
}
}}
>
Log out
</p>
</div>
)}
<div>
<Link href={'/example'}>
<a>Another example page</a>
</Link>
</div>
<div>
<div>Your favorite food is {favoriteFood}.</div>
</div>
</div>
)
}
// Just an example.
const mockFetchData = async userId => ({
user: {
...(userId && {
id: userId,
}),
},
favoriteFood: 'pizza',
})
Index.getInitialProps = async ctx => {
// Get the AuthUserInfo object. This is set in `withAuthUser.js`.
// The AuthUserInfo object is available on both the server and client.
const AuthUserInfo = get(ctx, 'myCustomData.AuthUserInfo', null)
const AuthUser = get(AuthUserInfo, 'AuthUser', null)
// You can also get the token (e.g., to authorize a request when fetching data)
// const AuthUserToken = get(AuthUserInfo, 'token', null)
// You can fetch data here.
const data = await mockFetchData(get(AuthUser, 'id'))
return {
data,
}
}
Index.displayName = 'Index'
Index.propTypes = {
AuthUserInfo: PropTypes.shape({
AuthUser: PropTypes.shape({
id: PropTypes.string.isRequired,
email: PropTypes.string.isRequired,
emailVerified: PropTypes.bool.isRequired,
}),
token: PropTypes.string,
}),
data: PropTypes.shape({
user: PropTypes.shape({
id: PropTypes.string,
}).isRequired,
favoriteFood: PropTypes.string.isRequired,
}).isRequired,
}
Index.defaultProps = {
AuthUserInfo: null,
}
// Use `withAuthUser` to get the authed user server-side, which
// disables static rendering.
// Use `withAuthUserInfo` to include the authed user as a prop
// to your component.
export default withAuthUser(withAuthUserInfo(Index))
# For variables you need accessible at build time, add the variable to
# next.config.js. For secret values in local development, add the variable
# to .env.local, outside of source control.
# Update these with your Firebase app's values.
FIREBASE_AUTH_DOMAIN=my-example-app.firebaseapp.com
FIREBASE_CLIENT_EMAIL=my-example-app-email@example.com
FIREBASE_DATABASE_URL=https://my-example-app.firebaseio.com
FIREBASE_PROJECT_ID=my-example-app-id
FIREBASE_CLIENT_EMAIL=my-example-app-email@example.com
FIREBASE_PUBLIC_API_KEY=MyExampleAppAPIKey123
# Create another file in this directory named ".env.local", which you
# should not include in source control. In .env.local, set these secret
# environment variables:
FIREBASE_AUTH_DOMAIN=my-example-app.firebaseapp.com
FIREBASE_DATABASE_URL=https://my-example-app.firebaseio.com
# Your Firebase private key.
# FIREBASE_PRIVATE_KEY=some-key-here
# Secrets used by cookie-session.
# SESSION_SECRET_CURRENT=someSecretValue
# SESSION_SECRET_PREVIOUS=anotherSecretValue
SESSION_SECRET_CURRENT=someSecretValue
SESSION_SECRET_PREVIOUS=anotherSecretValue
......@@ -15,14 +15,9 @@
# misc
.DS_Store
.env.*local
.env
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Local dotenv files. We're following the file structure used in
# create-react-app and documented in the Ruby dotenv:
# https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use
.env.*local
yarn-error.log*
\ No newline at end of file
# With Firebase Authentication example
# Example: Firebase authentication with a serverless API
The goal is to authenticate users with firebase and store their auth token in sessions. A logged in user will see their messages on page load and then be able to post new messages.
This example includes Firebase authentication and serverless [API routes](https://nextjs.org/docs/api-routes/introduction). On login, the app calls `/api/login`, which stores the user's info (their decoded Firebase token) in a cookie so that it's available server-side in `getInitialProps`. On logout, the app calls `/api/logout` to destroy the cookie.
## How to use
### Using `create-next-app`
Execute [`create-next-app`](https://github.com/zeit/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init) or [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) to bootstrap the example:
Execute [`create-next-app`](https://github.com/zeit/next.js/tree/canary/packages/create-next-app) with [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) or [npx](https://github.com/zkat/npx#readme) to bootstrap the example:
```bash
npm init next-app --example with-firebase-authentication with-firebase-authentication-app
npx create-next-app --example with-firebase-authentication with-firebase-authentication-app
# or
yarn create next-app --example with-firebase-authentication with-firebase-authentication-app
```
......@@ -23,24 +23,14 @@ curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2
cd with-firebase-authentication
```
Set up firebase:
Set up Firebase:
- Create a project at the [Firebase console](https://console.firebase.google.com/).
- Get your account credentials from the Firebase console at _project settings>service accounts_, where you can click on _generate new private key_ and download the credentials as a json file. It will contain keys such as `project_id`, `client_email` and `client_id`. Now copy them into your project in the `credentials/server.js` file.
- Get your authentication credentials from the Firebase console under _project settings>general>your apps_ Add a new web app if you don't already have one. Under _Firebase SDK snippet_ choose _Config_ to get the configuration as JSON. It will include keys like `apiKey`, `authDomain` and `databaseUrl` and it goes into your project in `credentials/client.js`.
- Back at the Firebase web console, go to _Authentication>Sign-in method_ and enable _Google_.
- Create a database in the "Database" tab and select Firestore. Then go to "rules" and set up your write, read rules to this:
```
// Allow read/write access on all documents to any user signed in to the application
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth.uid != null;
}
}
}
```
- Copy the contents of `.env.example` into a new file called `.env`
- Get your account credentials from the Firebase console at _Project settings > Service accounts_, where you can click on _Generate new private key_ and download the credentials as a json file. It will contain keys such as `project_id`, `client_email` and `client_id`. Set them as environment variables in the `.env` file at the root of this project.
- Get your authentication credentials from the Firebase console under _Project settings > General> Your apps_ Add a new web app if you don't already have one. Under _Firebase SDK snippet_ choose _Config_ to get the configuration as JSON. It will include keys like `apiKey`, `authDomain` and `databaseUrl`. Set the appropriate environment variables in the `.env` file at the root of this project.
- Go to **Develop**, click on **Authentication** and in the **Sign-in method** tab enable authentication for the app.
- Set the environment variables `SESSION_SECRET_CURRENT` and `SESSION_SECRET_PREVIOUS` in the `.env` file. (These are used by [`cookie-session`](https://github.com/expressjs/cookie-session/#secret).]
Install it and run:
......
/* globals window */
import React, { useEffect, useState } from 'react'
import { useEffect, useState } from 'react'
import StyledFirebaseAuth from 'react-firebaseui/StyledFirebaseAuth'
import firebase from 'firebase/app'
import 'firebase/auth'
......
module.exports = {
// paste your firebase config here:
apiKey: '',
authDomain: '',
databaseURL: '',
projectId: '',
storageBucket: '',
messagingSenderId: '',
appId: '',
}
module.exports = {
// paste your firebase config here:
type: '',
project_id: '',
private_key_id: '',
private_key: '',
client_email: '',
client_id: '',
auth_uri: '',
token_uri: '',
auth_provider_x509_cert_url: '',
client_x509_cert_url: '',
}
require('./env.js')
require('dotenv').config()
module.exports = {
// Public, build-time env vars.
// https://nextjs.org/docs#build-time-configuration
env: {
FIREBASE_AUTH_DOMAIN: process.env.FIREBASE_AUTH_DOMAIN,
FIREBASE_DATABASE_URL: process.env.FIREBASE_DATABASE_URL,
......
{
"name": "with-firebase",
"name": "with-firebase-authentication",
"version": "1.0.0",
"scripts": {
"dev": "node server.js",
"dev": "next dev",
"build": "next build",
"start": "NODE_ENV=production node server.js"
"start": "next start"
},
"dependencies": {
"body-parser": "^1.17.1",
"express": "^4.14.0",
"express-session": "^1.15.2",
"firebase": "^7.6.2",
"cookie-session": "1.4.0",
"firebase": "^7.6.1",
"firebase-admin": "^8.9.0",
"isomorphic-unfetch": "2.0.0",
"isomorphic-unfetch": "^3.0.0",
"lodash": "4.17.15",
"next": "latest",
"react": "^16.7.0",
"react-dom": "^16.7.0",
"session-file-store": "^1.0.0"
"prop-types": "15.7.2",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-firebaseui": "4.0.0"
},
"devDependencies": {
"dotenv": "8.2.0"
}
}
import React, { Component } from 'react'
import firebase from 'firebase/app'
import 'firebase/auth'
import 'firebase/firestore'
import 'isomorphic-unfetch'
import clientCredentials from '../credentials/client'
import React from 'react'
import PropTypes from 'prop-types'
import { get } from 'lodash/object'
import Link from 'next/link'
import Router from 'next/router'
import withAuthUser from '../utils/pageWrappers/withAuthUser'
import withAuthUserInfo from '../utils/pageWrappers/withAuthUserInfo'
import logout from '../utils/auth/logout'
export async function getServerSideProps({ req, query }) {
const user =
req.session && req.session.decodedToken ? req.session.decodedToken : null
// don't fetch anything from firebase if the user is not found
// const snapshot = user && (await req.firebaseServer.firestore().collection('messages').get())
// let messages = []
// snapshot.forEach(function(doc) {
// messages.push(doc.data())
// });
const messages = null
return {
props: {
user,
messages,
},
}
}
export default class Index extends Component {
constructor(props) {
super(props)
this.state = {
user: this.props.user,
value: '',
messages: this.props.messages,
}
this.addDbListener = this.addDbListener.bind(this)
this.removeDbListener = this.removeDbListener.bind(this)
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
componentDidMount() {
firebase.initializeApp(clientCredentials)
const Index = props => {
const { AuthUserInfo, data } = props
const AuthUser = get(AuthUserInfo, 'AuthUser', null)
const { favoriteFood } = data
if (this.state.user) this.addDbListener()
firebase.auth().onAuthStateChanged(user => {
if (user) {
this.setState({ user: user })
return user
.getIdToken()
.then(token => {
// eslint-disable-next-line no-undef
return fetch('/api/login', {
method: 'POST',
// eslint-disable-next-line no-undef
headers: new Headers({ 'Content-Type': 'application/json' }),
credentials: 'same-origin',
body: JSON.stringify({ token }),
})
})
.then(res => this.addDbListener())
} else {
this.setState({ user: null })
// eslint-disable-next-line no-undef
fetch('/api/logout', {
method: 'POST',
credentials: 'same-origin',
}).then(() => this.removeDbListener())
}
})
}
return (
<div>
<p>Hi there!</p>
{!AuthUser ? (
<p>
You are not signed in.{' '}
<Link href={'/auth'}>
<a>Sign in</a>
</Link>
</p>
) : (
<div>
<p>You're signed in. Email: {AuthUser.email}</p>
<p
style={{
display: 'inlinelock',
color: 'blue',
textDecoration: 'underline',
cursor: 'pointer',
}}
onClick={async () => {
try {
await logout()
Router.push('/auth')
} catch (e) {
console.error(e)
}
}}
>
Log out
</p>
</div>
)}
<div>
<Link href={'/example'}>
<a>Another example page</a>
</Link>
</div>
<div>
<div>Your favorite food is {favoriteFood}.</div>
</div>
</div>
)
}
addDbListener() {
var db = firebase.firestore()
let unsubscribe = db.collection('messages').onSnapshot(
querySnapshot => {
var messages = {}
querySnapshot.forEach(function(doc) {
messages[doc.id] = doc.data()
})
if (messages) this.setState({ messages })
},
error => {
console.error(error)
}
)
this.setState({ unsubscribe })
}
// Just an example.
const mockFetchData = async userId => ({
user: {
...(userId && {
id: userId,
}),
},
favoriteFood: 'pizza',
})
removeDbListener() {
// firebase.database().ref('messages').off()
if (this.state.unsubscribe) {
this.state.unsubscribe()
}
}
Index.getInitialProps = async ctx => {
// Get the AuthUserInfo object. This is set in `withAuthUser.js`.
// The AuthUserInfo object is available on both the server and client.
const AuthUserInfo = get(ctx, 'myCustomData.AuthUserInfo', null)
const AuthUser = get(AuthUserInfo, 'AuthUser', null)
handleChange(event) {
this.setState({ value: event.target.value })
}
// You can also get the token (e.g., to authorize a request when fetching data)
// const AuthUserToken = get(AuthUserInfo, 'token', null)
handleSubmit(event) {
event.preventDefault()
var db = firebase.firestore()
const date = new Date().getTime()
db.collection('messages')
.doc(`${date}`)
.set({
id: date,
text: this.state.value,
})
this.setState({ value: '' })
}
// You can fetch data here.
const data = await mockFetchData(get(AuthUser, 'id'))
handleLogin() {
firebase.auth().signInWithPopup(new firebase.auth.GoogleAuthProvider())
return {
data,
}
}
handleLogout() {
firebase.auth().signOut()
}
Index.displayName = 'Index'
render() {
const { user, value, messages } = this.state
Index.propTypes = {
AuthUserInfo: PropTypes.shape({
AuthUser: PropTypes.shape({
id: PropTypes.string.isRequired,
email: PropTypes.string.isRequired,
emailVerified: PropTypes.bool.isRequired,
}),
token: PropTypes.string,
}),
data: PropTypes.shape({
user: PropTypes.shape({
id: PropTypes.string,
}).isRequired,
favoriteFood: PropTypes.string.isRequired,
}).isRequired,
}
return (
<div>
{user ? (
<button onClick={this.handleLogout}>Logout</button>
) : (
<button onClick={this.handleLogin}>Login</button>
)}
{user && (
<div>
<form onSubmit={this.handleSubmit}>
<input
type={'text'}
onChange={this.handleChange}
placeholder={'add message...'}
value={value}
/>
</form>
<ul>
{messages &&
Object.keys(messages).map(key => (
<li key={key}>{messages[key].text}</li>
))}
</ul>
</div>
)}
</div>
)
}
Index.defaultProps = {
AuthUserInfo: null,
}
// Use `withAuthUser` to get the authed user server-side, which
// disables static rendering.
// Use `withAuthUserInfo` to include the authed user as a prop
// to your component.
export default withAuthUser(withAuthUserInfo(Index))
const express = require('express')
const bodyParser = require('body-parser')
const session = require('express-session')
const FileStore = require('session-file-store')(session)
const next = require('next')
const admin = require('firebase-admin')
const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
const firebase = admin.initializeApp(
{
credential: admin.credential.cert(require('./credentials/server')),
// databaseURL: "https://<YOUR_PROJECT>.firebaseio.com",
},
'server'
)
app.prepare().then(() => {
const server = express()
server.use(bodyParser.json())
server.use(
session({
secret: 'geheimnis',
saveUninitialized: true,
store: new FileStore({ secret: 'geheimnis' }),
resave: false,
rolling: true,
cookie: { maxAge: 604800000, httpOnly: true }, // week
})
)
server.use((req, res, next) => {
req.firebaseServer = firebase
next()
})
server.post('/api/login', (req, res) => {
if (!req.body) return res.sendStatus(400)
const token = req.body.token
firebase
.auth()
.verifyIdToken(token)
.then(decodedToken => {
req.session.decodedToken = decodedToken
return decodedToken
})
.then(decodedToken => res.json({ status: true, decodedToken }))
.catch(error => res.json({ error }))
})
server.post('/api/logout', (req, res) => {
req.session.decodedToken = null
res.json({ status: true })
})
server.get('*', (req, res) => {
return handle(req, res)
})
server.listen(port, err => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})
})
import cookieSession from './cookieSession'
import cookieSessionRefresh from './cookieSessionRefresh'
// Load environment variables.
require('../../env')
export default handler => cookieSession(cookieSessionRefresh(handler))
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment