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

64 lines
1.6 KiB
JavaScript
Raw Normal View History

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')
})
})