1
0
Fork 0
mirror of synced 2024-06-01 18:20:18 +12:00
budibase/packages/worker/src/api/controllers/global/auth.js

202 lines
5.5 KiB
JavaScript
Raw Normal View History

const authPkg = require("@budibase/auth")
2021-04-22 08:08:04 +12:00
const { google } = require("@budibase/auth/src/middleware")
2021-06-28 02:46:04 +12:00
const { oidc } = require("@budibase/auth/src/middleware")
const { Configs, EmailTemplatePurpose } = require("../../../constants")
const { sendEmail, isEmailConfigured } = require("../../../utilities/email")
const { setCookie, getCookie, clearCookie, getGlobalUserByEmail, hash } =
authPkg.utils
2021-04-23 02:27:09 +12:00
const { Cookies } = authPkg.constants
const { passport } = authPkg.auth
const { checkResetPasswordCode } = require("../../../utilities/redis")
const {
getGlobalDB,
getTenantId,
isMultiTenant,
} = require("@budibase/auth/tenancy")
const env = require("../../../environment")
function googleCallbackUrl() {
let callbackUrl = `/api/global/auth`
if (isMultiTenant()) {
callbackUrl += `/${getTenantId()}`
}
callbackUrl += `/google/callback`
return callbackUrl
}
2021-07-23 02:26:14 +12:00
async function authInternal(ctx, user, err = null, info = null) {
if (err) {
console.error("Authentication error", err)
2021-07-09 00:12:25 +12:00
return ctx.throw(403, info ? info : "Unauthorized")
}
2021-04-07 22:33:16 +12:00
const expires = new Date()
expires.setDate(expires.getDate() + 1)
2021-04-08 02:15:05 +12:00
if (!user) {
2021-07-09 00:12:25 +12:00
return ctx.throw(403, info ? info : "Unauthorized")
}
2021-04-12 21:47:48 +12:00
2021-07-07 05:10:04 +12:00
// just store the user ID
ctx.cookies.set(Cookies.Auth, user.token, {
expires,
path: "/",
httpOnly: false,
overwrite: true,
})
}
exports.authenticate = async (ctx, next) => {
return passport.authenticate("local", async (err, user, info) => {
await authInternal(ctx, user, err, info)
2021-04-08 02:15:05 +12:00
2021-04-12 21:47:48 +12:00
delete user.token
ctx.body = { user }
})(ctx, next)
}
2021-04-11 22:35:55 +12:00
/**
* Reset the user password, used as part of a forgotten password flow.
*/
exports.reset = async ctx => {
const { email } = ctx.request.body
const configured = await isEmailConfigured()
if (!configured) {
2021-05-06 02:19:44 +12:00
ctx.throw(
400,
"Please contact your platform administrator, SMTP is not configured."
)
}
try {
const user = await getGlobalUserByEmail(email)
// only if user exists, don't error though if they don't
if (user) {
await sendEmail(email, EmailTemplatePurpose.PASSWORD_RECOVERY, {
user,
subject: "{{ company }} platform password reset",
})
}
} catch (err) {
console.log(err)
// don't throw any kind of error to the user, this might give away something
}
ctx.body = {
message: "Please check your email for a reset link.",
}
}
/**
* Perform the user password update if the provided reset code is valid.
*/
exports.resetUpdate = async ctx => {
const { resetCode, password } = ctx.request.body
2021-05-06 02:17:15 +12:00
try {
const userId = await checkResetPasswordCode(resetCode)
const db = getGlobalDB()
2021-05-06 02:17:15 +12:00
const user = await db.get(userId)
user.password = await hash(password)
await db.put(user)
ctx.body = {
message: "password reset successfully.",
}
} catch (err) {
ctx.throw(400, "Cannot reset password.")
}
}
2021-04-14 00:56:28 +12:00
exports.logout = async ctx => {
clearCookie(ctx, Cookies.Auth)
ctx.body = { message: "User logged out." }
2021-04-14 00:56:28 +12:00
}
2021-04-22 22:45:22 +12:00
/**
* The initial call that google authentication makes to take you to the google login screen.
* On a successful login, you will be redirected to the googleAuth callback route.
*/
2021-04-22 08:08:04 +12:00
exports.googlePreAuth = async (ctx, next) => {
const db = getGlobalDB()
let callbackUrl = googleCallbackUrl()
const config = await authPkg.db.getScopedConfig(db, {
2021-04-22 22:45:22 +12:00
type: Configs.GOOGLE,
workspace: ctx.query.workspace,
2021-04-22 22:45:22 +12:00
})
const strategy = await google.strategyFactory(config, callbackUrl)
2021-04-22 08:08:04 +12:00
return passport.authenticate(strategy, {
scope: ["profile", "email"],
})(ctx, next)
}
2021-04-22 05:40:32 +12:00
2021-04-21 23:12:22 +12:00
exports.googleAuth = async (ctx, next) => {
const db = getGlobalDB()
const callbackUrl = googleCallbackUrl()
2021-04-23 00:46:54 +12:00
const config = await authPkg.db.getScopedConfig(db, {
2021-04-22 22:48:37 +12:00
type: Configs.GOOGLE,
workspace: ctx.query.workspace,
2021-04-22 22:48:37 +12:00
})
const strategy = await google.strategyFactory(config, callbackUrl)
2021-04-22 08:08:04 +12:00
2021-04-21 23:12:22 +12:00
return passport.authenticate(
2021-04-22 08:08:04 +12:00
strategy,
{ successRedirect: "/", failureRedirect: "/error" },
async (err, user, info) => {
await authInternal(ctx, user, err, info)
2021-04-21 23:12:22 +12:00
ctx.redirect("/")
}
)(ctx, next)
2021-04-11 22:35:55 +12:00
}
2021-06-28 02:46:04 +12:00
async function oidcStrategyFactory(ctx, configId) {
const db = getGlobalDB()
const config = await authPkg.db.getScopedConfig(db, {
type: Configs.OIDC,
group: ctx.query.group,
})
2021-07-14 04:07:48 +12:00
const chosenConfig = config.configs.filter(c => c.uuid === configId)[0]
const protocol = env.NODE_ENV === "production" ? "https" : "http"
let callbackUrl = `${protocol}://${ctx.host}/api/global/auth`
if (isMultiTenant()) {
callbackUrl += `/${getTenantId()}`
}
callbackUrl += `/oidc/callback`
2021-07-14 04:07:48 +12:00
return oidc.strategyFactory(chosenConfig, callbackUrl)
}
2021-06-28 02:46:04 +12:00
/**
* The initial call that OIDC authentication makes to take you to the configured OIDC login screen.
* On a successful login, you will be redirected to the oidcAuth callback route.
*/
2021-06-28 02:46:04 +12:00
exports.oidcPreAuth = async (ctx, next) => {
const { configId } = ctx.params
const strategy = await oidcStrategyFactory(ctx, configId)
setCookie(ctx, configId, Cookies.OIDC_CONFIG)
2021-06-28 02:46:04 +12:00
return passport.authenticate(strategy, {
// required 'openid' scope is added by oidc strategy factory
2021-06-28 02:46:04 +12:00
scope: ["profile", "email"],
})(ctx, next)
}
exports.oidcAuth = async (ctx, next) => {
const configId = getCookie(ctx, Cookies.OIDC_CONFIG)
const strategy = await oidcStrategyFactory(ctx, configId)
2021-06-28 02:46:04 +12:00
return passport.authenticate(
strategy,
{ successRedirect: "/", failureRedirect: "/error" },
2021-07-08 00:28:55 +12:00
async (err, user, info) => {
await authInternal(ctx, user, err, info)
2021-04-21 23:12:22 +12:00
ctx.redirect("/")
}
)(ctx, next)
2021-04-11 22:35:55 +12:00
}