strongloop / loopback-example-passport

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

It is hard to use this loopback-example-passport because ... #32

Closed OwenBrotherwood closed 7 years ago

OwenBrotherwood commented 9 years ago

... I think the structure of the slc loopback default app has changed since the writing of this.

Currently, I am trying to find out how passport parts should be placed in the current slc loopback app.

I feel that ../boot/.js should be used instead of placing all the passport components in server.js

mailuser41 commented 9 years ago

Agree @OwenBrotherwood I figured out the same... how to move the app.get and app.post to another js...

artmunro commented 8 years ago

Agree. This example should show the steps in documentation to add passport to ANY project. This should be something like this...

  1. start with base loopback scaffolding
  2. Add passport components
  3. Add required files for model, configs, and routes
  4. Add sample client files to call given routes.

thoughts? Art

superkhau commented 8 years ago

@OwenBrotherwood @artmunro This example is definitely outdated and needs a refreshing. @jannyHou Can you take care of this?

jannyHou commented 8 years ago

@superkhau thank you I will take a look and update the steps to build the example with base scaffolding, btw, is this example going to be merged into another one?

superkhau commented 8 years ago

@jannyHou No, it won't be merged anymore. It'll remain standalone.

ddbaron commented 8 years ago

@jannyHou Thank you for doing this, what's the ETA on the refactoring?

jannyHou commented 8 years ago

@ddbaron To be honest this is not on our priority at this moment. But I am looking into issues in loopback-component-passport and will have a better understanding on the refactor job. I will post my proposal here for a public discussion in the future.

hackerunet commented 8 years ago

I'm sorry but, @ddbaron I totally disagree with you, your priority to provide documentation and accurate examples is for yourselves or to possible programmers using loopback? There are tons of comments in several loopback discussions regarding the right way to implement a passport-local strategy and few actually works. This is also my case, how can you say that loopback is as amazing as you say if cannot provide a simple authentication example for MVC based applications? You should say in your website ALERT PROGRAMMERS: IF YOU WANT MVC GO AWAY BECAUSE THIS DOESN'T SUPPORT THAT. No accurate examples that only confuses even more possible programmers and you are still saying loopback is the best over MEAN, over SAILS over everything? Please kill me now. this is my case:

Also Can Anyone help me out on this? in this example https://github.com/strongloop/loopback-example-passport/blob/master/server/server.js providers.json file setup a local strategy which has the following configuration:

{
  "local": {
    "provider": "local",
    "module": "passport-local",
    "usernameField": "email",
    "passwordField": "password",
    "authPath": "/auth/local",
    "successRedirect": "/app",
    "failureRedirect": "/login",
    "failureFlash": true
  }
}

It means that my post from login will submit username and password to the url /auth/local , so, When I do this I get nothing at all following all instructions from https://docs.strongloop.com/display/public/LB/Third-party+login+using+Passport https://github.com/strongloop/loopback-example-passport

So, I need to know 1) How can I get the flash messages back to /login url which is serving a view 2) How to pass a callback to the login process in order to console.log everything and see outputs This is my server login url:

app.get('/login', function(req, res, next) {
  res.render('public/login.ejs',
  {
    user:req.user,
    url: req.url,
    layout:'layouts/public.ejs'
  });
});

I have nothing declared in server.js that handles the /auth/local so I'm counting on passport loopback component. also, Why in this example: https://github.com/strongloop/loopback-example-passport We see an after signup auto login function and not a single basic login function working with passport using a local strategy?, is not very clear this part in the example, but if someone can help me to understand this will be great. regards server.js script:

'use strict';

// Basic variables declaration for environment
var loopback = require('loopback');
var boot = require('loopback-boot');
var app = module.exports = loopback();
var expressLayouts = require('express-ejs-layouts');

// Passport configurators..
var loopbackPassport = require('loopback-component-passport');
var PassportConfigurator = loopbackPassport.PassportConfigurator;
var passportConfigurator = new PassportConfigurator(app);

/*
 * body-parser is a piece of express middleware that
 *   reads a form's input and stores it as a javascript
 *   object accessible through `req.body`
 *
 */
var bodyParser = require('body-parser');

/**
 * Flash messages for passport
 *
 * Setting the failureFlash option to true instructs Passport to flash an
 * error message using the message given by the strategy's verify callback,
 * if any. This is often the best approach, because the verify callback
 * can make the most accurate determination of why authentication failed.
 */
var flash      = require('express-flash');

// attempt to build the providers/passport config
var config = {};
try {
  config = require('../config/providers.json');
} catch (err) {
  console.trace(err);
  process.exit(1); // fatal
}

// -- Add your pre-processing middleware here --

// Setup the view engine (jade)
var path = require('path');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(expressLayouts);
// boot scripts mount components like REST API
boot(app, __dirname);
// to support JSON-encoded bodies
app.middleware('parse', bodyParser.json());
// to support URL-encoded bodies
app.middleware('parse', bodyParser.urlencoded({
  extended: true
}));

// The access token is only available after boot
app.middleware('auth', loopback.token({
  model: app.models.accessToken,
}));

