1
0
Fork 0
mirror of synced 2024-06-28 11:00:55 +12:00
budibase/packages/server/src/api/controllers/auth.js

60 lines
1.6 KiB
JavaScript
Raw Normal View History

2020-05-07 21:53:34 +12:00
const jwt = require("jsonwebtoken")
const CouchDB = require("../../db")
const bcrypt = require("../../utilities/bcrypt")
const env = require("../../environment")
const { getAPIKey } = require("../../utilities/usageQuota")
const { generateUserID } = require("../../db/utils")
const { setCookie } = require("../../utilities")
2020-04-08 07:34:21 +12:00
exports.authenticate = async ctx => {
const appId = ctx.appId
if (!appId) ctx.throw(400, "No appId")
2020-12-05 01:22:45 +13:00
const { email, password } = ctx.request.body
2020-12-05 01:22:45 +13:00
if (!email) ctx.throw(400, "Email Required.")
if (!password) ctx.throw(400, "Password Required.")
2020-12-05 01:22:45 +13:00
// Check the user exists in the instance DB by email
const db = new CouchDB(appId)
const app = await db.get(appId)
2020-05-28 04:23:01 +12:00
let dbUser
try {
2020-12-05 01:22:45 +13:00
dbUser = await db.get(generateUserID(email))
2020-05-28 04:23:01 +12:00
} catch (_) {
// do not want to throw a 404 - as this could be
2020-12-05 01:22:45 +13:00
// used to determine valid emails
2020-05-28 04:23:01 +12:00
ctx.throw(401, "Invalid Credentials")
}
// authenticate
if (await bcrypt.compare(password, dbUser.password)) {
2020-05-07 21:53:34 +12:00
const payload = {
userId: dbUser._id,
roleId: dbUser.roleId,
version: app.version,
2020-05-07 21:53:34 +12:00
}
// if in cloud add the user api key, unless self hosted
if (env.CLOUD && !env.SELF_HOSTED) {
2020-10-10 09:42:20 +13:00
const { apiKey } = await getAPIKey(ctx.user.appId)
payload.apiKey = apiKey
}
2020-05-07 07:29:47 +12:00
const token = jwt.sign(payload, ctx.config.jwtSecret, {
2020-05-07 21:53:34 +12:00
expiresIn: "1 day",
})
2020-05-07 07:49:21 +12:00
setCookie(ctx, appId, token)
2020-05-07 07:29:47 +12:00
delete dbUser.password
ctx.body = {
token,
2020-05-07 21:53:34 +12:00
...dbUser,
appId,
2020-05-07 21:53:34 +12:00
}
} else {
2020-05-07 21:53:34 +12:00
ctx.throw(401, "Invalid credentials.")
}
2020-05-07 21:53:34 +12:00
}