Skip to content

Commit

Permalink
initial
Browse files Browse the repository at this point in the history
  • Loading branch information
Ladrillo committed Mar 1, 2022
0 parents commit 5036ab7
Show file tree
Hide file tree
Showing 17 changed files with 11,713 additions and 0 deletions.
14 changes: 14 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"env": {
"commonjs": true,
"es2021": true,
"node": true,
"jest": true
},
"extends": "eslint:recommended",
"parserOptions": {
"ecmaVersion": "latest"
},
"rules": {
}
}
36 changes: 36 additions & 0 deletions .github/lockdown.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# PLEASE DO NOT REMOVE THIS FILE

# Configuration for Repo Lockdown - https://github.com/dessant/repo-lockdown

# Skip issues and pull requests created before a given timestamp. Timestamp must
# follow ISO 8601 (`YYYY-MM-DD`). Set to `false` to disable
skipCreatedBefore: false

# Issues and pull requests with these labels will be ignored. Set to `[]` to disable
exemptLabels: []

# Comment to post before closing or locking. Set to `false` to disable
comment: false

# Label to add before closing or locking. Set to `false` to disable
label: false

# Close issues and pull requests
close: true

# Lock issues and pull requests
lock: true

# Limit to only `issues` or `pulls`
only: pulls
# Optionally, specify configuration settings just for `issues` or `pulls`
# issues:
# label: wontfix

# pulls:
# comment: >
# This repository does not accept pull requests, see the README for details.
# lock: false

