Skip to content

Commit

Permalink
[@dhealthdapps/backend] feat(routes): update of validationScheduler
Browse files Browse the repository at this point in the history
  • Loading branch information
kravchenkodhealth authored and evias committed Jan 3, 2023
1 parent cd34714 commit c939088
Show file tree
Hide file tree
Showing 5 changed files with 97 additions and 57 deletions.
2 changes: 2 additions & 0 deletions runtime/backend/src/common/Schedulers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
// internal dependencies
// common scope
import { AppConfiguration } from "../AppConfiguration";
import { ValidateChallengeScheduler } from "./schedulers/ValidateChallengeScheduler";

// discovery scope
import { DiscoveryAccountsModule } from "../discovery/modules/DiscoveryAccountsModule";
Expand Down Expand Up @@ -71,6 +72,7 @@ import { ReportNotifierCommand } from "../notifier/schedulers/ReportNotifier/Rep
* @since v0.1.0
*/
export const Schedulers: { [key: string]: any[] } = {
common: [ValidateChallengeScheduler],
database: [AppConfiguration.getDatabaseModule()],
discovery: [
DiscoveryAccountsModule,
Expand Down
20 changes: 17 additions & 3 deletions runtime/backend/src/common/gateways/AuthGateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@ import {
OnGatewayInit,
OnGatewayDisconnect,
} from "@nestjs/websockets";
import { EventEmitter2, OnEvent } from "@nestjs/event-emitter";

// internal dependencies
import { ValidateChallengeScheduler } from "../schedulers/ValidateChallengeScheduler";
import { BaseGateway } from "./BaseGateway";
import dappConfigLoader from "../../../config/dapp";

Expand All @@ -35,9 +37,21 @@ export class AuthGateway
OnGatewayInit,
OnGatewayDisconnect
{
@SubscribeMessage("auth.open")
handleEvent(@MessageBody() message: any) {
console.log("AUTHGATEWAY: Connection open");
constructor(
private readonly validateChallengeScheduler: ValidateChallengeScheduler,
protected readonly emitter: EventEmitter2,
) {
super(emitter);
}

@OnEvent("auth.open")
handleEvent(payload: any) {
console.log("AUTHGATEWAY: Connection open", { payload });
// this.validateChallengeScheduler.addCronJob(
// "*/10 * * * * *", // 10 sec
// payload.challenge,
// );
console.log({ payload });
return { msg: "You're connected" };
}

Expand Down
71 changes: 17 additions & 54 deletions runtime/backend/src/common/gateways/BaseGateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,11 @@ import {
import { Server } from "https";
import cookie from "cookie";
import cookieParser from "cookie-parser";
import { EventEmitter2 } from "@nestjs/event-emitter";

// internal dependencies
import dappConfigLoader from "../../../config/dapp";
import { AuthService } from "../services";
import { LogService } from "../services";

const dappConfig = dappConfigLoader();

Expand All @@ -36,83 +37,45 @@ const dappConfig = dappConfigLoader();
export abstract class BaseGateway
implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect
{
constructor(private readonly authService: AuthService) {
constructor(protected readonly emitter: EventEmitter2) {
this.clients = [];
this.logger = new LogService(`${dappConfig.dappName}/gateway`);
}

public validationInterval: any = null;
protected logger: LogService;

@WebSocketServer()
protected server: any;

protected clients: string[];

async handleConnection(ws: any, req: any) {
// const challenge = this.getChallengeFromUrl(client);
// this.clients.push(challenge);
console.log(req.headers.cookie);

const cookies = req.headers.cookie.split(";");
const challenge = cookies.find((cookie: string) =>
cookie.trim().includes("challenge"),
);

// parse challenge from cookie
const c: any = cookie.parse(req.headers.cookie);
const decoded = cookieParser.signedCookie(
decodeURIComponent(c.challenge),
process.env.SECURITY_AUTH_TOKEN_SECRET,
);

console.log({ decoded });

this.clients.push(challenge.split("=")[1]);
ws.challenge = challenge;

ws.emit("received_challenge", { challenge });
) as string;

console.log("client connected", this.clients);
this.performValidation(challenge.split("=")[1], ws);
// add cookie to ws object
ws.challenge = decoded;
// push challenge to client list
this.clients.push(decoded);

// console.log("cookie: ", req.headers);
}

performValidation(challenge: string, client: any) {
this.validationInterval = setInterval(async () => {
try {
const isValid = await this.authService.validateChallenge(challenge);
console.log({ address: isValid.address });
// trigger auth.open event with challenge passed
this.emitter.emit("auth.open", { challenge: decoded });

if (isValid.address) {
client.send("allowed_authentication");
clearInterval(this.validationInterval);
}
} catch (err) {
console.log({ isValid: false });
}
}, 10000);
this.logger.log("client connected", this.clients);
}

handleDisconnect(ws: any) {
// const challenge = this.getChallengeFromUrl(client);
console.log("BASEGATEWAY: Client disconnected");
const str = ws.challenge.split("=")[1];
const str = ws.challenge;
this.clients = this.clients.filter((c) => c !== str);
console.log("disconnect: ", this.clients);
clearInterval(this.validationInterval);

// this.clients = this.clients.filter(
// (clientId) => clientId !== server.client.id,
// );
this.logger.log("Client disconnected", this.clients);
}

afterInit(server: Server) {
console.log("GATEWAY INITIALIZED");
}

protected getChallengeFromUrl(client: any) {
const { url } = client;
const challenge = url.split("=")[1];

return challenge;
this.logger.log("Gateway initialized");
}
}
6 changes: 6 additions & 0 deletions runtime/backend/src/common/modules/AuthModule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import { Module } from "@nestjs/common";
import { PassportModule } from "@nestjs/passport";
import { JwtModule } from "@nestjs/jwt";
import { MongooseModule } from "@nestjs/mongoose";
import { SchedulerRegistry } from "@nestjs/schedule";
import { EventEmitter2 } from "@nestjs/event-emitter";

// internal dependencies
import { AccountSessionsModule } from "./AccountSessionsModule";
Expand All @@ -22,6 +24,7 @@ import { LogModule } from "../modules/LogModule";
import { AuthService } from "../services/AuthService";
import { AuthStrategy } from "../traits/AuthStrategy";
import { AuthController } from "../routes/AuthController";
import { ValidateChallengeScheduler } from "../schedulers/ValidateChallengeScheduler";
import {
AuthChallenge,
AuthChallengeSchema,
Expand Down Expand Up @@ -76,6 +79,9 @@ const auth = securityConfigLoader().auth;
RefreshStrategy,
CipherService,
AuthGateway,
ValidateChallengeScheduler,
SchedulerRegistry,
// EventEmitter2,
],
exports: [AuthService, CipherService],
})
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/**
* This file is part of dHealth dApps Framework shared under LGPL-3.0
* Copyright (C) 2022-present dHealth Network, All rights reserved.
*
* @package dHealth dApps Framework
* @subpackage Backend
* @author dHealth Network <[email protected]>
* @license LGPL-3.0
*/

import { Injectable } from "@nestjs/common";
import { CronJob } from "cron";
import { SchedulerRegistry } from "@nestjs/schedule";

import { AuthService } from "../services";

@Injectable()
export class ValidateChallengeScheduler {
constructor(
private readonly schedulerRegistry: SchedulerRegistry,
protected readonly authService: AuthService,
) {}

protected job: CronJob;

public addCronJob(cronExpression: string, challenge: string) {
this.job = new CronJob(
cronExpression, // cronTime
this.validate.bind(this, challenge), // onTick
undefined, // empty onComplete
false, // "startNow" (done with L183)
undefined, // timeZone
undefined, // empty resolves to default context
true, // "runOnInit"
);

// add cron to nest scheduler registry
this.schedulerRegistry.addCronJob(
`statistics:cronjobs:leaderboards:D`,
this.job,
);

this.job.start();

console.log("VALIDATION SCHEDULER IS UP AND RUNNING!!!!!!!!!!!!!!!!!!!!!!");
}

protected validate(challenge: string) {
this.authService.validateChallenge(challenge);
}

protected stopCronJob() {
this.job.stop();
}
}

0 comments on commit c939088

Please sign in to comment.