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

JamesHutton/back-end-project-week #493

Open
wants to merge 23 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
7df88b8
Initial commit. Added dependencies.
JJHutton81 Feb 13, 2019
6c0b12b
Added trello url to readme file.
JJHutton81 Feb 13, 2019
84e4839
Added knexfile, and set directories.
JJHutton81 Feb 13, 2019
c3630e4
Added notes and users migrations.
JJHutton81 Feb 13, 2019
869caac
Added db helper file.
JJHutton81 Feb 13, 2019
f588ae0
Added seed file and test notes.
JJHutton81 Feb 13, 2019
eedcd6d
Added simple server, and needed file directories for future steps.
JJHutton81 Feb 13, 2019
cccf02b
Added server info on index.js. Updated gitignore to prevent pradictab…
JJHutton81 Feb 13, 2019
406465f
Added process.env file. Added authenticate, and generatetoken functi…
JJHutton81 Feb 13, 2019
69dc0d1
Added getNotes function on file config/routes.js.
JJHutton81 Feb 13, 2019
f23812c
Added getNotesById function in config/routes.js.
JJHutton81 Feb 13, 2019
f7edb3b
Added post and edit endpoints in config/toutes.js.
JJHutton81 Feb 13, 2019
0478985
Created delete endpoint in config/routes.js.
JJHutton81 Feb 14, 2019
4407de7
Added register function on file config/routes.js.
JJHutton81 Feb 14, 2019
4a7ac3b
Added login function and test server running function on config/route…
JJHutton81 Feb 14, 2019
27246e3
Added rest endpoints and first draft of README and API documentation.
JJHutton81 Feb 14, 2019
b4e763f
Heroku said it couldn't find nodemon, so I reinstalled it.
JJHutton81 Feb 15, 2019
03bcaf8
Found out heroku uses npm, and I used yarn to install dependencies. I…
JJHutton81 Feb 15, 2019
3dcabd6
Removed yarn lock file.
JJHutton81 Feb 15, 2019
cd64f78
Changed scripts in package.json for heroku.
JJHutton81 Feb 15, 2019
ecfe822
Commented out the log in and register endpoints to see if the notes i…
JJHutton81 Feb 15, 2019
b2d8fc9
Un-commented out the register and log in endpoints, after testing was…
JJHutton81 Feb 15, 2019
21f1248
Added Heroku and Netlify info to the readme.md file.
JJHutton81 Feb 23, 2019
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
82 changes: 82 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,83 @@
.DS_Store
node_modules

# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# 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

# 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/

# TypeScript v1 declaration files
typings/

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# 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

# next.js build output
.next

# nuxt.js build output
.nuxt

# vuepress build output
.vuepress/dist

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/
129 changes: 80 additions & 49 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,71 +1,102 @@
# Back End Project Week
# Project Trello Board

This week you will build a backend for a note taking app called "Lambda Notes".
https://trello.com/b/IeOy1pGI/back-end-project-week

You are to treat this week as if you are working at a company and the instructor is your client. The _Project Managers_ are acting as your company's project managers (duh!) and will be your main support throughout the week.
## Netlify

The main objective of this week is to develop a backend to support the LambdaNotes app you built during the Front End project week, connect the two projects together, and add some additional features. You will use `Node.js`, `Express` and any other technologies you have learned to complete this assignment.
https://5c717a8e9c6a81e5e411eeb8--eloquent-mayer-b3e420.netlify.com/

## Git Commits
## Heroku

You are required to showcase progress with at least 4 commits a day. This will let your project manager know where you are and if you need help. This also allows the client to get progress reports from the company in a real world setting. This also protects you from losing your work if your computer fails.
https://dashboard.heroku.com/apps/beplambdanotes

## Trello Set Up
## Team

