feat: Implement user invitation backend functionality
This commit is contained in:
@@ -0,0 +1,23 @@
|
|||||||
|
import User from '../../../../models/user.js';
|
||||||
|
|
||||||
|
export default async (request, response) => {
|
||||||
|
const { token, password } = request.body;
|
||||||
|
|
||||||
|
if (!token) {
|
||||||
|
throw new Error('Invitation token is required!');
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = await User.query()
|
||||||
|
.findOne({ invitation_token: token })
|
||||||
|
.throwIfNotFound();
|
||||||
|
|
||||||
|
if (!user.isInvitationTokenValid()) {
|
||||||
|
throw new Error(
|
||||||
|
'Invitation link is not valid or expired. You can use reset password to get a new link.'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
await user.acceptInvitation(password);
|
||||||
|
|
||||||
|
response.status(204).end();
|
||||||
|
};
|
@@ -0,0 +1,13 @@
|
|||||||
|
export async function up(knex) {
|
||||||
|
return knex.schema.table('users', (table) => {
|
||||||
|
table.string('invitation_token');
|
||||||
|
table.timestamp('invitation_token_sent_at');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function down(knex) {
|
||||||
|
return knex.schema.table('users', (table) => {
|
||||||
|
table.dropColumn('invitation_token');
|
||||||
|
table.dropColumn('invitation_token_sent_at');
|
||||||
|
});
|
||||||
|
}
|
@@ -1,10 +1,16 @@
|
|||||||
|
import appConfig from '../../config/app.js';
|
||||||
import User from '../../models/user.js';
|
import User from '../../models/user.js';
|
||||||
import Role from '../../models/role.js';
|
import Role from '../../models/role.js';
|
||||||
|
import emailQueue from '../../queues/email.js';
|
||||||
|
import {
|
||||||
|
REMOVE_AFTER_30_DAYS_OR_150_JOBS,
|
||||||
|
REMOVE_AFTER_7_DAYS_OR_50_JOBS,
|
||||||
|
} from '../../helpers/remove-job-configuration.js';
|
||||||
|
|
||||||
const createUser = async (_parent, params, context) => {
|
const createUser = async (_parent, params, context) => {
|
||||||
context.currentUser.can('create', 'User');
|
context.currentUser.can('create', 'User');
|
||||||
|
|
||||||
const { fullName, email, password } = params.input;
|
const { fullName, email } = params.input;
|
||||||
|
|
||||||
const existingUser = await User.query().findOne({
|
const existingUser = await User.query().findOne({
|
||||||
email: email.toLowerCase(),
|
email: email.toLowerCase(),
|
||||||
@@ -17,7 +23,7 @@ const createUser = async (_parent, params, context) => {
|
|||||||
const userPayload = {
|
const userPayload = {
|
||||||
fullName,
|
fullName,
|
||||||
email,
|
email,
|
||||||
password,
|
status: 'pending',
|
||||||
};
|
};
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -32,7 +38,29 @@ const createUser = async (_parent, params, context) => {
|
|||||||
|
|
||||||
const user = await User.query().insert(userPayload);
|
const user = await User.query().insert(userPayload);
|
||||||
|
|
||||||
return user;
|
await user.generateInvitationToken();
|
||||||
|
|
||||||
|
const jobName = `Invitation Email - ${user.id}`;
|
||||||
|
const acceptInvitationUrl = `${appConfig.webAppUrl}/accept-invitation?token=${user.invitationToken}`;
|
||||||
|
|
||||||
|
const jobPayload = {
|
||||||
|
email: user.email,
|
||||||
|
subject: 'You are invited!',
|
||||||
|
template: 'invitation-instructions',
|
||||||
|
params: {
|
||||||
|
fullName: user.fullName,
|
||||||
|
acceptInvitationUrl,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const jobOptions = {
|
||||||
|
removeOnComplete: REMOVE_AFTER_7_DAYS_OR_50_JOBS,
|
||||||
|
removeOnFail: REMOVE_AFTER_30_DAYS_OR_150_JOBS,
|
||||||
|
};
|
||||||
|
|
||||||
|
await emailQueue.add(jobName, jobPayload, jobOptions);
|
||||||
|
|
||||||
|
return { user, acceptInvitationUrl };
|
||||||
};
|
};
|
||||||
|
|
||||||
export default createUser;
|
export default createUser;
|
||||||
|
@@ -22,7 +22,7 @@ const forgotPassword = async (_parent, params) => {
|
|||||||
const jobPayload = {
|
const jobPayload = {
|
||||||
email: user.email,
|
email: user.email,
|
||||||
subject: 'Reset Password',
|
subject: 'Reset Password',
|
||||||
template: 'reset-password-instructions',
|
template: 'reset-password-instructions.ee',
|
||||||
params: {
|
params: {
|
||||||
token: user.resetPasswordToken,
|
token: user.resetPasswordToken,
|
||||||
webAppUrl: appConfig.webAppUrl,
|
webAppUrl: appConfig.webAppUrl,
|
||||||
|
@@ -8,7 +8,7 @@ type Mutation {
|
|||||||
createFlow(input: CreateFlowInput): Flow
|
createFlow(input: CreateFlowInput): Flow
|
||||||
createRole(input: CreateRoleInput): Role
|
createRole(input: CreateRoleInput): Role
|
||||||
createStep(input: CreateStepInput): Step
|
createStep(input: CreateStepInput): Step
|
||||||
createUser(input: CreateUserInput): User
|
createUser(input: CreateUserInput): UserWithAcceptInvitationUrl
|
||||||
deleteConnection(input: DeleteConnectionInput): Boolean
|
deleteConnection(input: DeleteConnectionInput): Boolean
|
||||||
deleteCurrentUser: Boolean
|
deleteCurrentUser: Boolean
|
||||||
deleteFlow(input: DeleteFlowInput): Boolean
|
deleteFlow(input: DeleteFlowInput): Boolean
|
||||||
@@ -375,7 +375,6 @@ input DeleteStepInput {
|
|||||||
input CreateUserInput {
|
input CreateUserInput {
|
||||||
fullName: String!
|
fullName: String!
|
||||||
email: String!
|
email: String!
|
||||||
password: String!
|
|
||||||
role: UserRoleInput!
|
role: UserRoleInput!
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -520,6 +519,11 @@ type User {
|
|||||||
updatedAt: String
|
updatedAt: String
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type UserWithAcceptInvitationUrl {
|
||||||
|
user: User
|
||||||
|
acceptInvitationUrl: String
|
||||||
|
}
|
||||||
|
|
||||||
type Role {
|
type Role {
|
||||||
id: String
|
id: String
|
||||||
name: String
|
name: String
|
||||||
|
@@ -6,7 +6,7 @@ import { fileURLToPath } from 'url';
|
|||||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||||
|
|
||||||
const compileEmail = (emailPath, replacements = {}) => {
|
const compileEmail = (emailPath, replacements = {}) => {
|
||||||
const filePath = path.join(__dirname, `../views/emails/${emailPath}.ee.hbs`);
|
const filePath = path.join(__dirname, `../views/emails/${emailPath}.hbs`);
|
||||||
const source = fs.readFileSync(filePath, 'utf-8').toString();
|
const source = fs.readFileSync(filePath, 'utf-8').toString();
|
||||||
const template = handlebars.compile(source);
|
const template = handlebars.compile(source);
|
||||||
return template(replacements);
|
return template(replacements);
|
||||||
|
@@ -43,6 +43,11 @@ class User extends Base {
|
|||||||
type: ['string', 'null'],
|
type: ['string', 'null'],
|
||||||
format: 'date-time',
|
format: 'date-time',
|
||||||
},
|
},
|
||||||
|
invitationToken: { type: ['string', 'null'] },
|
||||||
|
invitationTokenSentAt: {
|
||||||
|
type: ['string', 'null'],
|
||||||
|
format: 'date-time',
|
||||||
|
},
|
||||||
trialExpiryDate: { type: 'string' },
|
trialExpiryDate: { type: 'string' },
|
||||||
roleId: { type: 'string', format: 'uuid' },
|
roleId: { type: 'string', format: 'uuid' },
|
||||||
deletedAt: { type: 'string' },
|
deletedAt: { type: 'string' },
|
||||||
@@ -210,6 +215,13 @@ class User extends Base {
|
|||||||
await this.$query().patch({ resetPasswordToken, resetPasswordTokenSentAt });
|
await this.$query().patch({ resetPasswordToken, resetPasswordTokenSentAt });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async generateInvitationToken() {
|
||||||
|
const invitationToken = crypto.randomBytes(64).toString('hex');
|
||||||
|
const invitationTokenSentAt = new Date().toISOString();
|
||||||
|
|
||||||
|
await this.$query().patch({ invitationToken, invitationTokenSentAt });
|
||||||
|
}
|
||||||
|
|
||||||
async resetPassword(password) {
|
async resetPassword(password) {
|
||||||
return await this.$query().patch({
|
return await this.$query().patch({
|
||||||
resetPasswordToken: null,
|
resetPasswordToken: null,
|
||||||
@@ -218,6 +230,14 @@ class User extends Base {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async acceptInvitation(password) {
|
||||||
|
return await this.$query().patch({
|
||||||
|
invitationToken: null,
|
||||||
|
invitationTokenSentAt: null,
|
||||||
|
password,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
async isResetPasswordTokenValid() {
|
async isResetPasswordTokenValid() {
|
||||||
if (!this.resetPasswordTokenSentAt) {
|
if (!this.resetPasswordTokenSentAt) {
|
||||||
return false;
|
return false;
|
||||||
@@ -230,6 +250,18 @@ class User extends Base {
|
|||||||
return now.getTime() - sentAt.getTime() < fourHoursInMilliseconds;
|
return now.getTime() - sentAt.getTime() < fourHoursInMilliseconds;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async isInvitationTokenValid() {
|
||||||
|
if (!this.invitationTokenSentAt) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const sentAt = new Date(this.invitationTokenSentAt);
|
||||||
|
const now = new Date();
|
||||||
|
const seventyTwoHoursInMilliseconds = 1000 * 60 * 60 * 72;
|
||||||
|
|
||||||
|
return now.getTime() - sentAt.getTime() < seventyTwoHoursInMilliseconds;
|
||||||
|
}
|
||||||
|
|
||||||
async generateHash() {
|
async generateHash() {
|
||||||
if (this.password) {
|
if (this.password) {
|
||||||
this.password = await bcrypt.hash(this.password, 10);
|
this.password = await bcrypt.hash(this.password, 10);
|
||||||
|
@@ -9,6 +9,7 @@ import getAppsAction from '../../../controllers/api/v1/users/get-apps.js';
|
|||||||
import getInvoicesAction from '../../../controllers/api/v1/users/get-invoices.ee.js';
|
import getInvoicesAction from '../../../controllers/api/v1/users/get-invoices.ee.js';
|
||||||
import getSubscriptionAction from '../../../controllers/api/v1/users/get-subscription.ee.js';
|
import getSubscriptionAction from '../../../controllers/api/v1/users/get-subscription.ee.js';
|
||||||
import getPlanAndUsageAction from '../../../controllers/api/v1/users/get-plan-and-usage.ee.js';
|
import getPlanAndUsageAction from '../../../controllers/api/v1/users/get-plan-and-usage.ee.js';
|
||||||
|
import acceptInvitationAction from '../../../controllers/api/v1/users/accept-invitation.js';
|
||||||
|
|
||||||
const router = Router();
|
const router = Router();
|
||||||
|
|
||||||
@@ -49,4 +50,6 @@ router.get(
|
|||||||
asyncHandler(getPlanAndUsageAction)
|
asyncHandler(getPlanAndUsageAction)
|
||||||
);
|
);
|
||||||
|
|
||||||
|
router.post('/invitation', asyncHandler(acceptInvitationAction));
|
||||||
|
|
||||||
export default router;
|
export default router;
|
||||||
|
@@ -0,0 +1,23 @@
|
|||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>Invitation instructions</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<p>
|
||||||
|
Hello {{ fullName }},
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
You have been invited to join our platform. To accept the invitation, click the link below.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
<a href="{{ acceptInvitationUrl }}">Accept invitation</a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
If you did not expect this invitation, you can ignore this email.
|
||||||
|
</p>
|
||||||
|
</body>
|
||||||
|
</html>
|
@@ -9,7 +9,7 @@
|
|||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p>
|
<p>
|
||||||
Someone has requested a link to change your password, and you can do this through the link below.
|
Someone has requested a link to change your password, and you can do this through the link below within 72 hours.
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p>
|
<p>
|
||||||
|
@@ -2,12 +2,15 @@ import { gql } from '@apollo/client';
|
|||||||
export const CREATE_USER = gql`
|
export const CREATE_USER = gql`
|
||||||
mutation CreateUser($input: CreateUserInput) {
|
mutation CreateUser($input: CreateUserInput) {
|
||||||
createUser(input: $input) {
|
createUser(input: $input) {
|
||||||
id
|
user {
|
||||||
email
|
|
||||||
fullName
|
|
||||||
role {
|
|
||||||
id
|
id
|
||||||
|
email
|
||||||
|
fullName
|
||||||
|
role {
|
||||||
|
id
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
acceptInvitationUrl
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
`;
|
`;
|
||||||
|
@@ -198,6 +198,7 @@
|
|||||||
"userForm.password": "Password",
|
"userForm.password": "Password",
|
||||||
"createUser.submit": "Create",
|
"createUser.submit": "Create",
|
||||||
"createUser.successfullyCreated": "The user has been created.",
|
"createUser.successfullyCreated": "The user has been created.",
|
||||||
|
"createUser.invitationEmailInfo": "Invitation email will be sent if SMTP credentials are valid. Otherwise, you can share the invitation link manually: <link></link>",
|
||||||
"editUser.submit": "Update",
|
"editUser.submit": "Update",
|
||||||
"editUser.successfullyUpdated": "The user has been updated.",
|
"editUser.successfullyUpdated": "The user has been updated.",
|
||||||
"userList.fullName": "Full name",
|
"userList.fullName": "Full name",
|
||||||
|
@@ -2,6 +2,7 @@ import { useMutation } from '@apollo/client';
|
|||||||
import LoadingButton from '@mui/lab/LoadingButton';
|
import LoadingButton from '@mui/lab/LoadingButton';
|
||||||
import Grid from '@mui/material/Grid';
|
import Grid from '@mui/material/Grid';
|
||||||
import Stack from '@mui/material/Stack';
|
import Stack from '@mui/material/Stack';
|
||||||
|
import Alert from '@mui/material/Alert';
|
||||||
import MuiTextField from '@mui/material/TextField';
|
import MuiTextField from '@mui/material/TextField';
|
||||||
import useEnqueueSnackbar from 'hooks/useEnqueueSnackbar';
|
import useEnqueueSnackbar from 'hooks/useEnqueueSnackbar';
|
||||||
import * as React from 'react';
|
import * as React from 'react';
|
||||||
@@ -26,9 +27,9 @@ function generateRoleOptions(roles) {
|
|||||||
export default function CreateUser() {
|
export default function CreateUser() {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const formatMessage = useFormatMessage();
|
const formatMessage = useFormatMessage();
|
||||||
const [createUser, { loading }] = useMutation(CREATE_USER);
|
const [createUser, { loading, data }] = useMutation(CREATE_USER);
|
||||||
const { data, loading: isRolesLoading } = useRoles();
|
const { data: rolesData, loading: isRolesLoading } = useRoles();
|
||||||
const roles = data?.data;
|
const roles = rolesData?.data;
|
||||||
const enqueueSnackbar = useEnqueueSnackbar();
|
const enqueueSnackbar = useEnqueueSnackbar();
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
@@ -38,7 +39,6 @@ export default function CreateUser() {
|
|||||||
variables: {
|
variables: {
|
||||||
input: {
|
input: {
|
||||||
fullName: userData.fullName,
|
fullName: userData.fullName,
|
||||||
password: userData.password,
|
|
||||||
email: userData.email,
|
email: userData.email,
|
||||||
role: {
|
role: {
|
||||||
id: userData.role?.id,
|
id: userData.role?.id,
|
||||||
@@ -54,8 +54,6 @@ export default function CreateUser() {
|
|||||||
'data-test': 'snackbar-create-user-success',
|
'data-test': 'snackbar-create-user-success',
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
navigate(URLS.USERS);
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw new Error('Failed while creating!');
|
throw new Error('Failed while creating!');
|
||||||
}
|
}
|
||||||
@@ -89,15 +87,6 @@ export default function CreateUser() {
|
|||||||
fullWidth
|
fullWidth
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<TextField
|
|
||||||
required={true}
|
|
||||||
name="password"
|
|
||||||
label={formatMessage('userForm.password')}
|
|
||||||
type="password"
|
|
||||||
data-test="password-input"
|
|
||||||
fullWidth
|
|
||||||
/>
|
|
||||||
|
|
||||||
<Can I="update" a="Role">
|
<Can I="update" a="Role">
|
||||||
<ControlledAutocomplete
|
<ControlledAutocomplete
|
||||||
name="role.id"
|
name="role.id"
|
||||||
@@ -125,6 +114,26 @@ export default function CreateUser() {
|
|||||||
>
|
>
|
||||||
{formatMessage('createUser.submit')}
|
{formatMessage('createUser.submit')}
|
||||||
</LoadingButton>
|
</LoadingButton>
|
||||||
|
|
||||||
|
{data && (
|
||||||
|
<Alert
|
||||||
|
severity="info"
|
||||||
|
color="primary"
|
||||||
|
sx={{ fontWeight: '500' }}
|
||||||
|
>
|
||||||
|
{formatMessage('createUser.invitationEmailInfo', {
|
||||||
|
link: () => (
|
||||||
|
<a
|
||||||
|
href={data.createUser.acceptInvitationUrl}
|
||||||
|
target="_blank"
|
||||||
|
rel="noreferrer"
|
||||||
|
>
|
||||||
|
{data.createUser.acceptInvitationUrl}
|
||||||
|
</a>
|
||||||
|
),
|
||||||
|
})}
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
</Stack>
|
</Stack>
|
||||||
</Form>
|
</Form>
|
||||||
</Grid>
|
</Grid>
|
||||||
|
Reference in New Issue
Block a user