2022-08-06 02:21:12 +12:00
|
|
|
import { Cookies, Headers } from "../constants"
|
|
|
|
import { getCookie, clearCookie, openJwt } from "../utils"
|
|
|
|
import { getUser } from "../cache/user"
|
|
|
|
import { getSession, updateSessionTTL } from "../security/sessions"
|
|
|
|
import { buildMatcherRegex, matches } from "./matchers"
|
|
|
|
import { SEPARATOR } from "../db/constants"
|
2022-08-12 00:50:05 +12:00
|
|
|
import { ViewName } from "../db/utils"
|
2022-08-06 02:21:12 +12:00
|
|
|
import { queryGlobalView } from "../db/views"
|
|
|
|
import { getGlobalDB, doInTenant } from "../tenancy"
|
|
|
|
import { decrypt } from "../security/encryption"
|
2022-05-29 08:38:22 +12:00
|
|
|
const identity = require("../context/identity")
|
2022-08-06 02:21:12 +12:00
|
|
|
const env = require("../environment")
|
|
|
|
|
2022-08-06 04:13:03 +12:00
|
|
|
const ONE_MINUTE = env.SESSION_UPDATE_PERIOD || 60 * 1000
|
2022-08-06 02:21:12 +12:00
|
|
|
|
|
|
|
interface FinaliseOpts {
|
|
|
|
authenticated?: boolean
|
|
|
|
internal?: boolean
|
|
|
|
publicEndpoint?: boolean
|
|
|
|
version?: string
|
|
|
|
user?: any
|
|
|
|
}
|
2021-04-11 22:35:55 +12:00
|
|
|
|
2022-08-06 02:21:12 +12:00
|
|
|
function timeMinusOneMinute() {
|
|
|
|
return new Date(Date.now() - ONE_MINUTE).toISOString()
|
2021-06-22 04:13:06 +12:00
|
|
|
}
|
|
|
|
|
2022-08-06 02:21:12 +12: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-12 11:24:48 +13:00
|
|
|
if (apiKey === env.INTERNAL_API_KEY) {
|
|
|
|
return { valid: true }
|
|
|
|
}
|
2022-02-15 10:37:40 +13:00
|
|
|
const decrypted = decrypt(apiKey)
|
|
|
|
const tenantId = decrypted.split(SEPARATOR)[0]
|
2022-03-15 08:05:02 +13:00
|
|
|
return doInTenant(tenantId, async () => {
|
|
|
|
const db = getGlobalDB()
|
|
|
|
// api key is encrypted in the database
|
|
|
|
const userId = await queryGlobalView(
|
2022-08-12 00:50:05 +12:00
|
|
|
ViewName.BY_API_KEY,
|
2022-03-15 08:05:02 +13:00
|
|
|
{
|
|
|
|
key: apiKey,
|
|
|
|
},
|
|
|
|
db
|
|
|
|
)
|
|
|
|
if (userId) {
|
|
|
|
return {
|
|
|
|
valid: true,
|
|
|
|
user: await getUser(userId, tenantId, populateUser),
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
throw "Invalid API key"
|
|
|
|
}
|
|
|
|
})
|
2022-02-12 11:24:48 +13:00
|
|
|
}
|
|
|
|
|
2021-08-05 20:59:08 +12: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.
|
|
|
|
*/
|
2022-08-26 06:41:47 +12:00
|
|
|
export = (
|
2021-09-14 04:38:12 +12:00
|
|
|
noAuthPatterns = [],
|
2022-09-15 22:23:51 +12:00
|
|
|
opts: { publicAllowed: boolean; populateUser?: Function } = {
|
2022-08-06 02:21:12 +12:00
|
|
|
publicAllowed: false,
|
|
|
|
}
|
2021-09-14 04:38:12 +12:00
|
|
|
) => {
|
2021-08-05 20:59:08 +12:00
|
|
|
const noAuthOptions = noAuthPatterns ? buildMatcherRegex(noAuthPatterns) : []
|
2022-08-06 02:21:12 +12:00
|
|
|
return async (ctx: any, next: any) => {
|
2021-08-05 20:59:08 +12:00
|
|
|
let publicEndpoint = false
|
2021-07-24 02:29:14 +12:00
|
|
|
const version = ctx.request.headers[Headers.API_VER]
|
2021-04-22 03:42:44 +12:00
|
|
|
// the path is not authenticated
|
2021-08-05 20:59:08 +12:00
|
|
|
const found = matches(ctx, noAuthOptions)
|
|
|
|
if (found) {
|
|
|
|
publicEndpoint = true
|
2021-04-11 22:35:55 +12:00
|
|
|
}
|
2021-04-22 03:42:44 +12:00
|
|
|
try {
|
2021-12-18 03:08:48 +13:00
|
|
|
// check the actual user is authenticated first, try header or cookie
|
|
|
|
const headerToken = ctx.request.headers[Headers.TOKEN]
|
|
|
|
const authCookie = getCookie(ctx, Cookies.Auth) || openJwt(headerToken)
|
2022-08-06 08:35:26 +12:00
|
|
|
const apiKey = ctx.request.headers[Headers.API_KEY]
|
|
|
|
const tenantId = ctx.request.headers[Headers.TENANT_ID]
|
2021-06-22 04:13:06 +12:00
|
|
|
let authenticated = false,
|
|
|
|
user = null,
|
2022-08-06 08:35:26 +12:00
|
|
|
internal = false
|
|
|
|
if (authCookie && !apiKey) {
|
2021-10-13 04:13:54 +13:00
|
|
|
const sessionId = authCookie.sessionId
|
|
|
|
const userId = authCookie.userId
|
2022-08-06 08:35:26 +12: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-07 05:10:04 +12:00
|
|
|
}
|
2022-08-06 08:35:26 +12:00
|
|
|
user.csrfToken = session.csrfToken
|
2022-09-06 23:25:57 +12:00
|
|
|
|
2022-09-15 22:23:51 +12:00
|
|
|
if (session?.lastAccessedAt < timeMinusOneMinute()) {
|
2022-08-06 08:35:26 +12: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-07 05:10:04 +12:00
|
|
|
// remove the cookie as the user does not exist anymore
|
2021-04-24 05:07:39 +12:00
|
|
|
clearCookie(ctx, Cookies.Auth)
|
|
|
|
}
|
|
|
|
}
|
2021-06-22 04:13:06 +12:00
|
|
|
// this is an internal request, no user made it
|
2022-02-12 11:24:48 +13: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-22 04:13:06 +12:00
|
|
|
}
|
2021-08-05 20:59:08 +12:00
|
|
|
if (!user && tenantId) {
|
|
|
|
user = { tenantId }
|
2022-07-28 04:15:01 +12:00
|
|
|
} else if (user) {
|
2022-07-04 08:13:15 +12:00
|
|
|
delete user.password
|
2021-08-05 20:59:08 +12:00
|
|
|
}
|
2021-04-24 05:07:39 +12:00
|
|
|
// be explicit
|
2022-08-06 08:35:26 +12:00
|
|
|
if (authenticated !== true) {
|
2021-06-22 04:13:06 +12:00
|
|
|
authenticated = false
|
2021-04-22 03:42:44 +12:00
|
|
|
}
|
2021-06-22 04:13:06 +12:00
|
|
|
// isAuthenticated is a function, so use a variable to be able to check authed state
|
2021-08-05 20:59:08 +12:00
|
|
|
finalise(ctx, { authenticated, user, internal, version, publicEndpoint })
|
2022-05-24 09:14:44 +12:00
|
|
|
|
|
|
|
if (user && user.email) {
|
2022-05-29 08:38:22 +12:00
|
|
|
return identity.doInUserContext(user, next)
|
2022-05-24 09:14:44 +12:00
|
|
|
} else {
|
2022-05-24 20:54:36 +12:00
|
|
|
return next()
|
2022-05-24 09:14:44 +12:00
|
|
|
}
|
2022-08-06 02:21:12 +12:00
|
|
|
} catch (err: any) {
|
2022-11-04 21:30:44 +13:00
|
|
|
console.error("Auth Error", err?.message || err)
|
2021-11-17 09:56:24 +13:00
|
|
|
// invalid token, clear the cookie
|
|
|
|
if (err && err.name === "JsonWebTokenError") {
|
|
|
|
clearCookie(ctx, Cookies.Auth)
|
|
|
|
}
|
2021-04-29 05:13:21 +12:00
|
|
|
// allow configuring for public access
|
2021-08-05 20:59:08 +12:00
|
|
|
if ((opts && opts.publicAllowed) || publicEndpoint) {
|
|
|
|
finalise(ctx, { authenticated: false, version, publicEndpoint })
|
2022-05-29 08:38:22 +12:00
|
|
|
return next()
|
2021-04-29 05:13:21 +12:00
|
|
|
} else {
|
|
|
|
ctx.throw(err.status || 403, err)
|
|
|
|
}
|
2021-04-22 03:42:44 +12:00
|
|
|
}
|
2021-04-11 22:35:55 +12:00
|
|
|
}
|
|
|
|
}
|