Skip to content
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

completed build #81

Open
wants to merge 4 commits 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
54 changes: 50 additions & 4 deletions api/auth/auth-router.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,35 @@
const router = require('express').Router();
const db = require('../../data/dbConfig')
const bcrypt = require('bcryptjs')
const { checkFormat, checkNameTaken,} = require('./auth.middleware')
const JWT = require('jsonwebtoken')
const { JWT_SECRET,BCRYPT_ROUNDS } = require('../../config')

router.post('/register', (req, res) => {
res.end('implement register, please!');
function generateToken(user) {
const payload = {
subject: user.id,
username: user.username
}
const options = {
expiresIn: '1d'
};
return JWT.sign(payload,JWT_SECRET,options)
}

router.post('/register', checkFormat, checkNameTaken, async (req, res, next) => {
try {
const { username, password } = req.body;
const newUser = {
username: username,
password: await bcrypt.hash(password, BCRYPT_ROUNDS)
};
const newID = await db('users').insert(newUser);
const [result] = await db('users').where('id',newID);

res.status(201).json(result);
} catch (err) {
next(err)
}
/*
IMPLEMENT
You are welcome to build additional middlewares to help with the endpoint's functionality.
Expand Down Expand Up @@ -29,8 +57,26 @@ router.post('/register', (req, res) => {
*/
});

router.post('/login', (req, res) => {
res.end('implement login, please!');
router.post('/login', checkFormat, async (req, res, next) => {
try {
const { username, password } = req.body;

db('users').where('username', username).first()
.then(user => {
if (user && bcrypt.compareSync(password, user.password)) {
const token = generateToken(user);
res.status(200).json({
message: `welcome, ${username}`,
token: token
});
}else{
next({ status: 401, message: 'invalid credentials'});
}
})
} catch (err) {
next(err)
}

/*
IMPLEMENT
You are welcome to build additional middlewares to help with the endpoint's functionality.
Expand Down
53 changes: 53 additions & 0 deletions api/auth/auth.middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
const db = require('../../data/dbConfig')
const jwt = require('jsonwebtoken')
const { JWT_SECRET } = require('../../config')

const restricted = (req, res, next) => {
const token = req.headers.authorization
if (token) {
jwt.verify(token, JWT_SECRET, (err, decoded) => {
if (err) {
next({ status: 401, message: `invalid token: ${err.message}` })
} else {
req.decodedJWT = decoded
next();
}
})
} else {
next({ status: 402, message: 'token required' })
}
}

const checkFormat = (req, res, next) => {
try {
const { username, password } = req.body
if (username && password) {
next();
} else {
next({ status: 400, message: "username and password required" })
}
} catch (err) {
next(err)
}
}

const checkNameTaken = async (req, res, next) => {
try {
const { username } = req.body
const [user] = await db('users').where('username', username)
.select('username')
if (!user) {
next();
} else {
next({ status: 400, message: "username taken" })
}
} catch (err) {
next(err)
}
}

module.exports = {
checkFormat,
checkNameTaken,
restricted
}
9 changes: 7 additions & 2 deletions api/jokes/jokes-router.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
// do not make changes to this file
const router = require('express').Router();
const jokes = require('./jokes-data');
const { restricted } = require('../auth/auth.middleware')

router.get('/', (req, res) => {
res.status(200).json(jokes);
router.get('/', restricted, (req, res, next) => {
try {
res.status(200).json(jokes);
} catch (err) {
next(err)
}
});

module.exports = router;
7 changes: 7 additions & 0 deletions api/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,11 @@ server.use(express.json());
server.use('/api/auth', authRouter);
server.use('/api/jokes', restrict, jokesRouter); // only logged-in users should have access!

// eslint-disable-next-line no-unused-vars
server.use((err, req, res, next) => {
res.status(err.status || 500).json({
message: err.message
})
})

module.exports = server;
60 changes: 58 additions & 2 deletions api/server.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,60 @@
// Write your tests here
test('sanity', () => {
expect(true).toBe(false)
const db = require('../data/dbConfig')
const request = require('supertest')
const server = require('./server')

beforeAll(async () => {
await db.migrate.rollback();
await db.migrate.latest();
})

beforeEach(async () => {
await db('users').truncate()
})



describe('[GET] /jokes', () => {
const newUser = { username: "user", password: "1234" }
test('receives an error with no token present', async () => {
await request(server).post('/api/auth/register').send(newUser)
await request(server).post('/api/auth/login').send(newUser)
const data = await request(server).get('/api/jokes')
expect(data.body.message).toBe('token required')
})
test('returns a list of jokes while authorized', async () => {
await request(server).post('/api/auth/register').send(newUser)
const res = await request(server).post('/api/auth/login').send(newUser)
const data = await request(server).get('/api/jokes').set('Authorization', `${res.body.token}`)
expect(data.body).toHaveLength(3)
})
})

describe('[POST] /auth/register', () => {
const newUser = { username: "user", password: "1234" }
test('new users are listed in the database', async () => {
await request(server).post('/api/auth/register').send(newUser)
const rows = await db('users')
expect(rows).toHaveLength(1)
})
test('returns username and hashed password', async () => {
const res = await request(server).post('/api/auth/register').send(newUser)
expect(res.body.username).toMatch(newUser.username)
expect(res.body.password).not.toMatch(newUser.password)
})

})

describe('[POST] /auth/login', () => {
const newUser = { username: "user", password: "1234" }
test('new user obtains a token when logging in', async () => {
await request(server).post('/api/auth/register').send(newUser)
const res = await request(server).post('/api/auth/login').send(newUser)
expect(res.body.token).toBeDefined()
})
test('incorrect password gives an error', async () => {
await request(server).post('/api/auth/register').send(newUser)
const res = await request(server).post('/api/auth/login').send({ username: newUser.username, password: '123'})
expect(res.body.message).toBe('invalid credentials')
})
})
4 changes: 4 additions & 0 deletions config/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
module.exports = {
BCRYPT_ROUNDS: process.env.BCRYPT_ROUNDS || 8,
JWT_SECRET: process.env.JWT_SECRET || 'shh'
}
Loading