Skip to main content

Node Authentication using passport.js - Part 2

In this article, we will see how to integrate login using passport authentication.

Firstly, add the login template in views folder. create a file login.handlebars in views folder

1{{#if message}}
2 <div class="ui negative message transition hidden">
3 <i class="close icon"></i>
4 <div class="header">
5 {{message}}
6 </div>
7 </div>
8 {{/if}}
9 <div class="ui middle aligned center aligned grid container">
10 <div class="column">
11 <h2 class="ui teal image header">
12 <img src="/images/favicon.png" class="image"/>
13 <div class="content">
14 Cloudnweb.dev
15 </div>
16 </h2>
17 <form action="/login" method="POST" class="ui large form">
18 <div class="ui stacked segment">
19 <div class="field">
20 <div class="ui left icon input">
21 <i class="user icon"></i>
22 <input type="text" name="email" placeholder="Enter Email Address"/>
23 </div>
24 </div>
25 <div class="field">
26 <div class="ui left icon input">
27 <i class="lock icon"></i>
28 <input type="password" name="password" placeholder="Enter Password"/>
29 </div>
30 </div>
31 <input type="submit" class="ui fluid large teal submit button" value="Login"> </div>
32 </form>
33 <div class="ui message">
34 New Here?
35 <a href="/signup">Sign Up</a>
36 </div>
37 </div>
38 </div>

After that, we add the login routes in the routes folder. So, add the following code in routes/index.js

1app.get("/login", (req, res) => {
2 res.render("login")
3})
4
5app.post(
6 "/login",
7 passport.authenticate("local-login", {
8 successRedirect: "/",
9 failureRedirect: "/login",
10 failureFlash: true,
11 })
12)

In the above code, passport is a middleware that uses the strategy called local-login in the config/passport.js

Therefore, add the following code in config/passport.js

1passport.use(
2 "local-login",
3 new LocalStrategy(
4 {
5 // by default, local strategy uses username and password, we will override with email
6 usernameField: "email",
7 passwordField: "password",
8 passReqToCallback: true, // allows us to pass back the entire request to the callback
9 },
10 function(req, email, password, done) {
11 // callback with email and password from our form
12
13 // find a user whose email is the same as the forms email
14 // we are checking to see if the user trying to login already exists
15 User.findOne({ email: email }, function(err, user) {
16 // if there are any errors, return the error before anything else
17 if (err) return done(err)
18 console.log("user", user)
19 console.log("password", password)
20 // if no user is found, return the message
21 if (!user)
22 return done(null, false, req.flash("loginMessage", "No user found.")) // req.flash is the way to set flashdata using connect-flash
23
24 // if the user is found but the password is wrong
25 if (!user.validPassword(password))
26 return done(
27 null,
28 false,
29 req.flash("loginMessage", "Oops! Wrong password.")
30 ) // create the loginMessage and save it to session as flashdata
31
32 // all is well, return successful user
33 return done(null, user)
34 })
35 }
36 )
37)

Mainly, it checks whether the email is exists in the database and check the passport. as a result, it will return the success of the login to the route.

In conclusion, we can run the application using node app.js

Comments

Popular posts from this blog

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...