Merge pull request #7559 from Budibase/user-invite-validation

Apply validation to invite users by email + results modal
This commit is contained in:
Rory Powell 2022-09-01 09:19:03 +01:00 committed by GitHub
commit 53cb288526
8 changed files with 246 additions and 73 deletions

View File

@ -44,7 +44,11 @@
] ]
} }
function validateInput(email, index) { function validateInput(input, index) {
if (input.email) {
input.email = input.email.trim()
}
const email = input.email
if (email) { if (email) {
const res = emailValidator(email) const res = emailValidator(email)
if (res === true) { if (res === true) {
@ -95,7 +99,7 @@
bind:dropdownValue={input.role} bind:dropdownValue={input.role}
options={Constants.BudibaseRoleOptions} options={Constants.BudibaseRoleOptions}
error={input.error} error={input.error}
on:blur={() => validateInput(input.email, index)} on:blur={() => validateInput(input, index)}
/> />
</div> </div>
<div class="icon"> <div class="icon">

View File

@ -0,0 +1,75 @@
<script>
import { Body, ModalContent, Table } from "@budibase/bbui"
import { onMount } from "svelte"
export let inviteUsersResponse
let hasSuccess
let hasFailure
let title
let failureMessage
let unsuccessfulUsers
const setTitle = () => {
if (hasSuccess) {
title = "Users invited!"
} else if (hasFailure) {
title = "Oops!"
}
}
const setFailureMessage = () => {
if (hasSuccess) {
failureMessage = "However there was a problem inviting some users."
} else {
failureMessage = "There was a problem inviting users."
}
}
const setUsers = () => {
unsuccessfulUsers = inviteUsersResponse.unsuccessful.map(user => {
return {
email: user.email,
reason: user.reason,
}
})
}
onMount(() => {
hasSuccess = inviteUsersResponse.successful.length
hasFailure = inviteUsersResponse.unsuccessful.length
setTitle()
setFailureMessage()
setUsers()
})
const failedSchema = {
email: {},
reason: {},
}
</script>
<ModalContent showCancelButton={false} {title} confirmText="Done">
{#if hasSuccess}
<Body size="XS">
Your users should now receive an email invite to get access to their
Budibase account
</Body>
{/if}
{#if hasFailure}
<Body size="XS">
{failureMessage}
</Body>
<Table
schema={failedSchema}
data={unsuccessfulUsers}
allowEditColumns={false}
allowEditRows={false}
allowSelectRows={false}
/>
{/if}
</ModalContent>
<style>
</style>

View File

@ -7,7 +7,6 @@
Table, Table,
Layout, Layout,
Modal, Modal,
ModalContent,
Search, Search,
notifications, notifications,
Pagination, Pagination,
@ -23,6 +22,7 @@
import { goto } from "@roxi/routify" import { goto } from "@roxi/routify"
import OnboardingTypeModal from "./_components/OnboardingTypeModal.svelte" import OnboardingTypeModal from "./_components/OnboardingTypeModal.svelte"
import PasswordModal from "./_components/PasswordModal.svelte" import PasswordModal from "./_components/PasswordModal.svelte"
import InvitedModal from "./_components/InvitedModal.svelte"
import DeletionFailureModal from "./_components/DeletionFailureModal.svelte" import DeletionFailureModal from "./_components/DeletionFailureModal.svelte"
import ImportUsersModal from "./_components/ImportUsersModal.svelte" import ImportUsersModal from "./_components/ImportUsersModal.svelte"
import { createPaginationStore } from "helpers/pagination" import { createPaginationStore } from "helpers/pagination"
@ -59,6 +59,7 @@
$: userData = [] $: userData = []
$: createUsersResponse = { successful: [], unsuccessful: [] } $: createUsersResponse = { successful: [], unsuccessful: [] }
$: deleteUsersResponse = { successful: [], unsuccessful: [] } $: deleteUsersResponse = { successful: [], unsuccessful: [] }
$: inviteUsersResponse = { successful: [], unsuccessful: [] }
$: page = $pageInfo.page $: page = $pageInfo.page
$: fetchUsers(page, searchEmail) $: fetchUsers(page, searchEmail)
$: { $: {
@ -96,8 +97,7 @@
admin: user.role === Constants.BudibaseRoles.Admin, admin: user.role === Constants.BudibaseRoles.Admin,
})) }))
try { try {
const res = await users.invite(payload) inviteUsersResponse = await users.invite(payload)
notifications.success(res.message)
inviteConfirmationModal.show() inviteConfirmationModal.show()
} catch (error) { } catch (error) {
notifications.error("Error inviting user") notifications.error("Error inviting user")
@ -144,10 +144,10 @@
userData = await removingDuplicities({ groups, users }) userData = await removingDuplicities({ groups, users })
if (!userData.users.length) return if (!userData.users.length) return
return createUser() return createUsers()
} }
async function createUser() { async function createUsers() {
try { try {
createUsersResponse = await users.create( createUsersResponse = await users.create(
await removingDuplicities(userData) await removingDuplicities(userData)
@ -164,7 +164,7 @@
if (onboardingType === "emailOnboarding") { if (onboardingType === "emailOnboarding") {
createUserFlow() createUserFlow()
} else { } else {
await createUser() await createUsers()
} }
} }
@ -281,16 +281,7 @@
</Modal> </Modal>
<Modal bind:this={inviteConfirmationModal}> <Modal bind:this={inviteConfirmationModal}>
<ModalContent <InvitedModal {inviteUsersResponse} />
showCancelButton={false}
title="Invites sent!"
confirmText="Done"
>
<Body size="S"
>Your users should now recieve an email invite to get access to their
Budibase account</Body
></ModalContent
>
</Modal> </Modal>
<Modal bind:this={onboardingTypeModal}> <Modal bind:this={onboardingTypeModal}>

View File

@ -29,3 +29,15 @@ export interface BulkDeleteUsersResponse {
successful: UserDetails[] successful: UserDetails[]
unsuccessful: { _id: string; email: string; reason: string }[] unsuccessful: { _id: string; email: string; reason: string }[]
} }
export interface InviteUserRequest {
email: string
userInfo: any
}
export type InviteUsersRequest = InviteUserRequest[]
export interface InviteUsersResponse {
successful: { email: string }[]
unsuccessful: { email: string; reason: string }[]
}

View File

@ -1,9 +1,13 @@
import { EmailTemplatePurpose } from "../../../constants"
import { checkInviteCode } from "../../../utilities/redis" import { checkInviteCode } from "../../../utilities/redis"
import { sendEmail } from "../../../utilities/email"
import { users } from "../../../sdk" import { users } from "../../../sdk"
import env from "../../../environment" import env from "../../../environment"
import { BulkDeleteUsersRequest, CloudAccount, User } from "@budibase/types" import {
BulkDeleteUsersRequest,
CloudAccount,
InviteUserRequest,
InviteUsersRequest,
User,
} from "@budibase/types"
import { import {
accounts, accounts,
cache, cache,
@ -191,58 +195,27 @@ export const tenantUserLookup = async (ctx: any) => {
} }
export const invite = async (ctx: any) => { export const invite = async (ctx: any) => {
let { email, userInfo } = ctx.request.body const request = ctx.request.body as InviteUserRequest
const existing = await usersCore.getGlobalUserByEmail(email) const response = await users.invite([request])
if (existing) {
ctx.throw(400, "Email address already in use.") // explicitly throw for single user invite
if (response.unsuccessful.length) {
const reason = response.unsuccessful[0].reason
if (reason === "Unavailable") {
ctx.throw(400, reason)
} else {
ctx.throw(500, reason)
} }
if (!userInfo) {
userInfo = {}
} }
userInfo.tenantId = tenancy.getTenantId()
const opts: any = {
subject: "{{ company }} platform invitation",
info: userInfo,
}
await sendEmail(email, EmailTemplatePurpose.INVITATION, opts)
ctx.body = { ctx.body = {
message: "Invitation has been sent.", message: "Invitation has been sent.",
} }
await events.user.invited()
} }
export const inviteMultiple = async (ctx: any) => { export const inviteMultiple = async (ctx: any) => {
let users = ctx.request.body const request = ctx.request.body as InviteUsersRequest
let existing = false ctx.body = await users.invite(request)
let existingEmail
for (let user of users) {
if (await usersCore.getGlobalUserByEmail(user.email)) {
existing = true
existingEmail = user.email
break
}
}
if (existing) {
ctx.throw(400, `${existingEmail} already exists`)
}
for (let i = 0; i < users.length; i++) {
let userInfo = users[i].userInfo
if (!userInfo) {
userInfo = {}
}
userInfo.tenantId = tenancy.getTenantId()
const opts: any = {
subject: "{{ company }} platform invitation",
info: userInfo,
}
await sendEmail(users[i].email, EmailTemplatePurpose.INVITATION, opts)
}
ctx.body = {
message: "Invitations have been sent.",
}
} }
export const inviteAccept = async (ctx: any) => { export const inviteAccept = async (ctx: any) => {

View File

@ -1,3 +1,5 @@
import { InviteUsersResponse } from "@budibase/types"
jest.mock("nodemailer") jest.mock("nodemailer")
import { import {
TestConfiguration, TestConfiguration,
@ -27,7 +29,8 @@ describe("/api/global/users", () => {
describe("invite", () => { describe("invite", () => {
it("should be able to generate an invitation", async () => { it("should be able to generate an invitation", async () => {
const { code, res } = await api.users.sendUserInvite(sendMailMock) const email = structures.users.newEmail()
const { code, res } = await api.users.sendUserInvite(sendMailMock, email)
expect(res.body).toEqual({ message: "Invitation has been sent." }) expect(res.body).toEqual({ message: "Invitation has been sent." })
expect(sendMailMock).toHaveBeenCalled() expect(sendMailMock).toHaveBeenCalled()
@ -35,13 +38,27 @@ describe("/api/global/users", () => {
expect(events.user.invited).toBeCalledTimes(1) expect(events.user.invited).toBeCalledTimes(1)
}) })
it("should not be able to generate an invitation for existing user", async () => {
const { code, res } = await api.users.sendUserInvite(
sendMailMock,
config.defaultUser!.email,
400
)
expect(res.body.message).toBe("Unavailable")
expect(sendMailMock).toHaveBeenCalledTimes(0)
expect(code).toBeUndefined()
expect(events.user.invited).toBeCalledTimes(0)
})
it("should be able to create new user from invite", async () => { it("should be able to create new user from invite", async () => {
const { code } = await api.users.sendUserInvite(sendMailMock) const email = structures.users.newEmail()
const { code } = await api.users.sendUserInvite(sendMailMock, email)
const res = await api.users.acceptInvite(code) const res = await api.users.acceptInvite(code)
expect(res.body._id).toBeDefined() expect(res.body._id).toBeDefined()
const user = await config.getUser("invite@test.com") const user = await config.getUser(email)
expect(user).toBeDefined() expect(user).toBeDefined()
expect(user._id).toEqual(res.body._id) expect(user._id).toEqual(res.body._id)
expect(events.user.inviteAccepted).toBeCalledTimes(1) expect(events.user.inviteAccepted).toBeCalledTimes(1)
@ -49,6 +66,37 @@ describe("/api/global/users", () => {
}) })
}) })
describe("inviteMultiple", () => {
it("should be able to generate an invitation", async () => {
const newUserInvite = () => ({
email: structures.users.newEmail(),
userInfo: {},
})
const request = [newUserInvite(), newUserInvite()]
const res = await api.users.sendMultiUserInvite(request)
const body = res.body as InviteUsersResponse
expect(body.successful.length).toBe(2)
expect(body.unsuccessful.length).toBe(0)
expect(sendMailMock).toHaveBeenCalledTimes(2)
expect(events.user.invited).toBeCalledTimes(2)
})
it("should not be able to generate an invitation for existing user", async () => {
const request = [{ email: config.defaultUser!.email, userInfo: {} }]
const res = await api.users.sendMultiUserInvite(request)
const body = res.body as InviteUsersResponse
expect(body.successful.length).toBe(0)
expect(body.unsuccessful.length).toBe(1)
expect(body.unsuccessful[0].reason).toBe("Unavailable")
expect(sendMailMock).toHaveBeenCalledTimes(0)
expect(events.user.invited).toBeCalledTimes(0)
})
})
describe("bulkCreate", () => { describe("bulkCreate", () => {
it("should ignore users existing in the same tenant", async () => { it("should ignore users existing in the same tenant", async () => {
const user = await config.createUser() const user = await config.createUser()

View File

@ -16,12 +16,12 @@ import {
migrations, migrations,
StaticDatabases, StaticDatabases,
ViewName, ViewName,
events,
} from "@budibase/backend-core" } from "@budibase/backend-core"
import { import {
MigrationType, MigrationType,
PlatformUserByEmail, PlatformUserByEmail,
User, User,
Account,
BulkCreateUsersResponse, BulkCreateUsersResponse,
CreateUserResponse, CreateUserResponse,
BulkDeleteUsersResponse, BulkDeleteUsersResponse,
@ -30,8 +30,12 @@ import {
RowResponse, RowResponse,
BulkDocsResponse, BulkDocsResponse,
AccountMetadata, AccountMetadata,
InviteUsersRequest,
InviteUsersResponse,
} from "@budibase/types" } from "@budibase/types"
import { groups as groupUtils } from "@budibase/pro" import { groups as groupUtils } from "@budibase/pro"
import { sendEmail } from "../../utilities/email"
import { EmailTemplatePurpose } from "../../constants"
const PAGE_LIMIT = 8 const PAGE_LIMIT = 8
@ -551,3 +555,53 @@ const bulkDeleteProcessing = async (dbUser: User) => {
// let server know to sync user // let server know to sync user
await apps.syncUserInApps(userId) await apps.syncUserInApps(userId)
} }
export const invite = async (
users: InviteUsersRequest
): Promise<InviteUsersResponse> => {
const response: InviteUsersResponse = {
successful: [],
unsuccessful: [],
}
const matchedEmails = await searchExistingEmails(users.map(u => u.email))
const newUsers = []
// separate duplicates from new users
for (let user of users) {
if (matchedEmails.includes(user.email)) {
response.unsuccessful.push({ email: user.email, reason: "Unavailable" })
} else {
newUsers.push(user)
}
}
// overwrite users with new only
users = newUsers
// send the emails for new users
const tenantId = tenancy.getTenantId()
for (let user of users) {
try {
let userInfo = user.userInfo
if (!userInfo) {
userInfo = {}
}
userInfo.tenantId = tenantId
const opts: any = {
subject: "{{ company }} platform invitation",
info: userInfo,
}
await sendEmail(user.email, EmailTemplatePurpose.INVITATION, opts)
response.successful.push({ email: user.email })
await events.user.invited()
} catch (e) {
console.error(`Failed to send email invitation email=${user.email}`, e)
response.unsuccessful.push({
email: user.email,
reason: "Failed to send email",
})
}
}
return response
}

View File

@ -3,6 +3,7 @@ import {
BulkCreateUsersResponse, BulkCreateUsersResponse,
BulkDeleteUsersRequest, BulkDeleteUsersRequest,
CreateUserResponse, CreateUserResponse,
InviteUsersRequest,
User, User,
UserDetails, UserDetails,
} from "@budibase/types" } from "@budibase/types"
@ -19,17 +20,21 @@ export class UserAPI {
// INVITE // INVITE
sendUserInvite = async (sendMailMock: any) => { sendUserInvite = async (sendMailMock: any, email: string, status = 200) => {
await this.config.saveSmtpConfig() await this.config.saveSmtpConfig()
await this.config.saveSettingsConfig() await this.config.saveSettingsConfig()
const res = await this.request const res = await this.request
.post(`/api/global/users/invite`) .post(`/api/global/users/invite`)
.send({ .send({
email: "invite@test.com", email,
}) })
.set(this.config.defaultHeaders()) .set(this.config.defaultHeaders())
.expect("Content-Type", /json/) .expect("Content-Type", /json/)
.expect(200) .expect(status)
if (status !== 200) {
return { code: undefined, res }
}
const emailCall = sendMailMock.mock.calls[0][0] const emailCall = sendMailMock.mock.calls[0][0]
// after this URL there should be a code // after this URL there should be a code
@ -51,6 +56,17 @@ export class UserAPI {
.expect(200) .expect(200)
} }
sendMultiUserInvite = async (request: InviteUsersRequest, status = 200) => {
await this.config.saveSmtpConfig()
await this.config.saveSettingsConfig()
return this.request
.post(`/api/global/users/multi/invite`)
.send(request)
.set(this.config.defaultHeaders())
.expect("Content-Type", /json/)
.expect(status)
}
// BULK // BULK
bulkCreateUsers = async (users: User[], groups: any[] = []) => { bulkCreateUsers = async (users: User[], groups: any[] = []) => {