-
Notifications
You must be signed in to change notification settings - Fork 26
Auth exercise #25
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
Open
janauhrich
wants to merge
6
commits into
pce-uw-jscript400:master
Choose a base branch
from
janauhrich:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Auth exercise #25
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| const mongoose = require("mongoose"); | ||
|
|
||
| const schema = mongoose.Schema( | ||
| { | ||
| username: { | ||
| type: String, | ||
| required: true | ||
| }, | ||
| password: { | ||
| type: String, | ||
| required: true | ||
| }, | ||
| admin: { | ||
| type: Boolean, | ||
| default: false, | ||
| required: true | ||
| } | ||
| }, | ||
| { timestamps: { createdAt: "created_at", updatedAt: "updated_at" } } | ||
| ); | ||
|
|
||
| module.exports = mongoose.model("User", schema); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,129 @@ | ||
| const router = require("express").Router(); | ||
| const User = require("../models/user"); | ||
| const bcrypt = require("bcrypt"); | ||
| const jwot = require("jsonwebtoken"); | ||
| const { SECRET_KEY } = process.env; | ||
|
|
||
| // Starting route | ||
| // http://localhost:5000/api/ | ||
|
|
||
| // GET | ||
| // http://localhost:5000/api/users | ||
|
|
||
| router.get("/users", async (req, res, next) => { | ||
| const status = 200; | ||
| const response = await User.find().select("-__v -password"); | ||
| res.json({ status, response }); | ||
| }); | ||
|
|
||
| // POST | ||
| // http://localhost:5000/api/signup | ||
| // username & password in the body | ||
|
|
||
| router.post("/signup", async (req, res, next) => { | ||
| const status = 201; | ||
| try { | ||
| //get username and password, make sure both are provided | ||
| const username = req.body.username; | ||
| const password = req.body.password; | ||
| if (!username || !password) | ||
| throw new Error(`Please enter a valid username and password`); | ||
| if (password.length < 8) throw new Error(`Please create stronger password`); | ||
|
|
||
| //make sure username already exists | ||
| let user = await User.findOne({ username }); | ||
| if (user) throw new Error(`User ${username} already exists.`); | ||
|
|
||
| //hash password | ||
| const saltRounds = 10; | ||
| const hashedPassword = await bcrypt.hash(password, saltRounds); | ||
| const userInformation = await User.create({ | ||
| username, | ||
| password: hashedPassword | ||
| }); | ||
|
|
||
| //reassign user, this time find the one you just created | ||
| user = await User.findOne({ username }); | ||
|
|
||
| //JWOT | ||
| const payload = { id: user._id }; | ||
| const options = { expiresIn: "1 day" }; | ||
| const token = jwot.sign(payload, SECRET_KEY, options); | ||
|
|
||
| const response = token; | ||
|
|
||
| res.json({ status, response }); | ||
| } catch (e) { | ||
| console.error(e); | ||
| const error = e; | ||
| error.status = 400; | ||
| next(error); | ||
| } | ||
| }); | ||
|
|
||
| //POST | ||
| // http://localhost:5000/api/login | ||
|
|
||
| router.post("/login", async (req, res, next) => { | ||
| const status = 200; | ||
| try { | ||
| //get username and password, make sure both are provided | ||
| const username = req.body.username; | ||
| const password = req.body.password; | ||
| if (!username || !password) | ||
| throw new Error(`Please enter a valid username and password`); | ||
| //username lookup | ||
| const user = await User.findOne({ username }); | ||
| if (!user) throw new Error(`Account could not be found`); | ||
|
|
||
| //check password | ||
| const isValid = await bcrypt.compare(password, user.password); | ||
| if (!isValid) throw new Error(`Please enter a valid username and password`); | ||
|
|
||
| //JWOT | ||
| const payload = { id: user._id }; | ||
| const options = { expiresIn: "1 day" }; | ||
| const token = jwot.sign(payload, SECRET_KEY, options); | ||
|
|
||
| const response = token; | ||
| res.json({ status, response }); | ||
| } catch (e) { | ||
| console.error(e); | ||
| const error = e; | ||
| error.status = 400; | ||
| next(error); | ||
| } | ||
| }); | ||
|
|
||
| // PATCH | ||
| // http://localhost:5000/api/users/5d4fcfb6b64f4427ea074fd4/permissions | ||
| // send admin jwot in auth header | ||
|
|
||
| router.patch("/users/:id/permissions", async (req, res, next) => { | ||
| let status = 204; | ||
| try { | ||
| //check jwot for permissions | ||
| const token = req.headers.authorization.split("Bearer ")[1]; | ||
| const payload = jwot.verify(token, SECRET_KEY); | ||
| const requestor = await User.findOne({ _id: payload.id }); | ||
| const requestorIsAdmin = requestor.admin === true ? true : false; | ||
|
|
||
| if (!token || !payload || !requestor || !requestorIsAdmin) | ||
| throw new Error(`You are not authorized to change permissions`); | ||
|
|
||
| const user = await User.findById(req.params.id); | ||
| if (!user) throw new Error(`Account could not be found`); | ||
|
|
||
| user.admin = true; | ||
| user.save(); | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. You'll want this to be |
||
|
|
||
| res.json({ status }); | ||
| } catch (e) { | ||
| console.error(e); | ||
| const error = e; | ||
| error.status = 400; | ||
| next(error); | ||
| } | ||
| }); | ||
|
|
||
| module.exports = router; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,49 +1,71 @@ | ||
| const mongoose = require('mongoose') | ||
| const Book = require('../api/models/book') | ||
| const config = require('../nodemon.json') | ||
| const mongoose = require("mongoose"); | ||
| const Book = require("../api/models/book"); | ||
| const User = require("../api/models/user"); | ||
| const config = require("../nodemon.json"); | ||
| const bcrypt = require("bcrypt"); | ||
|
|
||
| const reset = async () => { | ||
| mongoose.connect(config.env.MONGO_DB_CONNECTION, { useNewUrlParser: true }) | ||
| await Book.deleteMany() // Deletes all records | ||
| return await Book.create([ | ||
| { | ||
| title: 'The Colour of Magic', | ||
| published: 1983, | ||
| authors: [ | ||
| { | ||
| name: 'Sir Terry Pratchett', | ||
| dob: '04-28-1948' | ||
| } | ||
| ] | ||
| }, | ||
| { | ||
| title: 'Stardust', | ||
| published: 1997, | ||
| authors: [ | ||
| { | ||
| name: 'Neil Gaiman', | ||
| dob: '11-10-1960' | ||
| } | ||
| ] | ||
| }, | ||
| { | ||
| title: 'Good Omens: The Nice and Accurate Prophecies of Agnes Nutter, Witch', | ||
| published: 1990, | ||
| authors: [ | ||
| { | ||
| name: 'Neil Gaiman', | ||
| dob: '11-10-1960' | ||
| }, | ||
| { | ||
| name: 'Sir Terry Pratchett', | ||
| dob: '04-28-1948' | ||
| } | ||
| ] | ||
| } | ||
| ]) | ||
| } | ||
| mongoose.connect(config.env.MONGO_DB_CONNECTION, { useNewUrlParser: true }); | ||
| await Book.deleteMany(); // Deletes all records | ||
| await User.deleteMany(); // Deletes all records | ||
|
|
||
| reset().catch(console.error).then((response) => { | ||
| console.log(`Seeds successful! ${response.length} records created.`) | ||
| return mongoose.disconnect() | ||
| }) | ||
| const hashedPassword = await bcrypt.hash('password', 10); | ||
| return ( | ||
| await Book.create([ | ||
| { | ||
| title: "The Colour of Magic", | ||
| published: 1983, | ||
| authors: [ | ||
| { | ||
| name: "Sir Terry Pratchett", | ||
| dob: "04-28-1948" | ||
| } | ||
| ] | ||
| }, | ||
| { | ||
| title: "Stardust", | ||
| published: 1997, | ||
| authors: [ | ||
| { | ||
| name: "Neil Gaiman", | ||
| dob: "11-10-1960" | ||
| } | ||
| ] | ||
| }, | ||
| { | ||
| title: | ||
| "Good Omens: The Nice and Accurate Prophecies of Agnes Nutter, Witch", | ||
| published: 1990, | ||
| authors: [ | ||
| { | ||
| name: "Neil Gaiman", | ||
| dob: "11-10-1960" | ||
| }, | ||
| { | ||
| name: "Sir Terry Pratchett", | ||
| dob: "04-28-1948" | ||
| } | ||
| ] | ||
| } | ||
| ]), | ||
| User.create([ | ||
| { | ||
| username: "admin", | ||
| password: hashedPassword, | ||
| admin: "true" | ||
| }, | ||
| { | ||
| username: "regularUser", | ||
| password: hashedPassword, | ||
| admin: "false" | ||
| } | ||
| ]) | ||
| ); | ||
| }; | ||
|
|
||
| reset() | ||
| .catch(console.error) | ||
| .then(response => { | ||
| console.log(`Seeds successful! ${response.length} records created.`); | ||
| return mongoose.disconnect(); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Just using
requester.adminwould have the same effect.