- Use your existing Trello account from the Front End Project, or create a new one.
- Create a new board called "Lambda Notes(Backend) - {Your Name}".
- Create lists titled `Backlog`,`To do`, `Blocked`, `In Progress`, and `Done`.
- Fill in the `To do` list with the MVP features listed below.
- Fill in the `backlog` list with all the extra features listed below.
- Share your board with the project manager that has been assigned to you. If you have not been assigned yet, reach out to your Section Lead for guidance.
- Add your Trello URL to your project's README.md file. Commit the change, push it to your repository & submit a pull request.
### Developers
[James Hutton](https://github.com/FreeKeyBoy)

## Backend MVP Features:
## Tech Stack

We recommend that you finish all the MVP features before trying to deploy.
Lambda Notes utilizes [Heroku](https://www.heroku.com/) and [Netlify](https://www.netlify.com/) for deployment, and is built in full stack JavaScript with a [React.js](https://reactjs.org/) frontend, a [Node.js](https://nodejs.org/en/) and [Express.js](https://expressjs.com/) backend, Blockstack's [Gaia](https://github.com/blockstack/gaia/blob/master/README.md) high-performance decentralized storage system is used to store notes in production, and a [SQLite3](https://www.sqlite.org/index.html) database in development.

- Add data persistenc using a Relational Database. We suggest you start with `SQLite3`.
- Create a Web API for the React application you built in the front-end project week.
- Build endpoints for each of the following features:
- Display a list of notes.
- Create a note with a _title_ and _content_.
- View an existing note.
- Edit an existing note.
- Delete an existing note.
- Modify your front-end so that it uses your newly created Web API.
### Rationale

Upon your first commit, please submit a Pull Request and add _both_ the **Trello Set Up** and **Backend MVP Features** Task lists to your first Pull Request comment.
#### Frontend
- netlify

---
- React

**Once you have completed the "Minimum Viable Product" requirements, message your project manager for approval**. If approved, you may continue to deploy and work on the Extra Features. Please add the Extra Features you implement to the list you added to the comment on your first PR.
- Blazing fast rendering with the virtual DOM
- Robust developer tools for debugging
- Component based structure maximizes reusablity and makes codebase more maintainable
- Unidirectional data flow increases app performance and makes debugging easier
- API friendly library works seamlessly with and is extendable across numerous frameworks to leverage advanced UI development

## Deployment
- Styled Components

After your PM certifies that all MVP features are complente, it's time to work on deploying it online for the world to see. We recommend you deploy your server to [Heroku](https://devcenter.heroku.com/articles/getting-started-with-nodejs#introduction), and your front end to [netlify](https://www.netlify.com/blog/2016/09/29/a-step-by-step-guide-deploying-on-netlify/). Both services provide free tiers and easy to use interfaces.
- Scopes styles to a component to avoid style leaks
- Linters will show unused components so they can be removed
- Source order independence eliminates the need to import files in a certain order
- Compose new styles from existing components
- Passing properties to the component allows for more flexibility

Additionally, it is recommended that you keep your front end and backend codebases in separate GitHub repositories. This helps with deploying, since the different parts of your application will be deployed on different platforms.
#### Backend

## Extra Features:
- heroku

Once your MVP has been approved, you have been given a feature list that the client would love to have completed. Your goal would be to finish MVP as soon as you can and get working the list of extra features.
- Node.js

- Setup Auto-Deploy on Heroku
- Provide documentation for how to interface with your api.
- Add pagination for long lists of notes.
- Create and display tags that can be added to notes and stored in the Database.
- Allow users to clone notes.
- Search functionality.
- Create a Registration Page that allows users to create accounts for your app and sign in with email/password.
- Allow users to sign in with a third party service (google, facebook, github, club penguin, etc...)
- Allow users to create Lists and assign notes to a list.
- Allow users to attach images to notes.
- Allow multiple users to collaborate on notes.
- Add Unit and Integration Tests.
- Utilizes Google's V8 JS engine which is lightening fast, highly performant, and more scalable
- Event loop allows non-blocking I/O operations which enhances speed of code execution
- Integrates seamlessly with microservices architecture
- Fullstack JS allows JS developers to work on both client and server sides potentially increasing productivity and saving money for startups

## Super Duper Extra Credit Bonus Features
- Express

- Add a payment form integrating with _Stripe_ that allows Users to buy a _"Premium"_ version of Lambda Notes.
- Gate your favorite feature behind the _premium_ paywall
- Includes numerous routing features and separate handlers for HTTP methods
- Serves static files such as images and CSS / JS files
- Integrates seamlessly with many popular template engine and NPM module plugins

You will notice that this repository does not have any starter code. This is on purpose. You are to start from scratch using any files you have built throughout your time here at Lambda School as reference.
## API

### Third Party API

[Gaia](https://github.com/blockstack/gaia)

- Blockstack applications use the Gaia storage system to store data on behalf of a user. When the user logs in to an application, the authentication process gives the application the URL of a Gaia hub, which performs writes on behalf of that user. The Gaia hub authenticates writes to a location by requiring a valid authentication token, generated by a private key authorized to write at that location.

- [Stripe](https://stripe.com/docs/api)

- Users can pay for the premium version of the serbvice. Stripe verifies and charges their credit card.

- [Blockstack](https://github.com/blockstack/blockstack.js/blob/master/src/auth/README.md)
- Users can sign up/log in using Blockstack's bearer token-based authentication system.

### API Endpoints

| Method | Endpoint | Request | Response |
| ------ | ------------------- | --------------------- | ----------------------------- |
| GET | /users/profile | | Object of logged in user |
| GET | /users/subscription | email\ | Object with subscription type |
| GET | /payment | | Array of invoice objects |
| POST | /payment | userId, stripeCharges | Invoice |
| GET | /notes | | Array of notes |
| GET | /notes/:id | | Single note |
| POST | /create | | Create note object |
| PUT | /edit/:id | | Edit existing note object |
| DELETE | /delete/:id/ | | Delete an existing note |
| GET | /auth/logout | | 200 on successful logout |

## Security

### Authentication & Authorization

#### Blockstack

Blockstack Authentication provides single sign on and authentication without third parties or remote servers. Blockstack Authentication is a bearer token-based authentication system. From an app user's perspective, it functions similar to legacy third-party authentication techniques that they're familiar with. For an app developer, the flow is a bit different from the typical client-server flow of centralized sign in services (e.g., OAuth). Rather, with Blockstack, the authentication flow happens entirely client-side.

### Payments

#### Stripe & Credits

Stripe is used to securely verify user credit cards and payments. After a user submits a payment, if it is successful, Stripe will send back a response the the payment is valid as well as an invoice that is saved to the database. Once this is complete, the user can access the premium features.
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 morgan = require("morgan");

const configureRoutes = require("../config/routes.js");

const server = express();

server.use(helmet());
server.use(cors());
server.use(express.json());
server.use(morgan("short"));

configureRoutes(server);

module.exports = {
server
};
44 changes: 44 additions & 0 deletions auth/authenticate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
const jwt = require("jsonwebtoken");

const jwtKey =
process.env.JWT_SECRET ||
"add a .env file to root of project with the JWT_SECRET variable";

// Add an authentication function
function authenticate(req, res, next) {
const token = req.get("Authorization");

if (token) {
jwt.verify(token, jwtKey, (err, decoded) => {
if (err) return res.status(401).json(err);

req.decoded = decoded;

next();
});
} else {
return res.status(401).json({
error: "No token provided, must be set on the Authorization Header"
});
}
}

// Add a function to generate a JWT
function generateToken(user) {
const payload = {
usernanme: user.usernanme
};

// TODO: Determine best practice for jwtid
const options = {
expiresIn: "8h",
jwtid: "8675309"
};

return jwt.sign(payload, jwtKey, options);
}

module.exports = {
authenticate,
generateToken
};
Loading