Skip to content

Completed Integrated testing #12

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .config/secrets.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = {
jwtSecret: process.env.JWT_SECRET || 'add a third table for many to many',
};
5 changes: 5 additions & 0 deletions .idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions .idea/modules.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions .idea/web-sprint-challenge-authentication-and-testing.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,20 @@ Be prepared to demonstrate your understanding of this week's concepts by answeri

1. Differences between using _sessions_ or _JSON Web Tokens_ for authentication.

sessions are stored in the servers memory, json web tokens are stateless.

2. What does `bcrypt` do to help us store passwords in a secure manner.

bcrypt encrypts your data to help guard against brute force attacks.

3. How are unit tests different from integration and end-to-end testing.

unit test test one specific aspect or function of your code, integration testing tests modules as a group, end-to-end testing tests the entire application from start to end

4. How _Test Driven Development_ changes the way we write applications and tests.

test driven development forces you to write tests first that fail and then write the code to make them pass

You are expected to be able to answer questions in these areas. Your responses contribute to your Sprint Challenge grade.

## Instructions
Expand Down
31 changes: 31 additions & 0 deletions __tests__/jokesRouterTests.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
const superTest = require('supertest');
const server = require('../api/server');
const db = require("../database/dbConfig")

beforeAll(async () => {
// run the seeds programatically before each test to start fresh
await db.seed.run()
})

afterAll(async () => {
// close the database connection so the test process doesn't hang or give a warning
await db.destroy()
})



describe("Jokes Router Integration Tests", ()=> {



it("POST / Initial test to ensure unAuth user cannot access endpoints", async ()=>{
let res = await superTest(server)
.get("/api/jokes")
expect(res.statusCode).toBe(401)
expect(res.type).toBe("application/json")
expect(res.body.you).toBe("shall not pass!")

})


});
9 changes: 9 additions & 0 deletions __tests__/serverStatusTest.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const superTest = require('supertest');
const server = require('../api/server');

test("GET / and test its up and returning the welcome data", async ()=>{
const res = await superTest(server).get("/")
expect(res.statusCode).toBe(200)
expect(res.type).toBe("application/json")
expect(res.body.data).toBe("welcome to the api")
})
88 changes: 88 additions & 0 deletions __tests__/userLoginTests.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
const superTest = require('supertest');
const server = require('../api/server');
const db = require("../database/dbConfig")
const user_valid = require('../auth/user_validation')
const bcrypt = require("bcryptjs");

beforeAll(async () => {
// run the seeds programatically before each test to start fresh
await db.seed.run()
})

afterAll(async () => {
// close the database connection so the test process doesn't hang or give a warning
await db.destroy()
})

async function CreateTest(person){
const [id] = await db('users').insert(person, 'id');

return db('users')
.where({ id })
.first();
}




describe("User Register Tests", ()=>{
it("POST / tests registering of new user and Loggin in", async()=>{
let res = await superTest(server)
.post("/api/auth/register")
.send({username:"testerBean", password:"BeanPassword"})
expect(res.statusCode).toBe(201)
expect(res.type).toBe("application/json")
expect(res.body.username).toBe("testerBean")

})

it("POST / test registering user without the proper information {username}. Should FAIL", async ()=>{
const res = await superTest(server)
.post("/api/auth/register")
.send({
username: '',
password:'asfdasdfas',
})
expect(res.statusCode).toBe(409)
expect(res.type).toBe("application/json")
expect(res.body.message).toBe("Please enter a username")
})

it("POST / test registering user without the proper information {password}. Should FAIL", async ()=>{
const res = await superTest(server)
.post("/api/auth/register")
.send({
username: 'asfdasdfas',
password:'',
})
expect(res.statusCode).toBe(409)
expect(res.type).toBe("application/json")
expect(res.body.message).toBe("Please enter a password")
})

it("POST / test registering user without the proper information {password}. Should FAIL", async ()=> {

});

})

describe("Test Logging in a user", ()=>{
it("POST/ Login user should return a 200", async ()=>{

const res = await superTest(server)
.post("/api/auth/login")
.send({username:"testerBean", password:"BeanPassword"})
expect(res.statusCode).toBe(200)
expect(res.type).toBe("application/json")
expect(res.body.message).toBe("Welcome testerBean!")
},99999)
it("POST / Login user with bad credentials should FAIL", async () =>{
const res = await superTest(server)
.post("/api/auth/login")
.send({username:"testerBean2", password:"BeanPassword"})
expect(res.statusCode).toBe(401)
expect(res.type).toBe("application/json")
expect(res.body.message).toBe("Invalid Credentials")
})
})

