Skip to content

Commit

Permalink
implement v1 configured routing & working on swagger
Browse files Browse the repository at this point in the history
  • Loading branch information
samayun committed Dec 19, 2021
1 parent 7c60ed0 commit 5e5bfc1
Show file tree
Hide file tree
Showing 18 changed files with 761 additions and 604 deletions.
2 changes: 2 additions & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
coverage
node_modules
24 changes: 24 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"extends": ["eslint:recommended"],
"env": {
"node": true,
"mocha": true,
"es6": true
},
"parserOptions": {
"ecmaVersion": 6
},
"rules": {
"comma-dangle": [2, "never"],
"max-len": [
2,
{
"code": 100,
"tabWidth": 2
}
],
"semi": 2,
"keyword-spacing": 2,
"indent": [2, 2, { "SwitchCase": 1 }]
}
}
10 changes: 10 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"proseWrap": "never",
"printWidth": 99999,
"semi": true,
"trailingComma": "none",
"singleQuote": true,
"bracketSpacing": true,
"arrowParens": "avoid",
"tabWidth": 4
}
6 changes: 5 additions & 1 deletion app/services/crud/mongodb.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,13 @@ class MongoCrud {
return await new this.Model(params).save();
}
async update(keys, params) {
return await this.Model.findOneAndUpdate(keys, {
const updated = await this.Model.findOneAndUpdate(key, {
$set: params,
});
return {
...updated._doc,
...params,
};
}
async deleteOne(key) {
return await this.Model.findOneAndDelete(key);
Expand Down
164 changes: 91 additions & 73 deletions modules/authentication/routes/index.js
Original file line number Diff line number Diff line change
@@ -1,82 +1,100 @@
// require("dotenv").config();
const router = require("express").Router();
const { JWT } = require("jwt-auth-helper");
const authenticate = require("../../../app/middlewares/isAuth");
const authService = require("../services/authService");

const {
registerValidator,
loginValidator,
} = require("../validator/auth.validator");
const { JWT } = require('jwt-auth-helper');
const authenticate = require('../../../app/middlewares/isAuth');
const authService = require('../services/authService');

const jwt = new JWT(process.env.JWT_SECRET_KEY || "JWT_SECRET_KEY");
const { registerValidator, loginValidator } = require('../validator/auth.validator');

module.exports = (routes) => {
routes.use("/api/auth", router);
const jwt = new JWT(process.env.JWT_SECRET_KEY || 'JWT_SECRET_KEY');

// POST /api/auth/login
router.post("/login", loginValidator, async (req, res, next) => {
try {
const user = await authService.login({
email: req.body.email,
password: req.body.password,
});
// generate access token
const access_token = await jwt.generateJWTToken({ ...user });
const path = '/v1/auth';
const router = require('express').Router();

res.json({
status: "success",
message: `${user.name} logged in successfully`,
data: user,
access_token,
});
} catch (error) {
console.log(error);
next(error);
}
});
module.exports = () => {
// POST /api/auth/login
router.post('/login', loginValidator, async (req, res, next) => {
try {
/* #swagger.tags = ['User']
/* #swagger.basePath = 'auth'
#swagger.description = 'Endpoint to sign in a specific user' */

/**
* POST /api/auth/register
* { name : "Salman Akash", email: "[email protected], password: "123456"}
* */
router.post("/register", registerValidator, async (req, res, next) => {
try {
const user = await authService.register(req.body);
// generate access token
const access_token = await jwt.generateJWTToken({ ...user });
/* #swagger.parameters['obj'] = {
in: 'body',
description: 'User information.',
required: true,
schema: { $ref: "#/definitions/AddUser" }
} */

res.json({
status: "success",
message: `${user.name} register successfully`,
data: access_token,
});
} catch (error) {
next(error);
}
});
// GET /api/auth/profile
router.get("/profile", authenticate, async (req, res, next) => {
try {
res.json({
status: "success",
message: `Valid profile`,
data: await authService.profile(req.user.email),
});
} catch (error) {
next(error);
}
});
// GET /api/auth/users
router.get("/users", authenticate, async (req, res, next) => {
try {
res.json({
status: "success",
message: `Valid profile`,
data: await authService.getUsers(),
});
} catch (error) {
next(error);
}
});
/* #swagger.security = [{
"apiKeyAuth": []
}] */
const user = await authService.login({
email: req.body.email,
password: req.body.password
});
// generate access token
const access_token = await jwt.generateJWTToken({ ...user });

res.json({
status: 'success',
message: `${user.name} logged in successfully`,
data: user,
access_token
});
} catch (error) {
console.log(error);
next(error);
}
});

/**
* POST /api/auth/register
* { name : "Salman Akash", email: "[email protected], password: "123456"}
* */
router.post('/register', registerValidator, async (req, res, next) => {
/* #swagger.tags = ['User']
#swagger.description = 'Endpoint to sign up a specific user' */
try {
const user = await authService.register(req.body);
// generate access token
const access_token = await jwt.generateJWTToken({ ...user });

res.json({
status: 'success',
message: `${user.name} register successfully`,
data: access_token
});
} catch (error) {
next(error);
}
});
// GET /api/auth/profile
router.get('/profile', authenticate, async (req, res, next) => {
try {
res.json({
status: 'success',
message: `Valid profile`,
data: await authService.profile(req.user.email)
});
} catch (error) {
next(error);
}
});
// GET /api/auth/users
router.get('/users', authenticate, async (req, res, next) => {
try {
res.json({
status: 'success',
message: `Valid profile`,
data: await authService.getUsers()
});
} catch (error) {
next(error);
}
});
return {
path,
router
};
};
50 changes: 25 additions & 25 deletions modules/authentication/validator/auth.validator.js
Original file line number Diff line number Diff line change
@@ -1,36 +1,36 @@
exports.registerValidator = async (req, res, next) => {
const { name, username, phone, email, password, confirmPassword } = req.body;
if (!name) return next(new Error("Name is required"));
// if (!username) return next(new Error('username is required'));
// if (!phone) return next(new Error('phone is required'));
if (!email) return next(new Error("email is required"));
const { name, username, phone, email, password, confirmPassword } = req.body;
if (!name) return next(new Error('Name is required'));
// if (!username) return next(new Error('username is required'));
// if (!phone) return next(new Error('phone is required'));
if (!email) return next(new Error('email is required'));

if (!/^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/gi.test(email)) {
return next(new Error("You must use valid email "));
}
if (!/^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/gi.test(email)) {
return next(new Error('You must use valid email '));
}

if (!password) return next(new Error("password is required"));
if (!password) return next(new Error('password is required'));

if (password.length < 6) {
return next(new Error("Password must be at least 6 character"));
}
// if (password !== confirmPassword) return next(new Error('password doesn\'t match'));
next();
if (password.length < 6) {
return next(new Error('Password must be at least 6 character'));
}
// if (password !== confirmPassword) return next(new Error('password doesn\'t match'));
next();
};

exports.loginValidator = async (req, res, next) => {
const { email, password, confirmPassword } = req.body;
const { email, password, confirmPassword } = req.body;

if (!email) return next(new Error("email is required 😢"));
if (!email) return next(new Error('email is required 😢'));

if (!/^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/gi.test(email)) {
return next(new Error("You must use valid email 😢"));
}
if (!password) return next(new Error("password is required 😢"));
if (!/^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/gi.test(email)) {
return next(new Error('You must use valid email 😢'));
}
if (!password) return next(new Error('password is required 😢'));

if (password.length < 6) {
return next(new Error("Password must be at least 6 character 😢"));
}
// if (password !== confirmPassword) return next(new Error('password doesn\'t match'));
next();
if (password.length < 6) {
return next(new Error('Password must be at least 6 character 😢'));
}
// if (password !== confirmPassword) return next(new Error('password doesn\'t match'));
next();
};
22 changes: 22 additions & 0 deletions modules/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const fs = require('fs');
const { resolve, join } = require('path');

module.exports = () => {
// let routes = [];
const modulePath = resolve(`${__dirname}`);
const modules = fs.readdirSync(modulePath);
const routers = modules
.map(mod => {
const routePath = join(modulePath, mod);

// If only modules have routes_directory/index.js means it's RESTful route
// otherwise It may be utilities module or GraphQL based modules

if (fs.existsSync(routePath + '/routes/index.js')) {
return require(routePath + '/routes/index')();
// routes.push(`${routePath}/routes/index.js`);
}
})
.filter(mod => !!mod);
return routers;
};
Loading

0 comments on commit 5e5bfc1

Please sign in to comment.