master
tnud0 2 years ago
parent 02f5d1d5f9
commit 6dfbe3b006
  1. 11
      src/api/controllers/v1/auth.controller.js
  2. 18
      src/api/controllers/v1/path.controller.js
  3. 90
      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. 5
      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 messages from '../../../config/messages';
import { hash, compare } from 'bcryptjs';
import { handler as ErrorHandler } from '../../middlewares/error';
import User from '../../../common/models/user.model';
@ -34,9 +35,7 @@ exports.loginToken = async (req, res, next) => res.json({
exports.updatePassword = async(req,res,next) => {
const { current_password, new_password } = req.body;
// cónt
const {new_password} = req.body;
const {user} = req.locals;
// console.log(user);
if (user) {
@ -49,17 +48,13 @@ exports.updatePassword = async (req, res, next) => {
id: user.id
}
},
).then( async () => {
const user = await User.get(12);
console.log(user);
res.json({
test: 1,
code: 0,
message: messages.UPDATE_SUCCESS
});
}).catch(ex => {
ErrorHandler(ex, req, res, next);
});
}
};
};

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

@ -1,10 +1,11 @@
import { pick } from 'lodash';
// import httpStatus from 'http-status';
import messages from '../../../config/messages';
// import { hash, compare } from 'bcryptjs';
import { handler as ErrorHandler } from '../../middlewares/error';
import User from '../../../common/models/user.model';
import uploadAdapter from '../../../common/services/adapters/upload-adapter';
import { hash } from 'bcryptjs';
/**
* Create
*
@ -73,13 +74,19 @@ exports.get = async (req, res, next) => res.json({ data: User.transform(req.loca
*/
exports.update = async (req, res, next) => {
const { user } = req.locals;
const dataChanged = user.getChangedProperties(req.body);
const updateUser = Object.assign(
user,
pick(req.body, dataChanged)
);
const dataChanged = User.getChangedProperties(req.body);
let new_properties = pick(req.body, dataChanged);
// const updateUser = Object.assign(
// user,
// pick(req.body, dataChanged)
// );
// const currentUser = await User.get(user.id)
// console.log(dataChanged);
return User.update(
updateUser,
new_properties,
{
where: {
id: user.id
@ -88,7 +95,8 @@ exports.update = async (req, res, next) => {
).then(() => {
res.json({
code: 0,
message: messages.UPDATE_SUCCESS
message: messages.UPDATE_SUCCESS,
// dataChanged: dataChanged
});
}).catch(ex => {
ErrorHandler(ex, req, res, next);
@ -104,12 +112,13 @@ exports.update = async (req, res, next) => {
*/
exports.delete = async (req, res, next) => {
const { user } = req.locals;
const updateUser = Object.assign(
user,
{ is_active: true }
);
// const new_user = Object.assign(
// user,
// isactive : false
// )
return User.update(
updateUser,
{ is_active: false},
{
where: {
id: user.id
@ -132,3 +141,58 @@ exports.getStaffPermission = async (req, res, next) => {
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: 'user',
/** Guest group */
GUEST: 'guest'
GUEST: 'guest',
ADMINISTRATOR: 'administrator'
};
/**
@ -33,8 +34,10 @@ const Configs = {
/** Include scheme in header */
HEADER_INCLUDE_SCHEME: true,
getStaffPermissions: (staffId) => {
console.log(staffId);
// console.log(staffId);
return [];
}
};
@ -134,7 +137,6 @@ const getTokenInfo = (req) => {
jwt.payload = jsonwentoken.decode(jwt.value, { json: true });
return jwt;
};
/**
* Get authentication info from service
*
@ -154,7 +156,7 @@ const getAuthInfo = (req) => {
// consumerGroups = consumerGroups.split(',').filter((item) => item.length > 0);
// console.log(consumerGroups);
// Check accessLevel
let accessLevel = ConsumerGroups.GUEST;
let accessLevel = ConsumerGroups.GUEST; // guest ?
const allAccessLevels = Object.values(ConsumerGroups);
for (let index = 0; index < allAccessLevels.length; index += 1) {
if (consumerGroups.includes(allAccessLevels[index])) {
@ -190,6 +192,7 @@ const loadInfo = async (req) => {
req.tokenInfo = tokenInfo;
req.authInfo = getAuthInfo(req);
console.log(req.authInfo);
// load permission for staff
if (req.authInfo.accessLevel === ConsumerGroups.STAFF && user !== null) {
req.user.permissions = await Configs.getStaffPermissions(
@ -213,9 +216,7 @@ const checkPermission = async (req, permissions, additionalCheck) => {
});
/** service permission required */
const permissionsToCheck = Array.isArray(permissions)
? permissions.slice(0)
: [];
const permissionsToCheck = Array.isArray(permissions)? permissions.slice(0): [];
// allow if require no permission
if (permissionsToCheck.length === 0) {
@ -227,12 +228,17 @@ const checkPermission = async (req, permissions, additionalCheck) => {
Configs.PERMISSION_USER
);
const adminPermissionIndex = permissionsToCheck.indexOf(
Configs.PERMISSION_ADMINISTRATOR
);
switch (req.authInfo.accessLevel) {
case ConsumerGroups.SERVICE:
// allow all access with service level
return null;
case ConsumerGroups.STAFF:
// remove user permission
console.log("1231231232");
if (userPermissionIndex !== -1) {
permissionsToCheck.splice(userPermissionIndex, 1);
}
@ -243,12 +249,20 @@ const checkPermission = async (req, permissions, additionalCheck) => {
}
break;
case ConsumerGroups.USER:
if (permissionsToCheck.indexOf(Configs.PERMISSION_USER) === -1) {
console.log("req.authInfo.accessLevel1");
if (userPermissionIndex === -1) {
apiError.status = httpStatus.FORBIDDEN;
apiError.message = 'Forbidden';
return apiError;
}
break;
case ConsumerGroups.ADMINISTRATOR:
if (adminPermissionIndex !== -1 && userPermissionIndex=== -1) {
console.log("ConsumerGroups.ADMINISTRATOR");
return null
};
break;
default:
// reject guest access
return apiError;

@ -8,7 +8,9 @@ import User from '../../common/models/user.model';
*/
exports.load = async (req, res, next) => {
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.user = user;
return next();
@ -86,3 +88,12 @@ exports.genarateToken = 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 middleware from '../../middlewares/authen.middleware';
import controller from '../../controllers/v1/auth.controller';
// import permissions from '../../../common/utils/Permissions';
import permissions from '../../../common/utils/Permissions';
import {
loginToken,
registerValidation,
loginValidation,
} from '../../validations/v1/auth.validation';
import { authorize } from '../../middlewares/auth.middleware';
const router = express.Router();

@ -34,13 +34,31 @@ router
)
.put(
validate(updateValidation),
authorize([permissions.USER_UPDATE]),
authorize([permissions.LOGGED_IN]),
middleware.load,
controller.update
)
.delete(
authorize([permissions.USER_DELETE]),
authorize([permissions.LOGGED_IN]),
middleware.load,
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;

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

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

@ -1,4 +1,5 @@
{
"123": "123",
"Invalid file!": "Invalid file!",
"Unauthorized": "Unauthorized",
"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'",
"Cannot read properties of undefined (reading 'id')": "Cannot read properties of undefined (reading 'id')",
"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