Compare commits

..

2 Commits

  1. 15
      src/api/controllers/v1/path.controller.js
  2. 80
      src/api/controllers/v1/staff.controller.js
  3. 38
      src/api/controllers/v1/user.controller.js
  4. 4
      src/api/middlewares/auth.middleware.js
  5. 19
      src/api/middlewares/staff.middleware.js
  6. 24
      src/api/middlewares/user.middleware.js
  7. 4
      src/api/routes/v1/image.route.js
  8. 36
      src/api/routes/v1/staff.route.js
  9. 10
      src/api/routes/v1/user.route.js
  10. 2
      src/common/models/user.model.js
  11. 7
      src/common/utils/Permissions.js
  12. 3
      src/config/locales/en.json

@ -193,17 +193,4 @@ exports.deleteMultiple = (req, res, next) => {
} catch (ex) { } catch (ex) {
return ErrorHandel(ex, req, res, next); return ErrorHandel(ex, req, res, next);
} }
}; };
// exports.downloadZipFolder = (req,res,next) => {
// try{
// 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);
// }
// };

@ -31,20 +31,7 @@ exports.create = async (req, res, next) => {
ErrorHandler(ex, req, res, next); ErrorHandler(ex, req, res, next);
}); });
// await User.destroy({
// where : {
// email: "teststaff@gmail.com"
// }
// }).then( rs => {
// return res.json({
// ms: "success"
// });
// }).catch(ex => {
// ErrorHandler(ex,req,res,next);
// })
}; };
/** /**
@ -57,10 +44,15 @@ exports.create = async (req, res, next) => {
exports.list = async (req, res, next) => { exports.list = async (req, res, next) => {
req.query.services = User.Services.STAFF; req.query.services = User.Services.STAFF;
// console.log(req.query) // console.log(req.query)
await User.list( await User.findAll(
req.query {
where : {
is_active: true,
service : "staff"
}
}
).then(result => { ).then(result => {
console.log(result ); // console.log(result );
res.json({ res.json({
code: 0, code: 0,
count: req.totalRecords, count: req.totalRecords,
@ -92,6 +84,12 @@ 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;
if (user.service !== "service") {
return res.status(404).json({
code: 404,
message : messages.NOT_FOUND
})
}
return User.update( return User.update(
req.body, req.body,
@ -119,6 +117,12 @@ 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;
if (user.service !== "service") {
return res.status(404).json({
code: 404,
message : messages.NOT_FOUND
})
}
return User.update( return User.update(
{ {
@ -139,6 +143,7 @@ exports.delete = async (req, res, next) => {
}).catch(ex => { }).catch(ex => {
ErrorHandler(ex, req, res, next); ErrorHandler(ex, req, res, next);
}); });
}; };
exports.getStaffPermission = async (req, res, next) => { exports.getStaffPermission = async (req, res, next) => {
@ -197,3 +202,44 @@ exports.active = async (req, res, next) => {
ErrorHandler(ex, req, res, next); ErrorHandler(ex, req, res, next);
}); });
}; };
exports.addService = async (req,res,next) => {
const {user} = req.locals;
return User.update({
service: 'service'
}, {
where: {
id: user.id
}
}).then(() => {
res.json({
code: 0,
message: messages.UPDATE_SUCCESS
});
}).catch(ex => {
ErrorHandler(ex, req, res, next);
})
};
exports.changePassword = async(req,res,next) => {
const {current_password, new_password } = req.body;
const {user} = req.locals;
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);
});
};

@ -42,8 +42,11 @@ exports.create = async (req, res, next) => {
*/ */
exports.list = async (req, res, next) => { exports.list = async (req, res, next) => {
req.query.services = User.Services.USER; req.query.services = User.Services.USER;
User.list( // console.log(req.query.services);
req.query User.list( {
service : "user",
is_active: true
}
).then(result => { ).then(result => {
res.json({ res.json({
code: 0, code: 0,
@ -142,37 +145,6 @@ 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) => { exports.updatePassword = async(req,res,next) => {
const {new_password} = req.body; const {new_password} = req.body;
const {user} = req.locals; const {user} = req.locals;

@ -238,10 +238,12 @@ const checkPermission = async (req, permissions, additionalCheck) => {
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"); // console.log("1231231232");
console.log("from staff");
if (userPermissionIndex !== -1) { if (userPermissionIndex !== -1) {
permissionsToCheck.splice(userPermissionIndex, 1); permissionsToCheck.splice(userPermissionIndex, 1);
} }
@ -252,7 +254,7 @@ const checkPermission = async (req, permissions, additionalCheck) => {
} }
break; break;
case ConsumerGroups.USER: case ConsumerGroups.USER:
console.log("req.authInfo.accessLevel1"); // console.log("from user");
if (userPermissionIndex === -1) { if (userPermissionIndex === -1) {
apiError.status = httpStatus.FORBIDDEN; apiError.status = httpStatus.FORBIDDEN;
apiError.message = 'Forbidden'; apiError.message = 'Forbidden';

@ -3,6 +3,7 @@ import { cloneDeep, pick } from 'lodash';
import { hash } from 'bcryptjs'; import { hash } from 'bcryptjs';
import { handler as ErrorHandler } from './error'; import { handler as ErrorHandler } from './error';
import User from '../../common/models/user.model'; import User from '../../common/models/user.model';
import messages from '../../config/messages';
/** /**
* Converter * Converter
* @param {*} str * @param {*} str
@ -71,7 +72,7 @@ exports.checkExistingEmail = async (req, res, next) => {
where: { email: req.body.email } where: { email: req.body.email }
}); });
if (user) { if (user) {
return res.status(400).json({ message: 'email have aldready exist', data: user , email: req.body.email}); return res.status(400).json({ message: 'email have aldready exist'});
} }
return next(); return next();
} catch (ex) { } catch (ex) {
@ -122,3 +123,19 @@ exports.prepareParamsUpdated = async (req, res, next) => {
next(); next();
}; };
// check current password
exports.checkCurrentPassword = async (req,res,next) => {
const {current_password, new_password} = req.body;
const {user} = req.locals;
const isCheck = await User.passwordMatches(user, current_password);
if (!isCheck) {
return res.status(404).json({
code : 0,
message : "email or password is incorrect!"
})
};
return next();
}

@ -3,6 +3,8 @@ import Moment from 'moment-timezone';
import JWT from 'jsonwebtoken'; import JWT from 'jsonwebtoken';
import { handler as ErrorHandler } from './error'; import { handler as ErrorHandler } from './error';
import User from '../../common/models/user.model'; import User from '../../common/models/user.model';
import permissions from '../../common/utils/Permissions';
/** /**
* Load item by id add to req locals. * Load item by id add to req locals.
*/ */
@ -27,12 +29,34 @@ exports.count = async (req, res, next) => {
req.totalRecords = await User.totalRecords( req.totalRecords = await User.totalRecords(
req.query req.query
); );
return next(); return next();
} catch (ex) { } catch (ex) {
return ErrorHandler(ex, req, res, next); return ErrorHandler(ex, req, res, next);
} }
}; };
/**
* Load count account with user service
*/
exports.countUser = async(req,res,next) => {
try{
req.totalRecords = await User.count({
where: {
is_active: true,
service : permissions.USER
}
});
console.log(req.query);
return next();
} catch (ex ) {
return ErrorHandler(ex,req,res,next);
};
};
/** /**
* Load item by id add to req locals. * Load item by id add to req locals.
*/ */

@ -1,7 +1,7 @@
import express from 'express'; import express from 'express';
// import validate from 'express-validation'; // import validate from 'express-validation';
// import { authorize } from '../../middlewares/auth.middleware'; import { authorize } from '../../middlewares/auth.middleware';
// import Permissions from '../../../common/utils/Permissions'; import Permissions from '../../../common/utils/Permissions';
import { uploader } from '../../../common/services/adapters/upload-adapter'; import { uploader } from '../../../common/services/adapters/upload-adapter';
import controller from '../../controllers/v1/image.controller'; import controller from '../../controllers/v1/image.controller';

@ -16,13 +16,15 @@ const router = express.Router();
router router
.route('/') .route('/')
.get( .get(
authorize([permissions.LOGGED_IN]), authorize([permissions.SERVICE]),
middleware.count, middleware.count,
// middleware.load,
controller.list controller.list
) )
.post( .post(
validate(createValidation), validate(createValidation),
authorize([permissions.LOGGED_IN]), authorize([permissions.SERVICE]),
middleware.prepareParams, middleware.prepareParams,
middleware.checkExistingEmail, middleware.checkExistingEmail,
controller.create controller.create
@ -31,34 +33,56 @@ router
router router
.route('/:id') .route('/:id')
.get( .get(
authorize([permissions.SERVICE]),
middleware.load, middleware.load,
controller.get controller.get
// controller.addService
) )
.put( .put(
validate(updateValidation), validate(updateValidation),
authorize([permissions.LOGGED_IN]), authorize([permissions.SERVICE]),
middleware.load, middleware.load,
middleware.prepareParamsUpdated, middleware.prepareParamsUpdated,
controller.update controller.update
) )
.delete( .delete(
authorize([permissions.LOGGED_IN]), authorize([permissions.SERVICE]),
middleware.load, middleware.load,
controller.delete controller.delete
); );
router router
.route('/:id/block') .route('/:id/block')
.post( .post(
authorize([permissions.LOGGED_IN]), authorize([permissions.STAFF]),
middleware.load, middleware.load,
controller.block controller.block
); );
router router
.route('/:id/active') .route('/:id/active')
.post( .post(
authorize([permissions.LOGGED_IN]), authorize([permissions.STAFF]),
middleware.load, middleware.load,
controller.active controller.active
); );
// super admin change password for themself
router
.route("/resetpassword/:id")
.post(
authorize([permissions.SERVICE]),
middleware.load,
middleware.checkCurrentPassword,
controller.changePassword
);
//super admin change password for admin
router
.route("/change-password/:id")
.post(
authorize([permissions.SERVICE]),
middleware.load,
controller.changePassword
);
export default router; export default router;

@ -15,11 +15,13 @@ const router = express.Router();
router router
.route('/') .route('/')
.get( .get(
authorize([permissions.STAFF]),
validate(listValidation), validate(listValidation),
middleware.count, middleware.countUser,
controller.list controller.list
) )
.post( .post(
authorize([permissions.STAFF]),
validate(createValidation), validate(createValidation),
// authorize([permissions.USER_CREATE]), // authorize([permissions.USER_CREATE]),
middleware.checkEmail, middleware.checkEmail,
@ -34,12 +36,12 @@ router
) )
.put( .put(
validate(updateValidation), validate(updateValidation),
authorize([permissions.LOGGED_IN]), authorize([permissions.STAFF]),
middleware.load, middleware.load,
controller.update controller.update
) )
.delete( .delete(
authorize([permissions.LOGGED_IN]), authorize([permissions.STAFF]),
middleware.load, middleware.load,
controller.delete controller.delete
); );
@ -55,7 +57,7 @@ router.route("/:id/reset-password").
router.route("/change-password/:id"). router.route("/change-password/:id").
post( post(
authorize([permissions.LOGGED_IN]), authorize([permissions.STAFF]),
middleware.load, middleware.load,
// middleware.checkCurrentPassword, // middleware.checkCurrentPassword,
controller.updatePassword controller.updatePassword

@ -770,7 +770,7 @@ User.get = async (userId) => {
is_active: true is_active: true
} }
}); });
console.log(user); // console.log(user);
if (isNil(user)) { if (isNil(user)) {
throw new APIError({ throw new APIError({
status: httpStatus.NOT_FOUND, status: httpStatus.NOT_FOUND,

@ -2,9 +2,12 @@ import { serviceName } from '../../config/vars';
export default { export default {
// Service Permission // Service Permission
// service: user : 'user'
USER: 'user', USER: 'user',
// ADMINISTRATOR : 'administrator', // service: staff : 'staff'
LOGGED_IN: 'staff', STAFF: 'staff',
SERVICE: 'service',
// For Product Route // For Product Route
PRODUCT_VIEW: `${serviceName}_product_view`, PRODUCT_VIEW: `${serviceName}_product_view`,

@ -27,5 +27,6 @@
"column user.services does not exist": "column user.services does not exist", "column user.services does not exist": "column user.services does not exist",
"log is not defined": "log is not defined", "log is not defined": "log is not defined",
"connect ETIMEDOUT 113.177.27.200:5432": "connect ETIMEDOUT 113.177.27.200:5432", "connect ETIMEDOUT 113.177.27.200:5432": "connect ETIMEDOUT 113.177.27.200:5432",
"Validation error: Validation isEmail on email failed": "Validation error: Validation isEmail on email failed" "Validation error: Validation isEmail on email failed": "Validation error: Validation isEmail on email failed",
"WHERE parameter \"id\" has invalid \"undefined\" value": "WHERE parameter \"id\" has invalid \"undefined\" value"
} }
Loading…
Cancel
Save