Skip to content

Commit cbfaa1d

Browse files
committed
update all files
1 parent c08b158 commit cbfaa1d

Some content is hidden

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

47 files changed

+478
-279
lines changed

.env.example

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@
33
# Environment Name
44
NODE_ENV=development
55

6+
# TimeZone
7+
TZ=UTC
8+
69
# Server listen to this port
710
PORT=3000
811

@@ -11,17 +14,19 @@ CORS_URL=*
1114

1215
# Databse
1316
# YOUR_MONGO_DB_NAME
14-
DB_NAME=afteracademy-blog-db
17+
DB_NAME=blogs-db
18+
DB_MIN_POOL_SIZE=2
19+
DB_MAX_POOL_SIZE=5
1520

1621
#localhost or IP of the server
1722
# If using the docker installation then use 'mongo' for host name else localhost or ip or db server
1823
#YOUR_MONGO_DB_HOST_NAME
19-
DB_HOST=mongo
24+
DB_HOST=localhost
2025

2126
DB_PORT=27017
2227

2328
#YOUR_MONGO_DB_USER_NAME
24-
DB_USER=afteracademy-blog-db-user
29+
DB_USER=blogs-db-user
2530

2631
#YOUR_MONGO_DB_USER_PWD
2732
DB_USER_PWD=changeit
@@ -36,7 +41,9 @@ DB_ADMIN_PWD=changeit
3641
# LOG_DIR=YOUR_DIRECTORY_PATH_FOR_LOG_FILES
3742

3843
# Token Info
39-
ACCESS_TOKEN_VALIDITY_DAYS=30
40-
REFRESH_TOKEN_VALIDITY_DAYS=120
41-
TOKEN_ISSUER=afteracademy.com
42-
TOKEN_AUDIENCE=afteracademy.com
44+
# 2 DAYS: 172800 Sec
45+
ACCESS_TOKEN_VALIDITY_SEC=172800
46+
# 7 DAYS: 604800 Sec
47+
REFRESH_TOKEN_VALIDITY_SEC=604800
48+
TOKEN_ISSUER=api.dev.xyz.com
49+
TOKEN_AUDIENCE=xyz.com

.gitignore

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,4 +22,16 @@ coverage
2222

