Skip to content

Commit fe057f7

Browse files
feat: linters & update test (#8)
1 parent f201589 commit fe057f7

30 files changed

+351
-281
lines changed

.env.example

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
SECRET_KEY = 'foo';
2+
EXPIRES_IN = '1h';

README.md

+16-5
Original file line numberDiff line numberDiff line change
@@ -32,20 +32,31 @@ A Microservice API based on the hexagonal architecture using NodeJS + ExpressJS
3232
- [NodeJS](https://nodejs.org/en/) >= v20.1.0
3333
- [Docker](https://www.docker.com/)
3434

35-
### SetUp
35+
## SetUp
3636

37-
#### Install
37+
### Install
3838

3939
```zsh
4040
npm install
4141
```
4242

43-
### Before running the project
43+
## Running
44+
45+
### Local
46+
47+
#### Create environment vars
48+
4449
```zsh
4550
cp .env.example .env
4651
```
4752

48-
#### Run the app using Docker
53+
#### Run
54+
55+
```zsh
56+
npm run start
57+
```
58+
59+
### Docker
4960

5061
Use the following commands to run the app
5162

@@ -65,7 +76,7 @@ Now you can do a HTTP request to:
6576
http://localhost:3001/users/123123123
6677
```
6778

68-
#### Test
79+
## Test
6980

7081
```zsh
7182
npm run test

app/internal/adapters/auth/index.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
export * from './jwt';
1+
export * from './jwt';

app/internal/adapters/auth/jwt.js

+39-12
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,42 @@
1-
import jsonwebtoken from "jsonwebtoken";
2-
import { defaultConfig } from "../../core/providers";
1+
import jsonwebtoken from 'jsonwebtoken';
32

4-
const generateToken = (admin_id, expires_in) => {
5-
return jsonwebtoken.sign({id: admin_id}, defaultConfig.security_key, {expiresIn:expires_in});
6-
}
3+
/**
4+
* Generates a JSON Web Token (JWT) for the specified admin ID and expiration time.
5+
*
6+
* @function
7+
* @memberof JWT
8+
* @param {string} adminID - The ID of the admin for whom the token is generated.
9+
* @param {string | number} expiresIn - The expiration time for the token (e.g., '2h', '7d', or a timestamp).
10+
* @param {string} secretKey - Security secretKey.
11+
* @returns {string} The generated JWT.
12+
*/
13+
const generateToken = (adminID, expiresIn, secretKey) =>
14+
jsonwebtoken.sign({ id: adminID }, secretKey, {
15+
expiresIn,
16+
});
717

8-
const verifyToken = (token) => {
9-
return jsonwebtoken.verify(token, defaultConfig.security_key);
10-
};
18+
/**
19+
* Verifies the authenticity of a JSON Web Token (JWT).
20+
*
21+
* @function
22+
* @memberof JWT
23+
* @param {string} token - The JWT to be verified.
24+
* @param {string} secretKey - The JWT secretKey used to be verify.
25+
* @returns {object} The decoded payload of the verified JWT.
26+
* @throws {Error} If the token verification fails.
27+
*/
28+
const verifyToken = (token, secretKey) => jsonwebtoken.verify(token, secretKey);
29+
30+
/**
31+
* JSON Web Token (JWT) utility functions for token generation and verification.
32+
*
33+
* @namespace
34+
* @typedef {Object} JWT
35+
* @property {function} generateToken - Function to generate a JWT.
36+
* @property {function} verifyToken - Function to verify the authenticity of a JWT.
37+
*/
1138

12-
export const Token ={
13-
generateToken,
14-
verifyToken
15-
};
39+
export const JWT = {
40+
generateToken,
41+
verifyToken,
42+
};
+8-8
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
1-
import express from "express";
2-
import { AuthController } from "../../core/controllers";
1+
import express from 'express';
2+
import { AuthController } from '../../core/controllers';
33

44
/**
55
* Create a new instance of UserRoutes.
66
* @param {express.Application} app - The Express application instance.
77
*/
8-
export const AuthRoute = (app) =>{
9-
const router = express.Router();
10-
app.use('/auth', router);
8+
export const AuthRoute = (app) => {
9+
const router = express.Router();
10+
app.use('/auth', router);
1111

12-
//Get Token
13-
router.get('/token', AuthController.getToken);
14-
};
12+
// Get Token
13+
router.get('/token', AuthController.getToken);
14+
};
+15-15
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,20 @@
1-
import express from "express";
2-
import { UsersController } from "../../core/controllers";
1+
import express from 'express';
2+
import { UsersController } from '../../core/controllers';
33

44
/**
55
* Create a new instance of UserRoutes.
66
* @param {express.Application} app - The Express application instance.
77
*/
8-
export const UsersRoute = (app) =>{
9-
const router = express.Router();
10-
app.use('/users', router);
11-
12-
//List by id
13-
router.get('/:id', UsersController.getById);
14-
// Create a new user
15-
router.post('/', UsersController.create)
16-
//Edit User
17-
router.put('/:id', UsersController.update);
18-
//Delete user
19-
router.delete('/:id', UsersController.delete);
20-
};
8+
export const UsersRoute = (app) => {
9+
const router = express.Router();
10+
app.use('/users', router);
11+
12+
// List by id
13+
router.get('/:id', UsersController.getById);
14+
// Create a new user
15+
router.post('/', UsersController.create);
16+
// Edit User
17+
router.put('/:id', UsersController.update);
18+
// Delete user
19+
router.delete('/:id', UsersController.delete);
20+
};
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import { AuthServices } from '../services';
21
import { constants } from 'http2';
2+
import { AuthServices } from '../services';
33

44
/**
55
* Callback function for performing a CRUD.
@@ -9,12 +9,16 @@ import { constants } from 'http2';
99
* @function getToken - Obtain the JWT token.
1010
*/
1111
export const AuthController = {
12-
getToken: (req, res, next) => {
13-
try {
14-
const token = AuthServices.getToken(req.body.admin_id, req.body.expires_in);
15-
res.status(constants.HTTP_STATUS_OK).json(token);
16-
} catch (err) {
17-
next(err);
18-
}
19-
},
20-
};
12+
getToken: (req, res, next) => {
13+
try {
14+
const token = AuthServices.getToken(
15+
req.body.adminId,
16+
req.config.auth.expiresIn,
17+
req.config.auth.securityKey,
18+
);
19+
res.status(constants.HTTP_STATUS_OK).json(token);
20+
} catch (err) {
21+
next(err);
22+
}
23+
},
24+
};
+1-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
export * from './main.controller';
22
export * from './users.controller';
3-
export * from './auth.controller';
3+
export * from './auth.controller';
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,5 @@
1-
import { UserServices } from '../services';
21
import { constants } from 'http2';
3-
import { Domain } from '../domain';
4-
5-
const {
6-
Models: { Responses },
7-
} = Domain;
2+
import { UserServices } from '../services';
83

94
/**
105
* Callback function for performing a CRUD.
@@ -17,38 +12,36 @@ const {
1712
* @function delete - Delete the information of a user using his ID.
1813
*/
1914
export const UsersController = {
20-
getById: (req, res, next) => {
21-
try {
22-
const message = UserServices.getById();
23-
res.status(constants.HTTP_STATUS_OK).json(message);
24-
} catch (err) {
25-
next(err);
26-
}
27-
},
28-
create: async (req, res, next) => {
29-
{
30-
try {
31-
const message = UserServices.create();
32-
res.status(constants.HTTP_STATUS_OK).json(message);
33-
} catch (err) {
34-
next(err);
35-
}
36-
}
37-
},
38-
update: async (req, res, next) => {
39-
try {
40-
const message = UserServices.update();
41-
res.status(constants.HTTP_STATUS_OK).json(message);
42-
} catch (err) {
43-
next(err);
44-
}
45-
},
46-
delete: async (req, res, next) => {
47-
try {
48-
const message = UserServices.delete();
49-
res.status(constants.HTTP_STATUS_OK).json(message);
50-
} catch (err) {
51-
next(err);
52-
}
53-
},
54-
}
15+
getById: (req, res, next) => {
16+
try {
17+
const message = UserServices.getById();
18+
res.status(constants.HTTP_STATUS_OK).json(message);
19+
} catch (err) {
20+
next(err);
21+
}
22+
},
23+
create: async (req, res, next) => {
24+
try {
25+
const message = UserServices.create();
26+
res.status(constants.HTTP_STATUS_OK).json(message);
27+
} catch (err) {
28+
next(err);
29+
}
30+
},
31+
update: async (req, res, next) => {
32+
try {
33+
const message = UserServices.update();
34+
res.status(constants.HTTP_STATUS_OK).json(message);
35+
} catch (err) {
36+
next(err);
37+
}
38+
},
39+
delete: async (req, res, next) => {
40+
try {
41+
const message = UserServices.deleteByID();
42+
res.status(constants.HTTP_STATUS_OK).json(message);
43+
} catch (err) {
44+
next(err);
45+
}
46+
},
47+
};

app/internal/core/domain/models/responses.models.js

+5-5
Original file line numberDiff line numberDiff line change
@@ -18,20 +18,20 @@ const simple = (message) => ({
1818
* @typedef {Object} TokenResponse
1919
* @property {string} access_token - The token created.
2020
* @property {string} expires_in - The expiration time of the toke.
21-
* @property {string} token_type - The token type for the request, by default is Bearer.
21+
* @property {string} tokenType - The token type for the request, by default is Bearer.
2222
*/
2323

2424
/**
2525
* Creates a token response object.
2626
* @param {string} token - The token created with the expiration time.
27-
* @property {string} expires_in - The expiration time of the token.
27+
* @property {string} expiresIn - The expiration time of the token.
2828
* @returns {TokenResponse} The token response with the information about the token created.
2929
*/
3030

31-
const tokenResponse = (token, expires_in) =>({
31+
const tokenResponse = (token, expiresIn) => ({
3232
access_token: token,
33-
expires_in: expires_in,
34-
token_type: "Bearer"
33+
expiresIn,
34+
tokenType: 'Bearer',
3535
});
3636

3737
export const Responses = {

app/internal/core/middlewares/auth.js

+20-14
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,24 @@
1-
import { Token } from '../../adapters/auth';
1+
import { JWT } from '../../adapters/auth';
22

3-
const tokenPaths =["/health/", "/users/"]
3+
const tokenPaths = ['/health/', '/users/'];
44

5-
export const tokenValidator = (req, res, next) => {
6-
const token = req.headers["authorization"] && req.headers["authorization"].split(" ")[1];
7-
if (token !== "undefined" && tokenPaths.includes(req.path.slice(0,7))){
8-
try {
9-
Token.verifyToken(token);
10-
next();
11-
}catch(err){
12-
next(err);
13-
}
14-
}else{
15-
next();
5+
/**
6+
* Express middleware to check credentials on specifics routes.
7+
* @param {import('express').Request} req - The Express request object.
8+
* @param {import('express').Response} res - The Express response object.
9+
* @param {import('express').NextFunction} next - The Express next function.
10+
*/
11+
export const Auth = (req, res, next) => {
12+
const token =
13+
req.headers.authorization && req.headers.authorization.split(' ')[1];
14+
if (token !== 'undefined' && tokenPaths.includes(req.path.slice(0, 7))) {
15+
try {
16+
JWT.verifyToken(token, req.defaultConfig.auth.secretKey);
17+
next();
18+
} catch (err) {
19+
next(err);
1620
}
21+
} else {
22+
next();
23+
}
1724
};
18-
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
11
import { defaultConfig } from '../providers';
22

3-
export const configurations = (req, res, next) => {
3+
/**
4+
* Express middleware to attach the configurations to the request object.
5+
* @param {import('express').Request} req - The Express request object.
6+
* @param {import('express').Response} res - The Express response object.
7+
* @param {import('express').NextFunction} next - The Express next function.
8+
*/
9+
export const Configurations = (req, res, next) => {
410
req.config = defaultConfig;
511
next();
612
};

app/internal/core/models/index.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
export * from './users';
1+
export * from './users';

0 commit comments

Comments
 (0)