master
tnud0 2 years ago
parent 02f5d1d5f9
commit 6dfbe3b006
  1. 25
      src/api/controllers/v1/auth.controller.js
  2. 22
      src/api/controllers/v1/path.controller.js
  3. 92
      src/api/controllers/v1/user.controller.js
  4. 30
      src/api/middlewares/auth.middleware.js
  5. 13
      src/api/middlewares/user.middleware.js
  6. 3
      src/api/routes/v1/auth.route.js
  7. 22
      src/api/routes/v1/user.route.js
  8. 7
      src/common/models/user.model.js
  9. 1
      src/common/utils/Permissions.js
  10. 8
      src/config/locales/en.json
  11. 14496
      yarn.lock

@ -1,6 +1,7 @@
import { hash, compare } from 'bcryptjs'; import { hash, compare } from 'bcryptjs';
import messages from '../../../config/messages'; import messages from '../../../config/messages';
import { hash, compare } from 'bcryptjs';
import { handler as ErrorHandler } from '../../middlewares/error'; import { handler as ErrorHandler } from '../../middlewares/error';
import User from '../../../common/models/user.model'; import User from '../../../common/models/user.model';
@ -33,33 +34,27 @@ exports.loginToken = async (req, res, next) => res.json({
}); });
exports.updatePassword = async (req, res, next) => { exports.updatePassword = async(req,res,next) => {
const { current_password, new_password } = req.body; const {new_password} = req.body;
// cónt const {user} = req.locals;
const { user } = req.locals;
// console.log(user); // console.log(user);
if (user) { if (user) {
const rounds = 10; const rounds = 10;
const new_pass = await hash(new_password, rounds); const new_pass = await hash(new_password, rounds);
return User.update( return User.update(
{ password: new_pass }, {password: new_pass},
{ {
where: { where: {
id: user.id id: user.id
} }
}, },
).then( async () => {
).then(async () => { res.json({
const user = await User.get(12);
console.log(user);
res.json({
test: 1,
code: 0, code: 0,
message: messages.UPDATE_SUCCESS message: messages.UPDATE_SUCCESS
}); });
}).catch(ex => { }).catch(ex => {
ErrorHandler(ex, req, res, next); ErrorHandler(ex, req, res, next);
}); });
} };
}; };

@ -3,6 +3,7 @@
import fs from 'fs'; import fs from 'fs';
import archiver from 'archiver'; import archiver from 'archiver';
import multer from 'multer'; import multer from 'multer';
import path from 'path';
import { handler as ErrorHandel } from '../../middlewares/errors'; import { handler as ErrorHandel } from '../../middlewares/errors';
// import ApiException from '../../../common/utils/APIException'; // import ApiException from '../../../common/utils/APIException';
import { import {
@ -194,18 +195,15 @@ exports.deleteMultiple = (req, res, next) => {
} }
}; };
// exports.downloadZipFolder = (req,res,next) => {
// try{
// exports.deleteMultiple = (req, res, next) => { // const user = req.user;
// try { // const namefile = `${user.name}-${Date.now()}.zip`;
// const path = req.body.path.replace(cdnConfig.uri, storageConfig.uri); // const dir = `${storageConfig.uri}/${user.id}/${namefile}`;
// fs.rm(path, { recursive: true }, err => {
// if (err) {
// return res.status(400).json({ code: 400, message: 'lỗi', detail: err }); // }catch(ex ) {
// } // return ErrorHandel(ex,req,res,next);
// return res.json({ code: 0, message: 'success' });
// });
// return null;
// } catch (ex) {
// return ErrorHandel(ex, req, res, next);
// } // }
// }; // };

@ -1,10 +1,11 @@
import { pick } from 'lodash'; import { pick } from 'lodash';
// import httpStatus from 'http-status'; // import httpStatus from 'http-status';
import messages from '../../../config/messages'; import messages from '../../../config/messages';
// import { hash, compare } from 'bcryptjs';
import { handler as ErrorHandler } from '../../middlewares/error'; import { handler as ErrorHandler } from '../../middlewares/error';
import User from '../../../common/models/user.model'; import User from '../../../common/models/user.model';
import uploadAdapter from '../../../common/services/adapters/upload-adapter'; import uploadAdapter from '../../../common/services/adapters/upload-adapter';
import { hash } from 'bcryptjs';
/** /**
* Create * Create
* *
@ -73,13 +74,19 @@ exports.get = async (req, res, next) => res.json({ data: User.transform(req.loca
*/ */
exports.update = async (req, res, next) => { exports.update = async (req, res, next) => {
const { user } = req.locals; const { user } = req.locals;
const dataChanged = user.getChangedProperties(req.body); const dataChanged = User.getChangedProperties(req.body);
const updateUser = Object.assign( let new_properties = pick(req.body, dataChanged);
user, // const updateUser = Object.assign(
pick(req.body, dataChanged) // user,
); // pick(req.body, dataChanged)
// );
// const currentUser = await User.get(user.id)
// console.log(dataChanged);
return User.update( return User.update(
updateUser, new_properties,
{ {
where: { where: {
id: user.id id: user.id
@ -88,7 +95,8 @@ exports.update = async (req, res, next) => {
).then(() => { ).then(() => {
res.json({ res.json({
code: 0, code: 0,
message: messages.UPDATE_SUCCESS message: messages.UPDATE_SUCCESS,
// dataChanged: dataChanged
}); });
}).catch(ex => { }).catch(ex => {
ErrorHandler(ex, req, res, next); ErrorHandler(ex, req, res, next);
@ -104,18 +112,19 @@ exports.update = async (req, res, next) => {
*/ */
exports.delete = async (req, res, next) => { exports.delete = async (req, res, next) => {
const { user } = req.locals; const { user } = req.locals;
const updateUser = Object.assign( // const new_user = Object.assign(
user, // user,
{ is_active: true } // isactive : false
); // )
return User.update( return User.update(
updateUser, { is_active: false},
{ {
where: { where: {
id: user.id id: user.id
} }
} }
).then(() => { ).then( () => {
res.json({ res.json({
code: 0, code: 0,
message: messages.REMOVE_SUCCESS message: messages.REMOVE_SUCCESS
@ -132,3 +141,58 @@ exports.getStaffPermission = async (req, res, next) => {
data: story data: story
}); });
}; };
// exports.addRole = async(req,res,next) => {
// const {user} = req.locals;
// const admin = ['administrator'];
// // const user.permissions[0] = admin;
// return User.update({
// permissions: admin,
// service: 'administrator'
// },
// {
// where : {id : user.id}
// }
// ).then( async () => {
// const new_user = await User.get(req.params.id);
// console.log(new_user);
// res.json(
// {
// code: 0,
// messages: messages.CREATE_SUCCESS
// }
// );
// }).catch( ex => {
// ErrorHandler(ex, req, res, next);
// })
// }
exports.updatePassword = async(req,res,next) => {
const {new_password} = req.body;
const {user} = req.locals;
// console.log(user);
if (user) {
const rounds = 10;
const new_pass = await hash(new_password, rounds);
return User.update(
{password: new_pass},
{
where: {
id: user.id
}
},
).then( async () => {
res.json({
code: 0,
message: messages.UPDATE_SUCCESS
});
}).catch(ex => {
ErrorHandler(ex, req, res, next);
});
};
};

@ -10,7 +10,8 @@ const ConsumerGroups = {
/** User group with all permissions if granted */ /** User group with all permissions if granted */
USER: 'user', USER: 'user',
/** Guest group */ /** Guest group */
GUEST: 'guest' GUEST: 'guest',
ADMINISTRATOR: 'administrator'
}; };
/** /**
@ -33,8 +34,10 @@ const Configs = {
/** Include scheme in header */ /** Include scheme in header */
HEADER_INCLUDE_SCHEME: true, HEADER_INCLUDE_SCHEME: true,
getStaffPermissions: (staffId) => { getStaffPermissions: (staffId) => {
console.log(staffId); // console.log(staffId);
return []; return [];
} }
}; };
@ -134,7 +137,6 @@ const getTokenInfo = (req) => {
jwt.payload = jsonwentoken.decode(jwt.value, { json: true }); jwt.payload = jsonwentoken.decode(jwt.value, { json: true });
return jwt; return jwt;
}; };
/** /**
* Get authentication info from service * Get authentication info from service
* *
@ -154,7 +156,7 @@ const getAuthInfo = (req) => {
// consumerGroups = consumerGroups.split(',').filter((item) => item.length > 0); // consumerGroups = consumerGroups.split(',').filter((item) => item.length > 0);
// console.log(consumerGroups); // console.log(consumerGroups);
// Check accessLevel // Check accessLevel
let accessLevel = ConsumerGroups.GUEST; let accessLevel = ConsumerGroups.GUEST; // guest ?
const allAccessLevels = Object.values(ConsumerGroups); const allAccessLevels = Object.values(ConsumerGroups);
for (let index = 0; index < allAccessLevels.length; index += 1) { for (let index = 0; index < allAccessLevels.length; index += 1) {
if (consumerGroups.includes(allAccessLevels[index])) { if (consumerGroups.includes(allAccessLevels[index])) {
@ -190,6 +192,7 @@ const loadInfo = async (req) => {
req.tokenInfo = tokenInfo; req.tokenInfo = tokenInfo;
req.authInfo = getAuthInfo(req); req.authInfo = getAuthInfo(req);
console.log(req.authInfo);
// load permission for staff // load permission for staff
if (req.authInfo.accessLevel === ConsumerGroups.STAFF && user !== null) { if (req.authInfo.accessLevel === ConsumerGroups.STAFF && user !== null) {
req.user.permissions = await Configs.getStaffPermissions( req.user.permissions = await Configs.getStaffPermissions(
@ -213,9 +216,7 @@ const checkPermission = async (req, permissions, additionalCheck) => {
}); });
/** service permission required */ /** service permission required */
const permissionsToCheck = Array.isArray(permissions) const permissionsToCheck = Array.isArray(permissions)? permissions.slice(0): [];
? permissions.slice(0)
: [];
// allow if require no permission // allow if require no permission
if (permissionsToCheck.length === 0) { if (permissionsToCheck.length === 0) {
@ -227,12 +228,17 @@ const checkPermission = async (req, permissions, additionalCheck) => {
Configs.PERMISSION_USER Configs.PERMISSION_USER
); );
const adminPermissionIndex = permissionsToCheck.indexOf(
Configs.PERMISSION_ADMINISTRATOR
);
switch (req.authInfo.accessLevel) { switch (req.authInfo.accessLevel) {
case ConsumerGroups.SERVICE: case ConsumerGroups.SERVICE:
// allow all access with service level // allow all access with service level
return null; return null;
case ConsumerGroups.STAFF: case ConsumerGroups.STAFF:
// remove user permission // remove user permission
console.log("1231231232");
if (userPermissionIndex !== -1) { if (userPermissionIndex !== -1) {
permissionsToCheck.splice(userPermissionIndex, 1); permissionsToCheck.splice(userPermissionIndex, 1);
} }
@ -243,12 +249,20 @@ const checkPermission = async (req, permissions, additionalCheck) => {
} }
break; break;
case ConsumerGroups.USER: case ConsumerGroups.USER:
if (permissionsToCheck.indexOf(Configs.PERMISSION_USER) === -1) { console.log("req.authInfo.accessLevel1");
if (userPermissionIndex === -1) {
apiError.status = httpStatus.FORBIDDEN; apiError.status = httpStatus.FORBIDDEN;
apiError.message = 'Forbidden'; apiError.message = 'Forbidden';
return apiError; return apiError;
} }
break; break;
case ConsumerGroups.ADMINISTRATOR:
if (adminPermissionIndex !== -1 && userPermissionIndex=== -1) {
console.log("ConsumerGroups.ADMINISTRATOR");
return null
};
break;
default: default:
// reject guest access // reject guest access
return apiError; return apiError;

@ -8,7 +8,9 @@ import User from '../../common/models/user.model';
*/ */
exports.load = async (req, res, next) => { exports.load = async (req, res, next) => {
try { try {
const user = await User.get(req.params.id); const id = req.params.id;
// console.log(id);
const user = await User.get(id);
req.locals = req.locals ? req.locals : {}; req.locals = req.locals ? req.locals : {};
req.locals.user = user; req.locals.user = user;
return next(); return next();
@ -86,3 +88,12 @@ exports.genarateToken = async (req, res, next) => {
// exports.loginFacebook= async (req,res,next)=>{ // exports.loginFacebook= async (req,res,next)=>{
// } // }
exports.checkCurrentPassword = async (req, res, next) => {
const { user } = req.locals;
// console.log(user);
const isCheck = await User.passwordMatches(user, req.body.current_password);
if (!isCheck) {
return res.status(400).json({ message: 'Password incorrect'});
}
return next();
};

@ -3,12 +3,13 @@ import express from 'express';
import validate from 'express-validation'; import validate from 'express-validation';
import middleware from '../../middlewares/authen.middleware'; import middleware from '../../middlewares/authen.middleware';
import controller from '../../controllers/v1/auth.controller'; import controller from '../../controllers/v1/auth.controller';
// import permissions from '../../../common/utils/Permissions'; import permissions from '../../../common/utils/Permissions';
import { import {
loginToken, loginToken,
registerValidation, registerValidation,
loginValidation, loginValidation,
} from '../../validations/v1/auth.validation'; } from '../../validations/v1/auth.validation';
import { authorize } from '../../middlewares/auth.middleware';
const router = express.Router(); const router = express.Router();

@ -34,13 +34,31 @@ router
) )
.put( .put(
validate(updateValidation), validate(updateValidation),
authorize([permissions.USER_UPDATE]), authorize([permissions.LOGGED_IN]),
middleware.load, middleware.load,
controller.update controller.update
) )
.delete( .delete(
authorize([permissions.USER_DELETE]), authorize([permissions.LOGGED_IN]),
middleware.load, middleware.load,
controller.delete controller.delete
); );
router.route("/:id/reset-password").
post(
authorize([permissions.USER]),
middleware.load,
middleware.checkCurrentPassword,
controller.updatePassword
);
router.route("/change-password/:id").
post(
authorize([permissions.LOGGED_IN]),
middleware.load,
// middleware.checkCurrentPassword,
controller.updatePassword
);
export default router; export default router;

@ -336,10 +336,10 @@ User.EVENT_SOURCE = `${serviceName}.user`;
*/ */
User.addHook('beforeCreate', async (model) => { User.addHook('beforeCreate', async (model) => {
const user = model; const user = model;
if (user.password) { if (user.password) {
const rounds = 10; const rounds = 10;
user.password = await hash(user.password, rounds); user.password = await hash(user.password, rounds);
console.log(123212312312321312);
} }
return user; return user;
@ -351,7 +351,7 @@ User.addHook('beforeUpdate', async (model, options) => {
// has pass // has pass
if (password) { if (password) {
const rounds = 10; const rounds = 10;
user.password = await hash(password, rounds); user.password = await hash(password, rounds);
} }
return user; return user;
@ -627,8 +627,10 @@ User.getChangedProperties = ({ newModel, oldModel }, includeRestrictedFields = t
'permissions' 'permissions'
]; ];
allChangableProperties.push(...privateFiles); allChangableProperties.push(...privateFiles);
// console.log(allChangableProperties);
} }
if (!oldModel) { if (!oldModel) {
// console.log("old model");
return allChangableProperties; return allChangableProperties;
} }
@ -761,6 +763,7 @@ User.get = async (userId) => {
is_active: true is_active: true
} }
}); });
console.log(user);
if (isNil(user)) { if (isNil(user)) {
throw new APIError({ throw new APIError({
status: httpStatus.NOT_FOUND, status: httpStatus.NOT_FOUND,

@ -3,6 +3,7 @@ import { serviceName } from '../../config/vars';
export default { export default {
// Service Permission // Service Permission
USER: 'user', USER: 'user',
// ADMINISTRATOR : 'administrator',
LOGGED_IN: 'staff', LOGGED_IN: 'staff',
// For Product Route // For Product Route

@ -1,4 +1,5 @@
{ {
"123": "123",
"Invalid file!": "Invalid file!", "Invalid file!": "Invalid file!",
"Unauthorized": "Unauthorized", "Unauthorized": "Unauthorized",
"NOT_FOUND!": "NOT_FOUND!", "NOT_FOUND!": "NOT_FOUND!",
@ -17,5 +18,10 @@
"ENOENT: no such file or directory, open 'public/12/about.jpg'": "ENOENT: no such file or directory, open 'public/12/about.jpg'", "ENOENT: no such file or directory, open 'public/12/about.jpg'": "ENOENT: no such file or directory, open 'public/12/about.jpg'",
"Cannot read properties of undefined (reading 'id')": "Cannot read properties of undefined (reading 'id')", "Cannot read properties of undefined (reading 'id')": "Cannot read properties of undefined (reading 'id')",
"Forbidden": "Forbidden", "Forbidden": "Forbidden",
"ENOENT: no such file or directory, open 'public/5/50ba9c5e20a3fcfda5b2.jpeg'": "ENOENT: no such file or directory, open 'public/5/50ba9c5e20a3fcfda5b2.jpeg'" "ENOENT: no such file or directory, open 'public/5/50ba9c5e20a3fcfda5b2.jpeg'": "ENOENT: no such file or directory, open 'public/5/50ba9c5e20a3fcfda5b2.jpeg'",
"invalid input syntax for type integer: \"[object Object]\"": "invalid input syntax for type integer: \"[object Object]\"",
"Cannot access 'user' before initialization": "Cannot access 'user' before initialization",
"Không tìm thấy người dùng này!": "Không tìm thấy người dùng này!",
"Không tìm thấy người dùng này!!!!": "Không tìm thấy người dùng này!!!!",
"Missing where attribute in the options parameter": "Missing where attribute in the options parameter"
} }

14496
yarn.lock

File diff suppressed because it is too large Load Diff
Loading…
Cancel
Save