# Repository to extend settings from
# _extends: repo
125 changes: 125 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Snowpack dependency directory (https://snowpack.dev/)
web_modules/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env
.env.test

# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache

# Next.js build output
.next
out

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

# Stores VSCode versions used for testing VSCode extensions
.vscode-test

# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*

# Mac Cruft
.DS_Store

# VSCode
.vscode

# databases
*.db3
59 changes: 59 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# Authentication and Testing Sprint Challenge

**Read these instructions carefully. Understand exactly what is expected _before_ starting this Sprint Challenge.**

This challenge allows you to practice the concepts and techniques learned over the past sprint and apply them in a concrete project. This sprint explored **Authentication and Testing**. During this sprint, you studied **authentication, JSON web tokens, unit testing, and backend testing**. In your challenge this week, you will demonstrate your mastery of these skills by creating **a dad jokes app**.

This is an individual assessment. All work must be your own. All projects will be submitted to Codegrade for automated review. You will also be given feedback by code reviewers on Monday following the challenge submission. For more information on the review process [click here.](https://www.notion.so/bloomtech/How-to-View-Feedback-in-CodeGrade-c5147cee220c4044a25de28bcb6bb54a)

You are not allowed to collaborate during the sprint challenge.

## Project Setup

- [ ] Run `npm install` to install your dependencies.
- [ ] Build your database executing `npm run migrate`.
- [ ] Run tests locally executing `npm test`.

## Project Instructions

Dad jokes are all the rage these days! In this challenge, you will build a real wise-guy application.

Users must be able to call the `[POST] /api/auth/register` endpoint to create a new account, and the `[POST] /api/auth/login` endpoint to get a token.

We also need to make sure nobody without the token can call `[GET] /api/jokes` and gain access to our dad jokes.

We will hash the user's password using `bcryptjs`, and use JSON Web Tokens and the `jsonwebtoken` library.

### MVP

Your finished project must include all of the following requirements (further instructions are found inside each file):

- [ ] An authentication workflow with functionality for account creation and login, implemented inside `api/auth/auth-router.js`.
- [ ] Middleware used to restrict access to resources from non-authenticated requests, implemented inside `api/middleware/restricted.js`.
- [ ] A minimum of 2 tests per API endpoint, written inside `api/server.test.js`.

**IMPORTANT Notes:**

- Do not exceed 2^8 rounds of hashing with `bcryptjs`.
- If you use environment variables make sure to provide fallbacks in the code (e.g. `process.env.SECRET || "shh"`).
- You are welcome to create additional files but **do not move or rename existing files** or folders.
- Do not alter your `package.json` file except to install extra libraries. Do not update existing packages.
- The database already has the `users` table, but if you run into issues, the migration is available.
- In your solution, it is essential that you follow best practices and produce clean and professional results.
- Schedule time to review, refine, and assess your work and perform basic professional polishing.

## Submission format

- [ ] Submit via Codegrade by pushing commits to your `main` branch on Github.
- [ ] Check Codegrade before the deadline to compare its results against your local tests.
- [ ] Check Codegrade on the days following the Sprint Challenge for reviewer feedback.
- [ ] New commits will be evaluated by Codegrade if pushed _before_ the sprint challenge deadline.

## Interview Questions

Be prepared to demonstrate your understanding of this week's concepts by answering questions on the following topics.

1. Differences between using _sessions_ or _JSON Web Tokens_ for authentication.
2. What does `bcryptjs` do to help us store passwords in a secure manner?
3. How are unit tests different from integration and end-to-end testing?
4. How does _Test Driven Development_ change the way we write applications and tests?
59 changes: 59 additions & 0 deletions api/auth/auth-router.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
const router = require('express').Router();

router.post('/register', (req, res) => {
res.end('implement register, please!');
/*
IMPLEMENT
You are welcome to build additional middlewares to help with the endpoint's functionality.
DO NOT EXCEED 2^8 ROUNDS OF HASHING!
1- In order to register a new account the client must provide `username` and `password`:
{
"username": "Captain Marvel", // must not exist already in the `users` table
"password": "foobar" // needs to be hashed before it's saved
}
2- On SUCCESSFUL registration,
the response body should have `id`, `username` and `password`:
{
"id": 1,
"username": "Captain Marvel",
"password": "2a$08$jG.wIGR2S4hxuyWNcBf9MuoC4y0dNy7qC/LbmtuFBSdIhWks2LhpG"
}
3- On FAILED registration due to `username` or `password` missing from the request body,
the response body should include a string exactly as follows: "username and password required".
4- On FAILED registration due to the `username` being taken,
the response body should include a string exactly as follows: "username taken".
*/
});

router.post('/login', (req, res) => {
res.end('implement login, please!');
/*
IMPLEMENT
You are welcome to build additional middlewares to help with the endpoint's functionality.
1- In order to log into an existing account the client must provide `username` and `password`:
{
"username": "Captain Marvel",
"password": "foobar"
}
2- On SUCCESSFUL login,
the response body should have `message` and `token`:
{
"message": "welcome, Captain Marvel",
"token": "eyJhbGciOiJIUzI ... ETC ... vUPjZYDSa46Nwz8"
}
3- On FAILED login due to `username` or `password` missing from the request body,
the response body should include a string exactly as follows: "username and password required".
4- On FAILED login due to `username` not existing in the db, or `password` being incorrect,
the response body should include a string exactly as follows: "invalid credentials".
*/
});

module.exports = router;
17 changes: 17 additions & 0 deletions api/jokes/jokes-data.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// do not make changes to this file
const jokes = [
{
"id": "0189hNRf2g",
"joke": "I'm tired of following my dreams. I'm just going to ask them where they are going and meet up with them later."
},
{
"id": "08EQZ8EQukb",
"joke": "Did you hear about the guy whose whole left side was cut off? He's all right now."
},
{
"id": "08xHQCdx5Ed",
"joke": "Why didn’t the skeleton cross the road? Because he had no guts."
},
];

module.exports = jokes;
9 changes: 9 additions & 0 deletions api/jokes/jokes-router.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// do not make changes to this file
const router = require('express').Router();
const jokes = require('./jokes-data');

router.get('/', (req, res) => {
res.status(200).json(jokes);
});

module.exports = router;
14 changes: 14 additions & 0 deletions api/middleware/restricted.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
module.exports = (req, res, next) => {
next();
/*
IMPLEMENT
1- On valid token in the Authorization header, call next.
2- On missing token in the Authorization header,
the response body should include a string exactly as follows: "token required".
3- On invalid or expired token in the Authorization header,
the response body should include a string exactly as follows: "token invalid".
*/
};
19 changes: 19 additions & 0 deletions api/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
const express = require('express');
const cors = require('cors');
const helmet = require('helmet');

const restrict = require('./middleware/restricted.js');

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

const server = express();

server.use(helmet());
server.use(cors());
server.use(express.json());

server.use('/api/auth', authRouter);
server.use('/api/jokes', restrict, jokesRouter); // only logged-in users should have access!

module.exports = server;
4 changes: 4 additions & 0 deletions api/server.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// Write your tests here
test('sanity', () => {
expect(true).toBe(false)
})
6 changes: 6 additions & 0 deletions data/dbConfig.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// do not make changes to this file
const knex = require('knex');
const knexConfig = require('../knexfile.js');
const environment = process.env.NODE_ENV || 'development';

module.exports = knex(knexConfig[environment]);
11 changes: 11 additions & 0 deletions data/migrations/20201123181212_users.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
exports.up = function (knex) {
return knex.schema.createTable('users', users => {
users.increments();
users.string('username', 255).notNullable().unique();
users.string('password', 255).notNullable();
});
};

exports.down = function (knex) {
return knex.schema.dropTableIfExists('users');
};
6 changes: 6 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
const server = require('./api/server.js');

const PORT = process.env.PORT || 3300;
server.listen(PORT, () => {
console.log(`\n=== Server listening on port ${PORT} ===\n`);
});
Loading

0 comments on commit 5036ab7

Please sign in to comment.