在注册环回后获取访问令牌

问题描述 投票:0回答:2

是否可以在注册环回用户后立即获取访问令牌而无需登录用户?如果是这样你怎么做?我正在使用环回3

node.js loopbackjs reactjs-native
2个回答
0
投票

这是我目前的片段。您需要在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": []
}

1
投票

我会在after remote hook远程方法中添加一个users/create,因此在成功调用之后,您可以使用您可以从request对象获取的密码调用User.login()(以获取访问令牌)。因此,在注册请求之后,您将在响应中获得访问令牌。

© www.soinside.com 2019 - 2024. All rights reserved.