Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(server): [nan-869] email verification on signup #2173

Merged
merged 17 commits into from
May 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion packages/server/lib/clients/email.client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ class EmailClient {
if (process.env['MAILGUN_API_KEY'] === undefined || process.env['MAILGUN_API_KEY'] === 'EMPTY' || !this.client) {
logger.info('Email client not configured');
logger.info('The following email would have been sent:');
logger.info(email, subject, html);
logger.info(email, subject);
logger.info(html);
return;
}
return this.client.messages.create('email.nango.dev', {
Expand Down
19 changes: 19 additions & 0 deletions packages/server/lib/clients/workos.client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { WorkOS } from '@workos-inc/node';
import { NangoError } from '@nangohq/shared';

let workOs: WorkOS | null = null;

export function getWorkOSClient(): WorkOS {
if (!workOs) {
const apiKey = process.env['WORKOS_API_KEY'];
const clientId = process.env['WORKOS_CLIENT_ID'];

if (apiKey && clientId) {
khaliqgant marked this conversation as resolved.
Show resolved Hide resolved
workOs = new WorkOS(apiKey);
} else {
throw new NangoError('workos_not_configured');
}
}

return workOs;
}
157 changes: 7 additions & 150 deletions packages/server/lib/controllers/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,14 @@
import type { Request, Response, NextFunction } from 'express';
import { WorkOS } from '@workos-inc/node';
import crypto from 'crypto';
import util from 'util';
import { resetPasswordSecret, getUserFromSession } from '../utils/utils.js';
import { resetPasswordSecret } from '../utils/utils.js';
import jwt from 'jsonwebtoken';
import EmailClient from '../clients/email.client.js';
import type { User } from '@nangohq/shared';
import { isCloud, baseUrl, basePublicUrl, getLogger, Err, Ok } from '@nangohq/utils';
import { baseUrl, basePublicUrl, getLogger, Err, Ok } from '@nangohq/utils';
import type { Result } from '@nangohq/utils';
import {
userService,
accountService,
errorManager,
ErrorSourceEnum,
environmentService,
analytics,
AnalyticsTypes,
NangoError,
createOnboardingProvider
} from '@nangohq/shared';
import { getWorkOSClient } from '../clients/workos.client.js';
import { userService, accountService, errorManager, ErrorSourceEnum, NangoError } from '@nangohq/shared';

export interface WebUser {
id: number;
Expand All @@ -36,15 +26,6 @@ interface InviteAccountState extends InviteAccountBody {
token: string;
}

let workos: WorkOS | null = null;
if (process.env['WORKOS_API_KEY'] && process.env['WORKOS_CLIENT_ID']) {
workos = new WorkOS(process.env['WORKOS_API_KEY']);
} else {
if (isCloud) {
throw new NangoError('workos_not_configured');
}
}

const allowedProviders = ['GoogleOAuth'];

const parseState = (state: string): Result<InviteAccountState> => {
Expand Down Expand Up @@ -81,27 +62,6 @@ const createAccountIfNotInvited = async (name: string, state?: string): Promise<
};

class AuthController {
async signin(req: Request, res: Response<any, never>, next: NextFunction) {
try {
const getUser = await getUserFromSession(req);
if (getUser.isErr()) {
errorManager.errResFromNangoErr(res, getUser.error);
return;
}

const user = getUser.value;
const webUser: WebUser = {
id: user.id,
accountId: user.account_id,
email: user.email,
name: user.name
};
res.status(200).send({ user: webUser });
} catch (err) {
next(err);
}
}

async logout(req: Request, res: Response<any, never>, next: NextFunction) {
try {
req.session.destroy((err) => {
Expand All @@ -116,97 +76,6 @@ class AuthController {
}
}

async signup(req: Request, res: Response<any, never>, next: NextFunction) {
try {
if (req.body == null) {
errorManager.errRes(res, 'missing_body');
return;
}

const email = req.body['email'];
if (email == null) {
errorManager.errRes(res, 'missing_email_param');
return;
}

const name = req.body['name'];
if (name == null) {
errorManager.errRes(res, 'missing_name_param');
return;
}

const password = req.body['password'];
if (password == null) {
errorManager.errRes(res, 'missing_password_param');
return;
}

if ((await userService.getUserByEmail(email)) != null) {
errorManager.errRes(res, 'duplicate_account');
return;
}

let account;
let joinedWithToken = false;

if (req.body['account_id'] != null) {
const token = req.body['token'];
const validToken = userService.getInvitedUserByToken(token);
if (!validToken) {
errorManager.errRes(res, 'invalid_invite_token');
return;
}
account = await accountService.getAccountById(Number(req.body['account_id']));
joinedWithToken = true;
} else {
account = await accountService.createAccount(`${name}'s Organization`);
}

if (account == null) {
throw new NangoError('account_creation_failure');
}

const salt = crypto.randomBytes(16).toString('base64');
const hashedPassword = (await util.promisify(crypto.pbkdf2)(password, salt, 310000, 32, 'sha256')).toString('base64');
const user = await userService.createUser(email, name, hashedPassword, salt, account.id);

if (user == null) {
throw new NangoError('user_creation_failure');
}

const event = joinedWithToken ? AnalyticsTypes.ACCOUNT_JOINED : AnalyticsTypes.ACCOUNT_CREATED;
void analytics.track(event, account.id, {}, isCloud ? { email: email } : {});

if (isCloud && !joinedWithToken) {
// On Cloud version, create default provider config to simplify onboarding.
const env = await environmentService.getByEnvironmentName(account.id, 'dev');
if (env) {
await createOnboardingProvider({ envId: env.id });
}
}

if (joinedWithToken) {
await userService.markAcceptedInvite(req.body['token']);
}

req.login(user, function (err) {
if (err) {
return next(err);
}

const webUser: WebUser = {
id: user.id,
accountId: user.account_id,
email: user.email,
name: user.name
};
res.status(200).send({ user: webUser });
});
} catch (err) {
next(err);
}
}

async forgotPassword(req: Request, res: Response<any, never>, next: NextFunction) {
try {
const { email } = req.body;
Expand Down Expand Up @@ -324,10 +193,7 @@ class AuthController {
return;
}

if (!workos) {
errorManager.errRes(res, 'workos_not_configured');
return;
}
const workos = getWorkOSClient();

const oAuthUrl = workos.userManagement.getAuthorizationUrl({
clientId: process.env['WORKOS_CLIENT_ID'] || '',
Expand All @@ -343,6 +209,7 @@ class AuthController {

getManagedLoginWithInvite(req: Request, res: Response<any, never>, next: NextFunction) {
try {
const workos = getWorkOSClient();
const provider = req.query['provider'] as string;

if (!provider || !allowedProviders.includes(provider)) {
Expand All @@ -364,11 +231,6 @@ class AuthController {
return;
}

if (!workos) {
errorManager.errRes(res, 'workos_not_configured');
return;
}

const accountId = body.accountId;

const inviteParams: InviteAccountState = {
Expand All @@ -393,12 +255,7 @@ class AuthController {
try {
const { code, state } = req.query;

if (!workos) {
const error = new NangoError('workos_not_configured');
logger.error(error);
res.redirect(basePublicUrl);
return;
}
const workos = getWorkOSClient();

if (!code) {
const error = new NangoError('missing_managed_login_callback_code');
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { z } from 'zod';
import { asyncWrapper } from '../../../utils/asyncWrapper.js';
import { userService } from '@nangohq/shared';
import { getLogger, requireEmptyQuery, zodErrorToHTTP } from '@nangohq/utils';
import { sendVerificationEmail } from '../../../helpers/email.js';
import type { GetEmailByExpiredToken } from '@nangohq/types';

const logger = getLogger('Server.GetEmailByExpiredToken');

const validation = z
.object({
token: z.string().uuid()
})
.strict();

export const getEmailByExpiredToken = asyncWrapper<GetEmailByExpiredToken>(async (req, res) => {
const emptyQuery = requireEmptyQuery(req);
if (emptyQuery) {
res.status(400).send({ error: { code: 'invalid_query_params', errors: zodErrorToHTTP(emptyQuery.error) } });
return;
}

const val = validation.safeParse(req.params);

if (!val.success) {
res.status(400).send({
error: { code: 'invalid_body', errors: zodErrorToHTTP(val.error) }
});
return;
}

const { token } = val.data;

const user = await userService.refreshEmailVerificationToken(token);

if (!user || !user.email_verification_token) {
logger.error('Error refreshing email verification token');
res.status(500).send({
error: { code: 'error_refreshing_token', message: 'There was a problem refreshing the token. Please reach out to support.' }
});
return;
}

sendVerificationEmail(user.email, user.name, user.email_verification_token);

if (!user) {
res.status(404).send({ error: { code: 'user_not_found' } });
return;
}

res.status(200).send({ email: user.email, verified: user.email_verified, uuid: user.uuid });
});
39 changes: 39 additions & 0 deletions packages/server/lib/controllers/v1/account/getEmailByUuid.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { z } from 'zod';
import { asyncWrapper } from '../../../utils/asyncWrapper.js';
import { userService } from '@nangohq/shared';
import { requireEmptyQuery, zodErrorToHTTP } from '@nangohq/utils';
import type { GetEmailByUuid } from '@nangohq/types';

const validation = z
.object({
uuid: z.string().uuid()
})
.strict();

export const getEmailByUuid = asyncWrapper<GetEmailByUuid>(async (req, res) => {
const emptyQuery = requireEmptyQuery(req);
if (emptyQuery) {
res.status(400).send({ error: { code: 'invalid_query_params', errors: zodErrorToHTTP(emptyQuery.error) } });
return;
}

const val = validation.safeParse(req.params);

if (!val.success) {
res.status(400).send({
error: { code: 'invalid_body', errors: zodErrorToHTTP(val.error) }
});
return;
}

const { uuid } = val.data;

const user = await userService.getUserByUuid(uuid);

if (!user) {
res.status(404).send({ error: { code: 'user_not_found' } });
return;
}

res.status(200).send({ email: user.email, verified: user.email_verified });
});
8 changes: 8 additions & 0 deletions packages/server/lib/controllers/v1/account/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export * from './getEmailByUuid.js';
export * from './getEmailByExpiredToken.js';
export * from './resendVerificationEmailByUuid.js';
export * from './resendVerificationEmailByEmail.js';
export * from './signin.js';
export * from './signup.js';
export * from './signupWithToken.js';
export * from './validateEmailAndLogin.js';
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { z } from 'zod';
import { userService } from '@nangohq/shared';
import type { ResendVerificationEmailByEmail } from '@nangohq/types';
import { requireEmptyQuery, zodErrorToHTTP } from '@nangohq/utils';
import { sendVerificationEmail } from '../../../helpers/email.js';
import { asyncWrapper } from '../../../utils/asyncWrapper.js';

const validation = z
.object({
email: z.string().email()
})
.strict();

export const resendVerificationEmailByEmail = asyncWrapper<ResendVerificationEmailByEmail>(async (req, res) => {
const emptyQuery = requireEmptyQuery(req);
if (emptyQuery) {
res.status(400).send({ error: { code: 'invalid_query_params', errors: zodErrorToHTTP(emptyQuery.error) } });
return;
}

const val = validation.safeParse(req.body);

if (!val.success) {
res.status(400).send({
error: { code: 'invalid_body', errors: zodErrorToHTTP(val.error) }
});
return;
}

const { email } = val.data;

const user = await userService.getUserByEmail(email);

if (!user) {
res.status(404).send({ error: { code: 'user_not_found', message: 'User was not found in our system.' } });
return;
}

if (!user.email_verification_token) {
res.status(400).send({ error: { code: 'email_already_verified', message: 'Email address was already verified, please login.' } });
return;
}

sendVerificationEmail(user.email, user.name, user.email_verification_token);

res.status(200).send({ success: true });
});
Loading
Loading