Skip to content

Commit 06baed2

Browse files
captDaylighttimneutkens
authored andcommitted
820 firebase (vercel#1756)
* connecting to firebase * login and logout with sessions * setting messages on the client side * should have messages served on init * set messages in state * updating credentials * updating readme * more cred * iron out eslint issues * highlight where to put firebase variables * fix problem of database listener not picking up changes on load * remove isomorphic from main package.json
1 parent bbb8ff7 commit 06baed2

File tree

5 files changed

+238
-0
lines changed

5 files changed

+238
-0
lines changed

examples/with-firebase/README.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
2+
# With Firebase example
3+
4+
## How to use
5+
6+
Download the example [or clone the repo](https://github.com/zeit/next.js):
7+
8+
```bash
9+
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/with-firebase
10+
cd with-firebase
11+
```
12+
13+
Set up firebase:
14+
- create a project
15+
- get your service account credentials and client credentials and set both in firebaseCredentials.js
16+
- set your firebase database url in server.js
17+
- on the firebase Authentication console, select Google as your provider
18+
19+
Install it and run:
20+
21+
```bash
22+
npm install
23+
npm run dev
24+
```
25+
26+
Deploy it to the cloud with [now](https://zeit.co/now) ([download](https://zeit.co/download))
27+
28+
```bash
29+
now
30+
```
31+
32+
## The idea behind the example
33+
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.
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
module.exports = {
2+
clientCredentials: {
3+
// TODO firebase client config
4+
},
5+
serverCredentials: {
6+
// TODO service account json here
7+
}
8+
}

examples/with-firebase/package.json

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
{
2+
"scripts": {
3+
"dev": "node server.js",
4+
"build": "next build",
5+
"start": "NODE_ENV=production node server.js"
6+
},
7+
"dependencies": {
8+
"body-parser": "^1.17.1",
9+
"express": "^4.14.0",
10+
"express-session": "^1.15.2",
11+
"firebase": "^3.7.5",
12+
"firebase-admin": "^4.2.0",
13+
"isomorphic-fetch": "2.2.1",
14+
"next": "latest",
15+
"react": "^15.4.2",
16+
"react-dom": "^15.4.2",
17+
"session-file-store": "^1.0.0"
18+
}
19+
}

examples/with-firebase/pages/index.js

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
import React, { Component } from 'react'
2+
import firebase from 'firebase'
3+
import 'isomorphic-fetch'
4+
import { clientCredentials } from '../firebaseCredentials'
5+
6+
export default class Index extends Component {
7+
static async getInitialProps ({req, query}) {
8+
const user = req && req.session ? req.session.decodedToken : null
9+
const snap = await req.firebaseServer.database().ref('messages').once('value')
10+
return { user, messages: snap.val() }
11+
}
12+
13+
constructor (props) {
14+
super(props)
15+
this.state = {
16+
user: this.props.user,
17+
value: '',
18+
messages: this.props.messages
19+
}
20+
21+
this.addDbListener = this.addDbListener.bind(this)
22+
this.handleChange = this.handleChange.bind(this)
23+
this.handleSubmit = this.handleSubmit.bind(this)
24+
}
25+
26+
componentDidMount () {
27+
firebase.initializeApp(clientCredentials)
28+
29+
if (this.state.user) this.addDbListener()
30+
31+
firebase.auth().onAuthStateChanged(user => {
32+
if (user) {
33+
this.setState({ user: user })
34+
return user.getToken()
35+
.then((token) => {
36+
// eslint-disable-next-line no-undef
37+
return fetch('/api/login', {
38+
method: 'POST',
39+
// eslint-disable-next-line no-undef
40+
headers: new Headers({ 'Content-Type': 'application/json' }),
41+
credentials: 'same-origin',
42+
body: JSON.stringify({ token })
43+
})
44+
}).then((res) => this.addDbListener())
45+
} else {
46+
this.setState({ user: null })
47+
// eslint-disable-next-line no-undef
48+
fetch('/api/logout', {
49+
method: 'POST',
50+
credentials: 'same-origin'
51+
}).then(() => firebase.database().ref('messages').off())
52+
}
53+
})
54+
}
55+
56+
addDbListener () {
57+
firebase.database().ref('messages').on('value', snap => {
58+
const messages = snap.val()
59+
if (messages) this.setState({ messages })
60+
})
61+
}
62+
63+
handleChange (event) {
64+
this.setState({ value: event.target.value })
65+
}
66+
67+
handleSubmit (event) {
68+
event.preventDefault()
69+
const date = new Date().getTime()
70+
firebase.database().ref(`messages/${date}`).set({
71+
id: date,
72+
text: this.state.value
73+
})
74+
this.setState({ value: '' })
75+
}
76+
77+
handleLogin () {
78+
firebase.auth().signInWithPopup(new firebase.auth.GoogleAuthProvider())
79+
}
80+
81+
handleLogout () {
82+
firebase.auth().signOut()
83+
}
84+
85+
render () {
86+
const { user, value, messages } = this.state
87+
88+
return <div>
89+
{
90+
user
91+
? <button onClick={this.handleLogout}>Logout</button>
92+
: <button onClick={this.handleLogin}>Login</button>
93+
}
94+
{
95+
user &&
96+
<div>
97+
<form onSubmit={this.handleSubmit}>
98+
<input
99+
type={'text'}
100+
onChange={this.handleChange}
101+
placeholder={'add message'}
102+
value={value}
103+
/>
104+
</form>
105+
<ul>
106+
{
107+
messages &&
108+
Object.keys(messages).map(key => <li key={key}>{messages[key].text}</li>)
109+
}
110+
</ul>
111+
</div>
112+
}
113+
</div>
114+
}
115+
}

examples/with-firebase/server.js

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
const express = require('express')
2+
const bodyParser = require('body-parser')
3+
const session = require('express-session')
4+
const FileStore = require('session-file-store')(session)
5+
const next = require('next')
6+
const admin = require('firebase-admin')
7+
8+
const dev = process.env.NODE_ENV !== 'production'
9+
const app = next({ dev })
10+
const handle = app.getRequestHandler()
11+
12+
const firebase = admin.initializeApp({
13+
credential: admin.credential.cert(require('./firebaseCredentials').serverCredentials),
14+
databaseURL: '' // TODO database URL goes here
15+
}, 'server')
16+
17+
app.prepare()
18+
.then(() => {
19+
const server = express()
20+
21+
server.use(bodyParser.json())
22+
server.use(session({
23+
secret: 'geheimnis',
24+
saveUninitialized: true,
25+
store: new FileStore({path: '/tmp/sessions', secret: 'geheimnis'}),
26+
resave: false,
27+
rolling: true,
28+
httpOnly: true,
29+
cookie: { maxAge: 604800000 } // week
30+
}))
31+
32+
server.use((req, res, next) => {
33+
req.firebaseServer = firebase
34+
next()
35+
})
36+
37+
server.post('/api/login', (req, res) => {
38+
if (!req.body) return res.sendStatus(400)
39+
40+
const token = req.body.token
41+
firebase.auth().verifyIdToken(token)
42+
.then((decodedToken) => {
43+
req.session.decodedToken = decodedToken
44+
return decodedToken
45+
})
46+
.then((decodedToken) => res.json({ status: true, decodedToken }))
47+
.catch((error) => res.json({ error }))
48+
})
49+
50+
server.post('/api/logout', (req, res) => {
51+
req.session.decodedToken = null
52+
res.json({ status: true })
53+
})
54+
55+
server.get('*', (req, res) => {
56+
return handle(req, res)
57+
})
58+
59+
server.listen(3000, (err) => {
60+
if (err) throw err
61+
console.log('> Ready on http://localhost:3000')
62+
})
63+
})

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy