Giter Site home page Giter Site logo

loopback-example-user-management's Introduction

loopback-example-user-management

⚠️ This LoopBack 3 example project is no longer maintained. Please refer to LoopBack 4 Examples instead. ⚠️

$ git clone [email protected]:strongloop/loopback-example-user-management.git
$ cd loopback-example-user-management
$ npm install
$ node .
Notes

Project Layout

  • common/models contains the extended user files. user.js contains the logic for sending emails and password reset, while user.json contains the model definition.
  • server/boot/authentication.js enables authentication middleware with the enableAuth() method. It's this middleware that finds the access token id string (usually from the query string) and appends entire token instance onto the express request object as req.accessToken. From there, you can find the user's ID: req.accessToken.userId (used in the routes.js file, see directly below).
  • server/boot/routes.js contains all the routing logic. In this example, we have used Express to configure the routing since each LoopBack app is an extended version of an Express app.
  • server/viewscontains all the views (or pages) rendered by Express using the EJS templating framework
  • server/datasources.json contains the datasource configurations. Here is where we add an email datasource.
  • server/model-config.json contains the all the model configurations. Here is where we configure the extended user model (lowercase 'u') and the email model. The rest of the models are all built-in LoopBack models.
Note

All other files have not been modified from their defaults.

How do you register a new user?

  1. Create a form to gather sign up information
  2. Create a remote hook to send a verification email
Notes
  • Upon execution, user.verify sends an email using the provided options
  • The verification email is configured to redirect the user to the /verified route in our example. For your app, you should configure the redirect to match your use case
  • The options are self-explanatory except type, template and user
    • type - value must be email
    • template - the path to the template to use for the verification email
    • user - when provided, the information in the object will be used in the verification link email

How do you send an email verification for a new user registration?

See step 2 in the previous question

How do you log in a user?

  1. Create a form to accept login credentials
  2. Create an route to handle the login request

How do you log out a user?

  1. Create a logout link with the access token embedded into the URL
  2. Call User.logout with the access token
Notes
  • We use the LoopBack token middleware to process access tokens. As long as you provide access_token in the query string of URL, the access token object will be provided in req.accessToken property in your route handler

How do you perform a password reset for a registered user?

  1. Create a form to gather password reset info
  2. Create an endpoint to handle the password reset request. Calling User.resetPassword ultimately emits a resetPasswordRequest event and creates a temporary access token
  3. Register an event handler for the resetPasswordRequest that sends an email to the registered user. In our example, we provide a URL that redirects the user to a password reset page authenticated with a temporary access token
  4. Create a password reset form for the user to enter and confirm their new password
  5. Create an endpoint to process the password reset
  • For the resetPasswordRequest handler callback, you are provided with an info object which contains information related to the user that is requesting the password reset. Note that this example is set up to send an initial email to yourself (the FROM and TO fields are the same). You will eventually want to change the address in the FROM field.

More LoopBack examples

loopback-example-user-management's People

Contributors

0candy avatar adelriosantiago avatar alfred-nsh avatar b-admike avatar bajtos avatar crandmck avatar deniselee avatar dhmlau avatar dstroot avatar jacky96623 avatar loay avatar richardpringle avatar rmg avatar sam-github avatar sequoia avatar shairez avatar siddhipai avatar simonhoibm avatar superkhau avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

loopback-example-user-management's Issues

Login with username or email, and password

Bug or feature request

  • Bug
  • Feature request

Description of feature

  • Sign up form with username, email and password.
  • Login with either "username/password" or "email/password".

How to add user details using relations ?

I have looked at the loopback angular admin project and I have not been able to find a way to add user details for the user. How can I do this ?
I want to store the users details like first name, last name and mobile number in a seperate model and and upon registration store them in their respective models. Hope it makes sense.

Handle signup errors?

This is a corollary issue to my previous one - by simply posting to the /api/users route in the example errors are not handled at all (unlike login where we have an express route that handles it and calls user.login). This is what you get when you make an error at signup:

image