18 changes: 16 additions & 2 deletions api/server.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const cookieParser = require("cookie-parser");

const authenticate = require('../auth/authenticate-middleware.js');
const restrict = require('../auth/authenticate-middleware.js');
const authRouter = require('../auth/auth-router.js');
const jokesRouter = require('../jokes/jokes-router.js');

Expand All @@ -11,8 +12,21 @@ const server = express();
server.use(helmet());
server.use(cors());
server.use(express.json());
server.use(express.json());
server.use(cookieParser());

server.use('/api/auth', authRouter);
server.use('/api/jokes', authenticate, jokesRouter);
server.use('/api/jokes', restrict, jokesRouter);

server.get('/',(req,res,)=>{
res.status(200).json({data:"welcome to the api"})
})

server.use( (err, req, res, next) => {
console.log(err)
res.status(500).json({
message:"Something went wrong",
})
})

module.exports = server;
61 changes: 56 additions & 5 deletions auth/auth-router.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,62 @@
const router = require('express').Router();
const bcrypt = require("bcryptjs");
const Users = require('./users-model');
const jwt = require('jsonwebtoken');
const secrets = require("../.config/secrets")

router.post('/register', (req, res) => {
const user_valid = require('./user_validation')


router.post('/register', async (req, res, next) => {
// implement registration
});
try {
const { username, password } = req.body
const user = await Users.findBy({ username }).first()

if (user) {
return res.status(409).json({
message: "Username is already taken",
})
}
console.log(username)
if(username === "" || !username){
return res.status(409).json({message:"Please enter a username"})
}

if(password === "" || !password){
return res.status(409).json({message:"Please enter a password"})
}

const newUser = await Users.add({
username,
// hash the password with a time complexity of 14
password: await bcrypt.hash(password, 14),
})

router.post('/login', (req, res) => {
// implement login
await res.status(201).json({
'username': username , 'password': newUser.password})
} catch(err) {
next(err)
}
});

module.exports = router;
router.post('/login', async (req, res, next) => {
try {
const { username, password } = req.body
const user = await Users.findByUsername({ username }).first()

if (!user) {
return res.status(401).json({
message: "Invalid Credentials",
})
}

await user_valid(user,req, res,)


} catch(err) {
next(err)
}
})

module.exports = router;
34 changes: 29 additions & 5 deletions auth/authenticate-middleware.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,32 @@
/*
complete the middleware code to check if the user is logged in
before granting access to the next middleware/route handler
*/
const jwt = require("jsonwebtoken")
const secrets = require("../.config/secrets")

module.exports = (req, res, next) => {
res.status(401).json({ you: 'shall not pass!' });
const authError = { you: 'shall not pass!' }
try {
// token is coming from the client's cookie jar, in the "Cookie" header
const token = req.cookies.token
console.log(` token is ${token}`)
if (!token) {
console.log("!token")
return res.status(401).json(authError)
}

// decode the token, re-sign the payload, and check if signature is valid
jwt.verify(token, secrets.jwtSecret, (err, decoded) => {
console.log(`inside verify secret is ${secrets}`)
if (err) {
return res.status(401).json(authError)
}

// we know the user is authorized at this point,
// make the token's payload available to other middleware functions
req.token = decoded
next()
})
} catch(err) {

next(err)

}
};
29 changes: 29 additions & 0 deletions auth/user_validation.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
const jwt = require('jsonwebtoken');
const secrets = require("../.config/secrets")
const bcrypt = require("bcryptjs");


module.exports = async (user, req, res, next) =>{
const passwordValid = await bcrypt.compare(req.body.password, user.password)

if (!passwordValid) {
return res.status(401).json({
message: "Invalid Credentials",
})
}

const token = jwt.sign({
userID: user.id,
}, secrets.jwtSecret)


res.cookie("token", token)
res.cookie("username", user.username)

return res.json({
message: `Welcome ${user.username}!`,
token:token
})


}
Loading