1
0
Fork 0
mirror of synced 2024-09-29 16:51:33 +13:00
budibase/packages/server/src/api/controllers/user.js

68 lines
1.8 KiB
JavaScript
Raw Normal View History

2020-05-07 21:53:34 +12:00
const CouchDB = require("../../db")
const clientDb = require("../../db/clientDb")
2020-05-07 21:53:34 +12:00
const bcrypt = require("../../utilities/bcrypt")
2020-05-15 02:12:30 +12:00
const env = require("../../environment")
const getUserId = userName => `user_${userName}`
2020-04-08 04:25:09 +12:00
2020-04-10 03:53:48 +12:00
exports.fetch = async function(ctx) {
2020-05-07 21:53:34 +12:00
const database = new CouchDB(ctx.params.instanceId)
const data = await database.query("database/by_type", {
2020-04-10 03:53:48 +12:00
include_docs: true,
2020-05-07 21:53:34 +12:00
key: ["user"],
})
2020-04-09 03:57:27 +12:00
2020-05-07 21:53:34 +12:00
ctx.body = data.rows.map(row => row.doc)
}
2020-04-08 04:25:09 +12:00
2020-04-10 03:53:48 +12:00
exports.create = async function(ctx) {
2020-05-07 21:53:34 +12:00
const database = new CouchDB(ctx.params.instanceId)
2020-05-15 02:12:30 +12:00
const appId = (await database.get("_design/database")).metadata.applicationId
2020-05-07 21:53:34 +12:00
const { username, password, name } = ctx.request.body
2020-05-07 21:53:34 +12:00
if (!username || !password) ctx.throw(400, "Username and Password Required.")
2020-05-07 21:53:34 +12:00
const response = await database.post({
2020-05-15 02:12:30 +12:00
_id: getUserId(username),
username,
password: await bcrypt.hash(password),
2020-05-15 02:12:30 +12:00
name: name || username,
2020-05-07 21:53:34 +12:00
type: "user",
})
// the clientDB needs to store a map of users against the app
const db = new CouchDB(clientDb.name(env.CLIENT_ID))
const app = await db.get(appId)
app.userInstanceMap = {
...app.userInstanceMap,
2020-05-07 21:53:34 +12:00
[username]: ctx.params.instanceId,
}
await db.put(app)
2020-05-15 02:12:30 +12:00
ctx.status = 200
ctx.message = "User created successfully."
2020-04-11 03:37:59 +12:00
ctx.body = {
2020-05-15 02:12:30 +12:00
_rev: response.rev,
username,
name,
2020-04-11 03:37:59 +12:00
}
2020-05-07 21:53:34 +12:00
}
2020-04-10 03:53:48 +12:00
exports.destroy = async function(ctx) {
2020-05-07 21:53:34 +12:00
const database = new CouchDB(ctx.params.instanceId)
2020-05-15 02:12:30 +12:00
await database.destroy(getUserId(ctx.params.username))
ctx.message = `User ${ctx.params.username} deleted.`
ctx.status = 200
}
exports.find = async function(ctx) {
const database = new CouchDB(ctx.params.instanceId)
const user = await database.get(getUserId(ctx.params.username))
2020-04-11 03:37:59 +12:00
ctx.body = {
2020-05-15 02:12:30 +12:00
username: user.username,
name: user.name,
_rev: user._rev,
2020-04-11 03:37:59 +12:00
}
2020-05-07 21:53:34 +12:00
}