Skip to content
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

WIP: Exercise 4 #7

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions backend/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
JWT_SECRET=thecountryroads
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❌ If this stays, you will loose a ⭐ here.

⭐ For not having security issues according to instructions.

You have multiple options:
a) Mock jsonwebtoken node module in your tests, see our forum our group lichtow: Systems-Development-and-Frameworks/lichtow@6d164b9#diff-45f14d66b6a3b7ed6473601b04ce8c30013d014dfd73e439376d93e9196f93dcR98
b) Use dotenv-flow and commit a non-secret in .env.test
c) Explain in README.md one has to create a .env file before running the tests.

2 changes: 1 addition & 1 deletion backend/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"env": {
"browser": true,
"node": true,
"commonjs": true,
"es2021": true
},
Expand Down
7 changes: 6 additions & 1 deletion backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,14 @@
"author": "",
"license": "ISC",
"dependencies": {
"apollo-datasource-rest": "^0.9.5",
"apollo-datasource": "^0.7.2",
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@yiimnta Danke, dass du das geändert hast!

"apollo-server": "^2.19.0",
"bcrypt": "^5.0.0",
"dotenv": "^8.2.0",
"graphql": "^15.4.0",
"graphql-middleware": "^4.0.2",
"graphql-shield": "^7.4.2",
"jsonwebtoken": "^8.5.1",
"nodemon": "^2.0.6"
},
"devDependencies": {
Expand Down
82 changes: 0 additions & 82 deletions backend/src/DataSource/posts-data-source.js

This file was deleted.

28 changes: 0 additions & 28 deletions backend/src/DataSource/users-data-source.js

This file was deleted.

87 changes: 87 additions & 0 deletions backend/src/DataSources/posts-data-source.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
const {DataSource} = require('apollo-datasource');
const {UserInputError} = require('apollo-server');
const crypto = require('crypto');

class Post {
constructor (data) {
this.id = crypto.randomBytes(16).toString('hex');
this.voters = [];
this.votes = 0;
ilonae marked this conversation as resolved.
Show resolved Hide resolved
Object.assign(this, data);
}
}

class PostsDataSource extends DataSource {

constructor() {
super();
this.posts = [];
}

async allPosts () {
return this.posts;
}

async createPost (data, currUser) {
ilonae marked this conversation as resolved.
Show resolved Hide resolved

if(currUser){
ilonae marked this conversation as resolved.
Show resolved Hide resolved
const newPost = new Post({...data, author:currUser});
this.posts.push(newPost);

return newPost;
}

return null;
ilonae marked this conversation as resolved.
Show resolved Hide resolved
}

async votePost(id, value, currUser) {
const post = this.posts.find(e => e.id == id);
ilonae marked this conversation as resolved.
Show resolved Hide resolved

if (post) {

if(currUser) {

if(!post.voters.find(voter => voter.id == currUser.id)){
ilonae marked this conversation as resolved.
Show resolved Hide resolved

post.votes+= value;
post.voters.push(currUser);

return post;
}
else{
throw new UserInputError("This user voted on this post already");
ilonae marked this conversation as resolved.
Show resolved Hide resolved
}
}
}
else{
throw new UserInputError("No post with this ID", {invalidArgs: [id]});
ilonae marked this conversation as resolved.
Show resolved Hide resolved
}
}

async deletePost (id, currUser) {

const post = this.posts.find(e => e.id == id);

if (post) {

if(currUser) {

if( currUser.id == post.author.id) {

const deleteIndex = this.posts.indexOf(post);
this.posts.splice(deleteIndex,1);

return post;

}else {
throw new Error("Only authors of a post are allowed to delete their own posts.");
ilonae marked this conversation as resolved.
Show resolved Hide resolved
}
}
}
else{
throw new UserInputError("No post with this ID", {invalidArgs: [id]});
ilonae marked this conversation as resolved.
Show resolved Hide resolved
}

}
}
module.exports = {Post, PostsDataSource}
65 changes: 65 additions & 0 deletions backend/src/DataSources/users-data-source.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
const {DataSource} = require('apollo-datasource');
const {createAccessToken} = require('../token')
const crypto = require('crypto');
const bcrypt = require('bcrypt');

class User{
constructor(data){
this.id = crypto.randomBytes(16).toString('hex')
data.password = bcrypt.hashSync(data.password, 10);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
data.password = bcrypt.hashSync(data.password, 10);
data.passwordHash = bcrypt.hashSync(data.password, 10);

encryptedPassword would do as well.

Object.assign(this, data);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, it would be better to assign only white listed arguments here:

Suggested change
Object.assign(this, data);
const { id, name } = data
Object.assign(this, { id, name, passwordHash });

that way you don't save the clear text password in the user.

}
ilonae marked this conversation as resolved.
Show resolved Hide resolved
}

class UsersDataSource extends DataSource {

constructor() {
super();
this.users = []
}

async getUser(id) {
return this.users.find(user => user.id === id);
}

getUserByEmail(email) {
return this.users.find(user => user.email === email);
}

async signup(name, email, password) {
//trim
email = email.trim();
password = password.trim();

/*
Validate:
- Make sure the email address is not taken by another user.
- Accept only passwords with a length of at least 8 characters.
*/
if(this.getUserByEmail(email) || password.length < 8){
ilonae marked this conversation as resolved.
Show resolved Hide resolved
ilonae marked this conversation as resolved.
Show resolved Hide resolved
return null;
}

const newUser = new User({name, email, password});
this.users.push(newUser);
console.log(this.users);

return createAccessToken(newUser.id);
}

async login(email, password) {
ilonae marked this conversation as resolved.
Show resolved Hide resolved
let user = this.getUserByEmail(email);
console.log(user);

if(user && bcrypt.compareSync(password, user.password)){
ilonae marked this conversation as resolved.
Show resolved Hide resolved
return createAccessToken(user.id);
ilonae marked this conversation as resolved.
Show resolved Hide resolved
}

return null;
ilonae marked this conversation as resolved.
Show resolved Hide resolved
}

async allUsers() {
return this.users;
}
}
module.exports = {User, UsersDataSource}
Original file line number Diff line number Diff line change
@@ -1,16 +1,59 @@
const { createTestClient } = require("apollo-server-testing");
const {gql} = require("apollo-server");
const {ApolloServer, makeExecutableSchema} = require('apollo-server');
const {User, UsersDataSource} = require("./users-data-source");
const {Post, PostsDataSource} = require("./posts-data-source");
const Server = require("../server");
const {applyMiddleware} = require('graphql-middleware');
const server = require("../server");
const bcrypt = require('bcrypt');

let postsMemory = new PostsDataSource();
let usersMemory = new UsersDataSource();
const server = new Server({dataSources: ()=> ({postsDataSrc: postsMemory, usersDataSrc: usersMemory})});
const typeDefs = require('../schema');
const resolvers = require('../resolver');

const {query, mutate } = createTestClient(server);
const s = new server();

ilonae marked this conversation as resolved.
Show resolved Hide resolved
const testContext = (testToken) => {
let token = testToken || ''
token = token.replace('Bearer ', '')
try {
const decodedJwt = jwt.verify(
token,
process.env.JWTSECRET
)
return { decodedJwt }
} catch (e) {
return {}
}
}

const schema = applyMiddleware(makeExecutableSchema({typeDefs, resolvers}));
const setupServer = (ps, us, testToken) => {
const server = new ApolloServer({
schema,
context: testContext(testToken), // not sure if this is the correct way. but we didn`t find another solution to add the token as request (see https://github.com/apollographql/apollo-server/issues/2277)
dataSources: () => ({
posts: new PostsDataSource(ps, us)
})
})
return createTestClient(server)
}

describe("queries", () => {
const postData = [
{ id: 'post1', title: 'Item 1', votes: 0, voters: [], author: {} }
]
const userData = [
new User({name:'An', email:'an@gmail.com', password:'12345678'}),
new User({name:'Ilona', email:'ilona@gmail.com', password:'12345678'}),
new User({name:'Andrej', email:'andrej@gmail.com', password:'12345678'})
]
postData[0].author = userData[0];


const { query } = setupServer(postData, userData);


describe("USERS", () => {
const GET_USERS = gql`
Expand Down
24 changes: 24 additions & 0 deletions backend/src/context.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
require('dotenv').config();
const jwt = require('jsonwebtoken');

const context = ({req}) => {

let token = req.headers.authorization || '';
token = token.replace('Bearer ', '');

try {
const decodedJwt = jwt.verify(
token,
process.env.JWT_SECRET
);

console.log("context here", decodedJwt)

return {decodedJwt};

} catch(e) {
return {}
ilonae marked this conversation as resolved.
Show resolved Hide resolved
}
}

module.exports = {context};
yiimnta marked this conversation as resolved.
Show resolved Hide resolved