2020-05-07 11:53:34 +02:00
|
|
|
const jwt = require("jsonwebtoken")
|
|
|
|
const CouchDB = require("../../db")
|
2020-05-18 07:40:29 +02:00
|
|
|
const ClientDb = require("../../db/clientDb")
|
2020-05-07 11:53:34 +02:00
|
|
|
const bcrypt = require("../../utilities/bcrypt")
|
2020-05-14 16:12:30 +02:00
|
|
|
const env = require("../../environment")
|
2020-04-07 21:34:21 +02:00
|
|
|
|
2020-04-23 15:37:08 +02:00
|
|
|
exports.authenticate = async ctx => {
|
2020-05-07 11:53:34 +02:00
|
|
|
const { username, password } = ctx.request.body
|
2020-04-20 17:17:11 +02:00
|
|
|
|
2020-05-07 11:53:34 +02:00
|
|
|
if (!username) ctx.throw(400, "Username Required.")
|
|
|
|
if (!password) ctx.throw(400, "Password Required")
|
2020-04-07 21:34:21 +02:00
|
|
|
|
2020-05-07 11:53:34 +02:00
|
|
|
// find the instance that the user is associated with
|
2020-05-18 07:40:29 +02:00
|
|
|
const db = new CouchDB(ClientDb.name(env.CLIENT_ID))
|
2020-06-03 21:44:35 +02:00
|
|
|
const appId = ctx.params.appId
|
|
|
|
const app = await db.get(appId)
|
2020-05-07 11:53:34 +02:00
|
|
|
const instanceId = app.userInstanceMap[username]
|
2020-05-06 11:33:30 +02:00
|
|
|
|
2020-05-07 11:53:34 +02:00
|
|
|
if (!instanceId)
|
|
|
|
ctx.throw(500, "User is not associated with an instance of app", appId)
|
2020-05-06 11:33:30 +02:00
|
|
|
|
|
|
|
// Check the user exists in the instance DB by username
|
2020-05-07 11:53:34 +02:00
|
|
|
const instanceDb = new CouchDB(instanceId)
|
2020-05-06 11:33:30 +02:00
|
|
|
|
2020-05-27 18:23:01 +02:00
|
|
|
let dbUser
|
|
|
|
try {
|
|
|
|
dbUser = await instanceDb.get(`user_${username}`)
|
|
|
|
} catch (_) {
|
|
|
|
// do not want to throw a 404 - as this could be
|
|
|
|
// used to dtermine valid usernames
|
|
|
|
ctx.throw(401, "Invalid Credentials")
|
|
|
|
}
|
2020-05-06 11:33:30 +02:00
|
|
|
|
|
|
|
// authenticate
|
2020-04-23 15:37:08 +02:00
|
|
|
if (await bcrypt.compare(password, dbUser.password)) {
|
2020-05-07 11:53:34 +02:00
|
|
|
const payload = {
|
|
|
|
userId: dbUser._id,
|
2020-05-27 18:23:01 +02:00
|
|
|
accessLevelId: dbUser.accessLevelId,
|
2020-05-07 11:53:34 +02:00
|
|
|
instanceId: instanceId,
|
|
|
|
}
|
2020-05-06 21:29:47 +02:00
|
|
|
|
|
|
|
const token = jwt.sign(payload, ctx.config.jwtSecret, {
|
2020-05-07 11:53:34 +02:00
|
|
|
expiresIn: "1 day",
|
|
|
|
})
|
2020-05-06 21:49:21 +02:00
|
|
|
|
2020-05-07 11:53:34 +02:00
|
|
|
const ONE_DAY_FROM_NOW = new Date(Date.now() + 24 * 3600)
|
|
|
|
|
|
|
|
ctx.cookies.set("budibase:token", token, { expires: ONE_DAY_FROM_NOW })
|
2020-05-06 21:29:47 +02:00
|
|
|
|
2020-05-06 11:33:30 +02:00
|
|
|
ctx.body = {
|
|
|
|
token,
|
2020-05-07 11:53:34 +02:00
|
|
|
...dbUser,
|
|
|
|
}
|
2020-04-23 15:37:08 +02:00
|
|
|
} else {
|
2020-05-07 11:53:34 +02:00
|
|
|
ctx.throw(401, "Invalid credentials.")
|
2020-04-23 15:37:08 +02:00
|
|
|
}
|
2020-05-07 11:53:34 +02:00
|
|
|
}
|