1
0
Fork 0
mirror of https://github.com/terribleplan/next.js.git synced 2024-01-19 02:48:18 +00:00
next.js/examples/with-firebase-authentication/server.js
James Hegedus 84de7f9397 With Firebase Hosting Example (#2642)
* Rename Firebase Auth example

* Update gitignore to include npm5 lockfile

* Cloud Function

* Add Next app with two pages to demonstrate navigation

* Add Firebase Hosting and configuration to Host & Deploy

* Fix errors in rename for firebase-auth example

* Recommend pkg managers with caches for better perf

* Update with-firebase-hosting example

Fix code

* Update with-firebase-hosting example

Fix npm scripts and package.json files

* Update with-firebase-hosting example

Update README & install scripts

* Update with-firebase-hosting example

Update example package name

* Update with-firebase-hosting example

Fix to use single-quotes

* Update with-firebase-hosting example

VSCode did not like single-quotes! Sorry

* Fix gitignore file
2017-07-26 07:52:49 +02:00

64 lines
1.6 KiB
JavaScript

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 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: '' // TODO database URL goes here
}, 'server')
app.prepare()
.then(() => {
const server = express()
server.use(bodyParser.json())
server.use(session({
secret: 'geheimnis',
saveUninitialized: true,
store: new FileStore({path: '/tmp/sessions', secret: 'geheimnis'}),
resave: false,
rolling: true,
httpOnly: true,
cookie: { maxAge: 604800000 } // 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(3000, (err) => {
if (err) throw err
console.log('> Ready on http://localhost:3000')
})
})