Search code examples
node.jstwitter-bootstrapexpresspassport.jsconnect-flash

Alert message with Connect-flash and Jade


I'm building a site with login authentication using node.js, express, and Passport. For the signup page, I want the site to send a message when a username is already taken, right now the following code is working just fine, but I'd like to add an "alert" type message, with a slightly red background and highlighted text.

Code for signup.jade is this:

          div(class="col-lg-12")
                form(class="form" method="post" action="/SignupForm")
                    -if(message)
                        div#note #{message}                      
                    label(class="col-lg-12") username
                    input(type="text" name="username")
                    br
                    label(class="col-lg-12") password
                    input(type="password" name="password")
                    br
                    label(class="col-lg-12") email
                    input(type="email" name="email")
                    br
                    input(type="submit" value="Signup")

For my routes, my code is this (it is inside module.exports)

app.get('/SignupForm', function(req,res){                                       
    res.render('SignUp', {message: req.flash('signupMessage')});
});

app.post('/SignupForm', passport.authenticate('localSignup', {
    successRedirect: '/',
    failureRedirect: '/SignupForm',
    failureFlash: true
}));

And, finally, for the Passport.js file, this is the code:

passport.use('localSignup', new localStrategy({
    usernameField: 'username',
    passwordField: 'password',
    passReqToCallback: true
},
    function (req, username, password, done) {
        process.nextTick(function () {
            User.findOne({'username' : username}, function (err, user) {
                if (err)
                    return done(err);
                else if (user){
                    return done(null, false, req.flash('signupMessage', 'User already taken'));
                } else {
                    var newUser = new User({username: username, password: password);
                    newUser.save(function (err) {
                        if (err) throw err;
                        return done (null, newUser);
                    });
                }
            });
        });
    })
);

By the way, I've already tried using the bootstrap alert message, like this:

.alert.alert-danger !{ message }

But this immediately shows a highlighted area inside the signup page, even though the message has not been sent yet.


Solution

  • Not the best code, but it works.

    Jade file:

    -if(message == 'User already taken')
          .alert.alert-danger #{message}
    

    This way if no message is sent, there is no highlighted area inside the page and the message is only displayed when the jade files receives the String 'User already taken'.