app.middleware('session:before', loopback.cookieParser(app.get('cookieSecret')));
app.middleware('session', loopback.session({
  secret: 'asdf#$%&34563456',
  saveUninitialized: true,
  resave: true
}));
passportConfigurator.init();

// We need flash messages to see passport errors
app.use(flash());

passportConfigurator.setupModels({
  userModel: app.models.smart_account,
  userIdentityModel: app.models.smart_identity,
  userCredentialModel: app.models.smart_credential
});
for (var s in config) {
  var c = config[s];
  c.session = c.session !== false;
  passportConfigurator.configureProvider(s, c);
}
var ensureLoggedIn = require('connect-ensure-login').ensureLoggedIn;

app.get('/login', function(req, res, next) {
  res.render('public/login.ejs',
  {
    user:req.user,
    url: req.url,
    layout:'layouts/public.ejs'
  });
});

app.get('/signup', function(req, res, next) {
  res.render('public/signup.ejs', {
    user: req.user,
    url: req.url
  });
});

app.post('/signup', function(req, res, next) {
  var User = app.models.smart_account;

  var newUser = {};
  newUser.email = req.body.email.toLowerCase();
  newUser.username = req.body.username.trim();
  newUser.password = req.body.password;

  User.create(newUser, function(err, user) {
    if (err) {
      req.flash('error', err.message);
      return res.redirect('back');
    } else {
      // Passport exposes a login() function on req (also aliased as logIn())
      // that can be used to establish a login session. This function is
      // primarily used when users sign up, during which req.login() can
      // be invoked to log in the newly registered user.
      req.login(user, function(err) {
        if (err) {
          req.flash('error', err.message);
          return res.redirect('back');
        }
        return res.redirect('/app');
      });
    }
  });
});

app.get('/logout', function(req, res, next) {
  req.logout();
  res.redirect('/login');
});

app.get('/app', ensureLoggedIn('/login'), function(req, res, next) {
  res.render('private/app.ejs', {
    user: req.user,
    url: req.url,
  });
});

app.start = function() {
  // start the web server
  return app.listen(function() {
    app.emit('started');
    var baseUrl = app.get('url').replace(/\/$/, '');
    console.log('Web server listening at: %s', baseUrl);
    if (app.get('loopback-component-explorer')) {
      var explorerPath = app.get('loopback-component-explorer').mountPath;
      console.log('Browse your REST API at %s%s', baseUrl, explorerPath);
    }
  });
};

// start the server if `$ node server.js`
if (require.main === module) {
  app.start();
}
smyth64 commented 7 years ago

Really sad that strongloop is doing nothing about this problems! I'm really angry :(

hackerunet commented 7 years ago

Lack of documentation is a problem for developers, i had to abandon strongloop it was a time waste, really sad. El 10/02/2017 09:46, "Smithi" notifications@github.com escribió:

Really sad that strongloop is doing nothing about this problems! I'm really angry :(

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/strongloop/loopback-example-passport/issues/32#issuecomment-278945376, or mute the thread https://github.com/notifications/unsubscribe-auth/AA2xqJOFY3EEETOD1KxAAI96M-aoeDv3ks5rbGo2gaJpZM4ECvg6 .

OwenBrotherwood commented 7 years ago

same here

superkhau commented 7 years ago

Really sad that strongloop is doing nothing about this problems! I'm really angry :(

I wouldn't say nothing. ;) We are all busy on various things, but I'll see if we can give you a hand. As we are also a community project, you are free to contribute updates too. ;)

@raymondfeng Should we dedicate some time to updating this example to make sure it works for some of the above use cases described? There is obvious frustration here with the current example.

smyth64 commented 7 years ago

@superkhau Yes please merge my pull request.

Nothing is more annoying than using a demo that doesn't work. People want to use this in production. I had to invest about 8 hours to understand all the code and implement this fix. I don't want anybody else to feel this pain :)

superkhau commented 7 years ago

@smith64fx Thank you for the PR. I agree, broken demos are a pain. The good thing is we have community members like you who are willing to share solutions. :+1: Will get it landed.

hackerunet commented 7 years ago

Well, the problem is no standarization about the procedures to accomplish a small job so production is not going to be as companies usually expect to be. Strongloop cannot be used in production of new software if timeframes are a concern.

superkhau commented 7 years ago

Well, the problem is no standarization about the procedures to accomplish a small job so production is not going to be as companies usually expect to be. Strongloop cannot be used in production of new software if timeframes are a concern.

This is definitely a valid concern. These are things that have been in place for a long time now, I've taken the initiative to make things more transparent for our community (it's obviously taking time to spur change), but know for sure things will change as part of the work we're doing on the next version of loopback.

For example, I've come up with a small list of principles, such as "Community first" -- to prevent barrier to entry, put yourself in the shoes of a new user before releasing things, etc. It's as you said though, the protocols are not fully set in stone/documented ATM.

First things first is to make a set of transparent principles and get community consensus. Anyways, some other ideas include actual board of community maintainers with repo access so that we don't take on all the work ourselves (such as applying labels, figuring out which repos are suffering like this one, etc). The backlog of things to do is big, but this should give you a bit of insight into the things being planned for 2017.

stale[bot] commented 7 years ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.