GithubHelp home page GithubHelp logo

week-6-bhkm-'s Introduction

Week-6&7-BHKM-

Database project

Andy, Christine, Emmanuel, Martha

Team BHKM - Bugbear

Project

  • This week's project will involve setting up a database which you connect to via a node.js server. You'll use your data to make a dynamic web app for your front-end.
  • Some suggested project ideas are below. Feel free to modify according to your interest, provided your idea has similar functionality.

Requirements

  • Login form with 2 fields - username and password
  • Users only have to log in once (i.e. implement a cookie-based session on login)
  • Username is visible on each page of the site after logging in
  • Any user-submitted content should be labelled with the authors username
  • There should be protected routes and unprotected routes that depend on the user having a cookie or not (or what level of access they have).
  • Website content should be stored in a database
  • Include thorough tests on the back-end, testing pure functions and testing routes using Supertest. If you make external API calls, use Nock to mock the response for your tests.
  • Test front-end logic, we don't expect tests on the DOM.

code of conduct

  • BEM
  • Ensure euqual number of commits
  • Commit often
  • Switch regularly but (do few commits first)
  • Compartmentalise and work on the dedicated branch (pushing only needed after milestones)
  • feature and fix branches

Idea

  • Users are able to search for peetpeeves, add comments or create new petpeeves that they have

  • You will need to make the requests and update the DOM in response using client-side JavaScript.

  • As well as serving static HTML and JS files, your server will also need to provide endpoints that return DB query results as JSON. You can query your server from the client using the XMLHttpRequest method.

  • You'll need to be able to make both POSTand GET requests to your server.

MVP

  • Mobile first design
  • Basic site with long list of previous inputs by user
  • Logo in top left, description and a search bar
  • Field inputs are category, name and rant

Stretch goals

  • Client-side and server-side validation on login form, including error handling that provides feedback to users
  • Add like functionality to content
  • Add comment functionality to content
  • Allow users to delete the content that they have submitted
  • Add roles and permissions - Have an "admin" level user (role) who can edit and delete all content ๐Ÿ˜ฑ (permissions)
  • Refactor xmlhttp to fetch and callbacks to promises
  • Email address for users

TO-DO

TO-DO / Process

Frontend

  • Setting up the HTML for the landing page
  • Putting in the log-in forms
  • Setting up the front-end validation

Backend

Database:

  • Create new database table for log-in info
  • New query
  • Backend validation via router and handler
Log in
  • Send username and password info to backend
  • Backend check to see if the two match
  • Sending sign up data to backend
  • Comparing user infor to databse checking if user existis
  • Hashing pasword
  • Sending error messages if user exists
Register
  • Post request from front end (form -> send to backend)
  • Backend Router -> Handler (use of similar functions to "postData" and "getData" from last week)
  • Update database
  • Hashing + salting pasword (Bcrypt module)

Code of Conduct

  • BEM
  • Ensure equal number of commits
  • Commit often
  • Switch regularly but (do few commits first)
  • Compartmentalise and work on the dedicated branch (pushing only needed after milestones)
  • Feature and fix branches

How to create local test database

  • pgcli (will get you into your 'username')

  • /d (gives you all tables currently accessible)

  • /l (gives you all local databases)

  • /c (lets you switch to a different database)

  • (once in the right database run) \i src/database/db_build.sql (the path starting at the root of your folder)

  • SELECT * FROM

  • go out of the pgcli and run: node <filebathtobuild.js> (node src/database/build.js = this will run the build file which will also build the remote database on heroku)

  • you can now outside of pgcli write: pgcli (selecting SELECT * from will populate the correct base)

Glossary

Hash - Server side - turns plain text password into hashed string of characters Link: https://github.com/foundersandcoders/ws-password-management

Salt - Random set of characters that generated by decrypt to make it difficult to decrupy usin ghte rainbow table Link: https://github.com/foundersandcoders/ws-password-management

Cookie - A cookie is a piece of data that your server, sends back to the browser, which the browser will then keep, and attach to every future request to that domain. Link: https://github.com/foundersandcoders/ws-cookies

Useful Tips

Add new table to database - node src.database/db_build.js SELECT * FROM *new added table

week-6-bhkm-'s People

Contributors

mkatenolan avatar xirusux avatar andy-mc-donald avatar emaggy avatar

Watchers

D Sofer avatar James Cloos avatar Victor Masson avatar  avatar  avatar Reuben George Thomas avatar

week-6-bhkm-'s Issues

might be worth putting instructions at the top of the readme

