是否可以在注册环回用户后立即获取访问令牌而无需登录用户?如果是这样你怎么做?我正在使用环回3
这是我目前的片段。您需要在common/models/account.js
文件(或您选择的任何名称)中添加自定义远程方法,其中Account
模型inherits内置User
模型:
module.exports = function (Account) {
Account.createAndLogin = function (data, cb) {
if (!data || !data.password) {
return cb(new Error("Attribute 'password' is mandatory to create a new user."));
}
Account.create(data, function (err, account) {
if (err) {
return cb(err, null);
}
Account.login({email: data.email, password: data.password}, function (err, token) {
if (err) {
return cb(err, null);
}
cb(err, {
id: token.id,
ttl: token.ttl,
created: token.created,
userId: token.userId,
account: account
});
});
});
};
Account.remoteMethod('createAndLogin', {
description: "Create and login in one remote method",
accepts: {arg: 'data', type: 'object', required: true, http: {source: 'body'}, description: 'Model instance data'},
returns: {arg: 'accessToken', type: 'object', root: true, description: 'User Model'},
http: {verb: 'post'}
});
};
编辑:由于Account
模型继承了内置的User
模型,您需要打开访问控制列表(ACL)到$ everyone。
所以你的common/models/account.json
文件应该如下所示:
{
"name": "Account",
"base": "User",
"idInjection": true,
"properties": {},
"validations": [],
"relations": {},
"acls": [
{
"principalType": "ROLE",
"principalId": "$everyone",
"permission": "ALLOW",
"property": "createAndLogin"
}
],
"methods": []
}
我会在after remote hook远程方法中添加一个users/create
,因此在成功调用之后,您可以使用您可以从request
对象获取的密码调用User.login()(以获取访问令牌)。因此,在注册请求之后,您将在响应中获得访问令牌。