在环回注册后获取访问令牌
getting access token after signing up in loopback
是否可以在环回中注册用户后立即获得访问令牌而无需登录用户?如果是这样,您将如何处理?我正在使用环回 3
我会在 users/create
远程方法中添加一个 after remote hook,因此在它成功调用后,您可以调用 User.login()(以获取访问令牌)您可能可以从 request
对象中获取。因此,在注册请求后,您将在响应中获得访问令牌。
这是我当前的片段。
您需要在 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
模型,您需要打开访问控制列表(ACLs)以$大家.
因此您的 common/models/account.json
文件应如下所示:
{
"name": "Account",
"base": "User",
"idInjection": true,
"properties": {},
"validations": [],
"relations": {},
"acls": [
{
"principalType": "ROLE",
"principalId": "$everyone",
"permission": "ALLOW",
"property": "createAndLogin"
}
],
"methods": []
}
是否可以在环回中注册用户后立即获得访问令牌而无需登录用户?如果是这样,您将如何处理?我正在使用环回 3
我会在 users/create
远程方法中添加一个 after remote hook,因此在它成功调用后,您可以调用 User.login()(以获取访问令牌)您可能可以从 request
对象中获取。因此,在注册请求后,您将在响应中获得访问令牌。
这是我当前的片段。
您需要在 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
模型,您需要打开访问控制列表(ACLs)以$大家.
因此您的 common/models/account.json
文件应如下所示:
{
"name": "Account",
"base": "User",
"idInjection": true,
"properties": {},
"validations": [],
"relations": {},
"acls": [
{
"principalType": "ROLE",
"principalId": "$everyone",
"permission": "ALLOW",
"property": "createAndLogin"
}
],
"methods": []
}