Skip to content

Commit

Permalink
Adding CORS!
Browse files Browse the repository at this point in the history
  • Loading branch information
javieraviles committed Jun 26, 2018
1 parent 96610f4 commit c462164
Show file tree
Hide file tree
Showing 4 changed files with 58 additions and 5 deletions.
35 changes: 33 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,25 @@ The main purpose of this repository is to build a good project setup and workflo

Koa is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs. Through leveraging generators Koa allows you to ditch callbacks and greatly increase error-handling. Koa does not bundle any middleware within core, and provides an elegant suite of methods that make writing servers fast and enjoyable.

Through a Travis-Heroku CI pipeline, this boilerplate is deployed [here](https://node-typescript-koa-rest.herokuapp.com/)! You can try to make requests to the different endpoints defined (GET /, GET /jwt, GET /users, POST /user...) and see how it works. The following Authorization header will have to be set (already signed with the boilerplate's secret) to pass the JWT middleware:
Through a Travis-Heroku CI pipeline, this boilerplate is deployed [here](https://node-typescript-koa-rest.herokuapp.com/)! You can try to make requests to the different defined endpoints and see how it works. The following Authorization header will have to be set (already signed with the boilerplate's secret) to pass the JWT middleware:

HEADER
```
Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjEiLCJuYW1lIjoiSmF2aWVyIEF2aWxlcyIsImVtYWlsIjoiYXZpbGVzbG9wZXouamF2aWVyQGdtYWlsLmNvbSJ9.7oxEVGy4VEtaDQyLiuoDvzdO0AyrNrJ_s9NU3vko5-k
```

AVAILABLE ENDPOINTS

| method | resource | description |
|:-------------------|:-----------------|:-----------------------------------------------------------------------------------------------|
| `GET` | `/` | Simple hello world response |
| `GET` | `/jwt` | Dummy endpoint to show how JWT info gets stored in ctx.state |
| `GET` | `/users` | returns the collection of users present in the DB |
| `GET` | `/users/:id` | returns the specified id user |
| `POST` | `/users` | creates a user in the DB (object user to be includued in request's body) |
| `PUT` | `/users/:id` | updates an already created user in the DB (object user to be includued in request's body) |
| `DELETE` | `/users/:id` | deletes a user from the DB (JWT token user ID must be the same as the user you want to delete) |

## Pre-reqs
To build and run this app locally you will need:
- Install [Node.js](https://nodejs.org/en/)
Expand All @@ -33,6 +46,7 @@ To build and run this app locally you will need:
* Winston Logger
* JWT auth koa-jwt
* Helmet (security headers)
* CORS

# Getting Started
- Clone the repository
Expand Down Expand Up @@ -286,15 +300,30 @@ app.use(function(ctx, next){

If you want to authenticate from the API, and you fancy the idea of an auth provider like Auth0, have a look at [jsonwebtoken — JSON Web Token signing and verification](https://github.com/auth0/node-jsonwebtoken)


## CORS
This boilerplate uses @koa/cors, a simple CORS middleware for koa. If you are not sure what this is about, click [here](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS).

```
// Enable CORS with default options
app.use(cors());
```
Have a look at [Official @koa/cors docs](https://github.com/koajs/cors) in case you want to specify 'origin' or 'allowMethods' properties.


## Helmet
This boilerplate uses koa-helmet is a wrapper for helmet to work with koa. It provides important security headers to make your app more secure by default.
This boilerplate uses koa-helmet, a wrapper for helmet to work with koa. It provides important security headers to make your app more secure by default.

Usage is the same as [helmet](https://github.com/helmetjs/helmet). Helmet offers 11 security middleware functions (clickjacking, DNS prefetching, Security Policy...), everything is set by default here.

```
// Enable helmet with default options
app.use(helmet());
```

Have a look at [Official koa-helmet docs](https://github.com/venables/koa-helmet) in case you want to customize which security middlewares are enabled.


# Dependencies
Dependencies are managed through `package.json`.
In that file you'll find two sections:
Expand All @@ -308,13 +337,15 @@ In that file you'll find two sections:
| koa-jwt | Middleware to validate JWT tokens. |
| koa-router | Router middleware for koa. |
| koa-helmet | Wrapper for helmet, important security headers to make app more secure|
| @koa/cors | Cross-Origin Resource Sharing(CORS) for koa |
| pg | PostgreSQL driver, needed for the ORM. |
| reflect-metadata | Used by typeORM to implement decorators. |
| typeorm | A very cool SQL ORM. |
| winston | Logging library. |
| class-validator | Decorator based entities validation. |
| pg-connection-string | Parser for database connection string |


## `devDependencies`

| Package | Description |
Expand Down
14 changes: 14 additions & 0 deletions package-lock.json

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

9 changes: 6 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "node-typescript-koa-rest",
"version": "1.2.0",
"description": "API REST using NodeJS and KOA framework, typescript. TypeORM for SQL with class-validators. Middlewares JWT and Winston.",
"version": "1.3.0",
"description": "API REST using NodeJS and KOA framework, typescript. TypeORM for SQL with class-validators. Middlewares JWT, CORS, Winston Logger.",
"main": "dist/server.js",
"scripts": {
"watch-server": "nodemon --watch 'src/**/*' -e ts,tsx --exec ts-node src/server.ts",
Expand Down Expand Up @@ -34,7 +34,8 @@
"sql",
"api",
"rest",
"heroku"
"heroku",
"cors"
],
"repository": "github:javieraviles/node-typescript-koa-rest",
"devDependencies": {
Expand All @@ -44,6 +45,7 @@
"@types/koa-helmet": "^3.1.2",
"@types/koa-jwt": "^3.3.0",
"@types/koa-router": "^7.0.28",
"@types/koa__cors": "^2.2.2",
"@types/node": "^6.0.110",
"@types/shelljs": "^0.7.9",
"@types/winston": "^2.3.9",
Expand All @@ -54,6 +56,7 @@
"typescript": "^2.8.3"
},
"dependencies": {
"@koa/cors": "^2.2.1",
"class-validator": "^0.8.5",
"dotenv": "^5.0.1",
"koa": "^2.5.1",
Expand Down
5 changes: 5 additions & 0 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import * as Koa from 'koa';
import * as jwt from 'koa-jwt';
import * as bodyParser from 'koa-bodyparser';
import * as helmet from 'koa-helmet';
import * as cors from '@koa/cors';
import * as winston from 'winston';
import * as dotenv from 'dotenv';
import { createConnection } from 'typeorm';
Expand Down Expand Up @@ -44,9 +45,13 @@ createConnection({
// Provides important security headers to make your app more secure
app.use(helmet());

// Enable cors with default options
app.use(cors());

// Logger middleware -> use winston as logger (logging.ts with config)
app.use(logger(winston));

// Enable bodyParser with default options
app.use(bodyParser());

// JWT middleware -> below this line routes are only reached if JWT token is valid, secret as env variable
Expand Down

0 comments on commit c462164

Please sign in to comment.