<model>.verify is not a function\n

So, I try to make a model, called user-basic which bases on built-in model User.
Here's the user-basic.json:

{
  "name": "user-basic", 
  "base": "User",
  "idInjection": true, 
  "properties": {},
  "validations": [],
  "relations": {},
  "acls": [
    {
      "principalType": "ROLE",
      "principalId": "$everyone",
      "accessType": "READ",
      "permission": "ALLOW"
    }
  ],
  "methods": {}
}

Here's the user-basic.js

var config = require('../../server/config.json');
var path = require('path');


module.exports = function(UserBasic) {
          UserBasic.afterRemote('create', function(ctx, member, next) {
            console.log('> user.afterRemote triggered');
            var options = {
              type: 'email',
              to: UserBasic.email,
              from: '[email protected]',
              subject: 'Thanks for registering.',
              template: path.resolve(__dirname, '../../server/views/verify.ejs'),
              redirect: '/verified',
              user: UserBasic
            };
            UserBasic.verify(options, function(err) {
              console.log('aaaaa', member.location, err);
              if (err) {
                next(err);
              } else {
                next();
              }
            });

          });

          //send password reset link when requested
          UserBasic.on('resetPasswordRequest', function(info) {
            var url = 'http://' + config.host + ':' + config.port + '/reset-password';
            var html = 'Click <a href="' + url + '?access_token=' +
              info.accessToken.id + '">here</a> to reset your password';

            UserBasic.app.models.Email.send({
              to: info.email,
              from: info.email,
              subject: 'Password reset',
              html: html
            }, function(err) {
              if (err) return console.log('> error sending password reset email');
              console.log('> sending password reset email to:', info.email);
            });
          });
        };

In DataSource, I am using Cloudant (couchDB), here it is:

{
  "db": {
    "name": "db",
    "connector": "memory"
  }, 
  "cloudant-pop": {
    "host": "userxxx.cloudant.com",
    "port": 443,
    "url": "https://userxxx.com",
    "database": "population",
    "password": "userxxx",
    "name": "cloudant-pop",
    "connector": "couch",
    "db": "population",
    "protocol": "https",
    "auth": {
      "admin": {
       "username": "userxxx",
        "password": "userxxx"
      },
      "reader": {
        "username": "userxxx",
        "password": "userxxx"
      },
      "writer": {
        "username": "userxxx",
        "password": "userxxx"
      }
    },
    "user": "userxxx"
  }, 
  "emailDs": {
    "name": "emailDs",
    "connector": "mail",
    "transports": [
      {
        "type": "smtp",
        "host": "smtp.gmail.com",
        "secure": true,
        "port": 465,
        "tls": {
          "rejectUnauthorized": false
        },
        "auth": {
          "user": "[email protected]",
          "pass": "aaa"
        }
      }
    ]
  }
}

This is my model-config.json, Since I want to store the user credential to my Cloudant DB so I connect my user-basic model to my Cloudant Datasource:

"user-basic": {
    "dataSource": "cloudant-pop",
    "public": true,
    "options": {
      "emailVerificationRequired": true
    }
  }

I ran the server and try POST a new user via http://0.0.0.0:3008/explorer. It gives me an error:

{
  "error": {
    "name": "TypeError",
    "status": 500,
    "message": "UserBasic.verify is not a function",
    "stack": "TypeError: UserBasic.verify is not a function\n    at /Users/yogieputra/Desktop/backend_powercube/common/models/user-basic.js:23:23\n    at Function.<anonymous> (/Users/yogieputra/Desktop/backend_powercube/node_modules/loopback/lib/model.js:207:11)\n    at execStack (/Users/yogieputra/Desktop/backend_powercube/node_modules/strong-remoting/lib/remote-objects.js:480:26)\n    at RemoteObjects.execHooks (/Users/yogieputra/Desktop/backend_powercube/node_modules/strong-remoting/lib/remote-objects.js:492:10)\n    at phaseAfterInvoke (/Users/yogieputra/Desktop/backend_powercube/node_modules/strong-remoting/lib/remote-objects.js:652:10)\n    at runHandler (/Users/yogieputra/Desktop/backend_powercube/node_modules/loopback-phase/lib/phase.js:130:5)\n    at iterate (/Users/yogieputra/Desktop/backend_powercube/node_modules/loopback-phase/node_modules/async/lib/async.js:146:13)\n    at Object.async.eachSeries (/Users/yogieputra/Desktop/backend_powercube/node_modules/loopback-phase/node_modules/async/lib/async.js:162:9)\n    at runHandlers (/Users/yogieputra/Desktop/backend_powercube/node_modules/loopback-phase/lib/phase.js:139:13)\n    at iterate (/Users/yogieputra/Desktop/backend_powercube/node_modules/loopback-phase/node_modules/async/lib/async.js:146:13)"
  }
}

When I check the Database, I got the user data that I've been POST recently.
Can you guys tell me what I've been missing?
Please help

Some Doubts

I was reading your example and using in angular. I'm going to resume the process and make the question:

  1. You fill a form sending your email and requesting a reset password.
  2. The server side get this request, create a temporal token against this user email, and send a reset confirmation email to this user email attaching the token id.
  3. The user link this email and the server again take this token id and oipen a new form when the user set the new password. Accept the form.
  4. The server take this form click and the token id. The questions are:
    ¿How you can recover the user Id if this data is not send by the form?, because in your code you write this:

User.findById(req.accessToken.userId, function(err, user) { ... }

Which is the origin of this data req.accessToken.userId?, because we only have the accessToken, that is, the access token id only.

So if I must recover the user id before reseting the password, How can i recover this data from the standard api, or I must to create a custom api for this query?.

Other question is, the temporal access token created before, I must to remove it??

Regards.

Cannot Pass Email with resetPassword angular SDK

I'm using Angular 1, With custom "Profile" model that based from built in "User" model.

When I call

Profile.resetPassword({email: "[email protected]"});

It always get 400 EMAIL_REQUIRED.

I also change to fire the request via $http

$http({ method:"POST", url: CONSTANT.HOST[CONSTANT.ENV] + 'api/v1/Profiles/reset', data: { email: "[email protected]" }, headers: { "Content-Type": "application/json", "Accept": "application/json" } }

But sadly it get the 400 EMAIL_REQUIRED also.

Any suggestion?

From equals to To when resetting password

Workflow to reproduce :

  • Clone this repository and set a mail datasource.
  • Register a user
  • On the home page click on the reset password link and enter the user email entered above.
  • The user is receiving the message with a From equals to its email address.

I tested it with gmail

Sample not running

Hello,
I cloned the source code form github.
I ran a nom install and run the server.
When clicking on the register button, I am getting this error:

user.afterRemote triggered
events.js:141
throw er; // Unhandled 'error' event
^

TypeError: next is not a function
at /WebstormProjects/user-management/loopback-example-user-management/common/models/user.js:20:23
at/WebstormProjects/user-management/loopback-example-user-management/node_modules/loopback/common/models/user.js:421:11

`req.accessToken` === `null`

There is a note in README.md:

We use the LoopBack token middleware to process access tokens. As long as you provide access_token in the query string of URL, the access token object will be provided in req.accessToken property in your route handler

I provide an access_token in url and try to get it with req.accessToken in the route handler and there is no access token, null instead. How to get access token?

POST /users return Buffer object

When accesing this sample with APIConnect we cannot access the data in the response object as it is a Buffer and the current microgateway does not understand Buffer objects.

Description/Steps to reproduce

Clone the loopback-example-user-management project
npm install
apic loopback:refresh
apic edit
click into the API and then into the Assemble tab
add a new Javascript policy after the Invoke policy
try to look at the message.body in that new policy
error is thrown

Expected result

A string and/or JSON object that can be viewed

Additional information

% node -e
linux x64 6.11.0
npm ls --prod --depth 0 | grep loopback
[email protected] /home/user/loopback-example-user-management
├── [email protected]
├── [email protected]
├── [email protected]

User Management & MySQL

Running this example on memory DB, it runs perfectly.
But, using MySQL as data-source, produce the following error:

C:\loopback-example-access-control\node_modules\mysql\lib\protocol\Parser.js:77
throw err; // Rethrow non-MySQL errors
^
ValidationError: The user instance is not valid. Details: email is invalid (value: "[email protected]"); username is invalid (value: "John").,ValidationError: The user instance is not valid. Details: email is invalid (value: "[email protected]"); username is invalid (value: "Jane").,ValidationError: The user instance is not valid. Details: email is invalid (value: "[email protected]"); username is invalid (value: "Bob").

Thanks,
Tal

User verification after regsiter Error User Not Found

I'm facing an error about verification user after register. I got Error :
Error 404 User not found: 5cdce19135f71a429681864a code: USER_NOT_FOUND Error: User not found: 5cdce19135f71a429681864a at /home/project/dev/my_server/node_modules/loopback/common/models/user.js:909:19 at /home/project/dev/my_server//node_modules/loopback-datasource-juggler/lib/dao.js:1781:62 at /home/project/dev/my_server//node_modules/loopback-datasource-juggler/lib/dao.js:1717:9 at /home/project/dev/my_server/r/node_modules/async/dist/async.js:1140:9 at /home/project/dev/my_server//node_modules/async/dist/async.js:473:16 at eachOfArrayLike ( /home/project/dev/my_server/node_modules/async/dist/async.js:1057:9) at eachOf ( /home/project/dev/my_server/node_modules/async/dist/async.js:1117:5) at _asyncMap ( /home/project/dev/my_server/node_modules/async/dist/async.js:1133:5) at Object.map ( /home/project/dev/my_server/node_modules/async/dist/async.js:1122:16) at allCb ( /home/project/dev/my_server/node_modules/loopback-datasource-juggler/lib/dao.js:1628:13) at /home/project/dev/my_server/node_modules/loopback-connector-mongodb/lib/mongodb.js:1373:9 at result ( /home/project/dev/my_server/node_modules/mongodb/lib/utils.js:410:17) at executeCallback ( /home/project/dev/my_server/node_modules/mongodb/lib/utils.js:402:9) at handleCallback ( /home/project/dev/my_server/node_modules/mongodb/lib/utils.js:128:55) at cursor.close ( /home/project/dev/my_server/node_modules/mongodb/lib/operations/cursor_ops.js:224:62) at handleCallback ( /home/project/dev/my_server/node_modules/mongodb/lib/utils.js:128:55)

I've checked in my mongo database. This user already existed with that id. I extended built-in User model and here is my code :
Users.json
{ "name": "Users", "plural": "users", "base": "User", "idInjection": true, "options": { "validateUpsert": true }, "restrictResetPasswordTokenScope": true, "emailVerificationRequired": true, "excludeBaseProperties": [ "realm" ], "hidden": [ "password" ], "properties": { "name": { "type": "string", "required": true }, "email": { "type": "string", "required": true }, "password": { "type": "string", "required": true }, "image_profile": { "type": "string" }, "gender": { "type": "string" }, "location": { "type": "string" }, "user_rank": { "type": "number", "required": true, "default": 0 }, "is_third_party": { "type": "boolean", "required": true, "default": false }, "is_active": { "type": "boolean", "required": true, "default": true }, "created": { "type": "date", "required": true, "defaultFn": "now" }, "modified": { "type": "date", "required": true, "defaultFn": "now" } }, "validations": [], "relations": { "accessTokens": { "type": "hasMany", "model": "AccessTokens", "foreignKey": "userId", "option": { "disableInclude": true } } }, "acls": [], "methods": {} }
Users.js
`'use strict';
const Constant = require('../../server/utils/constants');
var path = require('path');
module.exports = function(Users) {

Users.afterRemote('create',(ctx,user,next)=>{
    var options = {
        host : Constant.serverURL,
        type : 'email',
        to : user.email,
        from : '[email protected]',
        subject: 'Thanks for registering...',
        template: path.resolve(__dirname, '../../server/views/verify.ejs'),
        text : 'Please activate your account by clicking on this link or copying and pasting it in a new browser window:\n\t{href}',
        redirect: `/verified?uid=${user.id}`,
        user: user,
        protocol: 'http',
        host : 'localhost',
        port : 6001
    }

    user.verify(options,(err,success)=>{
        if(err){
            Users.deleteById(user.id);
            return next(err);
        }
        console.log('sent verify email to use register ' + success);
    })
    next();
})

Users.afterRemote('prototype.verify', (ctx, user, next) => {
    ctx.res.render('response', {
        title: 'A Link to reverify your identity has been sent to your email successfully',
        content: 'Please check your email and click on the verification link before loggin in',
        redirectTo: '/',
        redirectToLinkText: 'Login'
    });
})

//handle verify click on email
Users.verified = (req,res,uid,next)=>{
    console.log('user verified');
    //Mapping customer role for user after register
    Users.app.models.Role.findOne({where : { name :'customer'}})
    .then(role=>{
        return Users.app.models.RoleMapping.create({
            principalType: Users.app.models.RoleMapping.USER,
            principalId: user.id,
            roleId: role.id
        }).then(mapping=>{
            return mapping;
        })
    }).then(mapping=>{
        console.log(`user has registered with role mapping ${mapping}`);
        res.render('response', {
            title: 'Verify successed, account be actived',
            content: 'You can use account to login on xper system',
            redirectTo: `http://localhost:6001`,
            redirectToLinkText: 'Log in'
        });
    }).catch(err=>{
        console.log('mapping user role error', err);
        res.render('response', {
            title: 'Verify error, account not be actived',
            content: 'Error while creating your digital wallet'
        });
    })
}

Users.remoteMethod('verified',{
    accepts: [{ arg: 'req', type: 'Object', http: { source: 'req' } },
    { arg: 'res', type: 'Object', http: { source: 'res' } },
    { arg: 'uid', type: 'string', http: { source: 'query' } },
    ],
    returns: { arg: 'result', type: 'Object', root: true },
    http: { path: '/verified', verb: 'get' },
    description: 'user verify page'
})

};
`
And here is verify URL which I got in my email
http://localhost:6001/api/users/confirm?uid=5cdce19135f71a429681864a&redirect=%2Fapi%2Fusers%2Fverified%3Fuid%3D5cdce19135f71a429681864a&token=f1cceb588ae5ee7cc2a056b55cba2b34198e622bdf4d3aeb73436766f2063cb11bea1e4cf40c90988bc60a1499b9a90369898880f958c68ddbe140147faf4456

I have no idea why got this error. Please help. Thanks

Can't create user using Signup form

loopback deprecated Routes "/methods" and "/models" are considered dangerous and should not be used.
Disable them by setting "legacyExplorer=false" in "server/config.json" or via "app.set()". node_modules/loopback/node_modules/express/lib/router/layer.js:82:5

user.afterRemote triggered
/var/www/loopback-faq-user-management/common/models/user.js:21
next(err);
^
ReferenceError: next is not defined
at /var/www/loopback-faq-user-management/common/models/user.js:21:9
at /var/www/loopback-faq-user-management/node_modules/loopback/common/models/user.js:404:11
at /var/www/loopback-faq-user-management/node_modules/loopback/node_modules/nodemailer/node_modules/nodemailer-smtp-transport/src/smtp-transport.js:102:28
at SMTPConnection._actionAUTHComplete (/var/www/loopback-faq-user-management/node_modules/loopback/node_modules/nodemailer/node_modules/nodemailer-smtp-transport/node_modules/smtp-connection/src/smtp-connection.js:838:16)
at SMTPConnection. (/var/www/loopback-faq-user-management/node_modules/loopback/node_modules/nodemailer/node_modules/nodemailer-smtp-transport/node_modules/smtp-connection/src/smtp-connection.js:242:22)
at SMTPConnection._processResponse (/var/www/loopback-faq-user-management/node_modules/loopback/node_modules/nodemailer/node_modules/nodemailer-smtp-transport/node_modules/smtp-connection/src/smtp-connection.js:506:16)
at SMTPConnection._onData (/var/www/loopback-faq-user-management/node_modules/loopback/node_modules/nodemailer/node_modules/nodemailer-smtp-transport/node_modules/smtp-connection/src/smtp-connection.js:356:10)
at TLSSocket.emit (events.js:107:17)
at readableAddChunk (_stream_readable.js:163:16)
at TLSSocket.Readable.push (_stream_readable.js:126:10)

"User"-"user" clarification

Bug or feature request

[ ] Bug
[X] Feature request

Description of feature

Another name (eg client), instead of user, to be used for the User-based model for clarification.

Does the verify process work with loopback-component-passport?

http://docs.strongloop.com/pages/releaseview.action?pageId=3836277

Loopback seems to have two separate authentication processes - the one used in this example and the passport stuff. Passport provides a separate local authentication process for users not using Oauth - i.e. a typical username/password or email/password combo.

[EDIT] I think the isomorphic client is even another wrinkle for authentication ...

I can't see how the verify process works with the passport stuff... any advice/help would be much appreciated.

Is creating a your own model user that extends the base model User best practice?

In your example you have User "public: false" and a lower case user model. Is this best practice? If it is, I feel it would be worthwhile to explicitly state that in this example documentation.

"User": {
  "dataSource": "db",
  "public": false
},
"user": {
  "dataSource": "db",
  "public": true,
  "options": {
    "emailVerificationRequired": true
  }
}

Unable to verify the email conformations link

I was able to send the link to user for verifying the link but when i clicke the link , I am getting following errors ..
This site can’t be reached The web page at http://0.0.0.0:3000/api/users/confirm?uid=1&redirect=%2Fverified&token=450fac89ef248b754d01e373f29bbcb9741a91873003e58daf2e31c2f9ddbb9b3013f404fceecc436b7973ca549930bc826d0581949ce88baa0b6c061ad90493 might be temporarily down or it may have moved permanently to a new web address.
ERR_ADDRESS_INVALID

Openshift verification link

Hi just got all this working with a few changes because I use the Angular SDK so I don't want all the server redirects. It all works fine at home but when I click the verification link which is of the form host:port/api.... the webpage hangs if I change host:port to be my website name it fires through.

Any chance somewhere in the config there could be an option to override the host port with the website name if its defined in options please? or can you suggest another change? I can't even hack the server code because Openshift builds it

Resend email to unverified user didn't use email from field correctly

Steps to reproduce:

  1. Enter email and password in "Sign up form"
  2. Pass on email
  3. Login with email and password details from step 1
  4. Click on "click here"
Error: login failed as the email has not been verified
Click here for new email to complete registration. Click home to try login again or sign up. 
  1. Result: Email uses incorrect from field
Unhandled error for request POST /api/users/4/verify: Error: Mail command failed: 553 5.7.1 Sender address rejected: not owned by auth user.

Meanwhile registration uses correct from field, and reset email works too.
Overall edits:

User.afterRemote('create', function(context, user, next) {
    var options = {
      type: 'email',
      to: user.email,
      **from: user email from datasources auth',**
      subject: 'Thanks for registering.',
      template: path.resolve(__dirname, '../../server/views/verify.ejs'),
      redirect: '/verified',
      user: user
    };
//send password reset link when requested
  User.on('resetPasswordRequest', function(info) {
    var url = 'http://' + config.host + ':' + config.port + '/reset-password';
    var html = 'Click <a href="' + url + '?access_token=' +
        info.accessToken.id + '">here</a> to reset your password';

    User.app.models.Email.send({
      to: info.email,
      **from: 'user email from datasources auth',**
      subject: 'Password reset',
      html: html
    }, function(err) {
      if (err) return console.log('> error sending password reset email');
      console.log('> sending password reset email to:', info.email);
    });
  });

Password reset failed after changing the name of the app

  • Bug
  • Feature request

Description of feature

I installed the "leum". I changed the name of the app to appCustomer by altering all appropriate files one by one. Although I can sign up, and later login, I cannot reset the password.

I enter the e-mail in the "Reset password form" and press "Reset password". Then I am directed to "http://0.0.0.0:3000/request-password-reset" page, but I never receive the email for resetting the password.

Instead, the following is displayed:

.../appCustomer/common/models/user.js:50
    User.appCustomer.models.Email.send({
                    ^
TypeError: Cannot read property 'models' of undefined
    at EventEmitter.<anonymous> (.../appCustomer/common/models/user.js:50:21)
    at emitOne (events.js:115:13)
    at EventEmitter.emit (events.js:210:7)
    at onTokenCreated (.../node_modules/loopback/common/models/user.js:973:19)
    at .../node_modules/loopback-datasource-juggler/lib/relation-definition.js:1886:13
    at .../node_modules/loopback-datasource-juggler/lib/dao.js:410:21
    at doNotify (.../node_modules/loopback-datasource-juggler/lib/observer.js:99:49)
    at doNotify (.../node_modules/loopback-datasource-juggler/lib/observer.js:99:49)
    at doNotify (...k/node_modules/loopback-datasource-juggler/lib/observer.js:99:49)
    at doNotify (/home/pavlos/Projects/apic-loopback/node_modules/loopback-datasource-juggler/lib/observer.js:99:49)
    at Function.ObserverMixin._notifyBaseObservers (.../node_modules/loopback-datasource-juggler/lib/observer.js:122:5)
    at Function.ObserverMixin.notifyObserversOf (.../node_modules/loopback-datasource-juggler/lib/observer.js:97:8)
    at Function.ObserverMixin._notifyBaseObservers (.../node_modules/loopback-datasource-juggler/lib/observer.js:120:15)
    at Function.ObserverMixin.notifyObserversOf (.../node_modules/loopback-datasource-juggler/lib/observer.js:97:8)
    at Function.ObserverMixin._notifyBaseObservers (.../node_modules/loopback-datasource-juggler/lib/observer.js:120:15)
    at Function.ObserverMixin.notifyObserversOf (.../node_modules/loopback-datasource-juggler/lib/observer.js:97:8)

node: 8.0.0
Loopback: 3.8.0
LinuxMint: 18.1 (x64)
Firefox: 53.0.3(64-bit)

Remember Me Feature

this is a feature request

can you give few hints on how should we build the remember me feature such that it can be used both on mobile apps, progressive web apps etc.

How do you get "req.accessToken"? How do you make that "accessToken" is a prop of "req"?

So you have this line in your example:

if (!req.accessToken) return res.sendStatus(401);
link: https://github.com/strongloop/loopback-example-user-management/blob/master/server/boot/routes.js#L45

Ok, looks fine. But how do you push the accessToken into req so that the accessToken can be checked out that way?

In your login route I only see this. You only return the accessToken on the client:

      res.render('home', {
        email: req.body.email,
        accessToken: token.id
      });

link https://github.com/strongloop/loopback-example-user-management/blob/master/server/boot/routes.js#L36

And what does happen then? How the accessToken is a property of req, req.accessToken?

User management using Angular SDK

Please have a version with angular SDK. I've tried creating an application using the same but got stuck with logout and password reset. Can you help?

Cant find routes.js loopback 3.x

I am following the tutorial to setup sending emails for password reset but I cant find file routes.js. I am running loopback 3.x.

How to customize the verify email link?

Hi everyone, Hi @superkhau,

I need to change the pattern of the email verify url. How to customize the verify url in this case when I using the user model extended.

The verifyHref is concatenated in verify method. But I would to define my full link.

For example: The actual link is generated like this:

http://domain:3000/?uid=XXX&redirect=YYY&verificationToken=ZZZ

I would like my link to look like this:

http://domain:3000/YYY/ZZZ

Being the YYY the user id and ZZZ the verificationToken

Someone can help?
Thanks.

Authorization header

Bug or feature request

  • Bug
  • Feature request

Description of feature (or steps to reproduce if bug)

Try to perform a request with authorization header as the example:

curl -X GET -H "Authorization: $ACCESS_TOKEN"
http://localhost:3000/api/widgets

Link to sample repo to reproduce issue (if bug)

https://github.com/strongloop/loopback-example-user-management

Expected result

Response code 200 with the json of the users

Actual result (if bug)

{"error":{"statusCode":401,"name":"Error","message":"Autorización necesaria"}}

Additional information (Node.js version, LoopBack version, etc)

strongloop v6.0.2 (node v5.11.1)

Consistent processing after a user is created?

How can I use both the api and javascript to create and verify users? The current example works great because it only posts to /api/users. However if elsewhere you call user.create in code user.afterRemote('create'... is never invoked. However user.afterCreate is invoked either way. Should the verify logic move to user.afterCreate?

// Both `user.afterRemote('create'...` *and* `user.afterCreate` are
// invoked by posting to the route `/api/users`:

// fires
user.afterRemote('create', function(context, user) {
  console.log('> user.afterRemote triggered');

  var options = { ...
  };

  user.verify(options, function(err, response) { ...
  });

});

// fires
user.afterCreate = function(next, modelInstance) {
  console.log('> user.afterCreate triggered');

  // Call next() to continue
  next();
};

// However, If you use `User.create` to create a user 
// *only* `user.afterCreate` is invoked!
// Note that `user.afterRemote` is never called after 
// creating a user via `User.create`.

// DOES NOT FIRE
user.afterRemote('create', function(context, user) {
  console.log('> user.afterRemote triggered');

  var options = { ...
  };

  user.verify(options, function(err, response) { ...
  });

});

// fires
user.afterCreate = function(next, modelInstance) {
  console.log('> user.afterCreate triggered');

  // Call next() to continue
  next();
};

This works for both posting to the api as well as using user.create however I don't know how to get access to the res so that we can render the response:

  user.afterCreate = function(next, modelInstance) {
    console.log('> user.afterCreate triggered');

    var options = {
      type: 'email',
      to: this.email,
      from: '[email protected]',
      subject: 'Thanks for registering.',
      template: path.resolve(__dirname, '../../server/views/verify.ejs'),
      redirect: '/verified',
      user: this
    };

    this.verify(options, function(err, response) {
      if (err) {
        next(err);
        return;
      }

      console.log('> verification email sent:', response);

      // context.res.render('response', {
      //   title: 'Signed up successfully',
      //   content: 'Please check your email and click on the verification link '
      //     + 'before logging in.',
      //   redirectTo: '/',
      //   redirectToLinkText: 'Log in'
      // });

    });

    // Call next() to continue
    next();

  };

Reset password BUG

Bug or feature request

  • Bug
  • Feature request

Description of feature (or steps to reproduce if bug)

Reset password set email verified false.
After 'succesfully' password reset I can't login because the email turns to not verified or don't recevie a email to re-verified the account.

Link to sample repo to reproduce issue (if bug)

https://github.com/strongloop/loopback-example-user-management

Expected result

"emailVerified": true

Actual result (if bug)

"emailVerified": false

Additional information (Node.js version, LoopBack version, etc)

strongloop v6.0.2 (node v5.11.1)

Dependencies:
"loopback-datasource-juggler": "2.44.0",
"loopback-connector-mongodb": "^1.17.0",

Unable to sign up an user

I tried using ur example to check how the code works but unfortunately after user sign up , I find a page not found error. Wondering what could be the reason. Could you please help.

P.S. I'm new to node js and finding it tough to understand. :(

How do I modify template?

Is there documentation on what variables I get back to use in my ejs templates? I want to be able to use a template that contains the ejs variables such as auth link or what not.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.