strongloop / loopback-example-passport

LoopBack example for facebook login
Other
185 stars 134 forks source link

how to add workflow? #20

Closed dstroot closed 9 years ago

dstroot commented 9 years ago

Say I wanted to send a welcome email after a person signs up for the first time. Where/how is the best place and method to do so? Could someone just point me in the right direction?

dstroot commented 9 years ago

I used an afterCreate model hook. Code:

user.afterCreate = function (next, modelInstance) {

    /**
     * We are going to send welcome emails to users
     * when they sign up.  So when the loopback model
     * gets created let's send them an email.
     */

    // Get the main app object
    var app = user.app;

    // Access the Email model
    var Email = app.models.Email;

    // Render Jade file to HTML
    var html = jade.renderFile(path.resolve(__dirname, '../../client/views/mail/welcome.jade'), {
      name:          this.username,  // you can access the created model via `this`
      mailtoName:    cfg.smtp.name,
      mailtoAddress: cfg.smtp.address,
      blogLink:      cfg.blogurl,
      moment:        require('moment')
    });

    // Now create email text
    var text = [
      'Hello ' + this.username + '!',
      'We would like to welcome you as our newest member!',
      'Thanks so much for using our services! If you have any questions, or suggestions, feel free to email us here at ' + cfg.smtp.address + '.',
      'If you want to get the latest scoop check out our <a href="' + cfg.blogurl + '">blog.</a>',
      '  - The ' + cfg.smtp.name + ' team'
    ].join('\n\n');

    // Create email object
    var mailOptions = {
      to:       this.username + ' <' + this.email + '>',
      from:     cfg.smtp.name + ' <' + cfg.smtp.address + '>',
      subject:  'Welcome to ' + cfg.name + '!',
      text:     text,
      html:     html
    };

    // Send welcome email
    Email.send(mailOptions, function (err, mail) {
      if (err) {
        debug('[user.js][line 114] Error: ' + err);
      } else {
        debug('Message response: ' + mail.response);
      }
    });

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

  };