- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我已经阅读了几十篇关于 Promises 的文章,并且在大多数情况下,我得到了它们并且已经使用它们几年了。但是我有一个案例,我正在努力解决并且在我的所有阅读中都没有找到完全匹配的 - 除非我没有认出匹配。我的情况是这样的:
我有客户端和服务器应用程序。服务器应用程序是客户端的 API。用户发出登录请求,并在成功调用 Active Directory 并在该目录中找到用户后,进行 Sequelize 'Users.findOne' 调用,并将用户数据返回到随后的 .then 中的客户端。任何错误都有一个 .catch 。
一旦 findOne 成功,我想添加一个检查和另一个 Sequelize 调用,其中如果来自 Active Directory(办公室、公司、部门)的三个数据点中的任何一个与存储在用户表中的内容不匹配,我用用户更新它.更新电话。我不需要将此调用的结果返回给客户端,也不需要通知它任何失败。将两者都记录到服务器就足够了。我使用 winston 进行日志记录。不加和加加的代码如下。两者都有效,但我不确定较长的一个是否正确。
为了完整起见,我包括了对 AD 的 Passport 调用,以及通过 AD Group 的替代登录,但您可以忽略这些位。我在原始代码中添加了一行星号以指示我插入附加代码的位置,在第二个 list 中,我用星号行包围了代码,以便您可以轻松找到它。
那么我这样做是对的,还是什么?
注意:为简洁起见,您可以忽略星号后面的 return 语句之后的所有内容。这样的代码还不到一半。我只是想让你看看其余的,如果你认为它可能相关。
api.post('/login', passport.authenticate('ldapauth', {session: true, failureFlash: 'Invalid username or password.', failWithError: true}),
(req, res, next) => {
// this is only called if authentication was successful. this is called after the serializer.
// the authenticated user is found in req.user.
let adGroups = req.user.memberOf;
let office = req.user.physicalDeliveryOfficeName;
let company = req.user.company;
let department = req.user.department;
// console.log('Member Of', adGroups);
if (typeof req.user.sessionID !== 'undefined') {
winston.info(`\"Login Successful for \"${req.user.displayName}\" (${req.user.sAMAccountName})\" - SessionID: ${req.user.sessionID} ${req.ip} \"${req.method} ${req.originalUrl} HTTP/${req.httpVersion}\" \"${req.headers['referer']}\" \"${req.headers['user-agent']}\" \"${req.headers['content-length']}\"`,
{username: req.user.sAMAccountName, sessionID: req.user.sessionID, ip: req.ip, referrer: req.headers['referer'], url: req.originalUrl, query: req.method, route: 'Authentication'});
} else {
winston.info(`\"Login Successful for \"${req.user.displayName}\" (${req.user.sAMAccountName})\" - SessionID: ${req.user.dataValues.sid} ${req.ip} \"${req.method} ${req.originalUrl} HTTP/${req.httpVersion}\" \"${req.headers['referer']}\" \"${req.headers['user-agent']}\" \"${req.headers['content-length']}\"`,
{username: req.user.sAMAccountName, sessionID: req.user.dataValues.sid, ip: req.ip, referrer: req.headers['referer'], url: req.originalUrl, query: req.method, route: 'Authentication'});
}
// console.log('Req user: ', req.user);
// console.log('right here 1')
let tempAbilities = [];
let userAbilities = [];
let allAbilities = displayAbilities();
let include = [{
model: Roles,
where: {
active: 1
},
include: [ RolesPerms ]
}];
let options = {
where: {
username: req.user.sAMAccountName
},
include: include
};
let userID = null;
// TODO check if found user is 'active === 0' and if so, fail the authentication; use where clause "active != 0"
// console.log('right here 2')
Users.findOne(options).then(userResult => {
// console.log('user result', userResult);
if (userResult === null) {
if (typeof req.user.sessionID !== 'undefined') {
winston.info(`\"Login user not found - looking for group for \"${req.user.displayName}\" (${req.user.sAMAccountName})\" - SessionID: ${req.user.sessionID} ${req.ip} \"${req.method} ${req.originalUrl} HTTP/${req.httpVersion}\" \"${req.headers['referer']}\" \"${req.headers['user-agent']}\" \"${req.headers['content-length']}\"`,
{username: req.user.sAMAccountName, sessionID: req.user.sessionID, ip: req.ip, referrer: req.headers['referer'], url: req.originalUrl, query: req.method, route: 'Authentication'});
} else {
winston.info(`\"Login user not found - looking for group for \"${req.user.displayName}\" (${req.user.sAMAccountName})\" - SessionID: ${req.user.dataValues.sid} ${req.ip} \"${req.method} ${req.originalUrl} HTTP/${req.httpVersion}\" \"${req.headers['referer']}\" \"${req.headers['user-agent']}\" \"${req.headers['content-length']}\"`,
{username: req.user.sAMAccountName, sessionID: req.user.dataValues.sid, ip: req.ip, referrer: req.headers['referer'], url: req.originalUrl, query: req.method, route: 'Authentication'});
}
throw new Error('User not in SutterNow DB.')
}
userID = userResult.dataValues.id;
userResult.roles.forEach(rElement => {
rElement.roles_perms.forEach(rpElement => {
// console.log('rpElement', rpElement);
// if (abilities.findIndex(x => x.prop=="propVal")) --> an example of using an object property to find index
if (tempAbilities.indexOf(rpElement.dataValues.permission_name) === -1) {
tempAbilities.push(rpElement.dataValues.permission_name);
userAbilities.push(allAbilities[allAbilities.findIndex(x => x.name === rpElement.dataValues.permission_name)]);
}
})
});
req.session.rules = userAbilities;
let location = {
office: office,
company: company,
department: department
}
req.session.location = location
/****************************************************************************************************/
return res.json({id: userID, rules: userAbilities, location: location, "Message": "Login Successful"});
}).catch(err => {
// console.log('ah crap')
if (typeof req.user.sessionID !== 'undefined') {
winston.info(`\"Looking for group for \"${req.user.displayName}\" (${req.user.sAMAccountName})\" - SessionID: ${req.user.sessionID} ${req.ip} \"${req.method} ${req.originalUrl} HTTP/${req.httpVersion}\" \"${req.headers['referer']}\" \"${req.headers['user-agent']}\" \"${req.headers['content-length']}\"`,
{username: req.user.sAMAccountName, sessionID: req.user.sessionID, ip: req.ip, referrer: req.headers['referer'], url: req.originalUrl, query: req.method, route: 'Authentication'});
} else {
winston.info(`\"Looking for group for \"${req.user.displayName}\" (${req.user.sAMAccountName})\" - SessionID: ${req.user.dataValues.sid} ${req.ip} \"${req.method} ${req.originalUrl} HTTP/${req.httpVersion}\" \"${req.headers['referer']}\" \"${req.headers['user-agent']}\" \"${req.headers['content-length']}\"`,
{username: req.user.sAMAccountName, sessionID: req.user.dataValues.sid, ip: req.ip, referrer: req.headers['referer'], url: req.originalUrl, query: req.method, route: 'Authentication'});
}
const promA = Groups.findAll({
where: {
active: 1
},
include: [{
model: Roles,
where: {
active: 1
},
include: [ RolesPerms ]
}],
order: ['displayName']
});
const promB = GroupsRoles.findAll();
// console.error(err);
// user not found in our DB, but they're in AD; let's check if they belong to an approved group
Promise.all([promA, promB]).then(responses => {
// console.log('Response 1', responses[0]);
// console.log('Response 2', responses[1]);
if (typeof req.user.sessionID !== 'undefined') {
winston.info(`\"Found group results for \"${req.user.displayName}\" (${req.user.sAMAccountName})\" - SessionID: ${req.user.sessionID} ${req.ip} \"${req.method} ${req.originalUrl} HTTP/${req.httpVersion}\" \"${req.headers['referer']}\" \"${req.headers['user-agent']}\" \"${req.headers['content-length']}\"`,
{username: req.user.sAMAccountName, sessionID: req.user.sessionID, ip: req.ip, referrer: req.headers['referer'], url: req.originalUrl, query: req.method, route: 'Authentication'});
} else {
winston.info(`\"Found group results for \"${req.user.displayName}\" (${req.user.sAMAccountName})\" - SessionID: ${req.user.dataValues.sid} ${req.ip} \"${req.method} ${req.originalUrl} HTTP/${req.httpVersion}\" \"${req.headers['referer']}\" \"${req.headers['user-agent']}\" \"${req.headers['content-length']}\"`,
{username: req.user.sAMAccountName, sessionID: req.user.dataValues.sid, ip: req.ip, referrer: req.headers['referer'], url: req.originalUrl, query: req.method, route: 'Authentication'});
}
let foundGroup = ''
let foundRoles = []
let foundPerms = []
responses[0].forEach(el => {
// console.log('our el', el)
// console.log('our group', el.dataValues)
for (let j = 0; j < adGroups.length; j++) {
// console.log('adGroups j', adGroups[j])
if (adGroups[j].match(el.dataValues.username)) {
// console.log('found it', el.dataValues)
userID = el.id
foundGroup = el.dataValues.username;
foundRoles = el.dataValues;
break // TODO allow for membership in multiple groups, like I do multiple roles, below
}
}
});
foundRoles.roles.forEach(role => {
// console.log('roles_perms things', role.roles_perms);
role.roles_perms.forEach(roleP => {
if (foundPerms.indexOf(roleP.dataValues.permission_name) === -1) {
foundPerms.push(roleP.dataValues.permission_name);
userAbilities.push(allAbilities[allAbilities.findIndex(x => x.name === roleP.dataValues.permission_name)]);
}
})
});
req.session.rules = userAbilities;
let location = {
office: office,
company: company,
department: department
}
req.session.location = location
return res.json({id: 0, rules: userAbilities, location: location, "Message": "Login Successful via group membership"});
}).catch(err => {
console.error('the error ' + err);
return res.json({"Message": "Login failed. You neither had a user account in SutterNow, nor did you belong to a valid AD Group."})
});
});
return null;
// res.json({"Message":"Login successful"});
},
(err, req, res, next) => {
/* failWithErrors: true, above, makes this section get called to handle the error.
We don't handle the logging nor the json return here; instead, we setup the error object and pass it on
to the error handler which does those things. */
console.log('Authentication failed; passing error on to error handler...');
err.route = 'Authentication';
err.statusCode = 401;
err.status = 401;
err.shouldRedirect = req.headers['user-agent'].indexOf('Postman') > -1;
if (typeof req.flash === 'function' && typeof req.flash('error') !== 'undefined' && req.flash('error').length !== 0) {
err.message = req.flash('error').slice(-1)[0];
console.log('Flash error ' + req.flash('error').slice(-1)[0]);
res.statusMessage = req.flash('error').slice(-1)[0];
}
if (app.get('env') === 'production') {
console.log('stack redacted');
err.stack = '';// We want to obscure any data the user shouldn't see.
}
next(err);
// return res.json({"Message": "Login failed. " + err.message});
// return null;
}
);
api.post('/login', passport.authenticate('ldapauth', {session: true, failureFlash: 'Invalid username or password.', failWithError: true}),
(req, res, next) => {
// this is only called if authentication was successful. this is called after the serializer.
// the authenticated user is found in req.user.
let adGroups = req.user.memberOf;
let office = req.user.physicalDeliveryOfficeName;
let company = req.user.company;
let department = req.user.department;
// console.log('Member Of', adGroups);
if (typeof req.user.sessionID !== 'undefined') {
winston.info(`\"Login Successful for \"${req.user.displayName}\" (${req.user.sAMAccountName})\" - SessionID: ${req.user.sessionID} ${req.ip} \"${req.method} ${req.originalUrl} HTTP/${req.httpVersion}\" \"${req.headers['referer']}\" \"${req.headers['user-agent']}\" \"${req.headers['content-length']}\"`,
{username: req.user.sAMAccountName, sessionID: req.user.sessionID, ip: req.ip, referrer: req.headers['referer'], url: req.originalUrl, query: req.method, route: 'Authentication'});
} else {
winston.info(`\"Login Successful for \"${req.user.displayName}\" (${req.user.sAMAccountName})\" - SessionID: ${req.user.dataValues.sid} ${req.ip} \"${req.method} ${req.originalUrl} HTTP/${req.httpVersion}\" \"${req.headers['referer']}\" \"${req.headers['user-agent']}\" \"${req.headers['content-length']}\"`,
{username: req.user.sAMAccountName, sessionID: req.user.dataValues.sid, ip: req.ip, referrer: req.headers['referer'], url: req.originalUrl, query: req.method, route: 'Authentication'});
}
// console.log('Req user: ', req.user);
// console.log('right here 1')
let tempAbilities = [];
let userAbilities = [];
let allAbilities = displayAbilities();
let include = [{
model: Roles,
where: {
active: 1
},
include: [ RolesPerms ]
}];
let options = {
where: {
username: req.user.sAMAccountName
},
include: include
};
let userID = null;
// TODO check if found user is 'active === 0' and if so, fail the authentication; use where clause "active != 0"
// console.log('right here 2')
Users.findOne(options).then(userResult => {
// console.log('user result', userResult);
if (userResult === null) {
if (typeof req.user.sessionID !== 'undefined') {
winston.info(`\"Login user not found - looking for group for \"${req.user.displayName}\" (${req.user.sAMAccountName})\" - SessionID: ${req.user.sessionID} ${req.ip} \"${req.method} ${req.originalUrl} HTTP/${req.httpVersion}\" \"${req.headers['referer']}\" \"${req.headers['user-agent']}\" \"${req.headers['content-length']}\"`,
{username: req.user.sAMAccountName, sessionID: req.user.sessionID, ip: req.ip, referrer: req.headers['referer'], url: req.originalUrl, query: req.method, route: 'Authentication'});
} else {
winston.info(`\"Login user not found - looking for group for \"${req.user.displayName}\" (${req.user.sAMAccountName})\" - SessionID: ${req.user.dataValues.sid} ${req.ip} \"${req.method} ${req.originalUrl} HTTP/${req.httpVersion}\" \"${req.headers['referer']}\" \"${req.headers['user-agent']}\" \"${req.headers['content-length']}\"`,
{username: req.user.sAMAccountName, sessionID: req.user.dataValues.sid, ip: req.ip, referrer: req.headers['referer'], url: req.originalUrl, query: req.method, route: 'Authentication'});
}
throw new Error('User not in SutterNow DB.')
}
userID = userResult.dataValues.id;
userResult.roles.forEach(rElement => {
rElement.roles_perms.forEach(rpElement => {
// console.log('rpElement', rpElement);
// if (abilities.findIndex(x => x.prop=="propVal")) --> an example of using an object property to find index
if (tempAbilities.indexOf(rpElement.dataValues.permission_name) === -1) {
tempAbilities.push(rpElement.dataValues.permission_name);
userAbilities.push(allAbilities[allAbilities.findIndex(x => x.name === rpElement.dataValues.permission_name)]);
}
})
});
req.session.rules = userAbilities;
let location = {
office: office,
company: company,
department: department
}
req.session.location = location
/****************************************************************************************************/
// TODO is this supposed to be another .then chained between this one and the catch (or before this one)? if so, combine the catch?
if (userResult.dataValues.office !== office || userResult.dataValues.department !== department || userResult.dataValues.company !== company) {
// update the database with the new AD values
console.log('updating user')
Users.update({
// values
office: office,
department: department,
company: company
}, {
// options
where: {
id: userID
}
}).then(numAffected => {
winston.info(`\"Updated ${numAffected} user for ${req.user.dataValues.username}\" - SessionID: ${req.sessionID} ${req.ip} \"${req.method} ${req.originalUrl} HTTP/${req.httpVersion}\" \"${req.headers['referer']}\" \"${req.headers['user-agent']}\" \"${req.headers['content-length']}\"`,
{username: req.user.dataValues.username, sessionID: req.sessionID, ip: req.ip, referrer: req.headers['referer'], url: req.originalUrl, query: req.method, route: 'User Admin'});
return;
}).catch((err) => {
if (err) {
// Not sure how to get an error here. ensureAuthenticated handles invalid users attempting this PUT.
// console.log(err);
err.route = 'User Admin';
err.statusCode = 'UPDATE_USER_AT_LOGIN_BY_ID_ERROR';
err.status = 'UPDATE USER AT LOGIN BY ID ERROR';
err.shouldRedirect = req.headers['user-agent'].indexOf('Postman') > -1;
if (app.get('env') === 'production') {
console.log('stack redacted');
err.stack = '';// We want to obscure any data the user shouldn't see.
}
next(err);
}
});
}
/****************************************************************************************************/
return res.json({id: userID, rules: userAbilities, location: location, "Message": "Login Successful"});
}).catch(err => {
// console.log('ah crap')
if (typeof req.user.sessionID !== 'undefined') {
winston.info(`\"Looking for group for \"${req.user.displayName}\" (${req.user.sAMAccountName})\" - SessionID: ${req.user.sessionID} ${req.ip} \"${req.method} ${req.originalUrl} HTTP/${req.httpVersion}\" \"${req.headers['referer']}\" \"${req.headers['user-agent']}\" \"${req.headers['content-length']}\"`,
{username: req.user.sAMAccountName, sessionID: req.user.sessionID, ip: req.ip, referrer: req.headers['referer'], url: req.originalUrl, query: req.method, route: 'Authentication'});
} else {
winston.info(`\"Looking for group for \"${req.user.displayName}\" (${req.user.sAMAccountName})\" - SessionID: ${req.user.dataValues.sid} ${req.ip} \"${req.method} ${req.originalUrl} HTTP/${req.httpVersion}\" \"${req.headers['referer']}\" \"${req.headers['user-agent']}\" \"${req.headers['content-length']}\"`,
{username: req.user.sAMAccountName, sessionID: req.user.dataValues.sid, ip: req.ip, referrer: req.headers['referer'], url: req.originalUrl, query: req.method, route: 'Authentication'});
}
const promA = Groups.findAll({
where: {
active: 1
},
include: [{
model: Roles,
where: {
active: 1
},
include: [ RolesPerms ]
}],
order: ['displayName']
});
const promB = GroupsRoles.findAll();
// console.error(err);
// user not found in our DB, but they're in AD; let's check if they belong to an approved group
Promise.all([promA, promB]).then(responses => {
// console.log('Response 1', responses[0]);
// console.log('Response 2', responses[1]);
if (typeof req.user.sessionID !== 'undefined') {
winston.info(`\"Found group results for \"${req.user.displayName}\" (${req.user.sAMAccountName})\" - SessionID: ${req.user.sessionID} ${req.ip} \"${req.method} ${req.originalUrl} HTTP/${req.httpVersion}\" \"${req.headers['referer']}\" \"${req.headers['user-agent']}\" \"${req.headers['content-length']}\"`,
{username: req.user.sAMAccountName, sessionID: req.user.sessionID, ip: req.ip, referrer: req.headers['referer'], url: req.originalUrl, query: req.method, route: 'Authentication'});
} else {
winston.info(`\"Found group results for \"${req.user.displayName}\" (${req.user.sAMAccountName})\" - SessionID: ${req.user.dataValues.sid} ${req.ip} \"${req.method} ${req.originalUrl} HTTP/${req.httpVersion}\" \"${req.headers['referer']}\" \"${req.headers['user-agent']}\" \"${req.headers['content-length']}\"`,
{username: req.user.sAMAccountName, sessionID: req.user.dataValues.sid, ip: req.ip, referrer: req.headers['referer'], url: req.originalUrl, query: req.method, route: 'Authentication'});
}
let foundGroup = ''
let foundRoles = []
let foundPerms = []
responses[0].forEach(el => {
// console.log('our el', el)
// console.log('our group', el.dataValues)
for (let j = 0; j < adGroups.length; j++) {
// console.log('adGroups j', adGroups[j])
if (adGroups[j].match(el.dataValues.username)) {
// console.log('found it', el.dataValues)
userID = el.id
foundGroup = el.dataValues.username;
foundRoles = el.dataValues;
break // TODO allow for membership in multiple groups, like I do multiple roles, below
}
}
});
foundRoles.roles.forEach(role => {
// console.log('roles_perms things', role.roles_perms);
role.roles_perms.forEach(roleP => {
if (foundPerms.indexOf(roleP.dataValues.permission_name) === -1) {
foundPerms.push(roleP.dataValues.permission_name);
userAbilities.push(allAbilities[allAbilities.findIndex(x => x.name === roleP.dataValues.permission_name)]);
}
})
});
req.session.rules = userAbilities;
let location = {
office: office,
company: company,
department: department
}
req.session.location = location
return res.json({id: 0, rules: userAbilities, location: location, "Message": "Login Successful via group membership"});
}).catch(err => {
console.error('the error ' + err);
return res.json({"Message": "Login failed. You neither had a user account in SutterNow, nor did you belong to a valid AD Group."})
});
});
return null;
// res.json({"Message":"Login successful"});
},
(err, req, res, next) => {
/* failWithErrors: true, above, makes this section get called to handle the error.
We don't handle the logging nor the json return here; instead, we setup the error object and pass it on
to the error handler which does those things. */
console.log('Authentication failed; passing error on to error handler...');
err.route = 'Authentication';
err.statusCode = 401;
err.status = 401;
err.shouldRedirect = req.headers['user-agent'].indexOf('Postman') > -1;
if (typeof req.flash === 'function' && typeof req.flash('error') !== 'undefined' && req.flash('error').length !== 0) {
err.message = req.flash('error').slice(-1)[0];
console.log('Flash error ' + req.flash('error').slice(-1)[0]);
res.statusMessage = req.flash('error').slice(-1)[0];
}
if (app.get('env') === 'production') {
console.log('stack redacted');
err.stack = '';// We want to obscure any data the user shouldn't see.
}
next(err);
// return res.json({"Message": "Login failed. " + err.message});
// return null;
}
);
最佳答案
我想我想通了。我将添加的代码移到单独的 .then 中,并确保在不使用 res.json 之前返回该代码,而只返回对象。然后,无论用户表更新成功还是失败,我都会在新的 .then 中使用 res.json 返回该对象,因此:
api.post('/login', passport.authenticate('ldapauth', {session: true, failureFlash: 'Invalid username or password.', failWithError: true}),
(req, res, next) => {
// this is only called if authentication was successful. this is called after the serializer.
// the authenticated user is found in req.user.
let adGroups = req.user.memberOf;
let office = req.user.physicalDeliveryOfficeName;
let company = req.user.company;
let department = req.user.department;
// console.log('Member Of', adGroups);
if (typeof req.user.sessionID !== 'undefined') {
winston.info(`\"Login Successful for \"${req.user.displayName}\" (${req.user.sAMAccountName})\" - SessionID: ${req.user.sessionID} ${req.ip} \"${req.method} ${req.originalUrl} HTTP/${req.httpVersion}\" \"${req.headers['referer']}\" \"${req.headers['user-agent']}\" \"${req.headers['content-length']}\"`,
{username: req.user.sAMAccountName, sessionID: req.user.sessionID, ip: req.ip, referrer: req.headers['referer'], url: req.originalUrl, query: req.method, route: 'Authentication'});
} else {
winston.info(`\"Login Successful for \"${req.user.displayName}\" (${req.user.sAMAccountName})\" - SessionID: ${req.user.dataValues.sid} ${req.ip} \"${req.method} ${req.originalUrl} HTTP/${req.httpVersion}\" \"${req.headers['referer']}\" \"${req.headers['user-agent']}\" \"${req.headers['content-length']}\"`,
{username: req.user.sAMAccountName, sessionID: req.user.dataValues.sid, ip: req.ip, referrer: req.headers['referer'], url: req.originalUrl, query: req.method, route: 'Authentication'});
}
// console.log('Req user: ', req.user);
// console.log('right here 1')
let tempAbilities = [];
let userAbilities = [];
let allAbilities = displayAbilities();
let include = [{
model: Roles,
where: {
active: 1
},
include: [ RolesPerms ]
}];
let options = {
where: {
username: req.user.sAMAccountName
},
include: include
};
let userID = null;
// TODO check if found user is 'active === 0' and if so, fail the authentication; use where clause "active != 0"
// console.log('right here 2')
Users.findOne(options).then(userResult => {
// console.log('user result', userResult);
if (userResult === null) {
if (typeof req.user.sessionID !== 'undefined') {
winston.info(`\"Login user not found - looking for group for \"${req.user.displayName}\" (${req.user.sAMAccountName})\" - SessionID: ${req.user.sessionID} ${req.ip} \"${req.method} ${req.originalUrl} HTTP/${req.httpVersion}\" \"${req.headers['referer']}\" \"${req.headers['user-agent']}\" \"${req.headers['content-length']}\"`,
{username: req.user.sAMAccountName, sessionID: req.user.sessionID, ip: req.ip, referrer: req.headers['referer'], url: req.originalUrl, query: req.method, route: 'Authentication'});
} else {
winston.info(`\"Login user not found - looking for group for \"${req.user.displayName}\" (${req.user.sAMAccountName})\" - SessionID: ${req.user.dataValues.sid} ${req.ip} \"${req.method} ${req.originalUrl} HTTP/${req.httpVersion}\" \"${req.headers['referer']}\" \"${req.headers['user-agent']}\" \"${req.headers['content-length']}\"`,
{username: req.user.sAMAccountName, sessionID: req.user.dataValues.sid, ip: req.ip, referrer: req.headers['referer'], url: req.originalUrl, query: req.method, route: 'Authentication'});
}
throw new Error('User not in SutterNow DB.')
}
userID = userResult.dataValues.id;
userResult.roles.forEach(rElement => {
rElement.roles_perms.forEach(rpElement => {
// console.log('rpElement', rpElement);
// if (abilities.findIndex(x => x.prop=="propVal")) --> an example of using an object property to find index
if (tempAbilities.indexOf(rpElement.dataValues.permission_name) === -1) {
tempAbilities.push(rpElement.dataValues.permission_name);
userAbilities.push(allAbilities[allAbilities.findIndex(x => x.name === rpElement.dataValues.permission_name)]);
}
})
});
req.session.rules = userAbilities;
let location = {
office: office,
company: company,
department: department
}
req.session.location = location
let adLocation = {
office: userResult.dataValues.office,
company: userResult.dataValues.company,
department: userResult.dataValues.department
}
return {id: userID, rules: userAbilities, location: location, adLocation: adLocation, "Message": "Login Successful"};
}).then(result => {
if (result.adLocation.office !== result.location.office || result.adLocation.department !== result.location.department || result.adLocation.company !== result.location.company) {
// update the database with the new AD values
Users.update({
// values
office: office,
department: department,
company: company
}, {
// options
where: {
id: userID
}
}).then(numAffected => {
winston.info(`\"Updated ${numAffected} user for ${req.user.dataValues.username}\" - SessionID: ${req.sessionID} ${req.ip} \"${req.method} ${req.originalUrl} HTTP/${req.httpVersion}\" \"${req.headers['referer']}\" \"${req.headers['user-agent']}\" \"${req.headers['content-length']}\"`,
{username: req.user.dataValues.username, sessionID: req.sessionID, ip: req.ip, referrer: req.headers['referer'], url: req.originalUrl, query: req.method, route: 'User Admin'});
return res.json(result);
}).catch((err) => {
if (err) {
// Not sure how to get an error here. ensureAuthenticated handles invalid users attempting this PUT.
// console.log(err);
err.route = 'User Admin';
err.statusCode = 'UPDATE_USER_AT_LOGIN_BY_ID_ERROR';
err.status = 'UPDATE USER AT LOGIN BY ID ERROR';
err.shouldRedirect = req.headers['user-agent'].indexOf('Postman') > -1;
if (app.get('env') === 'production') {
console.log('stack redacted');
err.stack = '';// We want to obscure any data the user shouldn't see.
}
next(err);
}
});
} else {
return res.json(result);
}
}).catch(err => {
// console.log('ah crap')
if (typeof req.user.sessionID !== 'undefined') {
winston.info(`\"Looking for group for \"${req.user.displayName}\" (${req.user.sAMAccountName})\" - SessionID: ${req.user.sessionID} ${req.ip} \"${req.method} ${req.originalUrl} HTTP/${req.httpVersion}\" \"${req.headers['referer']}\" \"${req.headers['user-agent']}\" \"${req.headers['content-length']}\"`,
{username: req.user.sAMAccountName, sessionID: req.user.sessionID, ip: req.ip, referrer: req.headers['referer'], url: req.originalUrl, query: req.method, route: 'Authentication'});
} else {
winston.info(`\"Looking for group for \"${req.user.displayName}\" (${req.user.sAMAccountName})\" - SessionID: ${req.user.dataValues.sid} ${req.ip} \"${req.method} ${req.originalUrl} HTTP/${req.httpVersion}\" \"${req.headers['referer']}\" \"${req.headers['user-agent']}\" \"${req.headers['content-length']}\"`,
{username: req.user.sAMAccountName, sessionID: req.user.dataValues.sid, ip: req.ip, referrer: req.headers['referer'], url: req.originalUrl, query: req.method, route: 'Authentication'});
}
const promA = Groups.findAll({
where: {
active: 1
},
include: [{
model: Roles,
where: {
active: 1
},
include: [ RolesPerms ]
}],
order: ['displayName']
});
const promB = GroupsRoles.findAll();
// console.error(err);
// user not found in our DB, but they're in AD; let's check if they belong to an approved group
Promise.all([promA, promB]).then(responses => {
// console.log('Response 1', responses[0]);
// console.log('Response 2', responses[1]);
if (typeof req.user.sessionID !== 'undefined') {
winston.info(`\"Found group results for \"${req.user.displayName}\" (${req.user.sAMAccountName})\" - SessionID: ${req.user.sessionID} ${req.ip} \"${req.method} ${req.originalUrl} HTTP/${req.httpVersion}\" \"${req.headers['referer']}\" \"${req.headers['user-agent']}\" \"${req.headers['content-length']}\"`,
{username: req.user.sAMAccountName, sessionID: req.user.sessionID, ip: req.ip, referrer: req.headers['referer'], url: req.originalUrl, query: req.method, route: 'Authentication'});
} else {
winston.info(`\"Found group results for \"${req.user.displayName}\" (${req.user.sAMAccountName})\" - SessionID: ${req.user.dataValues.sid} ${req.ip} \"${req.method} ${req.originalUrl} HTTP/${req.httpVersion}\" \"${req.headers['referer']}\" \"${req.headers['user-agent']}\" \"${req.headers['content-length']}\"`,
{username: req.user.sAMAccountName, sessionID: req.user.dataValues.sid, ip: req.ip, referrer: req.headers['referer'], url: req.originalUrl, query: req.method, route: 'Authentication'});
}
let foundGroup = ''
let foundRoles = []
let foundPerms = []
responses[0].forEach(el => {
// console.log('our el', el)
// console.log('our group', el.dataValues)
for (let j = 0; j < adGroups.length; j++) {
// console.log('adGroups j', adGroups[j])
if (adGroups[j].match(el.dataValues.username)) {
// console.log('found it', el.dataValues)
userID = el.id
foundGroup = el.dataValues.username;
foundRoles = el.dataValues;
break // TODO allow for membership in multiple groups, like I do multiple roles, below
}
}
});
foundRoles.roles.forEach(role => {
// console.log('roles_perms things', role.roles_perms);
role.roles_perms.forEach(roleP => {
if (foundPerms.indexOf(roleP.dataValues.permission_name) === -1) {
foundPerms.push(roleP.dataValues.permission_name);
userAbilities.push(allAbilities[allAbilities.findIndex(x => x.name === roleP.dataValues.permission_name)]);
}
})
});
req.session.rules = userAbilities;
let location = {
office: office,
company: company,
department: department
}
req.session.location = location
return res.json({id: 0, rules: userAbilities, location: location, "Message": "Login Successful via group membership"});
}).catch(err => {
console.error('the error ' + err);
return res.json({"Message": "Login failed. You neither had a user account in SutterNow, nor did you belong to a valid AD Group."})
});
});
return null;
// res.json({"Message":"Login successful"});
},
(err, req, res, next) => {
/* failWithErrors: true, above, makes this section get called to handle the error.
We don't handle the logging nor the json return here; instead, we setup the error object and pass it on
to the error handler which does those things. */
console.log('Authentication failed; passing error on to error handler...');
err.route = 'Authentication';
err.statusCode = 401;
err.status = 401;
err.shouldRedirect = req.headers['user-agent'].indexOf('Postman') > -1;
if (typeof req.flash === 'function' && typeof req.flash('error') !== 'undefined' && req.flash('error').length !== 0) {
err.message = req.flash('error').slice(-1)[0];
console.log('Flash error ' + req.flash('error').slice(-1)[0]);
res.statusMessage = req.flash('error').slice(-1)[0];
}
if (app.get('env') === 'production') {
console.log('stack redacted');
err.stack = '';// We want to obscure any data the user shouldn't see.
}
next(err);
// return res.json({"Message": "Login failed. " + err.message});
// return null;
}
);
关于node.js - 另一个 Promise 问题 - 嵌套的 Sequelize 调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61959103/
我正在关注 Sequelize 纪录片。在 Model Definition 部分的底部,我想知道 sequelize 变量用于什么?我可以删除它吗? { sequelize, modelNa
我有这个原始 SQL 查询。 SELECT restaurants.name AS restaurant, ROUND((6371 * ACOS(COS(RADIANS(6.9271)
我有一个 postgres 数据库,我正在使用 Sequelize。从表 车辆 和 预订 我试图在给定开始日期和结束日期的情况下获得所有可用车辆。 如果我使用给定日期搜索 Bookings: Book
我正在尝试使用 HapiJS 和 Sequelize 开始一个项目,并且开始时,希望在没有 Sequelize CLI 的情况下使事情正常工作,以了解一切是如何结合在一起的。 我见过多个示例项目,例如
sequelize init:models 命令会创建一个“models”文件夹并添加一个 index.js。 有人能解释一下这个 index.js 文件到底做了什么,以及它如何适应 Sequeliz
查看此 Sequelize tutorial 中的 models/blog.js 定义. module.exports = (sequelize, type) => { return sequ
我收到一个错误 No overload matches this call 每当我尝试使用 @HasMany() 或 @BelongsTo 装饰器时。 我正在使用 nestjs/sequelize:
const gamem = await gamemodes.findAll({attributes: ['name']}); const newme = await gamemodes.fin
我们如何使用 sequelize 4.2 创建由所有模型应用/继承的自定义实例方法?在 Sequelize 3 中,我们曾经在扩展到所有其他模型的主模型的“定义”部分中有一个“instanceMeth
我正在使用 Typescript、NodeJS 和sequelize-auto-ts 进行模型生成。我想要放置包含查找查询的两个模型给了我错误的结果,这又是由于触发了错误的查询。这是有问题的两个模型;
假设我在用户表中有 5 列 name email state isOnline createdAt | N
我有两张表,其中一张表具有另一张表的 ID。 1:1 关系。 所以像 EventFeedback somePrimaryKey userEventID UserEvent us
如何使用对象创建具有现有关联的条目? 例如, User.create({ socialMedia: [{ socialId: 1, //should reference existing
如何创建在创建 Sequelize 模型的新实例时以编程方式生成的默认值?我已经在某处阅读了如何执行此操作,但在任何地方都找不到。我以为这与classMethods有关,但我不知道应该调用什么方法。
当我设置关联时,有没有办法使用 Sequelize (sequelizejs.com) 输出所有在对象上神奇创建的函数。 例如;我有一个用户模型,我设置 User.belongsToMany(User
我该如何制作 Music是`音乐? { id: 4 name: "playlist 1" created_at: "2015-04-21T21:43:07.000Z" updated_
我可以使用 sequelize 从可用模型创建数据库模式吗?我在一个缺少许多迁移且没有测试的项目上工作。要运行测试,我需要创建一个新的 db (sqlite3),但我无法使用迁移初始化其架构(因为它们
我有一个与其他模型相关联的简单 Sequelize 模型。 module.exports = function (sequelize, DataTypes) { var Votes = seque
我有一个像这样设置的协会: m.User.hasMany(m.Interests, { joinTableName: 'user_interests', foreignKey: 'user_id' }
我有以下型号: var User = Seq.define('user', { firstName: { type: Sequelize.STRING,
我是一名优秀的程序员,十分优秀!