0
votes

I have created a custom user model that inherits form the built-in User model. Then I added a boot script that creates a default user.

 User.create([{
   username: 'admin',
   email: '[email protected]',
   password: 'admin'
}], on_usersCreated);

This creates a document in the monogdb database,. However when I try to login, it send a 401 unauthorized request.

I tried to find the root of the problem, and it seems that loopback cannot fins such user in the database. More specifically, in node_modules/loopback/common/models/user there is this:

self.findOne({where: query}, function(err, user) {
  var defaultError = new Error('login failed');
  defaultError.statusCode = 401;
  ....

where

query = { email: "[email protected]" }

But the problem is that it cannot find a user with that email in the database although it does exist.

This is the user.json file

{
  "name": "user",
  "base": "User",
  "idInjection": true,
  "properties": {},
  "validations": [],
  "relations": {},
  "acls": [
   {
      "accessType": "*",
      "principalType": "ROLE",
      "principalId": "$everyone",
      "permission": "DENY"
   },
   {
      "accessType": "*",
      "principalType": "ROLE",
      "principalId": "admin",
      "permission": "ALLOW"
   }
 ],
 "methods": []
}
2
When you call User.create, did you assign User like var User = app.models.User or var User = app.models.user. - superkhau
User = app.models.User - ppoliani
It should be var user = app.models.user because you are extending the built-in User. - superkhau

2 Answers

1
votes

I managed to solve this issue. As @superkhau stressed out, you should use the custom User model to create the default users.

Additionally, I had to expose the user model API and hide the build-in User API; So in model-config.js

 ...
 "User": {
    "dataSource": "db",
    "public": false
 },

 "user": {
   "dataSource": "db",
   "public": true
 },
...
0
votes

You might have two collections: User and user. In your models, user extends from User. Which model did you use the create the user record?