Skip to content

Commit

Permalink
#174 [Backend] Setup Localhost Token And Cors
Browse files Browse the repository at this point in the history
  • Loading branch information
fdhhhdjd committed Mar 5, 2023
1 parent d05c740 commit ef93234
Show file tree
Hide file tree
Showing 20 changed files with 317 additions and 331 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ paths:
#!created_at 28/02/2023
#!description: New Token
/api/v1/admin/renew-token:
post:
get:
summary: New Token
tags: [New Token]
operationId: reNewToken
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,8 +116,8 @@ const adminController = {
sameSite: CONFIGS.NODE_ENV === CONSTANTS.ENVIRONMENT_PRODUCT ? true : false,
secure: CONFIGS.NODE_ENV === CONSTANTS.ENVIRONMENT_PRODUCT ? true : false,
domain:
CONFIGS.NODE_ENV === CONSTANTS.ENVIRONMENT_PRODUCT
? req.headers[CONSTANTS.HEADER_HEADER_FORWARDED_HOST]?.split(':')[0]
CONFIGS.NODE_ENV === CONSTANTS.ENVIRONMENT_PRODUCT ?
req.headers[CONSTANTS.HEADER_HEADER_FORWARDED_HOST]?.split(':')[0]
: CONSTANTS.HEADER_DOMAIN,
maxAge: CONSTANTS._1_MONTH,
});
Expand Down Expand Up @@ -261,8 +261,8 @@ const adminController = {
sameSite: CONFIGS.NODE_ENV === CONSTANTS.ENVIRONMENT_PRODUCT ? true : false,
secure: CONFIGS.NODE_ENV === CONSTANTS.ENVIRONMENT_PRODUCT ? true : false,
domain:
CONFIGS.NODE_ENV === CONSTANTS.ENVIRONMENT_PRODUCT
? req.headers[CONSTANTS.HEADER_HEADER_FORWARDED_HOST]?.split(':')[0]
CONFIGS.NODE_ENV === CONSTANTS.ENVIRONMENT_PRODUCT ?
req.headers[CONSTANTS.HEADER_HEADER_FORWARDED_HOST]?.split(':')[0]
: CONSTANTS.HEADER_DOMAIN,
maxAge: CONSTANTS._1_MONTH,
});
Expand Down Expand Up @@ -432,12 +432,12 @@ const adminController = {
class: student.class,
email: student.email,
gender:
student.gender.toLowerCase() === CONSTANTS.GENDER_MALE_STRING
? CONSTANTS.GENDER_MALE
student.gender.toLowerCase() === CONSTANTS.GENDER_MALE_STRING ?
CONSTANTS.GENDER_MALE
: CONSTANTS.GENDER_FEMALE,
avatar_uri:
student.gender.toLowerCase() === CONSTANTS.GENDER_MALE_STRING
? CONSTANTS.GENDER_IMAGE_MALE
student.gender.toLowerCase() === CONSTANTS.GENDER_MALE_STRING ?
CONSTANTS.GENDER_IMAGE_MALE
: CONSTANTS.GENDER_IMAGE_FEMALE,
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ const authorController = {
* @return {Object:{Number,String}
*/
createAuthor: async (req, res) => {
const { name, avatar_uri, dob, gender } = req.body.input.author_input;
const {
name, avatar_uri, dob, gender,
} = req.body.input.author_input;

// Check input
if (!name || !avatar_uri || !dob || !gender) {
Expand Down Expand Up @@ -72,7 +74,9 @@ const authorController = {
* @return {Object:{Number,String}
*/
updateAuthor: async (req, res) => {
const { author_id, name, avatar_uri, dob, gender } = req.body.input.author_input;
const {
author_id, name, avatar_uri, dob, gender,
} = req.body.input.author_input;

// Check input
if (!name || !avatar_uri || !dob || !gender || !author_id) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,10 @@ const bookController = {
* @return {Object:{Number,String}
*/
createBook: async (req, res) => {
const { name, author_id, image_uri, description, bookshelf, language, quantity, public_id_image } =
req.body.input.author_input;
const {
name, author_id, image_uri, description, bookshelf, language, quantity, public_id_image,
}
= req.body.input.author_input;

// Check input
if (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,103 +20,103 @@ const { returnReasons } = require('./handle_error');
* @function accessStudentMiddleware
*/
const accessStudentMiddleware = async (req, res, next) => {
try {
// Date Now
let now = new Date();

// Log request
console.info('[Request Time]:', now.toLocaleTimeString(), req.baseUrl, req.body, req.query);

// Take refresh Token from cookie
const refresh_token_cookie = req.cookies.libary_school;

// Take accessToken at headers
const accessToken = req.headers.authorization.split(' ')[1];

// Check header authorization
if (!refresh_token_cookie || !accessToken) {
return res.status(401).json({
status: 401,
message: returnReasons('401'),
element: {
result: 'Unauthorized',
},
});
}

// Take token
const { device_id } = req.device;

// Take data device student
const data_device = await user_device_model.getDeviceId(
{ device_uuid: device_id },
{ public_key: 'public_key' },
);

// Check data null
if (Array.isArray(data_device) && !data_device.length) {
return res.status(400).json({
status: 400,
message: returnReasons('400'),
});
}

// Convert pem
const publicKey = PASSWORD.decodePemPubKey(data_device[0].public_key);

// Take info from token
let auth_user_decode = TOKENS.verifyAccessToken(accessToken, publicKey);

// Check time Expired token
let check_access_token = HELPER.isAccessTokenValid(accessToken, publicKey);
if (!check_access_token) {
return res.status(401).json({
status: 401,
message: returnReasons('401'),
element: {
result: 'Expired Token',
},
});
}

// Check BlackList
try {
// Date Now
let now = new Date();

// Log request
console.info('[Request Time]:', now.toLocaleTimeString(), req.baseUrl, req.body, req.query);

// Take refresh Token from cookie
const refresh_token_cookie = req.cookies.libary_school;

// Take accessToken at headers
const accessToken = req.headers.authorization.split(' ')[1];

// Check header authorization
if (!refresh_token_cookie || !accessToken) {
return res.status(401).json({
status: 401,
message: returnReasons('401'),
element: {
result: 'Unauthorized',
},
});
}

// Take token
const { device_id } = req.device;

// Take data device student
const data_device = await user_device_model.getDeviceId(
{ device_uuid: device_id },
{ public_key: 'public_key' },
);

// Check data null
if (Array.isArray(data_device) && !data_device.length) {
return res.status(400).json({
status: 400,
message: returnReasons('400'),
});
}

// Convert pem
const publicKey = PASSWORD.decodePemPubKey(data_device[0].public_key);

// Take info from token
let auth_user_decode = TOKENS.verifyAccessToken(accessToken, publicKey);

// Check time Expired token
let check_access_token = HELPER.isAccessTokenValid(accessToken, publicKey);
if (!check_access_token) {
return res.status(401).json({
status: 401,
message: returnReasons('401'),
element: {
result: 'Expired Token',
},
});
}

// Check BlackList
try {
const token_black_list = await MEMORY_CACHE.getRangeCache(CONSTANTS.KEY_BACK_LIST, 0, 999999999);

// Check 2 token
const check_exits_refresh_token = token_black_list.indexOf(refresh_token_cookie) > -1;
const check_exits_access_token = token_black_list.indexOf(accessToken) > -1;

if (check_exits_refresh_token || check_exits_access_token) {
return res.status(400).json({
status: 400,
message: returnReasons('400'),
element: {
result: 'Invalid Token',
},
});
}

// save request
req.auth_user = auth_user_decode;
req.access_token = accessToken;

// Continue
next();
} catch (error) {
return res.status(500).json({
status: 500,
message: returnReasons('500'),
});
}
} catch (error) {
return res.status(503).json({
status: 503,
message: returnReasons('503'),
element: {
result: 'Out Of Service',
},
const token_black_list = await MEMORY_CACHE.getRangeCache(CONSTANTS.KEY_BACK_LIST, 0, 999999999);

// Check 2 token
const check_exits_refresh_token = token_black_list.indexOf(refresh_token_cookie) > -1;
const check_exits_access_token = token_black_list.indexOf(accessToken) > -1;

if (check_exits_refresh_token || check_exits_access_token) {
return res.status(400).json({
status: 400,
message: returnReasons('400'),
element: {
result: 'Invalid Token',
},
});
}

// save request
req.auth_user = auth_user_decode;
req.access_token = accessToken;

// Continue
next();
} catch (error) {
return res.status(500).json({
status: 500,
message: returnReasons('500'),
});
}
} catch (error) {
return res.status(503).json({
status: 503,
message: returnReasons('503'),
element: {
result: 'Out Of Service',
},
});
}
};
module.exports = accessStudentMiddleware;
3 changes: 1 addition & 2 deletions backend-manager-student/src/share/middleware/handle_error.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,5 @@ module.exports = {
* @param { code }
* @return { String }
*/
returnReasons: (code) =>
CONSTANTS.reasonPhraseCodeProNewMap().get(code) || CONSTANTS.reasonPhraseCodeProNewMap().get('default'),
returnReasons: (code) => CONSTANTS.reasonPhraseCodeProNewMap().get(code) || CONSTANTS.reasonPhraseCodeProNewMap().get('default'),
};
35 changes: 17 additions & 18 deletions backend-manager-student/src/share/models/author.model.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,15 @@ module.exports = {
* @created_at 03/01/2023
* @description create Author
*/
createAuthor: (data) =>
new Promise((resolve, reject) => {
try {
const result = knex('authors').insert(data).onConflict('author_id').merge().returning(['author_id']);
resolve(result);
} catch (error) {
reject(error);
}
}),
createAuthor: (data) => new Promise((resolve, reject) => {
try {
const result = knex('authors').insert(data).onConflict('author_id').merge()
.returning(['author_id']);
resolve(result);
} catch (error) {
reject(error);
}
}),

/**
* @author Nguyễn Tiến Tài
Expand All @@ -31,15 +31,14 @@ module.exports = {
* @created_at 03/01/2023
* @description Update Author
*/
updateAuthor: async (data, student_query, return_data) =>
new Promise((resolve, reject) => {
try {
const result = knex('authors').update(data).where(student_query).returning(return_data);
resolve(result);
} catch (error) {
reject(error);
}
}),
updateAuthor: async (data, student_query, return_data) => new Promise((resolve, reject) => {
try {
const result = knex('authors').update(data).where(student_query).returning(return_data);
resolve(result);
} catch (error) {
reject(error);
}
}),
/**
* @author Nguyễn Tiến Tài
* @created_at 03/01/2023
Expand Down
35 changes: 17 additions & 18 deletions backend-manager-student/src/share/models/book.model.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,15 @@ module.exports = {
* @created_at 03/01/2023
* @description create book
*/
createBook: (data) =>
new Promise((resolve, reject) => {
try {
const result = knex('books').insert(data).onConflict('book_id').merge().returning(['book_id']);
resolve(result);
} catch (error) {
reject(error);
}
}),
createBook: (data) => new Promise((resolve, reject) => {
try {
const result = knex('books').insert(data).onConflict('book_id').merge()
.returning(['book_id']);
resolve(result);
} catch (error) {
reject(error);
}
}),

/**
* @author Nguyễn Tiến Tài
Expand All @@ -31,15 +31,14 @@ module.exports = {
* @created_at 03/01/2023
* @description Update book
*/
updateBook: async (data, student_query, return_data) =>
new Promise((resolve, reject) => {
try {
const result = knex('books').update(data).where(student_query).returning(return_data);
resolve(result);
} catch (error) {
reject(error);
}
}),
updateBook: async (data, student_query, return_data) => new Promise((resolve, reject) => {
try {
const result = knex('books').update(data).where(student_query).returning(return_data);
resolve(result);
} catch (error) {
reject(error);
}
}),
/**
* @author Nguyễn Tiến Tài
* @created_at 03/01/2023
Expand Down
Loading

0 comments on commit ef93234

Please sign in to comment.