getting access token after signing up in loopback

333 Views Asked by At

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

2

There are 2 best solutions below

2
On BEST ANSWER

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": []
}
0
On

I would add an after remote hook to the users/create remote method, so after it's successfully called you can call User.login() (to get the access token) with the password that you probably can get from the request object. So after register request, you'd get the access token in the response.