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

During the weekend I made to the section data association in the tutorials. This part of the section explain what data association is and how we use it. Data association allows us to have…

During the weekend I made to the section data association in the tutorials. This part of the section explain what data association is and how we use it. Data association allows us to have multiple collections in our database that are related to one another. There are three different types of data associations; one to one, one to many, and many to many. There are two ways to write these association, by using embedding data and referencing data.

Embedding Data

For embedding data we made two different mongoose schemas, one for users and the other one for posts. In the Post schema we just added the title and the content the user would write. For the User schema we used email, name, and then we create an array where the posts the user writes would be inserted. We used the push method to embed the post created into the user collection. Now the post collection would hold all post created by all users. But the user collection would hold all users and within in each user object it would hold only the posts created by the one user.

var mongoose = require("mongoose");
mongoose.connect('mongodb://localhost/blog_demo', {useMongoClient: true});

//POST - title, content

var postSchema = new mongoose.Schema({
   title: String,
   content: String
});

var Post = mongoose.model("Post", postSchema);

//USER - email, name
var userSchema = new mongoose.Schema({
   email: String,
   name: String,
   posts:[postSchema]
});

var User = mongoose.model("User", userSchema);

// var newUser= new User({
//    email: "hermione@hogwarts.edu",
//    name: "Hermione Granger"
// });

// newUser.posts.push({
//    title: "How to brew polyjuice potion",
//    content: "Just kidding. Go to potions class to learn it!"
// });

// newUser.save(function(err, user){
//     if(err){
//          console.log(err);
//     }else{
//          console.log(user);
//     }
// });

// var newPost = new Post({
//     title: "This is a new post.",
//     content:"This is a new post for associations."
// });

// newPost.save(function(err, post){
//    if(err){
//        console.log(err);
//    } else{
//        console.log(post);
//    }
// });

User.findOne({ name: "Hermione Granger"}, function(err, user){
   if(err){
      console.log(err);
   }else{
      user.posts.push({
         title: "3 Thing I really hate",
         content: "Voldemort, Voldemort, Voldemort"
      });
      user.save(function(err, user){
         if(err){
            console.log(err);
         }else{
            console.log(user);
         }
      });
   }
});

Referencing Data

The second way we can create data association is through referencing data. In embedding data we push the whole post into the array but when referencing data we just keep just the ids of the post instead of the whole thing. I first created a new user in the database. When I had to create the post I had to find the user and then push the data from the post into the user object. once the post was created the id of the post would be referenced inside an th array in the user object. Then by using mongoose populate I was able to find the user by id and then targeting the post. When this happens the function runs after where if there isn’t an error it’ll write out the user object with the entire post they have created. But in the database when you search for the user and look in posts only the ids of the posts will come up.

database:

Running the code:

var mongoose = require("mongoose");
mongoose.connect('mongodb://localhost/blog_demo_2', {useMongoClient: true});

var Post = require("./models/post");
var User = require("./models/user");

// User.create({
//   email: "bob@gmail.com",
//   name: "Bob Belcher"
// });

// Post.create({
//   title: "How to cook the best burger pt.4",
//   content:"hfsbfksirfnilrf"
// }, function(err, post){
//     User.findOne({_id : "5a4f026397422c13d19164f6"}, function(err, foundUser){
//         if(err){
//             console.log(err);
//         }else{
//             foundUser.posts.push(post);
//             foundUser.save(function(err, data){
//                 if(err){
//                     console.log(err);   
//                 }else{
//                     console.log(data);
//                 }
//             });
//         }
//     });
// });

User.findOne({_id : "5a4f026397422c13d19164f6"}).populate("posts").exec(function(err, user){
    if(err){
        console.log(err);
    }else{
        console.log(user);
    }
});