Note: The `_` before a variable name is used to indicate that the variable isn't used. This is to avoid the VSCode warning about unused variable.
__Note: The \_ before a variable name is used to indicate that the variable isn't used. This is to avoid the VSCode warning about unused variable__
---
```ts
import http from 'http'
import http from 'http'
const server = http.createServer((\_req, res) => {
const server = http.createServer((\_req, res) => {
res.write('Some cool response!')
res.write('Some cool response!')
res.end()
res.end()
})
})
const port = 3000
const port = 3000
server.listen(port)
server.listen(port)
console.log('HTTP Server listening port', port)
console.log('HTTP Server listening port', port)
```
For this code to work, remember "type": "module" in your package.json. Also, you may need to change your port number to something other than 3000.
For this code to work, remember "type": "module" in your package.json. Also, you may need to change your port number to something other than 3000.
# PORT numbers
# PORT numbers
__The port number (16 bit unsigned integer) defines a port through which the communication to your application happens. Ports allow multiple applications to be located on the same host (IP).__
The port number (16 bit unsigned integer) defines a port through which the communication to your application happens. Ports allow multiple applications to be located on the same host (IP).
__The client connects to this port in some server (defined by an IP address), so the client and the server are able to communicate.__
The client connects to this port in some server (defined by an IP address), so the client and the server are able to communicate.
__Computers have several different ports at their disposal ___but_ __ some of them are being used and your application might not be able to assign those ports to itself.__
Computers have several different ports at their disposal but some of them are being used and your application might not be able to assign those ports to itself.
__Ports from 0 to 1023 are the system ports. There are restrictions in manually assigning applications to use them.__
---
<divclass='columns'markdown='1'>
<divmarkdown='1'>
Ports from 0 to 1023 are the system ports. There are restrictions in manually assigning applications to use them.
__Generally speaking, ports from 1024 to 65535 are available for user to assign applications to use them.__
Generally speaking, ports from 1024 to 65535 are available for user to assign applications to use them.
</div>
<divmarkdown='1'>


