2022-11-16 18:23:12 +01:00
|
|
|
import { Cookie, Header } from "../constants"
|
2022-08-05 16:21:12 +02:00
|
|
|
import { getCookie, clearCookie, openJwt } from "../utils"
|
|
|
|
import { getUser } from "../cache/user"
|
|
|
|
import { getSession, updateSessionTTL } from "../security/sessions"
|
|
|
|
import { buildMatcherRegex, matches } from "./matchers"
|
2022-11-16 18:23:12 +01:00
|
|
|
import { SEPARATOR, queryGlobalView, ViewName } from "../db"
|
2022-08-05 16:21:12 +02:00
|
|
|
import { getGlobalDB, doInTenant } from "../tenancy"
|
|
|
|
import { decrypt } from "../security/encryption"
|
2022-11-24 19:48:51 +01:00
|
|
|
import * as identity from "../context/identity"
|
|
|
|
import env from "../environment"
|
2022-11-26 15:46:01 +01:00
|
|
|
import { BBContext, EndpointMatcher } from "@budibase/types"
|
2022-08-05 16:21:12 +02:00
|
|
|
|
2022-11-24 19:48:51 +01:00
|
|
|
const ONE_MINUTE = env.SESSION_UPDATE_PERIOD
|
|
|
|
? parseInt(env.SESSION_UPDATE_PERIOD)
|
|
|
|
: 60 * 1000
|
2022-08-05 16:21:12 +02:00
|
|
|
|
|
|
|
interface FinaliseOpts {
|
|
|
|
authenticated?: boolean
|
|
|
|
internal?: boolean
|
|
|
|
publicEndpoint?: boolean
|
|
|
|
version?: string
|
|
|
|
user?: any
|
|
|
|
}
|
2021-04-11 12:35:55 +02:00
|
|
|
|
2022-08-05 16:21:12 +02:00
|
|
|
function timeMinusOneMinute() {
|
|
|
|
return new Date(Date.now() - ONE_MINUTE).toISOString()
|
2021-06-21 18:13:06 +02:00
|
|
|
}
|
|
|
|
|
2022-08-05 16:21:12 +02:00
|
|
|
function finalise(ctx: any, opts: FinaliseOpts = {}) {
|
|
|
|
ctx.publicEndpoint = opts.publicEndpoint || false
|
|
|
|
ctx.isAuthenticated = opts.authenticated || false
|
|
|
|
ctx.user = opts.user
|
|
|
|
ctx.internal = opts.internal || false
|
|
|
|
ctx.version = opts.version
|
|
|
|
}
|
|
|
|
|
|
|
|
async function checkApiKey(apiKey: string, populateUser?: Function) {
|
2022-02-11 23:24:48 +01:00
|
|
|
if (apiKey === env.INTERNAL_API_KEY) {
|
|
|
|
return { valid: true }
|
|
|
|
}
|
2022-02-14 22:37:40 +01:00
|
|
|
const decrypted = decrypt(apiKey)
|
|
|
|
const tenantId = decrypted.split(SEPARATOR)[0]
|
2022-03-14 20:05:02 +01:00
|
|
|
return doInTenant(tenantId, async () => {
|
|
|
|
const db = getGlobalDB()
|
|
|
|
// api key is encrypted in the database
|
2022-11-24 19:48:51 +01:00
|
|
|
const userId = (await queryGlobalView(
|
2022-08-11 14:50:05 +02:00
|
|
|
ViewName.BY_API_KEY,
|
2022-03-14 20:05:02 +01:00
|
|
|
{
|
|
|
|
key: apiKey,
|
|
|
|
},
|
|
|
|
db
|
2022-11-24 19:48:51 +01:00
|
|
|
)) as string
|
2022-03-14 20:05:02 +01:00
|
|
|
if (userId) {
|
|
|
|
return {
|
|
|
|
valid: true,
|
|
|
|
user: await getUser(userId, tenantId, populateUser),
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
throw "Invalid API key"
|
|
|
|
}
|
|
|
|
})
|
2022-02-11 23:24:48 +01:00
|
|
|
}
|
|
|
|
|
2021-08-05 10:59:08 +02:00
|
|
|
/**
|
|
|
|
* This middleware is tenancy aware, so that it does not depend on other middlewares being used.
|
|
|
|
* The tenancy modules should not be used here and it should be assumed that the tenancy context
|
|
|
|
* has not yet been populated.
|
|
|
|
*/
|
2023-01-11 10:37:37 +01:00
|
|
|
export default function (
|
2022-11-26 15:46:01 +01:00
|
|
|
noAuthPatterns: EndpointMatcher[] = [],
|
2022-11-28 15:09:18 +01:00
|
|
|
opts: { publicAllowed?: boolean; populateUser?: Function } = {
|
2022-08-05 16:21:12 +02:00
|
|
|
publicAllowed: false,
|
|
|
|
}
|
2022-11-26 15:46:01 +01:00
|
|
|
) {
|
2021-08-05 10:59:08 +02:00
|
|
|
const noAuthOptions = noAuthPatterns ? buildMatcherRegex(noAuthPatterns) : []
|
2022-11-26 15:46:01 +01:00
|
|
|
return async (ctx: BBContext | any, next: any) => {
|
2021-08-05 10:59:08 +02:00
|
|
|
let publicEndpoint = false
|
2022-11-16 18:23:12 +01:00
|
|
|
const version = ctx.request.headers[Header.API_VER]
|
2021-04-21 17:42:44 +02:00
|
|
|
// the path is not authenticated
|
2021-08-05 10:59:08 +02:00
|
|
|
const found = matches(ctx, noAuthOptions)
|
|
|
|
if (found) {
|
|
|
|
publicEndpoint = true
|
2021-04-11 12:35:55 +02:00
|
|
|
}
|
2021-04-21 17:42:44 +02:00
|
|
|
try {
|
2021-12-17 15:08:48 +01:00
|
|
|
// check the actual user is authenticated first, try header or cookie
|
2022-11-16 18:23:12 +01:00
|
|
|
const headerToken = ctx.request.headers[Header.TOKEN]
|
|
|
|
const authCookie = getCookie(ctx, Cookie.Auth) || openJwt(headerToken)
|
|
|
|
const apiKey = ctx.request.headers[Header.API_KEY]
|
|
|
|
const tenantId = ctx.request.headers[Header.TENANT_ID]
|
2021-06-21 18:13:06 +02:00
|
|
|
let authenticated = false,
|
|
|
|
user = null,
|
2022-08-05 22:35:26 +02:00
|
|
|
internal = false
|
|
|
|
if (authCookie && !apiKey) {
|
2021-10-12 17:13:54 +02:00
|
|
|
const sessionId = authCookie.sessionId
|
|
|
|
const userId = authCookie.userId
|
2022-08-05 22:35:26 +02:00
|
|
|
let session
|
|
|
|
try {
|
|
|
|
// getting session handles error checking (if session exists etc)
|
|
|
|
session = await getSession(userId, sessionId)
|
|
|
|
if (opts && opts.populateUser) {
|
|
|
|
user = await getUser(
|
|
|
|
userId,
|
|
|
|
session.tenantId,
|
|
|
|
opts.populateUser(ctx)
|
|
|
|
)
|
|
|
|
} else {
|
|
|
|
user = await getUser(userId, session.tenantId)
|
2021-07-06 19:10:04 +02:00
|
|
|
}
|
2022-08-05 22:35:26 +02:00
|
|
|
user.csrfToken = session.csrfToken
|
2022-09-06 13:25:57 +02:00
|
|
|
|
2022-09-15 12:23:51 +02:00
|
|
|
if (session?.lastAccessedAt < timeMinusOneMinute()) {
|
2022-08-05 22:35:26 +02:00
|
|
|
// make sure we denote that the session is still in use
|
|
|
|
await updateSessionTTL(session)
|
|
|
|
}
|
|
|
|
authenticated = true
|
|
|
|
} catch (err: any) {
|
|
|
|
authenticated = false
|
|
|
|
console.error("Auth Error", err?.message || err)
|
2021-07-06 19:10:04 +02:00
|
|
|
// remove the cookie as the user does not exist anymore
|
2022-11-16 18:23:12 +01:00
|
|
|
clearCookie(ctx, Cookie.Auth)
|
2021-04-23 19:07:39 +02:00
|
|
|
}
|
|
|
|
}
|
2021-06-21 18:13:06 +02:00
|
|
|
// this is an internal request, no user made it
|
2022-02-11 23:24:48 +01:00
|
|
|
if (!authenticated && apiKey) {
|
|
|
|
const populateUser = opts.populateUser ? opts.populateUser(ctx) : null
|
|
|
|
const { valid, user: foundUser } = await checkApiKey(
|
|
|
|
apiKey,
|
|
|
|
populateUser
|
|
|
|
)
|
|
|
|
if (valid && foundUser) {
|
|
|
|
authenticated = true
|
|
|
|
user = foundUser
|
|
|
|
} else if (valid) {
|
|
|
|
authenticated = true
|
|
|
|
internal = true
|
|
|
|
}
|
2021-06-21 18:13:06 +02:00
|
|
|
}
|
2021-08-05 10:59:08 +02:00
|
|
|
if (!user && tenantId) {
|
|
|
|
user = { tenantId }
|
2022-07-27 18:15:01 +02:00
|
|
|
} else if (user) {
|
2022-07-03 22:13:15 +02:00
|
|
|
delete user.password
|
2021-08-05 10:59:08 +02:00
|
|
|
}
|
2021-04-23 19:07:39 +02:00
|
|
|
// be explicit
|
2022-11-16 18:23:12 +01:00
|
|
|
if (!authenticated) {
|
2021-06-21 18:13:06 +02:00
|
|
|
authenticated = false
|
2021-04-21 17:42:44 +02:00
|
|
|
}
|
2021-06-21 18:13:06 +02:00
|
|
|
// isAuthenticated is a function, so use a variable to be able to check authed state
|
2021-08-05 10:59:08 +02:00
|
|
|
finalise(ctx, { authenticated, user, internal, version, publicEndpoint })
|
2022-05-23 23:14:44 +02:00
|
|
|
|
|
|
|
if (user && user.email) {
|
2022-05-28 22:38:22 +02:00
|
|
|
return identity.doInUserContext(user, next)
|
2022-05-23 23:14:44 +02:00
|
|
|
} else {
|
2022-05-24 10:54:36 +02:00
|
|
|
return next()
|
2022-05-23 23:14:44 +02:00
|
|
|
}
|
2022-08-05 16:21:12 +02:00
|
|
|
} catch (err: any) {
|
2022-11-04 09:30:44 +01:00
|
|
|
console.error("Auth Error", err?.message || err)
|
2021-11-16 21:56:24 +01:00
|
|
|
// invalid token, clear the cookie
|
|
|
|
if (err && err.name === "JsonWebTokenError") {
|
2022-11-16 18:23:12 +01:00
|
|
|
clearCookie(ctx, Cookie.Auth)
|
2021-11-16 21:56:24 +01:00
|
|
|
}
|
2021-04-28 19:13:21 +02:00
|
|
|
// allow configuring for public access
|
2021-08-05 10:59:08 +02:00
|
|
|
if ((opts && opts.publicAllowed) || publicEndpoint) {
|
|
|
|
finalise(ctx, { authenticated: false, version, publicEndpoint })
|
2022-05-28 22:38:22 +02:00
|
|
|
return next()
|
2021-04-28 19:13:21 +02:00
|
|
|
} else {
|
|
|
|
ctx.throw(err.status || 403, err)
|
|
|
|
}
|
2021-04-21 17:42:44 +02:00
|
|
|
}
|
2021-04-11 12:35:55 +02:00
|
|
|
}
|
|
|
|
}
|