Skip to content

Commit

Permalink
cleaned up server.js
Browse files Browse the repository at this point in the history
  • Loading branch information
ssb-jnk committed Mar 7, 2024
1 parent f26b68d commit 235aff8
Showing 1 changed file with 1 addition and 49 deletions.
50 changes: 1 addition & 49 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import ViteExpress from 'vite-express'
import { createLightship } from 'lightship'
import express from 'express'
import jwt from 'jsonwebtoken'
import jwksClient from 'jwks-rsa'
import { getReasonPhrase } from 'http-status-codes'
import dotenv from 'dotenv'

if (!process.env.VITE_JWKS_URI) {
if (!process.env.VITE_DAPLA_TEAM_API_URL) {
dotenv.config({ path: './.env.local' })
}

Expand All @@ -17,36 +15,6 @@ const PORT = process.env.PORT || 3000

app.use(express.json())

const client = jwksClient({
jwksUri: process.env.VITE_JWKS_URI,
})

app.post('/api/verify-token', (req, res) => {
if (!req.headers.authorization.startsWith('Bearer')) {
return res.status(401).json({ message: 'No token provided' })
}

const token = req.headers.authorization.split('Bearer ')[1]

const decodedToken = jwt.decode(token, { complete: true })
if (!decodedToken) return res.status(400).json({ message: 'Invalid token format' })

const kid = decodedToken.header.kid
getPublicKeyFromKeycloak(kid)
.then((publicKey) => {
jwt.verify(token, publicKey, { algorithms: ['RS256'] }, (err, decoded) => {
if (err) {
return res.status(401).json({ message: 'Invalid token' })
}
res.json({ user: decoded })
})
})
.catch((error) => {
console.error(error)
res.status(500).json({ message: 'Server error', error: error.message })
})
})

// DO NOT REMOVE, NECCESSARY FOR FRONTEND
app.get('/api/photo/:principalName', async (req, res, next) => {
const accessToken = req.headers.authorization.split(' ')[1]
Expand Down Expand Up @@ -94,22 +62,6 @@ function getFetchOptions(token) {
}
}

function getPublicKeyFromKeycloak(kid) {
return new Promise((resolve, reject) => {
client.getSigningKey(kid, (err, key) => {
if (err) {
reject(err)
return
}
if (!key) {
reject(new Error('No key found'))
return
}
resolve(key.getPublicKey())
})
})
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
app.use((err, req, res, next) => {
const statusCode = err.statusCode || 500
Expand Down

0 comments on commit 235aff8

Please sign in to comment.