</div>
</div>
# Request and response
# Request and response
__The request object is an object that is sent__ __ from the client to the server.__
The request object is an object that is sent ***from the client to the server.***
__The response object is an object that is sent__ __ from the server to the client__ __. When you modify the response object, you're essentially modifying how the server responds to the client.__
The response object is an object that is sent ***from the server to the client***. When you modify the response object, you're essentially modifying how the server responds to the client.
_const_ server = http.createServer(( _req_ , _res_ ) _=>_ {
```ts
const server = http.createServer((req, res) => {
res.write("Some cool response!");
res.write("Some cool response!");
res.end();
res.end();
});
});
```
# Exercise 1: Simple Request & Response
# Exercise 1: Simple Request & Response
<!--_class: "exercise invert" -->
Create a basic HTTP-server application. The application should respond to GET requests by returning a response with the following content: "Hello world!".
Create a basic HTTP-server application. The application should respond to GET requests by returning a response with the following content: "Hello world!".
Test your application either with _Postman,_ or by navigating your browser to http://localhost:<_your\_portnumber_>
Test your application either with client such as Insomnia or Postman, or by navigating your browser to `http://localhost:<your_portnumber>`
Initialize a new TypeScript project with appropriate `tsconfig.json` file and scripts for building and/or running the project in development mode using `ts-node`.
Create a very simple express project in `index.ts`
```ts
import express from 'express'
import express from 'express'
const server = express()
const server = express()
server.listen(3000, () => {
server.listen(3000, () => {
console.log('Listening to port 3000')
console.log('Listening to port 3000')
})
})
```
__Then start the server and connect to __ [http://localhost:3000](http://localhost:3000) __ with your browser.__ __ (See instructions on the next slide)_
Then start the server as you would any other TS project and connect to http://localhost:3000 with your browser or using an API tool such as Insomnia or Postman.
# Starting the server
__To make using the import statement possible, we need to edit the __ __package.json.__
__Add a new script "start" with the value "node index.js" under "scripts" object in the package. json__
__(you can name index.js to whatever file your server code is in)_
__Add "type": "module" property__
__Now you can run the server with __ _npm start_
# Express - Requests
# Express - Requests
__The server does not yet ___do___ anything except listens. That is because we have not defined how it should deal with incoming __ _requests._
The server does not yet *do* anything except listens. That is because we have not defined how it should deal with incoming **requests**.
__With Express you can easily process different kind of requests, e.g.,__
With Express you can easily process different kind of requests, e.g. GET, POST, DELETE etc.
Notice how we import `Request` and `Response` from `express`. These types are defined in express, but identically named types are also available from JavaScript basic library.
---
If you use the Request and Response types without importing them, JS mistakenly thinks they are different objects, and complains about incompatibility.
Käy läpi tämä esimerkki, ja anna sitten tehtäväksi ensinnäkin muuttaa portti ja palautusviesti muotoon "Hello world!". Tällä tavalla kaikkien pitää ymmärtää miten tämä toimii.
Anna heidän pähkäillä miten voi tehdä päätepisteen, johon pääsee näin localhost:5000/secondPage. Tämän jälkeen käy läpi yhdessä tämä heidän kanssa.
# Express - Endpoints
__To create a new ___endpoint ___we define what ___kind___ of request we're handling, then what the ___route___ to the endpoint is and finally what the endpoint ___does___.__
# Express - Endpoints
__In the below example we are creating an endpoint that handles a ____GET____ request to route ____/foobar__ __, that sends a response containing the string 'OK'.__
To create a new **endpoint** we define what *kind* of request we're handling, then what the *route* to the endpoint is and finally what the endpoint *does*.
In the below example we are creating an endpoint that handles a GET request to route `/foobar`, that sends a response containing the string 'OK'.
```ts
server.get('/foobar', (req, res) => {
server.get('/foobar', (req, res) => {
res.send('OK')
res.send('OK')
})
})
```
---
# Nodemon
# Nodemon
__Reminder____: If you are not using Nodemon in development, you are making your life unnecessarily difficult. Use Nodemon. __
Reminder : If you are not using Nodemon in development, you are making your life unnecessarily difficult. Use Nodemon.
__Instructions are ____below as a refresher.__
Instructions are below as a refresher.
# Nodemon with JavaScript
# Nodemon with JavaScript
One of the handiest packages out there is nodemon, which monitors your node program. Whenever you save your files, it reloads the program, showing you immediately the results of your changes.
One of the handiest packages out there is nodemon, which monitors your node program. Whenever you save your files, it reloads the program, showing you immediately the results of your changes.
Nodemon is installed as a dev dependency __npm install --save-dev nodemon__
Nodemon is installed as a dev dependency npm install --save-dev nodemon
To use nodemon, you should have a development script "dev": "nodemon ./index.js"
To use nodemon, you should have a development script "dev": "nodemon ./index.js"
# Nodemon with TypeScript
# Nodemon with TypeScript
To get Nodemon working with TypeScript we need additional package to run our TS code without waiting for it to compile. __npm install --save-dev nodemon ts-node__
To get Nodemon working with TypeScript we need additional package to run our TS code without waiting for it to compile. npm install --save-dev nodemon ts-node
After installing, nodemon works directly with .ts files. "dev": "nodemon ./index.ts"
After installing, nodemon works directly with .ts files. "dev": "nodemon ./index.ts"
# Exercise 2: Simple Express Server
# Exercise 2: Simple Express Server
<!--_class: "exercise invert" -->
Create a basic Express application. The application should respond to GET requests by returns a response with the following content: "Hello world!".
Create a basic Express application. The application should respond to GET requests by returns a response with the following content: "Hello world!".
Extra: Add a new endpoint to your application. So, in addition to accessing _http://localhost:3000_ , try to send something back from _http://localhost:3000/endpoint2_ .
**Extra**: Add a new endpoint to your application. So, in addition to accessing http://localhost:3000, try to send something back from http://localhost:3000/endpoint2.
---
<!-- ^ Tuon extran ei pitäisi olla extra, vaan perustehtävä. Extraksi ehkä toisen serverin käynnistäminen eri porttiin samanaikaisesti -->
Johdatteleva esimerkki vielä ennen seuraavaa tehtävää.
# Request query & param types
# Request query & param types
__Request parameters and query parameters are always of type ___string___. If a number is passed, it will be a string that contains a number. __
Request parameters and query parameters are always of type **string**. If a number is passed, it will be a string that contains a number.
__The example on right will ____always ____return 404, since the strict equality __ item.id === id
The example below will always return 404, since the strict equality `item.id === id` will never be true. This is because the `item.id` is of type **number** and `id` being of type **string**.
__will never be true. This is because the__ __ item.id ____is of type ___number ___and____ id ____being of type ___string___.__
---
import express from 'express'
```ts
import express, { Request, Response } from 'express'
Whenever you enter this endpoint from the browser, it
should respond with a JSON object with information on how many times the endpoint has been accessed.
# Exercise 3: Counter Server
<!--_class: "exercise invert" -->
Extra: Make it possible to set the counter to whichever
Create an API that consists of only one endpoint: `/counter`
Whenever you enter this endpoint from the browser, it should respond with a JSON object with information on how many times the endpoint has been accessed.
integer with a query parameter /counter?number=5
**Extra**: Make it possible to set the counter to whichever integer with a query parameter /counter?number=5
__Generally speaking, middleware is an application that does something in between some other applications. __
Generally speaking, middleware is an application that does something in between some other applications.
__There are tons of middleware libraries available for Express.__
There are tons of middleware libraries available for Express.
__What this means in Express: with a middleware, you can manipulate the ____the client request and server response __ __in the client-server communication.__
What this means in Express: with a middleware, you can manipulate the client request and server response in the client-server communication.
__Middleware__ __ functions are functions that have access to the ____request____ object (__ _req___), the ____response____ object (__ _res___), and the ___next___ function in the application's request-response cycle. When the ___next___ function is invoked, the next middleware function is executed.__
Middleware functions are functions that have access to the request object (`req`), the response object (`res`), and the `next` function in the application's request-response cycle. When the `next` function is invoked, the next middleware function is executed.
if (req.headers.Authentication === undefined) { // Read the request object
if (req.headers.Authentication === undefined) { // Read the request object
res.status(401).send('Missing Authentication Header') // Modify the response object
res.status(401).send('Missing Authentication Header') // Modify the response object
return
} else {
next() // Execute the next middleware
}
}
next() // Execute the next middleware
}
}
```
__In Express, .use() method initializes a middleware (argument 2) in a given path (argument 1).__
In Express, .use() method initializes a middleware (argument 2) in a given path (argument 1).
__In the middleware, the next() function will jump to the next middleware or endpoint.__
In the middleware, the next() function will jump to the next middleware or endpoint.
```ts
server.use('/customers', authCheck)
server.use('/customers', authCheck)
server.get('/customers', (req, res) => {
server.get('/customers', (req, res) => {
// we know that Authentication header is present
// we know that Authentication header is present
...
...
```
})
# Exercise 5: Logger Middleware
# Exercise 5: Logger Middleware
<!--_class: "exercise invert" -->
Create a new project called Student Registry. We will be developing this program in stages during this lecture. For now it should have a single GET endpoint /students that returns an empty list.
Create a new project called Student Registry. We will be developing this program in stages during this lecture. For now it should have a single GET endpoint `/students` that returns an empty list.
Create a logger middleware function that is used in all the project's endpoints. The middleware should log
Create a logger middleware function that is used in all the project's endpoints. The middleware should log
Add a middleware function that sends a response with status code 404 and an appropriate error message, if user tries to use an endpoint that does not exist.
Add a middleware function that sends a response with status code 404 and an appropriate error message, if user tries to use an endpoint that does not exist.
If you have not already done so, move all your middleware to a separate file, to keep your program clean and readable.
If you have not already done so, move all your middleware to a separate file, to keep your program clean and readable.
__We have gone through what a GET request is. Let's briefly go through what other types of requests are necessary for you.__
We have gone through what a GET request is. Let's briefly go through what other types of requests are necessary for you.
__GET /products/:id → Returns a single product identified by its id__
__GET /products →Returns all the products__
__POST /products → Creates a new product__
__DELETE /products/:id → Removes a single product identified by its id__
- GET `/products/:id` → Returns a single product identified by its id
- GET `/products` →Returns all the products
__PUT /products/:id → Updates an existing product__
- POST `/products` → Creates a new product
- DELETE `/products/:id` → Removes a single product identified by its id
- PUT `/products/:id` → Updates an existing product
Basic RESTFUL functionality is often referenced as a CRUD (Create, Read, Update, Delete).
Basic RESTFUL functionality is often referenced as a CRUD (Create, Read, Update, Delete).
# Handling request content
__To properly handle some requests, e.g., POST requests, in Express, a body-parser middleware must be taken into use. It's as simple as:__
const server = express()
# Handling request content
server.use(express.json())
To properly handle some requests, e.g., POST requests, in Express, a body-parser middleware must be taken into use. It's as simple as:
```ts
const server = express();
server.use(express.json());
```
You might encounter a separate body-parser being used. This is no longer necessary, as Express 4.16+ includes a body parser middleware built-in.
You might encounter a separate body-parser being used. This is no longer necessary, as Express 4.16+ includes a body parser middleware built-in.
express.urlencoded() __allows us to parse url-encoded forms by attaching the data to the request body.__
---
const app = express()
`express.urlencoded()` allows us to parse url-encoded forms by attaching the data to the request body.
```ts
const app = express();
app.use(express.json());
app.use(express.urlencoded({extended: false}));
```
app.use(express.json())
The "extended" parameter's false value only says that we are not dealing with any complicated objects (objects with sub objects, etc).
app.use(express.urlencoded({extended: false}))
__The "extended" parameter's false value only says that we are not dealing with any complicated objects (objects with sub objects, etc)_
# Basic POST request
# Basic POST request
const app = express()
```ts
const app = express();
app.use(express.json())
app.use(express.json());
app.use(express.urlencoded({extended: false}))
app.get("/", (req, res) => {
app.get("/", (req: Request, res: Response) => {
console.log("GET request init!");
console.log("GET request init!");
res.sendFile(__dirname + "/index.html");
});
res.sendFile(\_\_dirname + "/index.html");
app.post("/", (rreq: Request, res: Response) => {
})
app.post("/", (req, res) => {
console.log("POST request init!");
console.log("POST request init!");
console.log(req.body);
console.log(req.body);
res.redirect("/");
res.redirect("/");
});
```
})
# Request Body
# Request Body
__GET__ __ methods should not in general have body parameters. The GET method should only be used to get data, the request should not convey data. __
GET methods should not in general have body parameters. The GET method should only be used to get data, the request should not convey data.
__Despite this, most modern implementations can send and receive request bodies in all request types.__
Despite this, most modern implementations can send and receive request bodies in all request types.
__The requests that should not include body are ____CONNECT__ __, ____GET__ __, ____HEAD__ __, ____OPTIONS__ __, and ____TRACE__ __. __
The requests that should not include body are CONNECT, GET, HEAD, OPTIONS and TRACE.
# Request Body Types
__Request body is parsed by the express body parser, and therefore it can contain any basic JavaScript data types. Notice that this differs from the request parameters and queries.__
__This also means that you do not know what the data type of any given body parameter will be. It might be necessary to check this in some cases.__
# Request Body Types
# TypeScript Body Casting
__If you want to enforce type safety, the solution is to validate the user input before using it.__
Request body is parsed by the express body parser, and therefore it can contain any basic JavaScript data types. Notice that this differs from the request parameters and queries.
__This is usually a good idea even if not using TypeScript, since it is important to know what type all the variables are in your code.__
This also means that you do not know what the data type of any given body parameter will be. It might be necessary to check this in some cases.
import express, { NextFunction, Request, Response} from 'express'
const server = express()
server.use(express.json())
# TypeScript Body Casting
interface Body {
If you want to enforce type safety, the solution is to validate the user input before using it.
name: string
This is usually a good idea even if not using TypeScript, since it is important to know what type all the variables are in your code.
POST /student should expect the request body to include student _id_ , _name _ and _email_. If some of these parameters are missing, the endpoint should return a response with status code 400 and an error message. The endpoint should store the student information in an array called _students_. The endpoint should return an empty response with status code 201.
POST `/student` should expect the request body to include student *id*, *name* and *email*. If some of these parameters are missing, the endpoint should return a response with status code 400 and an error message. The endpoint should store the student information in an array called **students**. The endpoint should return an empty response with status code 201.
GET /student/:id should return the information of a single student, identified by the _id_ request parameter. The response should be in JSON format. If there is no such student, the endpoint should return 404.
GET `/student/:id` should return the information of a single student, identified by the *id* request parameter. The response should be in JSON format. If there is no such student, the endpoint should return 404.
Modify the GET /students endpoint to return the list of all student _ids_, without names or emails.
Modify the GET `/students` endpoint to return the list of all student *ids*, without names or emails.
PUT /student/:id should expect the request body to include student _name_ or _email_ . If both are missing, the endpoint should return a response with status code 400 and an error message. The endpoint should update an existing student identified by the request parameter _id_ .
PUT `/student/:id` should expect the request body to include student *name* or *email*. If both are missing, the endpoint should return a response with status code 400 and an error message. The endpoint should update an existing student identified by the request parameter *id*.
DELETE /student/:id should remove a student identified by the request parameter _id_ .
Both endpoints should return 404 if there is no student matching the request parameter _id_ . On success both endpoint should return an empty response with status code 204.
DELETE `/student/:id` should remove a student identified by the request parameter *id*.
Both endpoints should return 404 if there is no student matching the request parameter *id*. On success both endpoint should return an empty response with status code 204.
We can make a web application out of our REST-API. First you need to create a folder at the root of your application, and name it for example "public". When you add an index.html file there, with the example below it will served when you send a GET request to our server.
We can make a web application out of our REST-API. First you need to create a folder at the root of your application, and name it for example "public". When you add an index.html file there, with the example below it will served when you send a GET request to our server.
```ts
import express from 'express'
import express from 'express'
const server = express()
const server = express()
server.use(express.static('public')) // defaults to root route '/'
Until now we have been building our routes to index.js. This is fine for VERY small applications, but we'd like to keep our code readable even if our application grows in size.
Until now we have been building our routes to `index.ts`. This is fine for VERY small applications, but we'd like to keep our code readable even if our application grows in size.
__Routers__ are Express classes that are dedicated to route handling. We can use them to group routes to meaningful units that share functionality.
Routers do not require any installation since they are native express classes.
**Routers** are Express classes that are dedicated to route handling. We can use them to group routes to meaningful units that share functionality. Routers do not require any installation since they are native express classes.
The following application, while still being extremely simple, already has a problem: index.js file is doing several things.
The following application, while still being extremely simple, already has a problem: `index.ts` file is doing several things.
It handles two kinds of routes and starts the server. Usually it also adds middleware and some configuration.
It handles two kinds of routes and starts the server. Usually it also adds middleware and some configuration.
Most of the time it is best to separate the route handling to dedicated routers.
Most of the time it is best to separate the route handling to dedicated routers.
server.listen(3000, () => console.log('Listening to port 3000'))
server.listen(3000, () => console.log('Listening to port 3000'))
```
We create two routers, one for each logical unit: _authorsRouter.js_ and _articlesRouter.js_
---
The only difference in the route definition is in the route paths.
We create two routers, one for each logical unit: `authorsRouter.ts` and `articlesRouter.ts`. The only difference in the route definition is in the route paths.
* Authorization: Determining access rights based on your privileges
* Authorization: Determining access rights based on your privileges
* We shall first look at password authorization, and later token-based authentication.
* We shall first look at password authorization, and later token-based authentication.
# Storing passwords
# Storing passwords
# Password Hashing
# Password Hashing
Passwords should never be stored as plain text in to a database. Instead a password _hash_ should be stored instead.
Passwords should never be stored as plain text in to a database. Instead a password hash should be stored instead.
_Hash function_ maps data of any size (in our case a password) to a _hash _ of fixed length.
**Hash function** maps data of any size (in our case a password) to a hash of fixed length.
Hash functions are *one-way functions*, which means they can not be reversed. This means that you can not deduce the original password from the hash.
We can use (a variant of) the original hash function to compare a password and the hash and deduce if the hash matches the password or not.
Hash functions are _one-way functions_ , which means they can not be reversed. This means that you can not deduce the original password from the hash.
We can use (a variant of) the original hash function to compare a password and the hash and deduce if the hash _matches_ the password or not.
# Salting
# Salting
Bare hash functions produce identical results from identical inputs.
Bare hash functions produce identical results from identical inputs.
To add complexity, a some random data is added to the input. This data is called _salt_ and the process of adding the salt is called _salting_ .
To add complexity, a some random data is added to the input. This data is called salt and the process of adding the salt is called salting.
This means two identical passwords produce different hashes, since both have unique salt.
This means two identical passwords produce different hashes, since both have unique salt.
Salt can be stored in the hash or it can be stored separately. The hash function needs to know the salt in order to verify passwords against the hash.
Salt can be stored in the hash or it can be stored separately. The hash function needs to know the salt in order to verify passwords against the hash.
# Hashing a password
# Hashing a password
We will use Argon library to do our hashing and comparing. Install Argon with __npm install argon2__
We will use **Argon** library to do our hashing and comparing. Install Argon with `npm install argon2`
Using Argon to hash passwords is very straightforward. Salting is done automatically (although you can configure it in more detail if you wish to do so) and the salt is added to the hash.
Using Argon to hash passwords is very straightforward. Salting is done automatically (although you can configure it in more detail if you wish to do so) and the salt is added to the hash.
```ts
import argon2 from 'argon2'
import argon2 from 'argon2'
const password = process.argv[2]
const password = process.argv[2]
argon2.hash(password)
argon2.hash(password)
.then(result => console.log(result))
.then(result => console.log(result))
```
You can of course also use async/await syntax instead of .then()
You can of course also use _async/await_ syntax instead of _.then()
# Comparing hashes
# Comparing hashes
Notice if you run the example from the previous slide multiple times, you always get a different result. In order to verify that a particular password matches the hash, Argon's _verify_ function is used.
Notice if you run the example from the previous slide multiple times, you always get a different result. In order to verify that a particular password matches the hash, Argon's *verify* function is used.
Verify returns a promise that resolves to either _true,_ if the password matches the hash, or _false_ if it doesn't.
Verify returns a promise that resolves to either true, if the password matches the hash, or false if it doesn't.
With dotenv library, we can create environment variables that can be loaded into process.env. We can access the environment variables in our application with process.env.{variable\_name}.
With dotenv library, we can create environment variables that can be loaded into process.env. We can access the environment variables in our application with `process.env.<variable_name>`.
To use dotenv
To use dotenv
Install dotenv package with __npm install dotenv__
1) Install dotenv package with `npm install dotenv`
2) Create a `.env` file in to the root folder of your application where the values are declared
3) Import the dotenv configuration in the project `import 'dotenv/config'`
4) Access the variables defined in `.env` file `const PORT = process.env.PORT`
Create a __.env __ file in to the root folder of your application where the values are declared
Import the dotenv configuration in the projectimport 'dotenv/config'
Access the variables defined in __.env__ fileconst PORT = process.env.PORT
# .env File
# .env File
The custom environment variables are declared in the .env file. The file must be located in the folder from where the program is ran. This is usually the root folder.
The custom environment variables are declared in the .env file. The file must be located in the folder from where the program is ran. This is usually the root folder.
The variables are declared as in the example below, separated by line changes. All values are _strings _ (even if JS parses some automatically).
The variables are declared as in the example below, separated by line changes. All values are strings (even if JS parses some automatically).
Notice there are no spaces around the equals (=) sign, nor any kind of quotation marks.
Notice there are no spaces around the equals (=) sign, nor any kind of quotation marks.
```
API_URL=https://cataas.com
PORT=3000
```
API\_URL=https://cataas.com
PORT=3000
# dotenv in Development
# dotenv in Development
* In many cases the environment variables are configured on the platform from where the program is ran. In those cases you might want to run dotenv only in development mode.
* In many cases the environment variables are configured on the platform from where the program is ran. In those cases you might want to run dotenv only in development mode.
* Install as dev dependency __npm install --save-dev dotenv__
* Install as dev dependency `npm install --save-dev dotenv`
* Create __.env__ file as usual.
* Create `.env` file as usual.
* Optionally include ENVIRONMENT=development variable
* Optionally include `ENVIRONMENT=development` variable
* Run your application from config.json script that preloads dotenv"dev": "nodemon -r dotenv/config index.js"
* Run your application from `package.json` script that preloads dotenv `"dev": "nodemon -r dotenv/config index.js"`
* Access environment variables as usualconst PORT = process.env.PORT
* Access environment variables as usual `const PORT = process.env.PORT`
# Exercise 5: Environmental Login
Add an admin login to the Students API. We want to store admin credentials in environment variables.
Add dotenv library as dependency.
Add a .env file that defines an admin username and an admin password hash.
Add an endpoint POST /admin that also expects two request body parameters, _username _ and _password_ . The endpoint should
# Exercise 5: Environmental Login
<!--_class: "exercise invert" -->
check that the username matches the one defined in the .env file
check that the password matches the hash defined in the .env file
Add an admin login to the Students API. We want to store admin credentials in environment variables.
if they match, it should return a response with status code204 (No Content)
Add dotenv library as dependency. Then add a `.env` file that defines an admin username and an admin password hash.
if they do not match, it should return a response with status code 401 (Unauthorized)
Add an endpoint POST `/admin` that also expects two request body parameters, *username* and *password*. The endpoint should
1) check that the username matches the one defined in the `.env` file
2) check that the password matches the hash defined in the `.env` file
3) if they match, it should return a response with status code 204 (No Content)
4) if they do not match, it should return a response with status code 401 (Unauthorized)
After verifying the identity of our user, we create a _token_ that we send to the client. The client stores that token and attaches it to all future requests. This token is enough to identify the request as authorized.
After verifying the identity of our user, we create a token that we send to the client. The client stores that token and attaches it to all future requests. This token is enough to identify the request as authorized.
Since the tokens are signed by us, we can also include data (such as user id) in the token. On all future requests we can rely that the id is correct since the JWT will be verified on every request.
Since the tokens are signed by us, we can also include data (such as user id) in the token. On all future requests we can rely that the id is correct since the JWT will be verified on every request.
@ -340,69 +325,68 @@ Tokens can (and should be) equipped with expiration dates.
# Creating a Token
# Creating a Token
Install the JSON Web Token package as dependency npm install jsonwebtoken
Install the JSON Web Token package as dependency `npm install jsonwebtoken`
Tokens are created with the _sign_ function that takes two parameters: _Payload:_ the data we want to include in the token. It can be empty. _Secret_ : either a string or a private key.
Tokens are created with the sign function that takes two parameters:
- Payload: the data we want to include in the token. It can be empty.
- Secret: either a string or a private key.
It can also accept an optional _options_ parameter. In that we can define the expiration date, compression algorithm, or many other things.
It can also accept an optional options parameter. In that we can define the expiration date, compression algorithm, or many other things.
```ts
import 'dotenv/config'
import 'dotenv/config'
import jwt from 'jsonwebtoken'
import jwt from 'jsonwebtoken'
const payload = { username: 'sugarplumfairy' }
const payload = { username: 'sugarplumfairy' }
const secret = process.env.SECRET
const secret = process.env.SECRET
const options = { expiresIn: '1h'}
const options = { expiresIn: '1h'}
const token = jwt.sign(payload, secret, options)
const token = jwt.sign(payload, secret, options)
console.log(token)
console.log(token)
```
The created JWT has three parts separated by period: header, payload and signature.
The created JWT has three parts separated by period: header, payload and signature.
# Exercise 6: Create a Token
# Exercise 6: Create a Token
<!--_class: "exercise invert" -->
Write a simple command line program that prints JSON Web tokens. Use the default algorithm (SHA256). Set the tokens to expire in fifteen minutes and include a payload of some JSON object.
Write a simple command line program that prints JSON Web tokens. Use the default algorithm (SHA256). Set the tokens to expire in fifteen minutes and include a payload of some JSON object.
Copy your JWT and paste it to [https://jwt.io](https://jwt.io) debugger. Verify that the debugger shows correct algorithm, data, and expiration date (iat).
Copy your JWT and paste it to https://jwt.io debugger. Verify that the debugger shows correct algorithm, data, and expiration date (iat).
Tokens are verified using the _verify_ function that takes two parameters:
Tokens are verified using the verify function that takes two parameters:
- Token: the token to be verified
- Secret: the secret that was used to create the token
_Token_ : the token to be verified
The verify function can also accept an optional options parameter.
_Secret_ : the secret that was used to create the token
The verify function returns a decoded token. Since it has been verified against our secret, we know that the information has not been altered.
The verify function can also accept an optional _options_ parameter.
If the token is invalid, the verify function throws an error. If this error is not caught, the program crashes.
The verify function returns a _decoded_ token. Since it has been verified against our secret, we know that the information has not been altered.
If the token is invalid, the verify function _throws an error_ . If this error is not caught, the program crashes.
# Exercise 7: Verify a Token
# Exercise 7: Verify a Token
<!--_class: "exercise invert" -->
Write a simple command line program that verifies JSON Web tokens.
Write a simple command line program that verifies JSON Web tokens.
The program should print the contents of the verified token. If the token is not valid, the program should print an error message and exit gracefully.
The program should print the contents of the verified token. If the token is not valid, the program should print an error message and exit gracefully.
Create a JWT in [https://jwt.io](https://jwt.io) debugger. Remember to set your secret value. Use your program to verify the token and see that the data entered is as it should be.
Create a JWT in https://jwt.io debugger. Remember to set your secret value. Use your program to verify the token and see that the data entered is as it should be.
When a user has received a token, it can be used to authenticate all future requests.
When a user has received a token, it can be used to authenticate all future requests.
Do this by adding the field _Authorization _ to the request header.
Do this by adding the field Authorization to the request header.
The value is "Bearer " plus the token.
The value is "Bearer " plus the token.
@ -410,295 +394,202 @@ This header can be added to requests generated by Fetch, Axios, or any other JS
Then protected routes can check that the authorization header is valid, and if not, send an error message. This is usually done using authorization middleware.
Then protected routes can check that the authorization header is valid, and if not, send an error message. This is usually done using authorization middleware.
# Authentication Middleware
# Authentication Middleware
A common way is to have user routes, such as login, logout or user creation in a separate router, which requires no token.
A common way is to have user routes, such as login, logout or user creation in a separate router, which requires no token.
Then all protected routes are set to use the authentication middleware.
Then all protected routes are set to use the authentication middleware.
The request parameter _user_ is set to the verified token data and can then be used in the actual route.
The request parameter user is set to the verified token data and can then be used in the actual route.
Let's look at the following example, written in JavaScript. There is a middleware that adds a _username _ property to the request object. Then the endpoint reads the username property and uses it to construct a response.
The above example uses a custom `AuthenticatedRequest` instead of regular `Request` as the type of the `req` object. This is because in TypeScript, if we try to add a new parameter, in this case "user", to a `Request` object, we get an error
```
What happens when we write the same code in TypeScript?
Property 'username' does not exist on type 'Request<ParamsDictionary,any,any,ParsedQs,Record<string,any>>'
We are trying to set a value to request property "username", but request objects are well defined objects that have no such property.
We are trying to set a value to request property "user", but request objects are well defined objects that have no such property.
We can not add or use properties that an object does not have. This is part of the type safety that TypeScript is here to enforce. If an object is of type Request, we know exactly what the properties are.
We can not add or use properties that an object does not have. This is part of the type safety that TypeScript is here to enforce. If an object is of type Request, we know exactly what the properties are.
The solution is to create an interface that extends the existing Request type. The new interface will have all the properties the Request has, plus the ones we define ourself.
---
interface CustomRequest extends Request {
username?: string
}
Since the interface extends Request, CustomRequest objects can be used anywhere where Request object is required.
Notice that the additional properties must be optional, signified by the question mark in the name. Otherwise existing Request objects can not be cast as CustomRequest objects.
This example has only a single string, but the extended object can be as complex as needed.
interface CustomRequest extends Request {
username?: string
}
Now we can use the "username" property when we declare that we are using CustomRequest instead of basic Request object.
import express, { Request, Response, NextFunction} from 'express'
The solution is to create an interface that extends the existing Request type. The new interface will have all the properties the Request has, plus the ones we define ourself.
```ts
interface AuthenticatedRequest extends Request {
user?: { username: string }
}
}
```
server.use(middleware)
Now our `AuthenticatedRequest` object can be used as a regular `Request` object (and hence is acceptable as a parameter to our Express route functions), and it can be used to store an object holding the authenticated username.
Modify the Students API /register and /login routes so that on success they return a response with status code 200 and a JWT with username as payload.
Modify the Students API `/register` and `/login` routes so that on success they return a response with status code 200 and a JWT with username as payload.
Secure all the routes in the _students _ router so that they require the user to be logged in to use the routes.
Secure all the routes in the students router so that they require the user to be logged in to use the routes.
Extra: Also modify the /admin route to return a JWT. Secure the POST, PUT and DELETE routes to require that in addition to being logged in, the user also needs to be an admin.
**Extra**: Also modify the `/admin` route to return a JWT. Secure the POST, PUT and DELETE routes to require that in addition to being logged in, the user also needs to be an admin.
Hint: Here you have some resources on sending a token with Postman.
*Hint*: Here you have some resources on sending a token with Postman.
Supertest is a library for testing API's. Let's see how to use it with Jest to test an Express app. Install supertest with
Supertest is a library for testing API's. Let's see how to use it with Jest to test an Express app. Install supertest, ts-jest and the required TypeScript types with
We now create a new test file and import our server there.
We now create a new test file and import our server there.
We use Supertest _request_ to get responses from our server. These responses can be tested just like any other Jest test.
We use Supertest request to get responses from our server. These responses can be tested just like any other Jest test.
_test/server.test.js_
</div>
<divmarkdown='1'>
import request from 'supertest'
```ts
//test/server.test.ts
import request from 'supertest'
import server from '../src/server.js'
import server from '../src/server.js'
describe('Server', () => {
describe('Server', () => {
it('Returns 404 on invalid address', async () => {
it('Returns 404 on invalid address', async () => {
const response = await request(server)
const response = await request(server)
.get('/invalidaddress')
.get('/invalidaddress')
expect(response.statusCode).toBe(404)
expect(response.statusCode).toBe(404)
})
})
it('Returns 200 on valid address', async () => {
it('Returns 200 on valid address', async () => {
const response = await request(server)
const response = await request(server)
.get('/')
.get('/')
expect(response.statusCode).toBe(200)
expect(response.statusCode).toBe(200)
expect(response.text).toEqual('Hello World!')
expect(response.text).toEqual('Hello World!')
})
})
})
})
```
# Common Resources
</div>
</div>
[https://www.npmjs.com/package/jest](https://www.npmjs.com/package/jest) → Official repository
[https://www.npmjs.com/package/supertest](https://www.npmjs.com/package/supertest) → Official repository
[https://jestjs.io/docs/api](https://jestjs.io/docs/api) → Jest API Docs. Very handy!
# Common Resources
[https://github.com/visionmedia/supertest](https://github.com/visionmedia/supertest) → Supertest's github repository. Includes guides for basic use cases.
https://www.npmjs.com/package/jest → Official repository
# Exercise 9: Test with Supertest
https://www.npmjs.com/package/supertest → Official repository
Use Supertest with Jest to create tests for the Students API /user/register and /user/login routes.
https://jestjs.io/docs/api → Jest API Docs. Very handy!
---
https://github.com/visionmedia/supertest → Supertest's github repository. Includes guides for basic use cases.