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

fix(authentication): email dependent app route registration #257

Merged
merged 2 commits into from
Jul 21, 2022
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
67 changes: 38 additions & 29 deletions modules/authentication/src/Authentication.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import ConduitGrpcSdk, {
GrpcCallback,
HealthCheckStatus,
} from '@conduitplatform/grpc-sdk';

import path from 'path';
import { isNil } from 'lodash';
import { status } from '@grpc/grpc-js';
Expand Down Expand Up @@ -46,7 +45,8 @@ export default class Authentication extends ManagedModule<Config> {
private adminRouter: AdminHandlers;
private userRouter: AuthenticationRoutes;
private database: DatabaseProvider;
private sendEmail: boolean = false;
private localSendVerificationEmail: boolean = false;
private refreshAppRoutesTimeout: NodeJS.Timeout | null = null;

constructor() {
super('authentication');
Expand All @@ -59,20 +59,7 @@ export default class Authentication extends ManagedModule<Config> {
await runMigrations(this.grpcSdk);
}

async onRegister() {
this.grpcSdk.bus!.subscribe('email:status:onConfig', () => {
this.onConfig()
.then(() => {
ConduitGrpcSdk.Logger.log('Updated authentication configuration');
})
.catch(() => {
ConduitGrpcSdk.Logger.error('Failed to update authentication config');
});
});
}

protected registerSchemas() {
// @ts-ignore
const promises = Object.values(models).map(model => {
const modelInstance = model.getInstance(this.database);
return this.database.createSchemaFromAdapter(modelInstance);
Expand All @@ -85,28 +72,35 @@ export default class Authentication extends ManagedModule<Config> {
if (!config.active) {
this.updateHealth(HealthCheckStatus.NOT_SERVING);
} else {
let refreshedOnce = false;
await this.registerSchemas();
this.adminRouter = new AdminHandlers(this.grpcServer, this.grpcSdk);
await this.refreshAppRoutes();
this.updateHealth(HealthCheckStatus.SERVING);
if (config.local.verification.send_email) {
this.grpcSdk.monitorModule('email', serving => {
this.sendEmail = serving;
this.refreshAppRoutes();
refreshedOnce = true;
this.grpcSdk.monitorModule('email', async serving => {
const alreadyEnabled = this.localSendVerificationEmail;
this.localSendVerificationEmail = serving;
if (serving) {
if (!alreadyEnabled) {
await this.refreshAppRoutes();
}
} else {
ConduitGrpcSdk.Logger.warn(
'Failed to enable email verification for local authentication strategy. Email module not serving.',
);
}
});
} else {
this.localSendVerificationEmail = false;
this.grpcSdk.unmonitorModule('email');
}
this.adminRouter = new AdminHandlers(this.grpcServer, this.grpcSdk);
if (!refreshedOnce) {
await this.refreshAppRoutes();
}
this.updateHealth(HealthCheckStatus.SERVING);
}
}

private async refreshAppRoutes() {
if (this.userRouter) {
await this.userRouter.registerRoutes();
this.userRouter.updateLocalHandlers(this.localSendVerificationEmail);
this.scheduleAppRouteRefresh();
return;
}
const self = this;
Expand All @@ -116,15 +110,30 @@ export default class Authentication extends ManagedModule<Config> {
self.userRouter = new AuthenticationRoutes(
self.grpcServer,
self.grpcSdk,
self.sendEmail,
self.localSendVerificationEmail,
);
return this.userRouter.registerRoutes();
this.scheduleAppRouteRefresh();
})
.catch(e => {
ConduitGrpcSdk.Logger.error(e.message);
});
}

private scheduleAppRouteRefresh() {
if (this.refreshAppRoutesTimeout) {
clearTimeout(this.refreshAppRoutesTimeout);
this.refreshAppRoutesTimeout = null;
}
this.refreshAppRoutesTimeout = setTimeout(async () => {
try {
await this.userRouter.registerRoutes();
} catch (err) {
ConduitGrpcSdk.Logger.error(err as Error);
}
this.refreshAppRoutesTimeout = null;
}, 800);
}

// gRPC Service
// produces login credentials for a user without them having to login
async userLogin(
Expand Down Expand Up @@ -207,7 +216,7 @@ export default class Authentication extends ManagedModule<Config> {
isVerified: !verify,
});

if (verify && this.sendEmail) {
if (verify && this.localSendVerificationEmail) {
const serverConfig = await this.grpcSdk.config.get('router');
const url = serverConfig.hostUrl;
const verificationToken: models.Token = await models.Token.getInstance().create({
Expand Down
47 changes: 13 additions & 34 deletions modules/authentication/src/handlers/local.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@ import { AuthUtils } from '../utils/auth';
import { TokenType } from '../constants/TokenType';
import { v4 as uuid } from 'uuid';
import { Config } from '../config';

import ConduitGrpcSdk, {
ConduitError,
Email,
GrpcError,
ParsedRouterRequest,
Expand All @@ -31,7 +29,7 @@ export class LocalHandlers implements IAuthenticationStrategy {

constructor(
private readonly grpcSdk: ConduitGrpcSdk,
private readonly sendEmail: boolean,
private readonly sendVerificationEmail: boolean,
) {
grpcSdk.config.get('router').then(config => {
this.clientValidation = config.security.clientValidation;
Expand Down Expand Up @@ -77,7 +75,7 @@ export class LocalHandlers implements IAuthenticationStrategy {
this.authenticate.bind(this),
);

if (this.emailModule) {
if (this.sendVerificationEmail) {
routingManager.route(
{
path: '/forgot-password',
Expand Down Expand Up @@ -214,23 +212,6 @@ export class LocalHandlers implements IAuthenticationStrategy {
}

async validate(): Promise<boolean> {
if (this.sendEmail) {
let emailConfig;
try {
emailConfig = await this.grpcSdk.config.get('email');
} catch (e) {
ConduitGrpcSdk.Logger.log(
'Cannot use email verification without Email module being enabled',
);
return (this.initialized = false);
}
if (!emailConfig.active) {
ConduitGrpcSdk.Logger.log(
'Cannot use email verification without Email module being enabled',
);
return (this.initialized = false);
}
}
if (!this.initialized) {
try {
await this.initDbAndEmail();
Expand Down Expand Up @@ -270,23 +251,21 @@ export class LocalHandlers implements IAuthenticationStrategy {
const serverConfig = await this.grpcSdk.config.get('router');
const url = serverConfig.hostUrl;

if (this.sendEmail) {
if (this.sendVerificationEmail) {
const verificationToken: Token = await Token.getInstance().create({
type: TokenType.VERIFICATION_TOKEN,
userId: user._id,
token: uuid(),
});
const result = { verificationToken, hostUrl: url };
const link = `${result.hostUrl}/hook/authentication/verify-email/${result.verificationToken.token}`;
if (this.sendEmail) {
await this.emailModule.sendEmail('EmailVerification', {
email: user.email,
sender: 'no-reply',
variables: {
link,
},
});
}
await this.emailModule.sendEmail('EmailVerification', {
email: user.email,
sender: 'no-reply',
variables: {
link,
},
});
}
delete user.hashedPassword;
return { user };
Expand Down Expand Up @@ -433,7 +412,7 @@ export class LocalHandlers implements IAuthenticationStrategy {

const appUrl = config.local.forgot_password_redirect_uri;
const link = `${appUrl}?reset_token=${passwordResetTokenDoc.token}`;
if (this.sendEmail) {
if (this.sendVerificationEmail) {
await this.emailModule.sendEmail('ForgotPassword', {
email: user.email,
sender: 'no-reply',
Expand Down Expand Up @@ -765,7 +744,7 @@ export class LocalHandlers implements IAuthenticationStrategy {
private async initDbAndEmail() {
const config = ConfigController.getInstance().config;

if (this.sendEmail) {
if (this.sendVerificationEmail) {
await this.grpcSdk.config.moduleExists('email');
this.emailModule = this.grpcSdk.emailProvider!;
}
Expand All @@ -788,7 +767,7 @@ export class LocalHandlers implements IAuthenticationStrategy {
ConduitGrpcSdk.Logger.log('phone authentication not active');
}

if (this.sendEmail) {
if (this.sendVerificationEmail) {
this.registerTemplates();
}
this.initialized = true;
Expand Down
11 changes: 8 additions & 3 deletions modules/authentication/src/routes/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import { OAuth2Settings } from '../handlers/oauth2/interfaces/OAuth2Settings';
type OAuthHandler = typeof oauth2;

export class AuthenticationRoutes {
private readonly localHandlers: LocalHandlers;
private localHandlers: LocalHandlers;
private readonly serviceHandler: ServiceHandler;
private readonly commonHandlers: CommonHandlers;
private readonly phoneHandlers: PhoneHandlers;
Expand All @@ -33,13 +33,18 @@ export class AuthenticationRoutes {
constructor(
readonly server: GrpcServer,
private readonly grpcSdk: ConduitGrpcSdk,
private readonly emailServing: boolean,
private localSendVerificationEmail: boolean,
) {
this._routingManager = new RoutingManager(this.grpcSdk.router!, server);
this.localHandlers = new LocalHandlers(grpcSdk, emailServing);
this.serviceHandler = new ServiceHandler(grpcSdk);
this.commonHandlers = new CommonHandlers(grpcSdk);
this.phoneHandlers = new PhoneHandlers(grpcSdk);
this.updateLocalHandlers(localSendVerificationEmail);
}

updateLocalHandlers(sendVerificationEmail: boolean) {
this.localSendVerificationEmail = sendVerificationEmail;
this.localHandlers = new LocalHandlers(this.grpcSdk, sendVerificationEmail);
}

async registerRoutes() {
Expand Down