Skip to content

Commit

Permalink
updated logging module and code cleanup with minor bug fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
xDAnkit committed Apr 30, 2018
1 parent 57134e9 commit cd8b6d7
Show file tree
Hide file tree
Showing 10 changed files with 957 additions and 1,819 deletions.
2,583 changes: 903 additions & 1,680 deletions package-lock.json

Large diffs are not rendered by default.

32 changes: 16 additions & 16 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,41 +29,41 @@
"good": "8.1.0",
"good-console": "7.1.0",
"good-squeeze": "5.0.2",
"hapi": "17.2.3",
"hapi-auth-jwt2": "8.0.0",
"hapi": "17.4.0",
"hapi-auth-jwt2": "8.1.0",
"hapi-swagger": "9.1.1",
"inert": "5.1.0",
"joi": "13.1.2",
"jsonwebtoken": "8.2.0",
"moment": "2.21.0",
"moment-timezone": "0.5.14",
"mongoose": "5.0.10",
"joi": "13.2.0",
"jsonwebtoken": "8.2.1",
"moment": "2.22.1",
"moment-timezone": "0.5.16",
"mongoose": "5.0.16",
"nconf": "0.10.0",
"nodemon": "1.17.1",
"nodemon": "1.17.3",
"path": "0.12.7",
"rotating-file-stream": "1.3.4",
"rotating-file-stream": "1.3.6",
"vision": "5.3.2"
},
"devDependencies": {
"@types/bcryptjs": "2.4.1",
"@types/boom": "7.2.0",
"@types/chai": "4.1.2",
"@types/hapi": "17.0.7",
"@types/joi": "13.0.6",
"@types/chai": "4.1.3",
"@types/hapi": "17.0.11",
"@types/joi": "13.0.8",
"@types/jsonwebtoken": "7.2.6",
"@types/mocha": "2.2.48",
"@types/mongoose": "5.0.7",
"@types/mocha": "5.2.0",
"@types/mongoose": "5.0.10",
"@types/nconf": "0.0.37",
"@types/node": "9.4.7",
"@types/sinon": "4.3.0",
"@types/sinon": "4.3.1",
"chai": "4.1.2",
"gulp": "3.9.1",
"gulp-env": "0.4.0",
"gulp-mocha": "5.0.0",
"gulp-rimraf": "0.2.2",
"gulp-shell": "0.6.5",
"gulp-tslint": "8.1.3",
"mocha": "5.0.4",
"mocha": "5.1.1",
"node": "9.8.0",
"sinon": "4.4.6",
"tslint": "5.9.1",
Expand Down
11 changes: 0 additions & 11 deletions src/api/tasks/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,6 @@ export default function (
const taskController = new TaskController(configs, database);
server.bind(taskController);

server.route({
method: 'GET',
path: '/tasks/test',
options: {
handler: taskController.testing,
auth: false,
tags: ['api', 'Helpers'],
description: 'Testing API Helpers',
}
});

server.route({
method: "GET",
path: "/tasks/{id}",
Expand Down
17 changes: 1 addition & 16 deletions src/api/tasks/task-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { ITask } from "./task";
import { IDatabase } from "../../database";
import { IServerConfigurations } from "../../configurations";
import { IRequest } from "../../interfaces/request";
import { ILogs } from "../logs/logs";
import { ILogging } from "../../plugins/logging/logging";

//Custom helper module
import * as Helper from "../../utils/helper";
Expand All @@ -18,21 +18,6 @@ export default class TaskController {
this.database = database;
}

public async testing(request: IRequest, h: Hapi.ResponseToolkit) {
let profile: any = {
_id: "AnkitJain"
};

//Logging user request
Helper.dbLogger("UserID", `Validate email payload ${JSON.stringify(profile)}`, "This is a request");
let res: any = await Helper.validateEmailDomain("[email protected]");

//Logging user request response
Helper.dbLogger("UserID", `Validate email payload reponse ${JSON.stringify(res)}`, "This is a response");

return h.response(res).code(200);
}

public async createTask(request: IRequest, h: Hapi.ResponseToolkit) {
var newTask: ITask = <ITask>request.payload;
newTask.userId = request.auth.credentials.id;
Expand Down
2 changes: 1 addition & 1 deletion src/api/users/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ UserSchema.pre("save", function(next) {
return next();
}

user.password = hashPassword(user.password);
user["password"] = hashPassword(user["password"]);

return next();
});
Expand Down
6 changes: 3 additions & 3 deletions src/database.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import * as Mongoose from "mongoose";
import { IDataConfiguration } from "./configurations";
import { ILogs, LogModel } from "./api/logs/logs";
import { ILogging, LoggingModel } from "./plugins/logging/logging";
import { IUser, UserModel } from "./api/users/user";
import { ITask, TaskModel } from "./api/tasks/task";

export interface IDatabase {
logModel: Mongoose.Model<ILogs>;
loggingModel: Mongoose.Model<ILogging>;
userModel: Mongoose.Model<IUser>;
taskModel: Mongoose.Model<ITask>;
}
Expand All @@ -25,7 +25,7 @@ export function init(config: IDataConfiguration): IDatabase {
});

return {
logModel: LogModel,
loggingModel: LoggingModel,
taskModel: TaskModel,
userModel: UserModel
};
Expand Down
9 changes: 9 additions & 0 deletions src/plugins/logging/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import * as Hapi from "hapi";
import { IDatabase } from "../../database";
import { IServerConfigurations } from "../../configurations";

export function init(
server: Hapi.Server,
configs: IServerConfigurations,
database: IDatabase
) {}
21 changes: 21 additions & 0 deletions src/plugins/logging/logging.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import * as Mongoose from "mongoose";

export interface ILogging extends Mongoose.Document {
userId: string; //User id for finding the operating user
//userType: string; //User type to finding user role - Decide in future - currently disabled
payload: String; //response or request payload to capture details
response: String; //Status message to capture the reponse
}

export const LoggingSchema = new Mongoose.Schema(
{
userId: { type: String, required: true },
payload: { type: String, required: true },
response: { type: String, required: true }
},
{
timestamps: true
}
);

export const LoggingModel = Mongoose.model<ILogging>("logging", LoggingSchema);
2 changes: 1 addition & 1 deletion src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import * as Hapi from "hapi";
import * as Boom from "boom";
import { IPlugin } from "./plugins/interfaces";
import { IServerConfigurations } from "./configurations";
import * as Logs from "./api/logs";
import * as Logs from "./plugins/logging";
import * as Tasks from "./api/tasks";
import * as Users from "./api/users";
import { IDatabase } from "./database";
Expand Down
93 changes: 2 additions & 91 deletions src/utils/helper.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,16 @@
import * as Jwt from "jsonwebtoken";
import * as Mongoose from "mongoose";
import { getDatabaseConfig, getServerConfigs, IServerConfigurations } from "../configurations";
import { LogModel } from "../api/logs/logs";
import { LoggingModel } from "../plugins/logging/logging";
import * as Boom from "boom";

let config: any = getServerConfigs();

//Blacklisted domains lists
//Which is not allowed at our platform
let blackListDomains: any = [
"gmail.com",
"rediffmail.com",
"outlook.com",
"live.com",
"hotmail.com",
"yahoomail.com",
"ymail.com",
"yahoo.co.in",
"yahoo.co.uk"];

//Database logging async call for storing users logs
export const dbLogger = async (userId: string, payload: string, response: string) => {

// create a new log
var newLog = new LogModel({ userId, payload, response });
var newLog = new LoggingModel({ userId, payload, response });

try {
newLog.save();
Expand All @@ -41,82 +28,6 @@ export const generateToken = (user: any) => {
return Jwt.sign(payload, jwtSecret, { expiresIn: jwtExpiration });
};

//To generate 5 digit numeric OTP
export const generateNumericOTP = () => {
return Math.floor(Math.random() * 90000) + 10000;
};

//To generate 5 digit alpha numeric OTP (exluding letters like 'i, I' since it creates issue for users in terms of reading)
export const generateAlphaNumericOTP = () => {
let verificationCode = "";
let charset = "abcdefghjkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ234567890";
for (let i = 0; i < 5; i++) {
verificationCode += charset.charAt(Math.floor(Math.random() * charset.length));
}
return verificationCode;
};


//Validate member email format via comparing it from available blacklist
export const validateEmailDomain = async (email: string) => {

let domainResponse = await this.getEmailDomain(email);
let responseSet: any = {};

//Checking returing isCurrentDomain reponse statusCode to validate isCurrentDomain status
//Handling if only since else will always be true, hence capturing false flag only

if (!domainResponse["statusCode"]) {
return domainResponse;
}

//To check email domain in blacklisted domains
for (let i = 0; i < blackListDomains.length; i++) {

//Preparing fallback response and returning it to its parent call
if (blackListDomains[i] === domainResponse["emailDomain"]) {
responseSet["statusCode"] = false;
responseSet["statusMessage"] = `@${blackListDomains[i]} is not allowed, please provide a valid corporate email address`;
responseSet["emailDomain"] = domainResponse["emailDomain"];
return responseSet;
}
}

//Preparing success response and returning it to its parent call
responseSet["statusCode"] = true;
responseSet["statusMessage"] = `@${domainResponse["emailDomain"]} is allowed`;
responseSet["emailDomain"] = domainResponse["emailDomain"];
return responseSet;
};

//To obtain email domain for evaluating office domain
export const getEmailDomain = async (email: string) => {

//To check whether the provided data in in valid email format or not
let isEmail = await this.checkEmailFormat(email);
let responseSet: any = {};

//Checking returing isEmail reponse statusCode to validate email status
//Handling if only since else will always be true, hence capturing false flag only

if (!isEmail["statusCode"]) {
return isEmail;
}

//To obtain email domain
try {
let currentDomain: string = email.substring(email.lastIndexOf("@") + 1);
responseSet["statusCode"] = true;
responseSet["statusMessage"] = "Email format is valid";
responseSet["emailDomain"] = currentDomain;
return responseSet;
} catch (error) {
responseSet["statusCode"] = false;
responseSet["statusMessage"] = "Unable to get email domain";
return responseSet;
}
};

//To obtain email domain for evaluating office domain
export const checkEmailFormat = (email: string) => {

Expand Down

0 comments on commit cd8b6d7

Please sign in to comment.