Passport Authentication immediately after New User Registrationphonegap ajax user authentication with nodejs-expresss-mongo-passportjsExpress.js Passport authentication automatically fails skips strategyHow to force authentication with PassportExpress4 and passport: Unable to authenticateNodeJS: Passport authentication not workingPassport-local-mongoose : Authenticate user right after registrationHow to hash password before saving to db to be compatible with passport module (passport local)Express req.body not WorkingNodeJS Passport local authentication Is not workingNodeJS - Passport local strategy gives me 404

Party going through airport security at separate times?

I make billions (#6)

Reducing the cost of the trip from the Sydney Airport (SYD) to CBD

A sequence that changes sign finally at infinity?

QR codes, do people use them?

Need a non-volatile memory IC with near unlimited read/write operations capability

How does the Melf's Minute Meteors spell interact with the Evocation wizard's Sculpt Spells feature?

Why is the Cauchy Distribution is so useful?

Distance between horizontal tree levels

Is it okay to use open source code to do an interview task?

How insert vertex in face?

How to properly translate the key phrase of Erdoğan's 2016 letter to Putin, "kusura bakmasınlar," to Russian

First Entry Member State schengen visa

How was the Shuttle loaded and unloaded from its carrier aircraft?

Is it possible to complete a PhD in CS in 3 years?

Intern not wearing safety equipment; how could I have handled this differently?

Why does the Antonov AN-225 not have any winglets?

Finding overlapping polygons in two shapefiles and deleting them in R?

Non-Chromatic Orchestral Instruments?

When an electron changes its spin, or any other intrinsic property, is it still the same electron?

What does Middle English "bihiȝten" mean?

Can a landlord force all residents to use the landlord's in-house debit card accounts?

What does collachrimation mean?

Write a function



Passport Authentication immediately after New User Registration


phonegap ajax user authentication with nodejs-expresss-mongo-passportjsExpress.js Passport authentication automatically fails skips strategyHow to force authentication with PassportExpress4 and passport: Unable to authenticateNodeJS: Passport authentication not workingPassport-local-mongoose : Authenticate user right after registrationHow to hash password before saving to db to be compatible with passport module (passport local)Express req.body not WorkingNodeJS Passport local authentication Is not workingNodeJS - Passport local strategy gives me 404






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








14















I'm trying to authenticate and login a user immediately after submitting a POST on the /register form. Ideally, I would like users to be able to register and then be redirected immediately to the dashboard without having to enter their credentials again.



My server is using Passport 0.1.17 with the local strategy configured to use email address and password for login. The current code is:



app.post('/register', function(req, res) 

// attach POST to new User variable
var registerUser = new User( email: req.body.email, password: req.body.password, name: req.body.name );

// save registerUser Mongo
registerUser.save(function(err)
if(err)
console.log(err);
else
console.log('registerUser: ' + registerUser.email + " saved.");

);

// here is where I am trying to authenticate and then redirect
passport.authenticate('local', failureRedirect: '/login', failureFlash: true ),
res.redirect('/dashboard');
);


How would I refactor this code to save the new user, then authenticate and finally redirect to the dashboard?



Thanks in advance!










share|improve this question



















  • 2





    Use req.logIn method to authenticate straight after registration.

    – moka
    Jul 30 '13 at 21:46











  • Thanks for referencing req.logIn, which I was previously unaware of. Can you provide more specific code. I tried the following after the final comment in the question above, but it did not work: req.login(registerUser, function(err) if (err) return next(err); return res.redirect('/dashboard'); );

    – surfearth
    Jul 30 '13 at 22:30












  • You need to provide details that are used to deserialize user, usually it is ID of a user that is stored in a session.

    – moka
    Jul 30 '13 at 22:41

















14















I'm trying to authenticate and login a user immediately after submitting a POST on the /register form. Ideally, I would like users to be able to register and then be redirected immediately to the dashboard without having to enter their credentials again.



My server is using Passport 0.1.17 with the local strategy configured to use email address and password for login. The current code is:



app.post('/register', function(req, res) 

// attach POST to new User variable
var registerUser = new User( email: req.body.email, password: req.body.password, name: req.body.name );

// save registerUser Mongo
registerUser.save(function(err)
if(err)
console.log(err);
else
console.log('registerUser: ' + registerUser.email + " saved.");

);

// here is where I am trying to authenticate and then redirect
passport.authenticate('local', failureRedirect: '/login', failureFlash: true ),
res.redirect('/dashboard');
);


How would I refactor this code to save the new user, then authenticate and finally redirect to the dashboard?



Thanks in advance!










share|improve this question



















  • 2





    Use req.logIn method to authenticate straight after registration.

    – moka
    Jul 30 '13 at 21:46











  • Thanks for referencing req.logIn, which I was previously unaware of. Can you provide more specific code. I tried the following after the final comment in the question above, but it did not work: req.login(registerUser, function(err) if (err) return next(err); return res.redirect('/dashboard'); );

    – surfearth
    Jul 30 '13 at 22:30












  • You need to provide details that are used to deserialize user, usually it is ID of a user that is stored in a session.

    – moka
    Jul 30 '13 at 22:41













14












14








14


6






I'm trying to authenticate and login a user immediately after submitting a POST on the /register form. Ideally, I would like users to be able to register and then be redirected immediately to the dashboard without having to enter their credentials again.



My server is using Passport 0.1.17 with the local strategy configured to use email address and password for login. The current code is:



app.post('/register', function(req, res) 

// attach POST to new User variable
var registerUser = new User( email: req.body.email, password: req.body.password, name: req.body.name );

// save registerUser Mongo
registerUser.save(function(err)
if(err)
console.log(err);
else
console.log('registerUser: ' + registerUser.email + " saved.");

);

// here is where I am trying to authenticate and then redirect
passport.authenticate('local', failureRedirect: '/login', failureFlash: true ),
res.redirect('/dashboard');
);


How would I refactor this code to save the new user, then authenticate and finally redirect to the dashboard?



Thanks in advance!










share|improve this question
















I'm trying to authenticate and login a user immediately after submitting a POST on the /register form. Ideally, I would like users to be able to register and then be redirected immediately to the dashboard without having to enter their credentials again.



My server is using Passport 0.1.17 with the local strategy configured to use email address and password for login. The current code is:



app.post('/register', function(req, res) 

// attach POST to new User variable
var registerUser = new User( email: req.body.email, password: req.body.password, name: req.body.name );

// save registerUser Mongo
registerUser.save(function(err)
if(err)
console.log(err);
else
console.log('registerUser: ' + registerUser.email + " saved.");

);

// here is where I am trying to authenticate and then redirect
passport.authenticate('local', failureRedirect: '/login', failureFlash: true ),
res.redirect('/dashboard');
);


How would I refactor this code to save the new user, then authenticate and finally redirect to the dashboard?



Thanks in advance!







node.js authentication express passport.js






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 6 '15 at 22:49









laggingreflex

15.4k20 gold badges98 silver badges157 bronze badges




15.4k20 gold badges98 silver badges157 bronze badges










asked Jul 30 '13 at 21:22









surfearthsurfearth

1,5972 gold badges14 silver badges28 bronze badges




1,5972 gold badges14 silver badges28 bronze badges







  • 2





    Use req.logIn method to authenticate straight after registration.

    – moka
    Jul 30 '13 at 21:46











  • Thanks for referencing req.logIn, which I was previously unaware of. Can you provide more specific code. I tried the following after the final comment in the question above, but it did not work: req.login(registerUser, function(err) if (err) return next(err); return res.redirect('/dashboard'); );

    – surfearth
    Jul 30 '13 at 22:30












  • You need to provide details that are used to deserialize user, usually it is ID of a user that is stored in a session.

    – moka
    Jul 30 '13 at 22:41












  • 2





    Use req.logIn method to authenticate straight after registration.

    – moka
    Jul 30 '13 at 21:46











  • Thanks for referencing req.logIn, which I was previously unaware of. Can you provide more specific code. I tried the following after the final comment in the question above, but it did not work: req.login(registerUser, function(err) if (err) return next(err); return res.redirect('/dashboard'); );

    – surfearth
    Jul 30 '13 at 22:30












  • You need to provide details that are used to deserialize user, usually it is ID of a user that is stored in a session.

    – moka
    Jul 30 '13 at 22:41







2




2





Use req.logIn method to authenticate straight after registration.

– moka
Jul 30 '13 at 21:46





Use req.logIn method to authenticate straight after registration.

– moka
Jul 30 '13 at 21:46













Thanks for referencing req.logIn, which I was previously unaware of. Can you provide more specific code. I tried the following after the final comment in the question above, but it did not work: req.login(registerUser, function(err) if (err) return next(err); return res.redirect('/dashboard'); );

– surfearth
Jul 30 '13 at 22:30






Thanks for referencing req.logIn, which I was previously unaware of. Can you provide more specific code. I tried the following after the final comment in the question above, but it did not work: req.login(registerUser, function(err) if (err) return next(err); return res.redirect('/dashboard'); );

– surfearth
Jul 30 '13 at 22:30














You need to provide details that are used to deserialize user, usually it is ID of a user that is stored in a session.

– moka
Jul 30 '13 at 22:41





You need to provide details that are used to deserialize user, usually it is ID of a user that is stored in a session.

– moka
Jul 30 '13 at 22:41












2 Answers
2






active

oldest

votes


















22














Here's the solution I came up with after reading about req.login:



app.post('/register', function(req, res) 
// attach POST to user schema
var user = new User( email: req.body.email, password: req.body.password, name: req.body.name );
// save in Mongo
user.save(function(err)
if(err)
console.log(err);
else
console.log('user: ' + user.email + " saved.");
req.login(user, function(err)
if (err)
console.log(err);

return res.redirect('/dashboard');
);

);
);


I would like to clean it up a bit and think that the err section could be more robust, but this is a functioning solution. Note that is someone else implements this, they should be aware that it is tailored to using the passport-local strategy with email instead of username.






share|improve this answer


















  • 1





    Query from a newbie: does that mean you’re storing the user’s password as plain text in your database? So if someone gets your database, they can read your user’s password?

    – Paul D. Waite
    Jul 15 '14 at 18:55







  • 2





    @Paul D. White: I know this is old, but to answer your question for the benefit of future readers, it is common to handle encryption within the User model class itself, in a way that is transparent to the rest of the application (which has the benefit of making it unavoidable).

    – Matt
    Mar 14 '15 at 23:48











  • @Matt: nice, cheers cheers.

    – Paul D. Waite
    Mar 15 '15 at 17:31


















0














I think you're looking for the register method, which will register (and hide the password)



https://www.npmjs.com/package/passport-local-mongoose (search the register method).



app.post('/register', function(req, res) 

// New user variable created.
// Note: Password is not part of the new User variable; you don't want to simply store sensitive information in the database.
var registerUser = new User( email: req.body.email, name: req.body.name );

// Register new user. Note the 2nd variable (password). If registration's successful (no errors), redirect.
registerUser.register(registerUser, req.body.password, function (err, newUser)
if(!err)
passport.authenticate('local', req, res, function()
res.redirect('/dashboard');
);

);
);





share|improve this answer



























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f17957650%2fpassport-authentication-immediately-after-new-user-registration%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    22














    Here's the solution I came up with after reading about req.login:



    app.post('/register', function(req, res) 
    // attach POST to user schema
    var user = new User( email: req.body.email, password: req.body.password, name: req.body.name );
    // save in Mongo
    user.save(function(err)
    if(err)
    console.log(err);
    else
    console.log('user: ' + user.email + " saved.");
    req.login(user, function(err)
    if (err)
    console.log(err);

    return res.redirect('/dashboard');
    );

    );
    );


    I would like to clean it up a bit and think that the err section could be more robust, but this is a functioning solution. Note that is someone else implements this, they should be aware that it is tailored to using the passport-local strategy with email instead of username.






    share|improve this answer


















    • 1





      Query from a newbie: does that mean you’re storing the user’s password as plain text in your database? So if someone gets your database, they can read your user’s password?

      – Paul D. Waite
      Jul 15 '14 at 18:55







    • 2





      @Paul D. White: I know this is old, but to answer your question for the benefit of future readers, it is common to handle encryption within the User model class itself, in a way that is transparent to the rest of the application (which has the benefit of making it unavoidable).

      – Matt
      Mar 14 '15 at 23:48











    • @Matt: nice, cheers cheers.

      – Paul D. Waite
      Mar 15 '15 at 17:31















    22














    Here's the solution I came up with after reading about req.login:



    app.post('/register', function(req, res) 
    // attach POST to user schema
    var user = new User( email: req.body.email, password: req.body.password, name: req.body.name );
    // save in Mongo
    user.save(function(err)
    if(err)
    console.log(err);
    else
    console.log('user: ' + user.email + " saved.");
    req.login(user, function(err)
    if (err)
    console.log(err);

    return res.redirect('/dashboard');
    );

    );
    );


    I would like to clean it up a bit and think that the err section could be more robust, but this is a functioning solution. Note that is someone else implements this, they should be aware that it is tailored to using the passport-local strategy with email instead of username.






    share|improve this answer


















    • 1





      Query from a newbie: does that mean you’re storing the user’s password as plain text in your database? So if someone gets your database, they can read your user’s password?

      – Paul D. Waite
      Jul 15 '14 at 18:55







    • 2





      @Paul D. White: I know this is old, but to answer your question for the benefit of future readers, it is common to handle encryption within the User model class itself, in a way that is transparent to the rest of the application (which has the benefit of making it unavoidable).

      – Matt
      Mar 14 '15 at 23:48











    • @Matt: nice, cheers cheers.

      – Paul D. Waite
      Mar 15 '15 at 17:31













    22












    22








    22







    Here's the solution I came up with after reading about req.login:



    app.post('/register', function(req, res) 
    // attach POST to user schema
    var user = new User( email: req.body.email, password: req.body.password, name: req.body.name );
    // save in Mongo
    user.save(function(err)
    if(err)
    console.log(err);
    else
    console.log('user: ' + user.email + " saved.");
    req.login(user, function(err)
    if (err)
    console.log(err);

    return res.redirect('/dashboard');
    );

    );
    );


    I would like to clean it up a bit and think that the err section could be more robust, but this is a functioning solution. Note that is someone else implements this, they should be aware that it is tailored to using the passport-local strategy with email instead of username.






    share|improve this answer













    Here's the solution I came up with after reading about req.login:



    app.post('/register', function(req, res) 
    // attach POST to user schema
    var user = new User( email: req.body.email, password: req.body.password, name: req.body.name );
    // save in Mongo
    user.save(function(err)
    if(err)
    console.log(err);
    else
    console.log('user: ' + user.email + " saved.");
    req.login(user, function(err)
    if (err)
    console.log(err);

    return res.redirect('/dashboard');
    );

    );
    );


    I would like to clean it up a bit and think that the err section could be more robust, but this is a functioning solution. Note that is someone else implements this, they should be aware that it is tailored to using the passport-local strategy with email instead of username.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Jul 31 '13 at 14:33









    surfearthsurfearth

    1,5972 gold badges14 silver badges28 bronze badges




    1,5972 gold badges14 silver badges28 bronze badges







    • 1





      Query from a newbie: does that mean you’re storing the user’s password as plain text in your database? So if someone gets your database, they can read your user’s password?

      – Paul D. Waite
      Jul 15 '14 at 18:55







    • 2





      @Paul D. White: I know this is old, but to answer your question for the benefit of future readers, it is common to handle encryption within the User model class itself, in a way that is transparent to the rest of the application (which has the benefit of making it unavoidable).

      – Matt
      Mar 14 '15 at 23:48











    • @Matt: nice, cheers cheers.

      – Paul D. Waite
      Mar 15 '15 at 17:31












    • 1





      Query from a newbie: does that mean you’re storing the user’s password as plain text in your database? So if someone gets your database, they can read your user’s password?

      – Paul D. Waite
      Jul 15 '14 at 18:55







    • 2





      @Paul D. White: I know this is old, but to answer your question for the benefit of future readers, it is common to handle encryption within the User model class itself, in a way that is transparent to the rest of the application (which has the benefit of making it unavoidable).

      – Matt
      Mar 14 '15 at 23:48











    • @Matt: nice, cheers cheers.

      – Paul D. Waite
      Mar 15 '15 at 17:31







    1




    1





    Query from a newbie: does that mean you’re storing the user’s password as plain text in your database? So if someone gets your database, they can read your user’s password?

    – Paul D. Waite
    Jul 15 '14 at 18:55






    Query from a newbie: does that mean you’re storing the user’s password as plain text in your database? So if someone gets your database, they can read your user’s password?

    – Paul D. Waite
    Jul 15 '14 at 18:55





    2




    2





    @Paul D. White: I know this is old, but to answer your question for the benefit of future readers, it is common to handle encryption within the User model class itself, in a way that is transparent to the rest of the application (which has the benefit of making it unavoidable).

    – Matt
    Mar 14 '15 at 23:48





    @Paul D. White: I know this is old, but to answer your question for the benefit of future readers, it is common to handle encryption within the User model class itself, in a way that is transparent to the rest of the application (which has the benefit of making it unavoidable).

    – Matt
    Mar 14 '15 at 23:48













    @Matt: nice, cheers cheers.

    – Paul D. Waite
    Mar 15 '15 at 17:31





    @Matt: nice, cheers cheers.

    – Paul D. Waite
    Mar 15 '15 at 17:31













    0














    I think you're looking for the register method, which will register (and hide the password)



    https://www.npmjs.com/package/passport-local-mongoose (search the register method).



    app.post('/register', function(req, res) 

    // New user variable created.
    // Note: Password is not part of the new User variable; you don't want to simply store sensitive information in the database.
    var registerUser = new User( email: req.body.email, name: req.body.name );

    // Register new user. Note the 2nd variable (password). If registration's successful (no errors), redirect.
    registerUser.register(registerUser, req.body.password, function (err, newUser)
    if(!err)
    passport.authenticate('local', req, res, function()
    res.redirect('/dashboard');
    );

    );
    );





    share|improve this answer





























      0














      I think you're looking for the register method, which will register (and hide the password)



      https://www.npmjs.com/package/passport-local-mongoose (search the register method).



      app.post('/register', function(req, res) 

      // New user variable created.
      // Note: Password is not part of the new User variable; you don't want to simply store sensitive information in the database.
      var registerUser = new User( email: req.body.email, name: req.body.name );

      // Register new user. Note the 2nd variable (password). If registration's successful (no errors), redirect.
      registerUser.register(registerUser, req.body.password, function (err, newUser)
      if(!err)
      passport.authenticate('local', req, res, function()
      res.redirect('/dashboard');
      );

      );
      );





      share|improve this answer



























        0












        0








        0







        I think you're looking for the register method, which will register (and hide the password)



        https://www.npmjs.com/package/passport-local-mongoose (search the register method).



        app.post('/register', function(req, res) 

        // New user variable created.
        // Note: Password is not part of the new User variable; you don't want to simply store sensitive information in the database.
        var registerUser = new User( email: req.body.email, name: req.body.name );

        // Register new user. Note the 2nd variable (password). If registration's successful (no errors), redirect.
        registerUser.register(registerUser, req.body.password, function (err, newUser)
        if(!err)
        passport.authenticate('local', req, res, function()
        res.redirect('/dashboard');
        );

        );
        );





        share|improve this answer















        I think you're looking for the register method, which will register (and hide the password)



        https://www.npmjs.com/package/passport-local-mongoose (search the register method).



        app.post('/register', function(req, res) 

        // New user variable created.
        // Note: Password is not part of the new User variable; you don't want to simply store sensitive information in the database.
        var registerUser = new User( email: req.body.email, name: req.body.name );

        // Register new user. Note the 2nd variable (password). If registration's successful (no errors), redirect.
        registerUser.register(registerUser, req.body.password, function (err, newUser)
        if(!err)
        passport.authenticate('local', req, res, function()
        res.redirect('/dashboard');
        );

        );
        );






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 25 at 23:13

























        answered Mar 25 at 22:44









        daCodadaCoda

        1,3683 gold badges15 silver badges22 bronze badges




        1,3683 gold badges15 silver badges22 bronze badges



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f17957650%2fpassport-authentication-immediately-after-new-user-registration%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현