new list of staff and add new staff function

master
tnud0 2 years ago
parent 3c9f2c8ca0
commit 8d0ff2ea54
  1. 28
      src/api/controllers/v1/staff.controller.js
  2. 2
      src/api/controllers/v1/user.controller.js
  3. 19
      src/api/middlewares/auth.middleware.js
  4. 5
      src/api/middlewares/authen.middleware.js
  5. 25
      src/api/middlewares/staff.middleware.js
  6. 3
      src/api/routes/v1/staff.route.js
  7. 14
      src/common/models/user.model.js
  8. 6
      src/config/locales/en.json

@ -3,6 +3,8 @@ import { pick } from 'lodash';
import messages from '../../../config/messages'; import messages from '../../../config/messages';
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 {hash} from 'bcryptjs';
/** /**
* Create * Create
@ -14,10 +16,12 @@ import User from '../../../common/models/user.model';
exports.create = async (req, res, next) => { exports.create = async (req, res, next) => {
// transform data // transform data
req.body.created_by = pick(req.user, ['id', 'name']); req.body.created_by = pick(req.user, ['id', 'name']);
// save data // save data
await User.create(req.body) await User.create(req.body)
.then(data => { .then(data => {
console.log(data);
res.json({ res.json({
code: 0, code: 0,
message: messages.CREATE_SUCCESS, message: messages.CREATE_SUCCESS,
@ -25,7 +29,22 @@ exports.create = async (req, res, next) => {
}); });
}).catch(ex => { }).catch(ex => {
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);
// })
}; };
/** /**
@ -36,16 +55,19 @@ exports.create = async (req, res, next) => {
* @returns {Promise<StorySchema[]>, APIException>} * @returns {Promise<StorySchema[]>, APIException>}
*/ */
exports.list = async (req, res, next) => { exports.list = async (req, res, next) => {
// req.query.types = User.Types.STAFF; req.query.services = User.Services.STAFF;
User.list( // console.log(req.query)
req.query await User.list(
req.query
).then(result => { ).then(result => {
console.log(result );
res.json({ res.json({
code: 0, code: 0,
count: req.totalRecords, count: req.totalRecords,
data: result.map( data: result.map(
x => User.transform(x) x => User.transform(x)
) )
}); });
}).catch(ex => { }).catch(ex => {
ErrorHandler(ex, req, res, next); ErrorHandler(ex, req, res, next);

@ -41,7 +41,7 @@ exports.create = async (req, res, next) => {
* @returns {Promise<StorySchema[]>, APIException>} * @returns {Promise<StorySchema[]>, APIException>}
*/ */
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( User.list(
req.query req.query
).then(result => { ).then(result => {

@ -73,6 +73,7 @@ function parseAuthHeader(headerValue) {
* @returns {Object} * @returns {Object}
*/ */
function getUserFromJwtPayload(jwtPayload) { function getUserFromJwtPayload(jwtPayload) {
const user = { const user = {
id: jwtPayload.id, id: jwtPayload.id,
name: jwtPayload.name, name: jwtPayload.name,
@ -102,6 +103,7 @@ function checkStaffPermission(req, requestedPermissions) {
if (requestedPermissions.includes(Configs.PERMISSION_LOGGED_IN)) { if (requestedPermissions.includes(Configs.PERMISSION_LOGGED_IN)) {
return true; return true;
} }
// check service permissions // check service permissions
const { permissions } = req.user; const { permissions } = req.user;
@ -135,6 +137,7 @@ const getTokenInfo = (req) => {
return null; return null;
} }
jwt.payload = jsonwentoken.decode(jwt.value, { json: true }); jwt.payload = jsonwentoken.decode(jwt.value, { json: true });
// console.log(jwt);
return jwt; return jwt;
}; };
/** /**
@ -192,7 +195,7 @@ const loadInfo = async (req) => {
req.tokenInfo = tokenInfo; req.tokenInfo = tokenInfo;
req.authInfo = getAuthInfo(req); req.authInfo = getAuthInfo(req);
console.log(req.authInfo); // 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(
@ -238,7 +241,7 @@ const checkPermission = async (req, permissions, additionalCheck) => {
return null; return null;
case ConsumerGroups.STAFF: case ConsumerGroups.STAFF:
// remove user permission // remove user permission
console.log("1231231232"); // console.log("1231231232");
if (userPermissionIndex !== -1) { if (userPermissionIndex !== -1) {
permissionsToCheck.splice(userPermissionIndex, 1); permissionsToCheck.splice(userPermissionIndex, 1);
} }
@ -257,12 +260,12 @@ const checkPermission = async (req, permissions, additionalCheck) => {
} }
break; break;
case ConsumerGroups.ADMINISTRATOR: // case ConsumerGroups.ADMINISTRATOR:
if (adminPermissionIndex !== -1 && userPermissionIndex=== -1) { // if (adminPermissionIndex !== -1 && userPermissionIndex=== -1) {
console.log("ConsumerGroups.ADMINISTRATOR"); // console.log("ConsumerGroups.ADMINISTRATOR");
return null // return null
}; // };
break; // break;
default: default:
// reject guest access // reject guest access
return apiError; return apiError;

@ -35,7 +35,7 @@ exports.loadUser = async (req, res, next) => {
try { try {
const user = await User.getUserByPhoneOrEmail({ email: req.body.email || req.body.username }); const user = await User.getUserByPhoneOrEmail({ email: req.body.email || req.body.username });
if (!user) { if (!user) {
return res.status(400).json({ message: 'email or password incorrect' }); return res.status(400).json({ message: 'email incorrect' });
} }
req.locals = { req.locals = {
user user
@ -47,10 +47,11 @@ exports.loadUser = async (req, res, next) => {
}; };
exports.checkPassword = async (req, res, next) => { exports.checkPassword = async (req, res, next) => {
const { user } = req.locals; const { user } = req.locals;
console.log(user.password);
// console.log(user); // console.log(user);
const isCheck = await User.passwordMatches(user, req.body.password); const isCheck = await User.passwordMatches(user, req.body.password);
if (!isCheck) { if (!isCheck) {
return res.status(400).json({ message: 'Email or password incorrect' }); return res.status(400).json({ message: ' password incorrect' });
} }
return next(); return next();
}; };

@ -44,10 +44,18 @@ exports.load = async (req, res, next) => {
*/ */
exports.count = async (req, res, next) => { exports.count = async (req, res, next) => {
try { try {
req.query.types = User.Types.STAFF; req.query.service = User.Types.STAFF;
req.totalRecords = await User.totalRecords( const total = await User.count({
req.query where: {
); service: req.query.service,
is_active : true
}
});
// console.log(total);
// req.totalRecords = await User.totalRecords(
// req.query
// );
req.totalRecords = total;
return next(); return next();
} catch (ex) { } catch (ex) {
return ErrorHandler(ex, req, res, next); return ErrorHandler(ex, req, res, next);
@ -57,11 +65,13 @@ exports.count = async (req, res, next) => {
/** /**
* Load item by id add to req locals. * Load item by id add to req locals.
*/ */
exports.checkEmail = async (req, res, next) => { exports.checkExistingEmail = async (req, res, next) => {
try { try {
const user = await User.findOne({ email: req.body.email }); const user = await User.findOne( {
where: { email: req.body.email }
});
if (user) { if (user) {
return res.status(400).json({ message: 'email have aldready exist' }); return res.status(400).json({ message: 'email have aldready exist', data: user , email: req.body.email});
} }
return next(); return next();
} catch (ex) { } catch (ex) {
@ -86,6 +96,7 @@ exports.prepareParams = async (req, res, next) => {
const params = cloneDeep(req.body); const params = cloneDeep(req.body);
params.type = User.Types.STAFF; params.type = User.Types.STAFF;
params.service = User.Services.STAFF; params.service = User.Services.STAFF;
// params.password = "123456";
if (params.name) { if (params.name) {
params.normalize_name = convertToEn(`${params.name}`); params.normalize_name = convertToEn(`${params.name}`);
} }

@ -22,8 +22,9 @@ router
) )
.post( .post(
validate(createValidation), validate(createValidation),
// authorize([permissions.LOGGED_IN]), authorize([permissions.LOGGED_IN]),
middleware.prepareParams, middleware.prepareParams,
middleware.checkExistingEmail,
controller.create controller.create
); );

@ -339,7 +339,7 @@ User.addHook('beforeCreate', async (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); console.log("pass created");
} }
return user; return user;
@ -452,6 +452,8 @@ function filterConditions(params) {
} }
delete options.services; delete options.services;
// console.log("delete services from asfsd");
if (options.genders) { if (options.genders) {
options.gender = { [Op.in]: options.genders.split(',') }; options.gender = { [Op.in]: options.genders.split(',') };
} }
@ -480,6 +482,7 @@ function filterConditions(params) {
// Date Filter // Date Filter
checkMinMaxOfConditionFields(options, 'created_at', 'Date'); checkMinMaxOfConditionFields(options, 'created_at', 'Date');
return options; return options;
} }
@ -561,7 +564,10 @@ User.transform = (params, includeRestrictedFields = true) => {
'created_by' 'created_by'
]; ];
fields.push(...privateFiles); fields.push(...privateFiles);
} };
// console.log(fields + "@@@");
fields.forEach((field) => { fields.forEach((field) => {
transformed[field] = params[field]; transformed[field] = params[field];
}); });
@ -589,6 +595,7 @@ User.transform = (params, includeRestrictedFields = true) => {
dateFields.forEach((field) => { dateFields.forEach((field) => {
transformed[field] = moment(params[field]).unix(); transformed[field] = moment(params[field]).unix();
}); });
// console.log(transformed);
return transformed; return transformed;
}; };
@ -837,10 +844,13 @@ User.list = async ({
min_total_debt, min_total_debt,
max_total_debt, max_total_debt,
}); });
const sorts = sortConditions({ const sorts = sortConditions({
sort_by, sort_by,
order_by order_by
}); });
return User.findAll({ return User.findAll({
where: options, where: options,
order: [sorts], order: [sorts],

@ -23,5 +23,9 @@
"Cannot access 'user' before initialization": "Cannot access 'user' before initialization", "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!",
"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" "Missing where attribute in the options parameter": "Missing where attribute in the options parameter",
"column user.services does not exist": "column user.services does not exist",
"log is not defined": "log is not defined",
"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"
} }
Loading…
Cancel
Save