我遇到了同样的问题,它位于api/services/passport.js 中:
// If the profile object contains a list of emails, grab the first one and
// add it to the user.
if (profile.hasOwnProperty('emails')) {
user.email = profile.emails[0].value;
}
// If the profile object contains a username, add it to the user.
if (profile.hasOwnProperty('username')) {
user.username = profile.username;
}
// If neither an email or a username was available in the profile, we don't
// have a way of identifying the user in the future. Throw an error and let
// whoever's next in the line take care of it.
if (!user.username && !user.email) {
return next(new Error('Neither a username nor email was available'));
}
Google 服务没有返回profile.username
属性。
因此,用户没有保存在数据库中,无法进行身份验证。然后护照回调接收一个空用户,因此处理错误的函数被触发,用户被重定向到登录页面。
此更改允许将该displayName
属性用作username
:
// If the profile object contains a list of emails, grab the first one and
// add it to the user.
if (profile.hasOwnProperty('emails')) {
user.email = profile.emails[0].value;
}
// If the profile object contains a username, add it to the user.
if (profile.hasOwnProperty('username')) {
user.username = profile.username;
}
/** Content not generated BEGIN */
// If the username property was empty and the profile object
// contains a property "displayName", add it to the user.
if (!user.username && profile.hasOwnProperty('displayName')) {
console.log(profile); // <= Use it to check the content given by Google about the user
user.username = profile.displayName;
}
/** Content not generated END */
// If neither an email or a username was available in the profile, we don't
// have a way of identifying the user in the future. Throw an error and let
// whoever's next in the line take care of it.
if (!user.username && !user.email) {
return next(new Error('Neither a username nor email was available'));
}
您也可以使用该profile.id
属性,因为profile.displayName
它不一定是唯一的(即:两个 Google 帐户可以有一个相同的displayName
)。但在不同的服务中也是如此:Twitter帐户也可以与Facebook帐户具有相同的用户名。如果两者都在您的应用程序上注册,您将遇到错误。这是生成的代码的问题sails-generate-auth
,您应该根据您想要的行为对其进行调整。
如果此解决方案也适用于您,我将提出 PR。