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

82 lines
2.1 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")
const environment = require("../../environment")
const { apiKeyTable } = require("../../db/dynamoClient")
const { generateUserID } = require("../../db/utils")
2020-04-08 07:34:21 +12:00
exports.authenticate = async ctx => {
2020-06-19 03:59:31 +12:00
if (!ctx.user.appId) ctx.throw(400, "No appId")
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("client_app_lookup")
2020-06-19 03:59:31 +12:00
const { clientId } = await masterDb.get(ctx.user.appId)
if (!clientId) {
ctx.throw(400, "ClientId not supplied")
}
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-19 03:59:31 +12:00
const app = await db.get(ctx.user.appId)
2020-05-07 21:53:34 +12:00
const instanceId = app.userInstanceMap[username]
2020-05-07 21:53:34 +12:00
if (!instanceId)
2020-06-19 03:59:31 +12:00
ctx.throw(
500,
"User is not associated with an instance of app",
ctx.user.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(generateUserID(username))
2020-05-28 04:23:01 +12:00
} 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-06-19 03:59:31 +12:00
appId: ctx.user.appId,
instanceId,
2020-05-07 21:53:34 +12:00
}
// if in cloud add the user api key
if (environment.CLOUD) {
payload.apiKey = await apiKeyTable.get({ primary: ctx.user.appId })
}
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-06-20 03:59:46 +12:00
const expires = new Date()
expires.setDate(expires.getDate() + 1)
2020-05-07 21:53:34 +12:00
2020-06-20 03:59:46 +12:00
ctx.cookies.set("budibase:token", token, {
expires,
path: "/",
httpOnly: false,
})
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
}