123 | );
124 | };
125 |
--------------------------------------------------------------------------------
/src/server/server.js:
--------------------------------------------------------------------------------
1 | require("dotenv").config({ path: "./variables.env" });
2 | const express = require("express");
3 | const cors = require("cors");
4 | const { uuid } = require("uuidv4");
5 | const {
6 | getUserByUsername,
7 | isEmptyObject,
8 | isPasswordCorrect,
9 | getAllBooks,
10 | getAllUsers,
11 | addBook,
12 | verifyToken,
13 | getFavoriteBooksForUser,
14 | getAudienceFromToken,
15 | generateToken,
16 | } = require("./shared");
17 | const Constants = require("./constants");
18 | const app = express();
19 | const port = process.env.PORT || 5000;
20 | app.listen(port, () => console.log(`Listening on port ${port}`));
21 | app.use(express.json());
22 | app.use(cors());
23 |
24 | app.get("/users", verifyToken, (req, res) => {
25 | const token = req.headers.authorization.split(" ")[1];
26 | if (getAudienceFromToken(token).includes(Constants.SHOW_USERS)) {
27 | getAllUsers().then((users) => {
28 | if (users && users.length > 0) {
29 | generateToken(token, null).then((token) => {
30 | res.status(200).send({ users: users, token: token });
31 | });
32 | } else res.status(500).send({ users: [], token: token });
33 | });
34 | } else
35 | res
36 | .status(403)
37 | .send({ message: "Not authorized to view users", token: token });
38 | });
39 |
40 | app.get("/books", verifyToken, (req, res) => {
41 | const token = req.headers.authorization.split(" ")[1];
42 | getAllBooks().then((books) => {
43 | if (books && books.length > 0) {
44 | generateToken(token, null).then((token) => {
45 | res.status(200).send({ books: books, token: token });
46 | });
47 | } else res.status(500).send({ books: [], token: token });
48 | });
49 | });
50 |
51 | app.post("/login", (req, res) => {
52 | let base64Encoding = req.headers.authorization.split(" ")[1];
53 | let credentials = Buffer.from(base64Encoding, "base64").toString().split(":");
54 | const username = credentials[0];
55 | const password = credentials[1];
56 | getUserByUsername(username).then((user) => {
57 | if (user && !isEmptyObject(user)) {
58 | isPasswordCorrect(user.key, password).then((result) => {
59 | if (!result)
60 | res
61 | .status(401)
62 | .send({ message: "username or password is incorrect" });
63 | else {
64 | generateToken(null, username).then((token) => {
65 | res
66 | .status(200)
67 | .send({ username: user.username, role: user.role, token: token });
68 | });
69 | }
70 | });
71 | } else
72 | res.status(401).send({ message: "username or password is incorrect" });
73 | });
74 | });
75 |
76 | app.get("/logout", verifyToken, (req, res) => {
77 | res.status(200).send({ message: "Signed out" });
78 | });
79 |
80 | app.get("/favorite", verifyToken, (req, res) => {
81 | const token = req.headers.authorization.split(" ")[1];
82 | getFavoriteBooksForUser(token).then((books) => {
83 | generateToken(token, null).then((token) => {
84 | res.status(200).send({ favorites: books, token: token });
85 | });
86 | });
87 | });
88 |
89 | app.post("/book", verifyToken, (req, res) => {
90 | const token = req.headers.authorization.split(" ")[1];
91 | if (getAudienceFromToken(token).includes(Constants.ADD_BOOK)) {
92 | addBook({ name: req.body.name, author: req.body.author, id: uuid() }).then(
93 | (err) => {
94 | if (err) res.status(500).send({ message: "Cannot add this book" });
95 | else {
96 | generateToken(token, null).then((token) => {
97 | res
98 | .status(200)
99 | .send({ message: "Book added successfully", token: token });
100 | });
101 | }
102 | }
103 | );
104 | } else
105 | res
106 | .status(403)
107 | .send({ message: "Not authorized to add a book", token: token });
108 | });
109 |
--------------------------------------------------------------------------------
/src/serviceWorker.js:
--------------------------------------------------------------------------------
1 | // This optional code is used to register a service worker.
2 | // register() is not called by default.
3 |
4 | // This lets the app load faster on subsequent visits in production, and gives
5 | // it offline capabilities. However, it also means that developers (and users)
6 | // will only see deployed updates on subsequent visits to a page, after all the
7 | // existing tabs open on the page have been closed, since previously cached
8 | // resources are updated in the background.
9 |
10 | // To learn more about the benefits of this model and instructions on how to
11 | // opt-in, read https://bit.ly/CRA-PWA
12 |
13 | const isLocalhost = Boolean(
14 | window.location.hostname === 'localhost' ||
15 | // [::1] is the IPv6 localhost address.
16 | window.location.hostname === '[::1]' ||
17 | // 127.0.0.0/8 are considered localhost for IPv4.
18 | window.location.hostname.match(
19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
20 | )
21 | );
22 |
23 | export function register(config) {
24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
25 | // The URL constructor is available in all browsers that support SW.
26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
27 | if (publicUrl.origin !== window.location.origin) {
28 | // Our service worker won't work if PUBLIC_URL is on a different origin
29 | // from what our page is served on. This might happen if a CDN is used to
30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374
31 | return;
32 | }
33 |
34 | window.addEventListener('load', () => {
35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
36 |
37 | if (isLocalhost) {
38 | // This is running on localhost. Let's check if a service worker still exists or not.
39 | checkValidServiceWorker(swUrl, config);
40 |
41 | // Add some additional logging to localhost, pointing developers to the
42 | // service worker/PWA documentation.
43 | navigator.serviceWorker.ready.then(() => {
44 | console.log(
45 | 'This web app is being served cache-first by a service ' +
46 | 'worker. To learn more, visit https://bit.ly/CRA-PWA'
47 | );
48 | });
49 | } else {
50 | // Is not localhost. Just register service worker
51 | registerValidSW(swUrl, config);
52 | }
53 | });
54 | }
55 | }
56 |
57 | function registerValidSW(swUrl, config) {
58 | navigator.serviceWorker
59 | .register(swUrl)
60 | .then(registration => {
61 | registration.onupdatefound = () => {
62 | const installingWorker = registration.installing;
63 | if (installingWorker == null) {
64 | return;
65 | }
66 | installingWorker.onstatechange = () => {
67 | if (installingWorker.state === 'installed') {
68 | if (navigator.serviceWorker.controller) {
69 | // At this point, the updated precached content has been fetched,
70 | // but the previous service worker will still serve the older
71 | // content until all client tabs are closed.
72 | console.log(
73 | 'New content is available and will be used when all ' +
74 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
75 | );
76 |
77 | // Execute callback
78 | if (config && config.onUpdate) {
79 | config.onUpdate(registration);
80 | }
81 | } else {
82 | // At this point, everything has been precached.
83 | // It's the perfect time to display a
84 | // "Content is cached for offline use." message.
85 | console.log('Content is cached for offline use.');
86 |
87 | // Execute callback
88 | if (config && config.onSuccess) {
89 | config.onSuccess(registration);
90 | }
91 | }
92 | }
93 | };
94 | };
95 | })
96 | .catch(error => {
97 | console.error('Error during service worker registration:', error);
98 | });
99 | }
100 |
101 | function checkValidServiceWorker(swUrl, config) {
102 | // Check if the service worker can be found. If it can't reload the page.
103 | fetch(swUrl, {
104 | headers: { 'Service-Worker': 'script' },
105 | })
106 | .then(response => {
107 | // Ensure service worker exists, and that we really are getting a JS file.
108 | const contentType = response.headers.get('content-type');
109 | if (
110 | response.status === 404 ||
111 | (contentType != null && contentType.indexOf('javascript') === -1)
112 | ) {
113 | // No service worker found. Probably a different app. Reload the page.
114 | navigator.serviceWorker.ready.then(registration => {
115 | registration.unregister().then(() => {
116 | window.location.reload();
117 | });
118 | });
119 | } else {
120 | // Service worker found. Proceed as normal.
121 | registerValidSW(swUrl, config);
122 | }
123 | })
124 | .catch(() => {
125 | console.log(
126 | 'No internet connection found. App is running in offline mode.'
127 | );
128 | });
129 | }
130 |
131 | export function unregister() {
132 | if ('serviceWorker' in navigator) {
133 | navigator.serviceWorker.ready
134 | .then(registration => {
135 | registration.unregister();
136 | })
137 | .catch(error => {
138 | console.error(error.message);
139 | });
140 | }
141 | }
142 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
2 |
3 | # System Requirements for Course
4 | Before running the project, please make sure you have the following:
5 |
6 | - Node.js LTS version which can be found [here](https://nodejs.org/en/download/). The course is upto date using this version at all times.
7 | - Please refer to the help section below to resolve most common questions.
8 |
9 | # Help
10 |
11 | ### - Can I use my own IDE to develop the project during the course ?
12 | Yes, feel free to use your own IDE for the course.
13 |
14 | ### - How do I check my Node version ?
15 | To check your current Node.js version, open your terminal and type the command below to see your current Node.js version.
16 | ```
17 | node -v
18 | ```
19 |
20 | ### - How do I install Node.js LTS version on my machine ?
21 | If you do not have the Node.js LTS version on your machine, you can download using either of the following:
22 | 1. Please go [here](https://nodejs.org/en/download/) and download the LTS version of Node.js installable file for your operating system.
23 |
24 | 2. Alternatively, you can use Node Version Manager (`nvm`) to install LTS version of Node.js in case
25 | you do not want to delete the existing Node version on your machine.
26 | `NVM` allows you to use multiple Node versions on your machine and prevent disrupting other
27 | projects you may be running with different `Node` versions.
28 |
29 | ### - How do I use nvm to install Node.js ?
30 | Click on [this link](https://github.com/nvm-sh/nvm) and follow the instructions provided in their README.md file
31 | to install nvm on your machine depending on your platform.
32 |
33 | ### - Should I install npm separately ?
34 | No, `npm` comes with `Node.js`
35 | No matter what approach you use to install Node.js, npm will always come with it.
36 |
37 | ### - How do I check my npm version ?
38 | Open your terminal and type the command below to get your npm version.
39 | ```
40 | npm -v
41 | ```
42 |
43 | ### - What version of npm comes with LTS version of Node.js ?
44 | Click on [this click](https://nodejs.org/en/download/) and the `npm` version should be mentioned under the title _**Downloads**_.
45 | You must ensure that the npm version and node version should match with what is mentioned on this official page.
46 |
47 | ### - What is the version of Material-UI used for this course ?
48 | This course uses v4.0.0 of Material-UI library
49 |
50 | ### - What is the React version need for this course ?
51 | ********************
52 | We are using `react` >=16.8.0 and `react-dom` >= 16.8.0 at all times. All the dependecies needed to run this project will be available in package.json
53 | file. You do not have to worry about finding the peer dependencies to run the project.
54 | All you need are the 2 following commands to get started as long as you have the right version of Node.
55 |
56 | `npm install`
57 |
58 | `npm start`
59 |
60 | Alternatively, you can also use `yarn` command.
61 |
62 | `yarn install`
63 |
64 | `yarn start`
65 |
66 |
67 | ### - Do I need Webpack or Babel to run this project ?
68 | No, You don’t need to install or configure tools. You just need the LTS version of Node.js and the npm version that comes with it.
69 | They are preconfigured and hidden so that you can focus on the code.
70 |
71 | ### - Which browser are we using for this course ?
72 | We shall be using the latest version of Chrome as of today. Be sure to install/update Chrome on your computer.
73 |
74 | ### - How do I open Chrome Browser in Mobile View ?
75 | - To open Chrome in Mobile view mode using Mac, press ```Command+Option+i```
76 |
77 | ### - How do I run the Client application in browser?
78 | To run the app in the development mode,
79 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
80 | We are using Chrome Developer console in this course.
81 |
82 | ### Where is the Node server running?
83 | Your server is will run at port 5000 and the URL for server APIs is [http://localhost:5000](http://localhost:5000).
84 |
85 | ### Is it mandatory to use Material-UI library for Styling?
86 | No, feel free to use simple CSS for styling or any other styling library you like. The focus of this course is to
87 | understand the use of JSON Web Token to secure the backend APIs and the front end styling is just an
88 | extra beautification layer.
89 |
90 | ### How to test the backend APIs using CLI and Postman?
91 | Install [Postman](https://www.postman.com/) on your machine and start creating the collections where you
92 | can keep track of the API end points currently under testing. They have extensive documentation on how to use the tool.
93 | in case your are interested.
94 |
95 | ### I am running into issues when installing `bcrypt` library. How do I resolve them?
96 | Install `bcrypt` from `npm` using the commands below.
97 | Note that `node-gyp` should be installed globally for the most recent Operating System on Mac which is Catalina.
98 | ```bash
99 | npm install -g node-gyp
100 | npm install --save bcrypt
101 | ```
102 |
103 | ### What user credentials are used in the Bookie App?
104 | Below are the credentials you may want to use when logging to the app as member or admin.
105 |
106 | **Member**
107 | ```bash
108 | deeksha30
109 | kdje89#$%
110 | ```
111 |
112 | **Admin**
113 | ```bash
114 | zenmade23
115 | 728193kfej**(
116 | ```
117 |
118 | ### How do I start the server?
119 | Go inside the `server/` directory and run teh command below.
120 | ```bash
121 | node server.js
122 | ```
123 | **Note:** Make sure you restart your server each time you checkout a new branch for every module and for
124 | every code change in the server side code.
125 |
126 |
127 | # Git Branches
128 | Checkout the branches listed below as you progress through different modules.
129 |
130 | ### MODULE 02
131 | `module02_jwt_security`
132 |
133 | ### MODULE 03
134 | `module03_jwt_security`
135 |
136 | ### MODULE 04
137 | There are 2 git branches used in this module.
138 |
139 | To send JWT in a Cookie, checkout `module04_jwt_security_cookies`
140 |
141 | To send JWT in Auth Header Bearer Token, checkout `module04_jwt_security_bearer_token`
142 |
143 | Below are the contents of `variables.env` file.
144 | ```
145 | SECRET=")x2f-l-opsnd)w!!z2m7ykvony99pt@6@6m+=q2uk3%w8*7$ow"
146 | ALGORITHM="HS256"
147 | ISSUER="BOOKIE_ORG"
148 | EXPIRY="1h"
149 | ```
150 |
151 |
152 | ### MODULE 05
153 | `module05_jwt_security_bearer_token_client`
154 |
155 | # Resources
156 |
157 | - [Proxying API Requests in React Development](https://create-react-app.dev/docs/proxying-api-requests-in-development/)
158 | - [JWT Debugger](https://jwt.io/)
159 | - [RFC 7519 - JSON Web Token (JWT) - IETF Tools](https://tools.ietf.org/html/rfc7519)
160 | - [Using HTTP cookies](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies)
161 | - [Decode JWT on the client using with jwt-decode](https://github.com/auth0/jwt-decode)
162 | - [GitHub code samples for usage of JWT by Auth0](https://github.com/auth0/jwt-handbook-samples/blob/master/stateless-sessions/app.js)
163 |
164 |
165 | Below are some good questions and answers by the community on StackOverflow.
166 | - [Authentication: JWT usage vs session](https://stackoverflow.com/questions/43452896/authentication-jwt-usage-vs-session)
167 | - [Where to save a JWT in a browser-based application and how to use it](https://stackoverflow.com/questions/26340275/where-to-save-a-jwt-in-a-browser-based-application-and-how-to-use-it)
168 | - [JavaScript and third party cookies](https://stackoverflow.com/questions/3363495/javascript-and-third-party-cookies)
169 | - [Which way to create cookie, by frontend or backend?](https://stackoverflow.com/questions/26082511/which-way-to-create-cookie-by-frontend-or-backend)
170 | - [How does server return JWT token to the client?](https://stackoverflow.com/questions/51503024/how-does-server-return-jwt-token-to-the-client)
171 |
172 |
173 |
174 |
175 |
176 |
--------------------------------------------------------------------------------