Week 12: Authentication and YelpCamp: Adding Authentication
Tags: javascript, webdev, codenewbie, beginners
Published: 2020-07-20 21:10:59

---
title: Week 12: Authentication and YelpCamp: Adding Authentication
published: true
description: 
tags: javascript, webdev, codenewbie, beginners
---


####This week was Authentication and YelpCamp: Adding Authentication from Colt Steele The Web Developer Bootcamp.
     -Introduction to Authentication
     -Secret Page Code Along Pt. 1
     -Secret Page Code Along Pt. 2
     -Secret Page Code Along Pt. 3
     -Secret Page Code Along Pt. 4
     -Secret Page Code Along Pt. 5
     -YelpCamp: Adding Auth Pt. 1 
     -YelpCamp: Adding Auth Pt. 2 
     -YelpCamp: Adding Auth Pt. 3 
     -YelpCamp: Adding Auth Pt. 4 


###Introduction to Authentication
We are going to be using passport.js for authentication. 
Passport.js is very commonly used. 
http://www.passportjs.org/

Passport-local
https://github.com/jaredhanson/passport-local

Passport is about providing a entry point into all different kinds of locations. 

Passport-local-mongoose

https://github.com/saintedlama/passport-local-mongoose
Authentication is made possible with sessions. 
HTTP is a stateless protocol which means when you send request, those requests are one-time things they do not contain information about history or previous request they are not linked together. A request does not have a state, it is just a one-time transaction Sessions are do keep the history and previous request it is more than just a one-time transaction. Sessions are just a way to make HTTP not stateless. 

###Secret Page Code Along Pt. 1
Getting started installing the necessary packages 
```javascript
npm install express mongoose –-save
npm install passport passport-local –-save
npm install passport-local-mongoose –save
npm install body-parser express-session –save
npm install ejs --save
```

Inside the app.js file 
```javascript 
var express = require(“express”); 
var mongoose = require(“mongoose”); 
mongoose.connect(“mongodb://localhost/auth_demo_app”); 
var app = express(); 
app.set(‘view engine’, ‘ejs’);
app.get(“/”, function(req, res) {
res.render(“home”); 
});
app.get(“/secret”, function(req,res) {
res.render(“secret”)
app.listen(process.env.PORT, process.env.IP, function() {
console.log(“server started”);
```
###Secret Page Code Along Pt. 2
In the user.js file 
```javascript 
Var mongoose = require(“mongoose”); 
Var UserSchema = new mongoose.Schema({
	username: String, 
	password: String
}); 
UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model(“User”, UserSchema);
``` 


Back in app.js
```javascript 
 app.use(require(“express-session”) ({
secret: “Rusty is the best and cutest dog in the world”, 
resave: false, 
saveUnitialized: false
})); 
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.serializeUser());
```

###Secret Page Code Along Pt. 3
```html 
<h1> Sign Up Form </h1> 
<form action=”/register” method=”POST”> 
<input type=”text” name=”username” placeholder=”username”>
<input type=”password” name=”password” placeholder=”password”>
<button>Submit</button> 
</form>
```
In app.js 
```javascript 
app.get(“/register”, function(req,res) {
res.render(“register”); 
res.send(“Register Post Route”); 
```
###Secret Page Code Along Pt. 4

Creating the log-in functionality 
Add login routes and login form 
Inside app.js we need to add two routes a POST and GET request. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ylkzxgcyuk9si20yyejm.png)

This is the form 



![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ja8f9b12g8mpwyv3liys.png)




Middleware 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/3jqbrtnyccjdejcw1i19.png)###Secret 



This is code that is supposed to run before the final route callback. It is possible to have multiple middleware stacks within each other. The idea is that middleware sits between the beginning of the route and at the end of the route 



Page Code Along Pt. 5
Add in the logout functionality and add isLoggedIn middleware to check and see if the user is actually logged in. 
A simple link is enough to logout a given user. 


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/19hqpgwu91affl8nvxfx.png)

In app.js time to add the logout functionality.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/co1pbkwxhnmg474cgzon.png)


Creating the middle ware that will check to make sure that the user is logged in to view the secret page, otherwise the user will be redirected to the log in page. 


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/lq4ks1pshyth5faaegih.png)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/igpd7zu558rcq38qe8om.png)





###YelpCamp: Adding Auth Pt. 1 

Time to add user authentication into our Yelp Camp Application. 
We are going to take the authentication concepts from the last lesson and apply them into this lesson.
First we will need to install the packages.  
```javascript 
npm install passport passport-local passport-local-mongoose express-session –save
```
In app.js 
We must make sure all the important require statements are applied. 


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/2hgx222y0ztf7niw2fc3.png)


In user.js 


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/3qm93cg11wz7e6u17kgk.png)

This sets up the user model with mongoose. 




###YelpCamp: Adding Auth Pt. 2 

Configure Passport and add register routes and templates. 
In app.js 



![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/n2y6rx0ir0ii3j0eehxj.png)


Time to add the routes and templates 

Here are the authorization routes 
The first route is to show the register form 
```javascript 
app.get(“/register”, function(req, res) {
res.render(“register”); 
}); 
```


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/86yh6kqem8nedsajt1nf.png)


Now time to create the login form 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/6igkk5lvej19xf16cx23.png)


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/zshwnzmgg1visrh28z68.png)


Now to create the route 
```javascript 
app.post(“/register”, function(req, res) {
var newUser = new User({username: req.body.username});
User.register(newUser, req.body.password, function(err, user) {
If(err) {
Console.log(err); 
Return res.render(“register”)
} 
passport.authenticate(“local”)(req, res, function(){
res.redirect(“/campgrounds”); 
}); 
});
```


###YelpCamp: Adding Auth Pt. 3 
Login needs to have two routes. GET request to show the form.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/echp6vjm25ul5taoemes.png)

And then a POST request to actually do the logging in. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/lgs357ojzwe1guw932ve.png)


This is to show the login form 
```javascript 

app.get(“/login”, function(req, res) {
res.render(“login);
}); 
```


###YelpCamp: Adding Auth Pt. 4 
Creating the logout logic and prevent anyone from accessing the new comment form without being signed in. 

First we must add the logout route 
```javascript 
app.get(“/logout”, function(req, res) {
req.logout();
res.redirect(“/campgrounds”);
```
Now we need to make the links go to the right route. 



![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/onhgmfhr676n5otbvrv7.png)


Now to prevent users that are not logged in from seeing the comment section. 
```javascript
Function isLoggedIn(req, res, next) {
If(req.isAuthenticated() {
Return next(); 
}
res.redirect(“/login”); 
}

```
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/qunu5px64wf5v3psqjtw.png)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/zrdj5p9onpy782uwiklw.png)



There has been a lot of hands-on coding for these lessons. 
I still have a lot to learn but I feel like the information is starting to make sense, because I can see how each piece of code impacts the overall project.