2020-05-07 11:53:34 +02:00
|
|
|
const jwt = require("jsonwebtoken")
|
2020-05-14 16:12:30 +02:00
|
|
|
const STATUS_CODES = require("../utilities/statusCodes")
|
|
|
|
const env = require("../environment")
|
2020-04-23 15:37:08 +02:00
|
|
|
|
|
|
|
module.exports = async (ctx, next) => {
|
2020-05-14 16:12:30 +02:00
|
|
|
const authHeader = ctx.get("Authorization")
|
|
|
|
|
|
|
|
if (
|
|
|
|
authHeader &&
|
|
|
|
authHeader.startsWith("Basic") &&
|
|
|
|
authHeader.split(" ")[1] === env.ADMIN_SECRET
|
|
|
|
) {
|
2020-05-07 15:04:32 +02:00
|
|
|
ctx.isAuthenticated = true
|
2020-05-14 16:12:30 +02:00
|
|
|
await next()
|
2020-05-07 15:04:32 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-05-07 11:53:34 +02:00
|
|
|
const token = ctx.cookies.get("budibase:token")
|
2020-05-06 21:29:47 +02:00
|
|
|
|
|
|
|
if (!token) {
|
2020-05-04 18:13:57 +02:00
|
|
|
ctx.isAuthenticated = false
|
2020-05-07 11:53:34 +02:00
|
|
|
await next()
|
|
|
|
return
|
|
|
|
}
|
2020-04-23 15:37:08 +02:00
|
|
|
|
|
|
|
try {
|
2020-05-07 11:53:34 +02:00
|
|
|
ctx.jwtPayload = jwt.verify(token, ctx.config.jwtSecret)
|
|
|
|
ctx.isAuthenticated = true
|
2020-04-23 15:37:08 +02:00
|
|
|
} catch (err) {
|
2020-05-07 15:04:32 +02:00
|
|
|
ctx.throw(err.status || STATUS_CODES.FORBIDDEN, err.text)
|
2020-04-23 15:37:08 +02:00
|
|
|
}
|
|
|
|
|
2020-05-07 11:53:34 +02:00
|
|
|
await next()
|
|
|
|
}
|