Skip to content
This repository was archived by the owner on Mar 23, 2020. It is now read-only.

Richardmachado #477

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
1 change: 1 addition & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
JWTKEY=is it secret, is it safe?
22 changes: 22 additions & 0 deletions api/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const express = require("express");
const helmet = require("helmet");
const cors = require("cors");

const authRouter = require("../auth/auth-router.js");
const usersRouter = require("../users/users-router.js");
const restricted = require("../auth/restricted-middleware.js");

const server = express();

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

server.use("/api/auth", authRouter);
server.use("/api/users", restricted, usersRouter);

server.get("/", (req, res) => {
res.send("Welcome to JSON Web Tokens, JWT!");
});

module.exports = server;
76 changes: 76 additions & 0 deletions auth/auth-router.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
const router = require("express").Router();
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken"); // <<< install this npm package

const Users = require("../users/users-model.js");
const { jwtSecret } = require("../config/secrets.js");

// for endpoints beginning with /api/auth
router.post("/register", (req, res) => {
let user = req.body;
const hash = bcrypt.hashSync(user.password, 10); // 2 ^ n
user.password = hash;

Users.add(user)
.then(saved => {
res.status(201).json(saved);
})
.catch(error => {
res.status(500).json(error);
});
});

router.post("/login", (req, res) => {
let { username, password } = req.body;

Users.findBy({ username })
.first()
.then(user => {
if (user && bcrypt.compareSync(password, user.password)) {
const token = generateToken(user); // get a token

res.status(200).json({
message: `Welcome ${user.username}!`,
token, // send the token
});
} else {
res.status(401).json({ message: "Invalid Credentials" });
}
})
.catch(error => {
console.log("ERROR: ", error);
res.status(500).json({ error: "/login error" });
});
});

router.get("/logout", (req, res) => {
if (req.session) {
req.session.destroy(err => {
if (err) {
res.status(500).json({
you: "can check out any time you like, but you can never leave",
});
} else {
res.status(200).json({ you: "logged out successfully" });
}
});
} else {
res.status(200).json({ bye: "felicia" });
}
});

function generateToken(user) {
const payload = {
subject: user.id,
username: user.username,
role: user.role || "user",
};

const options = {
expiresIn: "1h",
};

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

module.exports = router;
21 changes: 21 additions & 0 deletions auth/restricted-middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
const jwt= require('jsonwebtoken');

const {jwtSecret} = require ('../config/secrets.js');

module.exports = (req, res, next) => {
const { authorization } = req.headers;

if (authorization) {
jwt.verify(authorization, jwtSecret, (err, decodedToken) => {
if (err) {
res.status(401).json({ message: "Invalid Credentials" });
} else {
req.decodedToken = decodedToken;

next();
}
});
} else {
res.status(400).json({ message: "No credentials provided" });
}
};
3 changes: 3 additions & 0 deletions config/secrets.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = {
jwtSecret: process.env.JWTKEY || "is it secret, is it safe?"
};
5 changes: 5 additions & 0 deletions data/dbConfig.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const knex = require('knex');

const knexConfig = require('../knexfile.js');

module.exports = knex(knexConfig.development);
Binary file added data/users.db3
Binary file not shown.
6 changes: 6 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
require("dotenv").config();

const server = require('./api/server.js');

const port = process.env.PORT || 4000;
server.listen(port, () => console.log(`\n** Running on port ${port} **\n`));
45 changes: 45 additions & 0 deletions knexfile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// Update with your config settings.

module.exports = {

development: {
client: 'sqlite3',
connection: {
filename: './data/users.db3'
},
useNullAsDefault: true
},

staging: {
client: 'postgresql',
connection: {
database: 'my_db',
user: 'username',
password: 'password'
},
pool: {
min: 2,
max: 10
},
migrations: {
tableName: 'knex_migrations'
}
},

production: {
client: 'postgresql',
connection: {
database: 'my_db',
user: 'username',
password: 'password'
},
pool: {
min: 2,
max: 10
},
migrations: {
tableName: 'knex_migrations'
}
}

};
23 changes: 23 additions & 0 deletions login/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# production
/build

# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local

npm-debug.log*
yarn-debug.log*
yarn-error.log*
68 changes: 68 additions & 0 deletions login/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).

## Available Scripts

In the project directory, you can run:

### `yarn start`

Runs the app in the development mode.<br />
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.

The page will reload if you make edits.<br />
You will also see any lint errors in the console.

### `yarn test`

Launches the test runner in the interactive watch mode.<br />
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.

### `yarn build`

Builds the app for production to the `build` folder.<br />
It correctly bundles React in production mode and optimizes the build for the best performance.

The build is minified and the filenames include the hashes.<br />
Your app is ready to be deployed!

See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.

### `yarn eject`

**Note: this is a one-way operation. Once you `eject`, you can’t go back!**

If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.

Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.

You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.

## Learn More

You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).

To learn React, check out the [React documentation](https://reactjs.org/).

### Code Splitting

This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting

### Analyzing the Bundle Size

This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size

### Making a Progressive Web App

This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app

### Advanced Configuration

This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration

### Deployment

This section has moved here: https://facebook.github.io/create-react-app/docs/deployment

### `yarn build` fails to minify

This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify
Loading