email as default user identifier

This commit is contained in:
Martin McKeaveney 2020-12-04 12:22:45 +00:00
parent aa0d027f06
commit f05d696ef7
18 changed files with 92 additions and 79 deletions

View File

@ -44,9 +44,9 @@ Cypress.Commands.add("createApp", name => {
cy.contains("Next").click()
cy.get("input[name=username]")
cy.get("input[name=email]")
.click()
.type("test")
.type("test@test.com")
cy.get("input[name=password]")
.click()
.type("test")
@ -111,7 +111,7 @@ Cypress.Commands.add("addRow", values => {
})
})
Cypress.Commands.add("createUser", (username, password, accessLevel) => {
Cypress.Commands.add("createUser", (email, password, accessLevel) => {
// Create User
cy.contains("Users").click()
@ -123,7 +123,7 @@ Cypress.Commands.add("createUser", (username, password, accessLevel) => {
.type(password)
cy.get("input")
.eq(1)
.type(username)
.type(email)
cy.get("select")
.first()
.select(accessLevel)

View File

@ -62,6 +62,8 @@
</Select>
{:else if value.customType === 'password'}
<Input type="password" extraThin bind:value={block.inputs[key]} />
{:else if value.customType === 'email'}
<Input type="email" extraThin bind:value={block.inputs[key]} />
{:else if value.customType === 'table'}
<TableSelector bind:value={block.inputs[key]} />
{:else if value.customType === 'row'}

View File

@ -52,7 +52,9 @@
applicationName: string().required("Your application must have a name."),
},
{
username: string().required("Your application needs a first user."),
email: string()
.email()
.required("Your application needs a first user."),
password: string().required(
"Please enter a password for your first user."
),
@ -164,8 +166,7 @@
// Create user
const user = {
name: $createAppStore.values.username,
username: $createAppStore.values.username,
email: $createAppStore.values.email,
password: $createAppStore.values.password,
accessLevelId: $createAppStore.values.accessLevelId,
}

View File

@ -2,18 +2,18 @@
import { Input, Select } from "@budibase/bbui"
export let validationErrors
let blurred = { username: false, password: false }
let blurred = { email: false, password: false }
</script>
<h2>Create your first User</h2>
<div class="container">
<Input
on:input={() => (blurred.username = true)}
label="Username"
name="username"
placeholder="Username"
type="name"
error={blurred.username && validationErrors.username} />
on:input={() => (blurred.email = true)}
label="Email"
name="email"
placeholder="Email"
type="email"
error={blurred.email && validationErrors.email} />
<Input
on:input={() => (blurred.password = true)}
label="Password"

View File

@ -3,7 +3,7 @@ export const TableNames = {
}
// fields on the user table that cannot be edited
export const UNEDITABLE_USER_FIELDS = ["username", "password", "accessLevelId"]
export const UNEDITABLE_USER_FIELDS = ["email", "password", "accessLevelId"]
export const DEFAULT_PAGES_OBJECT = {
main: {

View File

@ -3,15 +3,15 @@ import API from "./api"
/**
* Performs a log in request.
*/
export const logIn = async ({ username, password }) => {
if (!username) {
return API.error("Please enter your username")
export const logIn = async ({ email, password }) => {
if (!email) {
return API.error("Please enter your email")
}
if (!password) {
return API.error("Please enter your password")
}
return await API.post({
url: "/api/authenticate",
body: { username, password },
body: { email, password },
})
}

View File

@ -5,8 +5,8 @@ import { writable } from "svelte/store"
const createAuthStore = () => {
const store = writable("")
const logIn = async ({ username, password }) => {
const user = await API.logIn({ username, password })
const logIn = async ({ email, password }) => {
const user = await API.logIn({ email, password })
if (!user.error) {
store.set(user.token)
location.reload()

View File

@ -10,21 +10,21 @@ exports.authenticate = async ctx => {
const appId = ctx.appId
if (!appId) ctx.throw(400, "No appId")
const { username, password } = ctx.request.body
const { email, password } = ctx.request.body
if (!username) ctx.throw(400, "Username Required.")
if (!email) ctx.throw(400, "Email Required.")
if (!password) ctx.throw(400, "Password Required.")
// Check the user exists in the instance DB by username
// Check the user exists in the instance DB by email
const db = new CouchDB(appId)
const app = await db.get(appId)
let dbUser
try {
dbUser = await db.get(generateUserID(username))
dbUser = await db.get(generateUserID(email))
} catch (_) {
// do not want to throw a 404 - as this could be
// used to determine valid usernames
// used to determine valid emails
ctx.throw(401, "Invalid Credentials")
}

View File

@ -20,16 +20,10 @@ exports.fetch = async function(ctx) {
exports.create = async function(ctx) {
const db = new CouchDB(ctx.user.appId)
const {
username,
password,
name,
accessLevelId,
permissions,
} = ctx.request.body
const { email, password, name, accessLevelId, permissions } = ctx.request.body
if (!username || !password) {
ctx.throw(400, "Username and Password Required.")
if (!email || !password) {
ctx.throw(400, "email and Password Required.")
}
const accessLevel = await checkAccessLevel(db, accessLevelId)
@ -37,10 +31,10 @@ exports.create = async function(ctx) {
if (!accessLevel) ctx.throw(400, "Invalid Access Level")
const user = {
_id: generateUserID(username),
username,
_id: generateUserID(email),
email,
password: await bcrypt.hash(password),
name: name || username,
name,
type: "user",
accessLevelId,
permissions: permissions || [BUILTIN_PERMISSION_NAMES.POWER],
@ -54,7 +48,7 @@ exports.create = async function(ctx) {
ctx.userId = response._id
ctx.body = {
_rev: response.rev,
username,
email,
name,
}
} catch (err) {
@ -76,22 +70,22 @@ exports.update = async function(ctx) {
user._rev = response.rev
ctx.status = 200
ctx.message = `User ${ctx.request.body.username} updated successfully.`
ctx.message = `User ${ctx.request.body.email} updated successfully.`
ctx.body = response
}
exports.destroy = async function(ctx) {
const database = new CouchDB(ctx.user.appId)
await database.destroy(generateUserID(ctx.params.username))
ctx.message = `User ${ctx.params.username} deleted.`
await database.destroy(generateUserID(ctx.params.email))
ctx.message = `User ${ctx.params.email} deleted.`
ctx.status = 200
}
exports.find = async function(ctx) {
const database = new CouchDB(ctx.user.appId)
const user = await database.get(generateUserID(ctx.params.username))
const user = await database.get(generateUserID(ctx.params.email))
ctx.body = {
username: user.username,
email: user.email,
name: user.name,
_rev: user._rev,
}

View File

@ -118,7 +118,7 @@ exports.clearApplications = async request => {
exports.createUser = async (
request,
appId,
username = "babs",
email = "babs",
password = "babs_password"
) => {
const res = await request
@ -126,7 +126,7 @@ exports.createUser = async (
.set(exports.defaultHeaders(appId))
.send({
name: "Bill",
username,
email,
password,
accessLevelId: BUILTIN_LEVEL_IDS.POWER,
})
@ -174,15 +174,14 @@ const createUserWithPermissions = async (
request,
appId,
permissions,
username
email
) => {
const password = `password_${username}`
const password = `password_${email}`
await request
.post(`/api/users`)
.set(exports.defaultHeaders(appId))
.send({
name: username,
username,
email,
password,
accessLevelId: BUILTIN_LEVEL_IDS.POWER,
permissions,
@ -203,7 +202,7 @@ const createUserWithPermissions = async (
Cookie: `budibase:${appId}:local=${anonToken}`,
"x-budibase-app-id": appId,
})
.send({ username, password })
.send({ email, password })
// returning necessary request headers
return {

View File

@ -34,8 +34,8 @@ describe("/users", () => {
describe("fetch", () => {
it("returns a list of users from an instance db", async () => {
await createUser(request, appId, "brenda", "brendas_password")
await createUser(request, appId, "pam", "pam_password")
await createUser(request, appId, "brenda@brenda.com", "brendas_password")
await createUser(request, appId, "pam@pam.com", "pam_password")
const res = await request
.get(`/api/users`)
.set(defaultHeaders(appId))
@ -43,8 +43,8 @@ describe("/users", () => {
.expect(200)
expect(res.body.length).toBe(2)
expect(res.body.find(u => u.username === "brenda")).toBeDefined()
expect(res.body.find(u => u.username === "pam")).toBeDefined()
expect(res.body.find(u => u.email === "brenda@brenda.com")).toBeDefined()
expect(res.body.find(u => u.email === "pam@pam.com")).toBeDefined()
})
it("should apply authorization to endpoint", async () => {
@ -67,7 +67,7 @@ describe("/users", () => {
const res = await request
.post(`/api/users`)
.set(defaultHeaders(appId))
.send({ name: "Bill", username: "bill", password: "bills_password", accessLevelId: BUILTIN_LEVEL_IDS.POWER })
.send({ name: "Bill", email: "bill@bill.com", password: "bills_password", accessLevelId: BUILTIN_LEVEL_IDS.POWER })
.expect(200)
.expect('Content-Type', /json/)
@ -79,7 +79,7 @@ describe("/users", () => {
await testPermissionsForEndpoint({
request,
method: "POST",
body: { name: "brandNewUser", username: "brandNewUser", password: "yeeooo", accessLevelId: BUILTIN_LEVEL_IDS.POWER },
body: { name: "brandNewUser", email: "brandNewUser@user.com", password: "yeeooo", accessLevelId: BUILTIN_LEVEL_IDS.POWER },
url: `/api/users`,
appId: appId,
permName1: BUILTIN_PERMISSION_NAMES.ADMIN,

View File

@ -16,7 +16,7 @@ router
controller.fetch
)
.get(
"/api/users/:username",
"/api/users/:email",
authorized(PermissionTypes.USER, PermissionLevels.READ),
controller.find
)
@ -32,7 +32,7 @@ router
controller.create
)
.delete(
"/api/users/:username",
"/api/users/:email",
authorized(PermissionTypes.USER, PermissionLevels.WRITE),
usage,
controller.destroy

View File

@ -1,4 +1,5 @@
const Koa = require("koa")
const destroyable = require("server-destroy")
const electron = require("electron")
const koaBody = require("koa-body")
const logger = require("koa-pino-logger")
@ -44,6 +45,7 @@ if (electron.app && electron.app.isPackaged) {
}
const server = http.createServer(app.callback())
destroyable(server)
server.on("close", () => console.log("Server Closed"))
@ -51,3 +53,14 @@ module.exports = server.listen(env.PORT || 4001, () => {
console.log(`Budibase running on ${JSON.stringify(server.address())}`)
automations.init()
})
process.on("uncaughtException", err => {
console.error(err)
server.close()
server.destroy()
})
process.on("SIGTERM", () => {
server.close()
server.destroy()
})

View File

@ -5,7 +5,7 @@ const usage = require("../../utilities/usageQuota")
module.exports.definition = {
description: "Create a new user",
tagline: "Create user {{inputs.username}}",
tagline: "Create user {{inputs.email}}",
icon: "ri-user-add-line",
name: "Create User",
type: "ACTION",
@ -16,9 +16,10 @@ module.exports.definition = {
schema: {
inputs: {
properties: {
username: {
email: {
type: "string",
title: "Username",
customType: "email",
title: "Email",
},
password: {
type: "string",
@ -32,7 +33,7 @@ module.exports.definition = {
pretty: accessLevels.BUILTIN_LEVEL_NAME_ARRAY,
},
},
required: ["username", "password", "accessLevelId"],
required: ["email", "password", "accessLevelId"],
},
outputs: {
properties: {
@ -59,13 +60,13 @@ module.exports.definition = {
}
module.exports.run = async function({ inputs, appId, apiKey }) {
const { username, password, accessLevelId } = inputs
const { email, password, accessLevelId } = inputs
const ctx = {
user: {
appId: appId,
},
request: {
body: { username, password, accessLevelId },
body: { email, password, accessLevelId },
},
}

View File

@ -12,17 +12,18 @@ const USERS_TABLE_SCHEMA = {
views: {},
name: "Users",
schema: {
username: {
email: {
type: "string",
constraints: {
type: "string",
email: true,
length: {
maximum: "",
},
presence: true,
},
fieldName: "username",
name: "username",
fieldName: "email",
name: "email",
},
accessLevelId: {
fieldName: "accessLevelId",
@ -35,7 +36,7 @@ const USERS_TABLE_SCHEMA = {
},
},
},
primaryDisplay: "username",
primaryDisplay: "email",
}
exports.AuthTypes = AuthTypes

View File

@ -101,10 +101,10 @@ exports.generateRowID = tableId => {
/**
* Gets parameters for retrieving users, this is a utility function for the getDocParams function.
*/
exports.getUserParams = (username = "", otherProps = {}) => {
exports.getUserParams = (email = "", otherProps = {}) => {
return getDocParams(
DocumentTypes.ROW,
`${ViewNames.USERS}${SEPARATOR}${DocumentTypes.USER}${SEPARATOR}${username}`,
`${ViewNames.USERS}${SEPARATOR}${DocumentTypes.USER}${SEPARATOR}${email}`,
otherProps
)
}

View File

@ -56,7 +56,7 @@
},
"login": {
"name": "Login Control",
"description": "A control that accepts username, password an also handles password resets",
"description": "A control that accepts email, password an also handles password resets",
"props": {
"logo": "string",
"title": "string",

View File

@ -10,7 +10,7 @@
export let buttonClass = ""
export let inputClass = ""
let username = ""
let email = ""
let password = ""
let loading = false
let error = false
@ -24,7 +24,7 @@
const login = async () => {
loading = true
await authStore.actions.logIn({ username, password })
await authStore.actions.logIn({ email, password })
loading = false
}
</script>
@ -32,7 +32,9 @@
<div class="root" use:styleable={$component.styles}>
<div class="content">
{#if logo}
<div class="logo-container"><img src={logo} alt="logo" /></div>
<div class="logo-container">
<img src={logo} alt="logo" />
</div>
{/if}
{#if title}
@ -42,9 +44,9 @@
<div class="form-root">
<div class="control">
<input
bind:value={username}
type="text"
placeholder="Username"
bind:value={email}
type="email"
placeholder="Email"
class={_inputClass} />
</div>
@ -62,7 +64,7 @@
</div>
{#if error}
<div class="incorrect-details-panel">Incorrect username or password</div>
<div class="incorrect-details-panel">Incorrect email or password</div>
{/if}
</div>
</div>