I like the test database instructions (although it might be worth mentioning you'll need the test url from the .env file), but the git clone, npm install, npm start/test instructions are important too. As a code reviewer the first thing I want to do is get the code cloned and running! Generally a good idea to put these instructions near the top of your readme

Few html suggestions

Screenshot 2019-08-09 at 09 22 46

Same screenshot as the last issue but don't forget to declare your language - I always like to put en-gb so that the computer knows it's proper English ๐Ÿ‡ฌ๐Ÿ‡ง

ALSO while I'm here in the html - you've not included a title.

And if I was you guys I would put the link to normalise above the style.css - I've had problems with this before, where normalise overrides changes in my style.css because I had placed it below in the html. Place above to make sure your changes override normalise!

put .env in your gitignore!

It's generally not a good idea to push your .env file to github - this is where you tend to store secret stuff like api keys and (ahem) database usernames and passwords. Usually the .env never gets pushed to master, and you share the variables privately with the rest of your team

Empty files

I imagine that you some ideas to fill the empty files, right? If after the issues some are still empty, it might be good to delete them for having a clean repo?

setToken Function

One way of fixing this:

This bit

getUD
      .getUD(username, password)
      .then(dbPassword => {
        console.log(dbPassword);
      })

Like you say returns an object. To get the password and run the compare function in bcrypt you can try and return dbPassword.rows from the getUD.js. You can then iterate through the response like this:

response.rows[0][password] 

which will get this part of the object:

rows:
   [ { password:
        '$2b$10$a9/KgpWGLJ6DhuT5fKExqegKc8tRdCMhWTO34gRIrAeycKHoolPLO' } ],

Data stream

If you have chance may be worth abstracting out your data streamer function as you use it a few times

simpler Pool (bonus)

fun fact you don't actually need the options object - all of the data is already stored in your database url:

let connectionString = process.env.DATABASE_URL;
// this variable must be called 'connectionString' for this to work
module.exports = new Pool({
  connectionString,
  ssl: !connectionString.includes("localhost")
})

npm start failed to run

It might just be me being inept, but I couldn't get your repo to run on local host.

Have taken screenshots of the error messages in case this is an actual problem and it's helpful in any way.

P.S. Yes, I did run npm i when I downloaded your repo.

Screenshot 2019-08-09 at 09 40 22

Screenshot 2019-08-09 at 09 40 13

(Almost) even commits!

Three of the members of the team have equal commits and one has a couple extra. When addressing issues you could level this out. ๐Ÿฅ‡

Bear.png

Do you use both of them? Get rid of one?

security

:D Good! Intruders scripts don't run :)

Limit inputs

In the SQL build file, there are character limits on username and password, but no limit on the login inputs. You can easily add this with a maxlength in the input field like:
<input type="text" maxlength="30" id="username">

Great use of no-js!!

Screenshot 2019-08-09 at 09 22 46

Had never heard of this before I checked out your code but had a quick google and think it's great that you're considering the no javascript user (although who would ever choose to disable js, right?!)

User posts as logged-in user

I feel it would make sense, once you're logged in, that you'd post as the signed-in user โ€“ rather than being able to pick your name again. Maybe try and store the username in the cookie?

Heroku build

CSS doesn't appear to be loading on Heroku app, works locally though

Nicely broken down

Super compartimentalised and makes the code nice to read and understand ๐Ÿ‘

Deployment

Your project is deployed on heroku and working with the DB! Congrats! ๐Ÿ…

A guest review

"When I visited the site, I was pleased to note that I would not have to give up my personal information in order to enter. I had a highly pressing thought to offload and the ability to do so without being hindered by logging in was a pleasant element of my visit. 10/10 would recommend."

Anonymous visitor

styling

Looking forward to some front end action :D and styling

Set a JWT in your guest logic

Handler.js, lines 164-167:

function guestLogic(req, res){
  res.writeHead(302, { Location: "/", 'Set-Cookie': 'logged_in=false' });
  res.end();
}

Because you're not setting this as a JWT you can end up with two cookies, one for being a guest and one for being logged in:

Screenshot 2019-08-16 at 10 33 51

It's amazing that you've managed to get the JWTs to work for the login route; it might be easier if you add this to the guest route too so there are no bugs later down the line.

Hashed

Nice hashed passwords
hash

Redirect on register

It should be relatively easy to re-direct to the main page when the user registers.

Great Idea

I love the idea. Have gained much catharsis already from submitting my bugbears ๐Ÿ› ๐Ÿป ๐Ÿ’ก

Lack of visible labels

I wasn't sure what each input field was for, perhaps visible labels can clarify what the user is supposed to type; Nice work on the aria labels though :)

Web view

Screenshot 2019-08-09 at 09 43 47

Not going to be harsh on the lack of css etc because it's not the point of this week, we don't have much (at least we didn't yesterday when I left) and it takes like, 15 mins to put together something. I love that the fields are required and won't let me submit a blank field. IF you have time, would be nice to get the dropdown to appear below the input field, and to have a 'please select here' in the input field, too. Otherwise, hope you have time to sprinkle some gorgeous CSS onto it!!

const

Use const whenever the value isn't reassigned e.g. most function

Consistent use of ES6

Have had a quick scan through your repo and your use of ES6 is consistent and correct (from what I can gather). Great job! ๐Ÿ’ƒ๐Ÿ’ƒ๐Ÿ’ƒ

getUD function(query file not passing correct response back to handler)

In handler.js line 110-124, getUD is being called, but dbPassword was not what you were expecting it to be(hashed password from the database).

getUD(username, password)
      .then(dbPassword => {
        console.log(dbPassword);
      })
      .then(result => {
        if (result == false) {
          console.log(result);
        } else {
          res.writeHead(301, {
            Location: "/",
            "Set-Cookie": `jwt=${cookie}`
          });
          res.end();
        }
      });

i took a look at where getUD is defined(getUD.js),
and you're resolving the promise with the response that comes back from the sql query.
this response is always a massive object, and your password is actually hidden inside the .rows property of this object, which is an array with objects inside it that represent the rows returned by your sql query.

const getUD = (username, password) => {
  return new Promise((resolve, reject) => {
    dbConnection
      .query(`SELECT password FROM login WHERE username= '${username}';`)
      .then(dbPassword => {
        // passwordHandling.comparePasswords(
        //   dbPassword[1],
        //   dbPassword[0][0].password
        // );
        resolve(dbPassword);
        console.log("dbPassword:", dbPassword);
        // console.log(dbPassword[1], dbPassword[0][0].password);
      })
      .catch(err => reject(err));
  });
};

dbPassword here isnt your database password, its an object with the value you want nested inside ๐Ÿ˜„
I've rewritten this to access the password and use it to resolve the response.

const getUD = (username, password) => {
  return new Promise((resolve, reject) => {
    dbConnection
      .query(`SELECT password FROM login WHERE username= '${username}';`)
      .then(sqlresponse => {
        console.log('response from password sql query', sqlresponse);
        //this is a massive object and you want the .rows property
        console.log('password is: ',sqlresponse.rows[0].password);
        resolve(sqlresponse.rows[0].password);
      })
      .catch(err => reject(err));
  });
};

It's fun to use

I know you teased me for saying this but it's actually really fun to play with so I'm going to say this again.

The little touches are really nice e.g. 'bearbug found on port 3000' and it actually feels like a really consistent project with the way it's branded etc.

Once you get the login page styled I think it's going to be really amazing

User Journey?

You have a good description of your idea on your README but there is a lack of a specific user journey. This is one of the requirements for this week and I think would be easy for you to add on.

Accessibility

Your page could be made accessible quickly and easily by addressing two issues:

  • Add a title
  • Add labels for your inputs

Sanitise inputs

Looks like a user tried to make their post into an h1 to draw attention to their bugbear! ๐Ÿ‘ฟ

You seem to be sanitising the inputs so that this cannot be done. I tried to work out how you had done this but couldn't see it in your code. Could you explain this in your presentation?

getUD.js query

So close to getting the compare passwords bit done before the code review, which is great stuff!

const getUD = (username, password) => {
  return new Promise((resolve, reject) => {
    dbConnection
      .query(`SELECT password FROM login WHERE username= '${username}';`)
      .then(dbPassword => {
        // passwordHandling.comparePasswords(
        //   dbPassword[1],
        //   dbPassword[0][0].password
        // );
        resolve(dbPassword);
        console.log("dbPasswod:", dbPassword);
        // console.log(dbPassword[1], dbPassword[0][0].password);
      })
      .catch(err => reject(err));
  });
};

You'll want to import in your hashPassword function from passwordHandling.js to hash the password you've passed as a paramater in line 4. Remember your hashPassword function returns a promise, so you might need a .then() to find the hash! Compare this hash to dbPassword and you should be golden.

PS. I think you'll need to resolve true or false, rather than resolving the password.

ES5

In script.js line 17, add arrow syntax? Check to see if there are any others

Congrats

Great improvements on last week and feels like a proper app, lovely stuff

great

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.