Skip to content

Instantly share code, notes, and snippets.

@alexjshaw
Last active August 24, 2023 13:28
Show Gist options
  • Save alexjshaw/a2563dcf5d30d95ea729f1b3f4818f82 to your computer and use it in GitHub Desktop.
Save alexjshaw/a2563dcf5d30d95ea729f1b3f4818f82 to your computer and use it in GitHub Desktop.
Post-Login-Redirect
import express from 'express'
import ViteExpress from 'vite-express'
import cors from 'cors'
import helmet from 'helmet'
import morgan from 'morgan'
import './database/mongo.js'
import { insertAd, getAds, deleteAd, updateAd } from './database/ads.js'
import { auth as jwtAuth } from 'express-oauth2-jwt-bearer'
import crypto from 'node:crypto'
import pkg from 'express-openid-connect'
const { auth, requiresAuth } = pkg
const app = express()
const jwtCheck = jwtAuth({
audience: 'AUDIENCE',
issuerBaseURL: 'BASE_URL',
tokenSigningAlg: 'RS256'
})
const config = {
authRequired: false,
auth0Logout: true,
baseURL: 'http://localhost:3000',
clientID: 'CLIENT_ID',
issuerBaseURL: 'BASE_URL',
secret: 'SECRET'
}
app.use(express.json())
app.use(cors())
app.use(auth(config))
// app.use(morgan('combined'))
app.use((req, res, next) => {
req.cspNonce = crypto.randomBytes(16).toString('hex')
next()
})
app.use(
helmet({
contentSecurityPolicy: {
directives: {
'script-src': ["'self'", (req, res) => `'nonce-${req.cspNonce}'`],
'connect-src': ["'self'", 'ws://localhost:24678']
}
}
})
)
function transformIndexHtml (html, req, res) {
const regex = /<script(.*?)/gi
const replacement = `<script nonce="${req.cspNonce}"$1`
return html.replace(regex, replacement)
}
app.get('/profile', requiresAuth(), (req, res) => {
res.send(JSON.stringify(req.oidc.user, null, 2));
})
app.get('/ads', jwtCheck, async (req, res) => {
const ads = await getAds()
res.json({ status: 'success', data: ads })
})
app.post('/ads', jwtCheck, async (req, res) => {
const newAdData = req.body
const newAd = await insertAd(newAdData)
res.json({ status: 'New ad inserted', data: newAd })
})
app.delete('/ads/:id', jwtCheck, async (req, res) => {
const deletedAdId = req.params.id
const deletedAd = await deleteAd(deletedAdId)
res.json({ status: 'Ad deleted', data: deletedAd })
})
app.put('/ads/:id', jwtCheck, async (req, res) => {
const updatedAdData = req.body
const updatedAdId = req.params.id
const updatedAd = await updateAd(updatedAdId, updatedAdData)
res.json({ status: 'Ad updated', data: updatedAd })
})
app.get('/hello', (req, res) => {
res.send('Hello Vite + React!')
})
// Error Catch Middleware
app.use((err, req, res, next) => {
console.error(err.stack)
res.status(500).send('Something broke!')
})
ViteExpress.config({ transformer: transformIndexHtml })
ViteExpress.listen(app, 3000, () =>
console.log('Server is listening on port 3000...')
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment