Second React Assignment

In the last section of react tutorials I learned about working with lists and conditionals. I learn how to make react render content conditionally. I ended up being able to show lists only when…

In the last section of react tutorials I learned about working with lists and conditionals. I learn how to make react render content conditionally. I ended up being able to show lists only when a condition was meet by the user. The most important thing I learned during this section was updating state immutably. This part talked about why its important never to directly change state. Instead we can copy arrays or objects using the split method which takes the information we want to change inside state and makes us a copy. Once we changes to the copies , we then update the state using setState. This allowed us to change the state without mutating it directly. Learning how to not change the state directly helps us be able to create a stable application with less bugs.

For the second assignment we had to take what we learned about creating lists, conditional, and state immutably. Then create a text box where the user inputs a name and then the length of the text is shown. We also had to add if the text the user entered was too short or too long. We then had to create inline boxes and these boxes would hold which letter the user entered. After this we had to create a click handler which deleted a letter the user clicked inside the boxes.

This is my code

 

 

Adding Authentication to YelpCamp

This week I worked on adding authentication to the YelpCamp app I was building through the bootcamp tutorials. I used the npms express-session, passport, passport-local, and passport-local-mongoose. The first I did was call the…

This week I worked on adding authentication to the YelpCamp app I was building through the bootcamp tutorials. I used the npms express-session, passport, passport-local, and passport-local-mongoose. The first I did was call the npms and configure passport so that it ran properly on the app. This included making the app start a session when a user logged in and make sure that passport was able to run user authentication method.

//Passport Configuration
app.use(require("express-session")({
    secret:"This is the YelpCamp secret!",
    resave: false,
    saveUninitialize: false
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

After setting up passport I created a user model that was then imported into our main app file. In this user model my user mongoose schema is held. We also called passport-local-mongoose which allowed us to export our user schema with access to passport methods.

var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");

var UserSchema = new mongoose.Schema({
    
    username: String,
    password: String
    
});

UserSchema.plugin(passportLocalMongoose);

module.exports = mongoose.model("User", UserSchema);

Once I had my user model was working properly I started creating the signup, login, and logout routes. The first routes I created were the sign up routes which was making sure the register page was called and then having the post route which handled he sign up logic. Then I created the register page which was an ejs file and it contained the registration form.

app.get("/register", function(req, res) {
    res.render("register");
});

//handle sign up logic

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"); 
        });
    });
});

<% include ./partials/header %>
<h1> Sign Up! </h1>

<form action="/register" method="POST">
    <input type="text" name="username" placeholder="username"/>
    <input type="password" name="password" placeholder="password"/>
    <button> Sign Up </button>
</form>

<% include ./partials/footer %>

The second set of routes I created were the login routes. The first route held the call for the sign page and then the second route handled the login logic. The second route I had to place a middle ware that made sure the user logging was authenticated before sending them to a different page. After both routes were running I created the ejs file that held the login form.

//show login form
app.get("/login", function(req, res){
    res.render("login");
});
// handling login logic
app.post("/login", passport.authenticate("local", 
    {
        successRedirect:"/campgrounds", 
        failureRedirect:"/login"
    }), function(req, res) {
        
});

<% include ./partials/header %>
<h1> Login! </h1>

<form action="/login" method="POST">
    <input type="text" name="username" placeholder="username"/>
    <input type="password" name="password" placeholder="password"/>
    <input type="submit" value="Login"/>
</form>

<% include ./partials/footer %>

The last route that I had to include was the log out page for which I had to only create one route because passport allows us to use a method that automatically runs the logic needed to log out a user. Then once the user was logged out I redirected them to a different page.

//logout route
app.get("/logout", function(req, res) {
    req.logout();
    res.redirect("/campgrounds");
})

The last thing thing I worked on this section was making sure that the right links were showing when a user was logged out and when they were logged in. This involved showing the login and sign up links when a user was not logged in and only showing the log out link when they were logged in. I also made sure that a user wasn’t able to add comments to a post when they were logged in. To do this I had to create a middleware that detected if a user was logged in and the add it to the comment routes. If a user wasn’t logged in and tried to add a comment it would then send them to the login page.

//middleware
function isLoggedIn(req, res, next){
    if(req.isAuthenticated()){
        return next();
    }
    res.redirect("/login");
}

<!DOCTYPE html>
<html>
 
    <header>
        <title> YelpCamp </title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <link rel="stylesheet" href="/stylesheets/main.css">
    </header>
    
    <body>
        
        <nav class="navbar navbar-default">
            <div class="container-fluid">
                <div class="navbar-header">
                    <a class="navbar-brand" href="/"> YelpCamp </a>
                </div>
                <div class="collapse navbar-collapse">
                    <ul class="nav navbar-nav navbar-right">
                        <% if(!currentUser){ %>
                        <li> <a href="/login"> Login </a> </li>
                        <li> <a href="/register"> Sign Up </a> </li>
                        <% }else{ %>
                        <li> <a href="#"> Signed in as <%= currentUser.username %> </a> </li>
                        <li> <a href="/logout"> Logout </a> </li>
                        <% } %>
                    </ul>
                </div>
            </div>
        </nav>

It was great learning about user authentication and I’m also 2-3 sections away from deploying this app so I’m really looking forward to learning how to deploy it.

First assignment with React

In the last few days I’ve been learning how to use react and finally got through some of the basics. After going through some of the basics I had to do a small assignment….

In the last few days I’ve been learning how to use react and finally got through some of the basics. After going through some of the basics I had to do a small assignment.

The instructions were:

  • Create TWO new components: UserInput and UserOutput
  • UserInput should hold an input element, UserOutput two paragraphs
  • Output multiple UserOutput components in the App component (any paragraph texts of your choice)
  • Pass a username (of your choice) to UserOutput via props and display it there
  • Add state to the App component (=> the username) and pass the username to the UserOutput component
  • Add a method to manipulate the state (=> an event-handler method)
  • Pass the event-handler method reference to the UserInput component and bind it to the input-change event
  • Ensure that the new input entered by the user overwrites the old username passed to UserOutput
  • Add two-way-binding to your input (in UserInput) to also display the starting username
  • Add styling of your choice to your components/ elements in the components – both with inline styles and stylesheets

I had a bit of problem passing properties to the components and adding styles with inline css styles. Since I’m still a bit new to React I had to keep going back to old code to remind myself how to do certain things. I did manage to fulfill all the instructions for the assignment

React assignment.

Intro to User Authentication

This week I worked on the user authentication section of the bootcamp tutorials. I learned about passport.js which helps us make user authentication much easier. I also learn about to new npm packages called…

This week I worked on the user authentication section of the bootcamp tutorials. I learned about passport.js which helps us make user authentication much easier. I also learn about to new npm packages called passport-local and passport-local-mongoose. The last thing I learn about was sessions which allows us to keep a user login until the user themselves sign out.

I created a simple form without styling it that allows a user login, register, and logout . I wrote code which allowed someone to sign in and be able to see a secret page which you can only see if you are login in. I did this by creating middleware. Middleware is some function that runs when the request is made and the response is received. When I tried to reach “/secrets” without logging in it would send me back to the index page. This was because of the middleware in the /secrets request which checks if the requested route was made by an authenticated user. If someone would try to login then there was another middleware which checked if the user existed. If they do exist then it sent them to the secrets page but if they didn’t they would just be redirected to the index page. This was really cool stuff to learn and I hope to learn a lot more about user authentication later on.

var express               = require("express"),
    mongoose              = require("mongoose"),
    passport              = require("passport"),
    bodyParser            = require("body-parser"),
    LocalStrategy         = require("passport-local"),
    passportLocalMongoose = require("passport-local-mongoose"),
    User                  = require("./models/user");
    
mongoose.connect("mongodb://localhost/auth_demo_app");

var app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended:true}));
app.use(require("express-session")({
    secret: "Doge developer",
    resave: false,
    saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());

passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

//===========
// Routes
//===========

app.get("/", function(req, res){
    res.render("home");
});

app.get("/secret", isLoggedIn, function(req, res){
    res.render("secret");
});

//Auth Routes

app.get("/register", function(req, res){
   //show sign up form
   res.render("register"); 
});

app.post("/register", function(req,res){
   //Handling user Sign-up
   req.body.username
   req.body.password
   User.register(new User({username: req.body.username}), req.body.password, function(err, user){
        if(err){
            console.log(err);
            return res.render('register');
        }else{
            passport.authenticate("local")(req, res, function(){
                res.redirect("/secret");
            });
        }
   });
});

// Login Routes
//render login form
app.get("/login", function(req, res){
   res.render("login"); 
});
//login logic
//middleware
app.post("/login", passport.authenticate("local", {
    successRedirect: "/secret",
    failureRedirect: "/login"
}), function(req, res){
});
//Logout Routes
app.get("/logout", function(req, res){
   req.logout();
   res.redirect("/");
});

function isLoggedIn(req, res, next){
    if(req.isAuthenticated()){
        return next();
    }
    res.redirect("/");
}

app.listen(process.env.PORT, process.env.IP, function(){
   console.log("Server started"); 
});

<h1>Login</h1>
<form action="/login" method="POST">
    <input type="text" name="username" placeholder="username">
    <input type="password" name="password" placeholder="password">
    <button>Login</button>
</form>

<li><a href="register"> Sign Up!</a></li>
<li><a href="login"> Login!</a></li>
<li><a href="logout"> Logout!</a></li>

<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>

<li><a href="register"> Sign Up!</a></li>
<li><a href="login"> Login!</a></li>
<li><a href="logout"> Logout!</a></li>

<h1> This is our Homepage</h1>

<li><a href="register"> Sign Up!</a></li>
<li><a href="login"> Login!</a></li>
<li><a href="logout"> Logout!</a></li>

<h1> This is the secret page! </h1>

<p> You found me </p>

<img src="https://dogemuchwow.com/wp-content/uploads/2017/11/web-developer-doge.jpg">

<li><a href="register"> Sign Up!</a></li>
<li><a href="login"> Login!</a></li>
<li><a href="logout"> Logout!</a></li>