1
0
Fork 0
mirror of synced 2024-06-30 20:10:54 +12:00
budibase/packages/server/src/api/controllers/auth.js

63 lines
1.7 KiB
JavaScript
Raw Normal View History

2020-05-07 21:53:34 +12:00
const jwt = require("jsonwebtoken")
const CouchDB = require("../../db")
const ClientDb = require("../../db/clientDb")
2020-05-07 21:53:34 +12:00
const bcrypt = require("../../utilities/bcrypt")
2020-04-08 07:34:21 +12:00
exports.authenticate = async ctx => {
2020-05-07 21:53:34 +12:00
const { username, password } = ctx.request.body
2020-05-07 21:53:34 +12:00
if (!username) ctx.throw(400, "Username Required.")
if (!password) ctx.throw(400, "Password Required")
2020-04-08 07:34:21 +12:00
const masterDb = new CouchDB("clientAppLookup")
const { clientId } = await masterDb.get(ctx.params.appId)
if (!clientId) {
ctx.throw(400, "ClientId not suplied")
}
2020-05-07 21:53:34 +12:00
// find the instance that the user is associated with
const db = new CouchDB(ClientDb.name(clientId))
2020-06-04 07:44:35 +12:00
const appId = ctx.params.appId
const app = await db.get(appId)
2020-05-07 21:53:34 +12:00
const instanceId = app.userInstanceMap[username]
2020-05-07 21:53:34 +12:00
if (!instanceId)
ctx.throw(500, "User is not associated with an instance of app", appId)
// Check the user exists in the instance DB by username
2020-05-07 21:53:34 +12:00
const instanceDb = new CouchDB(instanceId)
2020-05-28 04:23:01 +12: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")
}
// authenticate
if (await bcrypt.compare(password, dbUser.password)) {
2020-05-07 21:53:34 +12:00
const payload = {
userId: dbUser._id,
2020-05-28 04:23:01 +12:00
accessLevelId: dbUser.accessLevelId,
2020-05-07 21:53:34 +12:00
instanceId: instanceId,
}
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
2020-05-07 21:53:34 +12: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-07 07:29:47 +12:00
ctx.body = {
token,
2020-05-07 21:53:34 +12:00
...dbUser,
}
} else {
2020-05-07 21:53:34 +12:00
ctx.throw(401, "Invalid credentials.")
}
2020-05-07 21:53:34 +12:00
}