Skip to content

Commit 777f2e8

Browse files
chg: refactor all api for async behaviour workflow for protocol layer
1 parent 2d4b70c commit 777f2e8

File tree

181 files changed

+12612
-875
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

181 files changed

+12612
-875
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ typings/
5656

5757
# dotenv environment variables file
5858
.env
59+
*local.env
5960

6061
# next.js build output
6162
.next

notifications/.babelrc

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"presets": [
3+
"@babel/preset-env"
4+
]
5+
}

notifications/.eslintrc.js

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
module.exports = {
2+
env: {
3+
es2021: true,
4+
node: true,
5+
mocha:true,
6+
},
7+
extends: 'eslint:recommended',
8+
parserOptions: {
9+
ecmaVersion: 13,
10+
sourceType: 'module',
11+
},
12+
rules: {
13+
indent: ['error', 4],
14+
'linebreak-style': ['error', 'unix'],
15+
quotes: ['error', 'single'],
16+
semi: ['error', 'always'],
17+
'no-unused-vars': ['error', { argsIgnorePattern: '^((req|res|next)$|_)' }],
18+
'eol-last': ['error', 'always'],
19+
},
20+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
module.exports = Object.freeze({
2+
// Status Code
3+
STATUS_CODE_GENERALIZED_SUCCESS: '200',
4+
STATUS_CODE_GENERALIZED_ALREADY_EXISTS: '202',
5+
STATUS_CODE_GENERALIZED_INVALID_REQUEST: '400',
6+
STATUS_CODE_GENERALIZED_UNAUTHORIZED: '401',
7+
STATUS_CODE_GENERALIZED_NOT_FOUND: '404',
8+
STATUS_CODE_GENERALIZED_FAILED: '412',
9+
STATUS_CODE_GENERALIZED_CONFIG_MISMATCH: '422',
10+
STATUS_CODE_GENERALIZED_UPGRADE_REQUIRED: '426',
11+
STATUS_CODE_GENERALIZED_SEQUELIZE_ERROR: '500'
12+
}); // freeze prevents changes by users
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
module.exports = Object.freeze({
2+
MOM_MENTION: 'MOM_MENTION',
3+
TASK_ASSIGN: 'TASK_ASSIGN',
4+
PROJECT_ASSIGN: 'PROJECT_ASSIGN',
5+
COMMENT_MENTION: 'COMMENT_MENTION',
6+
NEW_COMMENT: 'NEW_COMMENT',
7+
TEAM_ASSIGN: 'TEAM_ASSIGN',
8+
TASK_APPROVE_SUCCESS: 'TASK_APPROVE_SUCCESS',
9+
TASK_APPROVE_FAIL: 'TASK_APPROVE_FAIL',
10+
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
module.exports = Object.freeze({
2+
EXCEPTION_EMAIL: {
3+
SUBJECT: '{{subject}}',
4+
BODY: '{{{text}}}',
5+
},
6+
}); // freeze prevents changes by users
+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
2+
const nodeEnvironment = process.env.NODE_ENV || 'development';
3+
const projectBaseDirectory = global.__basedir;
4+
const appEnvironment = process.env.APP_ENV ?? 'local';
5+
6+
if(appEnvironment === 'local') {
7+
require('dotenv').config({
8+
path: `${__dirname}/local.env`,
9+
});
10+
}
11+
12+
const environmentConfig = require('./environments/base');
13+
const mergedEnvironmentConfig = {
14+
...environmentConfig,
15+
nodeEnvironment,
16+
appEnvironment,
17+
projectBaseDirectory,
18+
};
19+
Object.freeze(mergedEnvironmentConfig);
20+
exports.mergedEnvironmentConfig = mergedEnvironmentConfig;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
module.exports = {
2+
appNamespace: process.env.BASE_APP_NAMESPACE ?? 'artifex-auth',
3+
servicePort: process.env.BASE_APP_PORT ?? '3008',
4+
mobileApplicationAllowedVersions: {
5+
ios: {
6+
minimumVersion: process.env.MOBILE_APP_IOS_MIN_ALLOWED_VERSION ?? '2.7.0', // App needs to be forcefully upgraded to this version
7+
optionalVersion: process.env.MOBILE_APP_IOS_MAX_ALLOWED_VERSION ?? '2.7.0', // App can be optionally upgraded to this version
8+
},
9+
android: {
10+
minimumVersion: process.env.MOBILE_APP_ANDROID_MIN_ALLOWED_VERSION ?? '2.7.0', // App needs to be forcefully upgraded to this version
11+
optionalVersion: process.env.MOBILE_APP_ANDROID_MAX_ALLOWED_VERSION ?? '2.7.0', // App can be optionally upgraded to this version
12+
}
13+
},
14+
intraServiceApiEndpoints: {
15+
authService: process.env.INTRA_SERVICE_AUTH_SERVICE_URL,
16+
pmService: process.env.INTRA_SERVICE_PROJECT_MANAGEMENT_URL,
17+
},
18+
jwtSecret:process.env.AUTH_ACCESS_JWT_SECRET,
19+
appUrl:process.env.APP_URL
20+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
module.exports = {
2+
'cors': {
3+
'whitelistUrls': [
4+
'*',
5+
'http://localhost:3000',
6+
'https://localhost:3000',
7+
'https://artifex.com',
8+
'http://artifex.com',
9+
'https://staging.artifex.com',
10+
'http://staging.artifex.com',
11+
'http://dev.artifex.com',
12+
'https://dev.artifex.com',
13+
'https://artifex-auth-dev.wemotive.in',
14+
'https://artifex-pm-dev.wemotive.in',
15+
'https://artifex.artifex-dev.com:3000',
16+
'https://auth.artifex-dev.com:3005'
17+
18+
]
19+
}
20+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
module.exports = {
2+
mongodb: {
3+
username: process.env.MONGODB_DATABASE_USERNAME,
4+
password: process.env.MONGODB_DATABASE_PASSWORD,
5+
name: process.env.MONGODB_DATABASE_NAME,
6+
host: process.env.MONGODB_DATABASE_HOST,
7+
}
8+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
module.exports = {
2+
email: {
3+
transport: {
4+
host: process.env.SMTP_HOST,
5+
port: process.env.SMTP_PORT,
6+
auth: {
7+
user: process.env.SMTP_AUTH_USERNAME,
8+
pass: process.env.SMTP_AUTH_PASSWORD,
9+
},
10+
},
11+
sender: process.env.SMTP_EMAIL_SENDER,
12+
exceptionEmailRecipients: process.env.SMTP_EXCEPTION_EMAIL_RECIPIENTS,
13+
templateDefaults: {
14+
header: {
15+
logoUrl: process.env.SMTP_EMAIL_TEMPLATE_HEADER_IMAGE_PATH,
16+
},
17+
},
18+
},
19+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import baseConfig from './env.base';
2+
import corsConfig from './env.cors';
3+
import dbConfig from './env.db';
4+
const mailConfig = require('./env.email');
5+
6+
7+
const mergedEnvironmentConfig = {
8+
...baseConfig,
9+
...corsConfig,
10+
...dbConfig,
11+
...mailConfig
12+
};
13+
14+
Object.freeze(mergedEnvironmentConfig);
15+
module.exports = mergedEnvironmentConfig;
+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import mongoose from 'mongoose';
2+
import { mergedEnvironmentConfig } from '../config/env.config.js';
3+
4+
const config = mergedEnvironmentConfig.mongodb;
5+
mongoose.connect(`${config.host}/${config.name}`,{
6+
useNewUrlParser:true
7+
});
8+
9+
mongoose.set('debug', (collectionName, method, query, doc) => {
10+
console.log(`[MONGOOS]:${collectionName}.${method}`, JSON.stringify(query), doc);
11+
});

notifications/app/init/router.init.js

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import { Router } from 'express';
2+
import glob from 'glob';
3+
import cors from 'cors';
4+
import { mergedEnvironmentConfig as config } from '../config/env.config';
5+
6+
const whitelist = config.cors.whitelistUrls;
7+
const corsOptionsDelegate = function (req, callback) {
8+
let corsOptions = {credentials: true};
9+
corsOptions['origin'] = (whitelist.indexOf(req.header('Origin')) !== -1);
10+
corsOptions['exposedHeaders'] = 'set-cookie';
11+
callback(null, corsOptions); // callback expects two parameters: error and optionsns
12+
};
13+
14+
module.exports = () => glob
15+
.sync('**/*.route.js', {
16+
cwd: `${global.__basedir}/modules/`,
17+
})
18+
.map((filename) => {
19+
// console.log(`Attempting to register router at: path ../modules/${filename} from relative path ${__dirname}`);
20+
return require(`../modules/${filename}`);
21+
})
22+
.filter((currentRouter) => {
23+
const isCurrentRouterValid = Object.getPrototypeOf(currentRouter) === Router;
24+
return isCurrentRouterValid;
25+
})
26+
.reduce(
27+
(rootRouter, router) => rootRouter.use(router, cors(corsOptionsDelegate)),
28+
Router({
29+
mergeParams: true,
30+
})
31+
);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
export { default as JsonWebToken } from './json-web-token';
2+
export { default as Token } from './token';
3+
// export { default as passportMobileLocalStrategy } from './strategies/passport-mobile-local';
4+
// export { default as passportOTPLocalStrategy } from './strategies/passport-OTP-local';
5+
export { default as passportJwtStrategy } from './strategies/passport-jwt';
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import jwt from 'jsonwebtoken';
2+
3+
class JsonWebToken {
4+
/**
5+
*
6+
* @param {*} options JWT options
7+
*/
8+
constructor(options) {
9+
this.options = options;
10+
}
11+
12+
/**
13+
* Sign JWT token
14+
* @param {*} token Instance of Token class
15+
*/
16+
sign(token) {
17+
return new Promise((resolve, reject) => {
18+
jwt.sign(
19+
token.payload,
20+
this.options.secret,
21+
{ expiresIn: token.exp },
22+
function (err, token) {
23+
if (err) {
24+
reject(err);
25+
} else {
26+
resolve(token);
27+
}
28+
}
29+
);
30+
});
31+
}
32+
33+
/**
34+
* Verify JWT token
35+
* @param {} jwtToken JWT token in String format
36+
*/
37+
verify(jwtToken) {
38+
return new Promise((resolve, reject) => {
39+
jwt.verify(jwtToken, this.options.secret, function (err, decoded) {
40+
if (err) {
41+
reject(err);
42+
} else {
43+
resolve(decoded);
44+
}
45+
});
46+
});
47+
}
48+
}
49+
50+
export default JsonWebToken;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
import passportJWT from 'passport-jwt';
2+
import { UnauthenticatedError } from '../../errors';
3+
import MESSAGES from '../../utils/messages';
4+
import {mergedEnvironmentConfig} from '../../../config/env.config';
5+
const JwtStrategy = passportJWT.Strategy;
6+
import { HEADERS } from '../../utils/constants';
7+
var httpContext = require('express-http-context');
8+
let currentUserToken = '';
9+
const tokenExtractor = function (req) {
10+
let token = null;
11+
let tokenArray = [];
12+
13+
if (req) {
14+
token = req.get(HEADERS.ACCESS_TOKEN);
15+
16+
if (!token) {
17+
throw new UnauthenticatedError(
18+
MESSAGES.LOGIN_ERROR_USER_ACCESS_TOKEN_INVALID
19+
);
20+
}
21+
22+
tokenArray = token.split(' ');
23+
}
24+
currentUserToken =tokenArray[1];
25+
return tokenArray[1];
26+
};
27+
28+
const opts = {
29+
jwtFromRequest: tokenExtractor, //ExtractJwt.fromAuthHeaderAsBearerToken(),
30+
secretOrKey: mergedEnvironmentConfig.jwtSecret,
31+
passReqToCallback: true,
32+
};
33+
34+
const passportJwtStrategy = new JwtStrategy(
35+
opts,
36+
async (req, jwtPayload, done) => {
37+
try {
38+
let user = {};
39+
40+
// if jwt payload contains user obj then its an inter service communication call
41+
if (jwtPayload.user) {
42+
user = jwtPayload.user;
43+
} else if (jwtPayload.userId) {
44+
//TODO: add db level auth check
45+
46+
// user = await User.findOne({
47+
// where: {
48+
// id: jwtPayload.userId
49+
// },
50+
// include: [{ model: UserOrganization, include: [{ model: Role }] }]
51+
// });
52+
53+
if (!user) {
54+
throw new UnauthenticatedError(
55+
MESSAGES.LOGIN_ERROR_USER_ACCESS_TOKEN_INVALID
56+
);
57+
} else if (user.enabled === false) {
58+
throw new UnauthenticatedError(
59+
MESSAGES.LOGIN_ERROR_USER_ACCOUNT_DEACTIVATED
60+
);
61+
}
62+
63+
64+
user = user.toJSON();
65+
}
66+
// httpContext.set('request.req.user.token',currentUserToken);
67+
// httpContext.set('request.req.user.id',user.id);
68+
user.currentUserToken = currentUserToken;
69+
return done(null, user);
70+
} catch (err) {
71+
return done(err, null);
72+
}
73+
}
74+
);
75+
76+
export default passportJwtStrategy;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Token {
2+
/**
3+
*
4+
* @param {*} payload token payload
5+
* @param {*} exp token expiry
6+
*/
7+
constructor(payload, exp) {
8+
this.payload = payload;
9+
this.exp = exp;
10+
}
11+
12+
setPayload(payload) {
13+
this.payload = payload;
14+
}
15+
16+
getPayload() {
17+
return this.payload;
18+
}
19+
20+
setExp(exp) {
21+
this.exp = exp;
22+
}
23+
24+
getExp() {
25+
return this.exp;
26+
}
27+
}
28+
29+
export default Token;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import ERRORS from './errors';
2+
3+
class BadRequestParameterError extends Error {
4+
constructor(message = ERRORS.BAD_REQUEST_PARAMETER_ERROR.message) {
5+
super(message);
6+
this.name = ERRORS.BAD_REQUEST_PARAMETER_ERROR.name;
7+
this.status = ERRORS.BAD_REQUEST_PARAMETER_ERROR.status;
8+
}
9+
}
10+
11+
export default BadRequestParameterError;

0 commit comments

Comments
 (0)