2323
# Environment varibles
2424
*.env
25-
*.env.*
25+
*.env.test
26+
27+
#keys
28+
keys/*
29+
!keys/*.md
30+
!keys/*.example
31+
32+
#temp
33+
temp
34+
.DS_Store
35+
36+
*.save
37+
*.save.*

src/app.ts

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
11
import express, { Request, Response, NextFunction } from 'express';
22
import Logger from './core/Logger';
3-
import bodyParser from 'body-parser';
43
import cors from 'cors';
54
import { corsUrl, environment } from './config';
65
import './database'; // initialize database
7-
import { NotFoundError, ApiError, InternalError } from './core/ApiError';
6+
import { NotFoundError, ApiError, InternalError, ErrorType } from './core/ApiError';
87
import routesV1 from './routes/v1';
98

109
process.on('uncaughtException', (e) => {
@@ -13,8 +12,8 @@ process.on('uncaughtException', (e) => {
1312

1413
const app = express();
1514

16-
app.use(bodyParser.json({ limit: '10mb' }));
17-
app.use(bodyParser.urlencoded({ limit: '10mb', extended: true, parameterLimit: 50000 }));
15+
app.use(express.json({ limit: '10mb' }));
16+
app.use(express.urlencoded({ limit: '10mb', extended: true, parameterLimit: 50000 }));
1817
app.use(cors({ origin: corsUrl, optionsSuccessStatus: 200 }));
1918

2019
// Routes
@@ -28,10 +27,13 @@ app.use((req, res, next) => next(new NotFoundError()));
2827
app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
2928
if (err instanceof ApiError) {
3029
ApiError.handle(err, res);
30+
if (err.type === ErrorType.INTERNAL)
31+
Logger.error(`500 - ${err.message} - ${req.originalUrl} - ${req.method} - ${req.ip}`);
3132
} else {
33+
Logger.error(`500 - ${err.message} - ${req.originalUrl} - ${req.method} - ${req.ip}`);
34+
Logger.error(err);
3235
if (environment === 'development') {
33-
Logger.error(err);
34-
return res.status(500).send(err.message);
36+
return res.status(500).send(err);
3537
}
3638
ApiError.handle(new InternalError(), res);
3739
}

src/auth/apikey.ts

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,19 +6,21 @@ import { PublicRequest } from 'app-request';
66
import schema from './schema';
77
import validator, { ValidationSource } from '../helpers/validator';
88
import asyncHandler from '../helpers/asyncHandler';
9+
import { Header } from '../core/utils';
910

1011
const router = express.Router();
1112

1213
export default router.use(
1314
validator(schema.apiKey, ValidationSource.HEADER),
1415
asyncHandler(async (req: PublicRequest, res, next) => {
15-
// @ts-ignore
16-
req.apiKey = req.headers['x-api-key'].toString();
16+
const key = req.headers[Header.API_KEY]?.toString();
17+
if (!key) throw new ForbiddenError();
1718

18-
const apiKey = await ApiKeyRepo.findByKey(req.apiKey);
19+
const apiKey = await ApiKeyRepo.findByKey(key);
20+
if (!apiKey) throw new ForbiddenError();
1921
Logger.info(apiKey);
2022

21-
if (!apiKey) throw new ForbiddenError();
23+
req.apiKey = apiKey;
2224
return next();
2325
}),
2426
);

src/auth/authUtils.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ export const createTokens = async (
3737
tokenInfo.audience,
3838
user._id.toString(),
3939
accessTokenKey,
40-
tokenInfo.accessTokenValidityDays,
40+
tokenInfo.accessTokenValidity,
4141
),
4242
);
4343

@@ -49,7 +49,7 @@ export const createTokens = async (
4949
tokenInfo.audience,
5050
user._id.toString(),
5151
refreshTokenKey,
52-
tokenInfo.refreshTokenValidityDays,
52+
tokenInfo.refreshTokenValidity,
5353
),
5454
);
5555

src/auth/authentication.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ export default router.use(
2525
if (!user) throw new AuthFailureError('User not registered');
2626
req.user = user;
2727

28-
const keystore = await KeystoreRepo.findforKey(req.user._id, payload.prm);
28+
const keystore = await KeystoreRepo.findforKey(req.user, payload.prm);
2929
if (!keystore) throw new AuthFailureError('Invalid access token');
3030
req.keystore = keystore;
3131

src/auth/authorization.ts

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,17 +8,25 @@ const router = express.Router();
88

99
export default router.use(
1010
asyncHandler(async (req: ProtectedRequest, res, next) => {
11-
if (!req.user || !req.user.roles || !req.currentRoleCode)
11+
if (!req.user || !req.user.roles || !req.currentRoleCodes)
1212
throw new AuthFailureError('Permission denied');
1313

14-
const role = await RoleRepo.findByCode(req.currentRoleCode);
15-
if (!role) throw new AuthFailureError('Permission denied');
14+
const roles = await RoleRepo.findByCodes(req.currentRoleCodes);
15+
if (roles.length === 0) throw new AuthFailureError('Permission denied');
1616

17-
const validRoles = req.user.roles.filter(
18-
(userRole) => userRole._id.toHexString() === role._id.toHexString(),
19-
);
17+
let authorized = false;
2018

21-
if (!validRoles || validRoles.length == 0) throw new AuthFailureError('Permission denied');
19+
for (const userRole of req.user.roles) {
20+
if (authorized) break;
21+
for (const role of roles) {
22+
if (userRole._id.equals(role._id)) {
23+
authorized = true;
24+
break;
25+
}
26+
}
27+
}
28+
29+
if (!authorized) throw new AuthFailureError('Permission denied');
2230

2331
return next();
2432
}),

src/auth/schema.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
1-
import Joi from '@hapi/joi';
1+
import Joi from 'joi';
2+
import { Header } from '../core/utils';
23
import { JoiAuthBearer } from '../helpers/validator';
34

45
export default {
56
apiKey: Joi.object()
67
.keys({
7-
'x-api-key': Joi.string().required(),
8+
[Header.API_KEY]: Joi.string().required(),
89
})
910
.unknown(true),
1011
auth: Joi.object()

src/config.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,23 @@
11
// Mapper for environment variables
22
export const environment = process.env.NODE_ENV;
33
export const port = process.env.PORT;
4+
export const timezone = process.env.TZ;
45

56
export const db = {
67
name: process.env.DB_NAME || '',
78
host: process.env.DB_HOST || '',
89
port: process.env.DB_PORT || '',
910
user: process.env.DB_USER || '',
1011
password: process.env.DB_USER_PWD || '',
12+
minPoolSize: parseInt(process.env.DB_MIN_POOL_SIZE || '5'),
13+
maxPoolSize: parseInt(process.env.DB_MAX_POOL_SIZE || '10'),
1114
};
1215

1316
export const corsUrl = process.env.CORS_URL;
1417

1518
export const tokenInfo = {
16-
accessTokenValidityDays: parseInt(process.env.ACCESS_TOKEN_VALIDITY_SEC || '0'),
17-
refreshTokenValidityDays: parseInt(process.env.REFRESH_TOKEN_VALIDITY_SEC || '0'),
19+
accessTokenValidity: parseInt(process.env.ACCESS_TOKEN_VALIDITY_SEC || '0'),
20+
refreshTokenValidity: parseInt(process.env.REFRESH_TOKEN_VALIDITY_SEC || '0'),
1821
issuer: process.env.TOKEN_ISSUER || '',
1922
audience: process.env.TOKEN_AUDIENCE || '',
2023
};

src/core/ApiError.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import {
99
ForbiddenResponse,
1010
} from './ApiResponse';
1111

12-
enum ErrorType {
12+
export enum ErrorType {
1313
BAD_TOKEN = 'BadTokenError',
1414
TOKEN_EXPIRED = 'TokenExpiredError',
1515
UNAUTHORIZED = 'AuthFailureError',

0 commit comments

Comments
 (0)