2021-04-22 03:42:44 +12:00
|
|
|
const authPkg = require("@budibase/auth")
|
|
|
|
const { clearCookie } = authPkg.utils
|
|
|
|
const { Cookies } = authPkg.constants
|
|
|
|
const { passport } = authPkg.auth
|
2021-04-02 08:34:43 +13:00
|
|
|
|
|
|
|
exports.authenticate = async (ctx, next) => {
|
2021-04-08 02:15:05 +12:00
|
|
|
return passport.authenticate("local", async (err, user) => {
|
2021-04-07 22:33:16 +12:00
|
|
|
if (err) {
|
2021-04-16 02:57:55 +12:00
|
|
|
return ctx.throw(403, "Unauthorized")
|
2021-04-07 22:33:16 +12:00
|
|
|
}
|
|
|
|
|
2021-04-08 02:15:05 +12:00
|
|
|
const expires = new Date()
|
|
|
|
expires.setDate(expires.getDate() + 1)
|
|
|
|
|
2021-04-12 21:47:48 +12:00
|
|
|
if (!user) {
|
2021-04-16 02:57:55 +12:00
|
|
|
return ctx.throw(403, "Unauthorized")
|
2021-04-12 21:47:48 +12:00
|
|
|
}
|
|
|
|
|
2021-04-11 22:35:55 +12:00
|
|
|
ctx.cookies.set(Cookies.Auth, user.token, {
|
2021-04-08 02:15:05 +12:00
|
|
|
expires,
|
|
|
|
path: "/",
|
|
|
|
httpOnly: false,
|
|
|
|
overwrite: true,
|
|
|
|
})
|
|
|
|
|
2021-04-12 21:47:48 +12:00
|
|
|
delete user.token
|
|
|
|
|
2021-04-16 02:57:55 +12:00
|
|
|
ctx.body = { user }
|
2021-04-02 08:34:43 +13:00
|
|
|
})(ctx, next)
|
|
|
|
}
|
2021-04-11 22:35:55 +12:00
|
|
|
|
2021-04-14 00:56:28 +12:00
|
|
|
exports.logout = async ctx => {
|
2021-04-14 03:56:45 +12:00
|
|
|
clearCookie(ctx, Cookies.Auth)
|
2021-04-16 03:49:35 +12:00
|
|
|
ctx.body = { message: "User logged out" }
|
2021-04-14 00:56:28 +12:00
|
|
|
}
|
|
|
|
|
2021-04-22 05:40:32 +12:00
|
|
|
// exports.googleAuth = async (ctx, next) =>
|
|
|
|
// passport.authenticate(
|
|
|
|
// "google",
|
|
|
|
// { successRedirect: "/", failureRedirect: "/" },
|
|
|
|
// (ctx
|
|
|
|
// setToken(ctx, next)
|
|
|
|
// )
|
|
|
|
|
2021-04-21 23:12:22 +12:00
|
|
|
exports.googleAuth = async (ctx, next) => {
|
|
|
|
return passport.authenticate(
|
|
|
|
"google",
|
|
|
|
{ successRedirect: "/", failureRedirect: "/" },
|
|
|
|
async (err, user) => {
|
|
|
|
if (err) {
|
|
|
|
return ctx.throw(403, "Unauthorized")
|
|
|
|
}
|
|
|
|
|
|
|
|
const expires = new Date()
|
|
|
|
expires.setDate(expires.getDate() + 1)
|
2021-04-14 00:56:28 +12:00
|
|
|
|
2021-04-21 23:12:22 +12:00
|
|
|
if (!user) {
|
|
|
|
return ctx.throw(403, "Unauthorized")
|
|
|
|
}
|
|
|
|
|
|
|
|
ctx.cookies.set(Cookies.Auth, user.token, {
|
|
|
|
expires,
|
|
|
|
path: "/",
|
|
|
|
httpOnly: false,
|
|
|
|
overwrite: true,
|
|
|
|
})
|
|
|
|
|
|
|
|
ctx.redirect("/")
|
|
|
|
}
|
|
|
|
)(ctx, next)
|
2021-04-11 22:35:55 +12:00
|
|
|
}
|