Search code examples
node.jsloopbackjsreactjs-native

getting access token after signing up in loopback


Is it possible to get access token immediately after signing up a user in loopback without having to log in the user? If so how do you go about that? Am using loopback 3


Solution

  • Here is my current snippet. You need to add a custom remote method in your common/models/account.js file (or whatever name you choose) where your Account Model inherits the built-in User Model:

    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'}
            });
    };
    

    Edit: Since the Account Model inherits the built-in User Model, you need to open the Access Control Lists (ACLs) to $everyone.

    So your common/models/account.json file should look like this:

    {
      "name": "Account",
      "base": "User",
      "idInjection": true,
      "properties": {},
      "validations": [],
      "relations": {},
      "acls": [
        {
          "principalType": "ROLE",
          "principalId": "$everyone",
          "permission": "ALLOW",
          "property": "createAndLogin"
        }
      ],
      "methods": []
    }