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 1 commit
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.

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
61 changes: 29 additions & 32 deletions backend/src/DataSource/posts-data-source.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,29 @@
const { RESTDataSource } = require('apollo-datasource-rest');
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
Object.assign(this, data)
this.id = crypto.randomBytes(16).toString('hex');
this.voters = [];
this.votes = 0;
Object.assign(this, data);
}
}

class PostsDataSource extends RESTDataSource {
class PostsDataSource extends DataSource {

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

async allPosts () {
return this.posts
return this.posts;
}

initialize({context}) {
//console.log('PostsDataSource: ', context)
this.context = context;
}

async createPost (data) {
Expand All @@ -32,28 +32,11 @@ class PostsDataSource extends RESTDataSource {
return newPost
}

async upvotePost(id, currUser) {
async votePost(id, currUser, value) {
const post = this.posts.find(e => e.id == id);
if (post) {
if(!post.voters.find(voters => voters.name == currUser.name)){
post.votes++
post.voters.push(currUser)
return post
}
else{
throw new UserInputError("This user voted on this post already", {invalidArgs: [currUser]});
}
}
else{
throw new UserInputError("No post with this ID", {invalidArgs: [id]});
}
}

async downvotePost(id, currUser) {
const post = this.posts.find(e => e.id == id);
if (post) {
if(!post.voters.find(voters => voters.name == currUser.name)){
post.votes--
post.votes+=value
post.voters.push(currUser)
return post
}
Expand All @@ -67,13 +50,27 @@ class PostsDataSource extends RESTDataSource {
}

async deletePost (id) {

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

if (post) {
const deleteIndex = this.posts.indexOf(post);
this.posts.splice(deleteIndex,1);
return post;
const currUser = await this.context.dataSources.usersDataSrc.getUser(this.context.decodedJwt.id);

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.");
}
}
}
else{
else {
throw new UserInputError("No post with this ID", {invalidArgs: [id]});
}

Expand Down
41 changes: 33 additions & 8 deletions backend/src/DataSource/users-data-source.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,49 @@
const { RESTDataSource } = require('apollo-datasource-rest');
const {DataSource} = require('apollo-datasource');
const {createAccessToken} = require('../token')
const crypto = require('crypto');
const bcrypt = require('bcrypt');

class User{
constructor(name){
this.name = name
constructor(data){
this.id = crypto.randomBytes(16).toString('hex')
data.password = bcrypt.hashSync(data.password, 10);
Object.assign(this, data);
}
}

class UsersDataSource extends RESTDataSource {
class UsersDataSource extends DataSource {

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

initialize({context}) {
//console.log('UsersDataSource: ', context)
async getUser(id) {
return this.users.find(user => user.id === id);
}

async getUser(name) {
return this.users.find(user => user.name === name);
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){
return null;
}

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

return createAccessToken(newUser.id);
}

async allUsers() {
Expand Down
9 changes: 9 additions & 0 deletions backend/src/Permissions/user-rules.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const {rule} = require('graphql-shield');

const isAuthenticated = rule({ cache: 'contextual' })(
async (parent, args, context, info) => {
return !!(await context.dataSources.usersDataSrc.getUser(context.decodedJwt.id));
},
)

module.exports = {isAuthenticated}
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(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
19 changes: 10 additions & 9 deletions backend/src/resolver.js
Original file line number Diff line number Diff line change
@@ -1,32 +1,33 @@
const resolvers = {
Query: {
posts: async (parent, args, context) => {
return await context.dataSources.postsDataSrc.allPosts()
return await context.dataSources.postsDataSrc.allPosts();
},
users: async (parent, args, context) => {
return await context.dataSources.usersDataSrc.allUsers()
return await context.dataSources.usersDataSrc.allUsers();
}
},
User: {
posts: async (parent, args, context) => {
let posts = await context.dataSources.postsDataSrc.allPosts();
return posts.filter(e => e.author.name == parent.name)
return posts.filter(e => e.author.name == parent.name);
}
},
Mutation: {
write: async (parent, args, context) => {
console.log('Mutation.write.postInput', args.post)
return await context.dataSources.postsDataSrc.createPost(args.post)
return await context.dataSources.postsDataSrc.createPost(args.post);
},
upvote: async (parent, args, context) => {
console.log('Mutation.upvote.args', args)
return await context.dataSources.postsDataSrc.upvotePost(args.id, args.voter)
return await context.dataSources.postsDataSrc.votePost(args.id, args.voter, 1);
},
downvote: async (parent, args, context) => {
return await context.dataSources.postsDataSrc.downvotePost(args.id, args.voter)
return await context.dataSources.postsDataSrc.votePost(args.id, args.voter, -1);
},
delete: async (parent, args, context) => {
return await context.dataSources.postsDataSrc.deletePost(args.id)
return await context.dataSources.postsDataSrc.deletePost(args.id);
},
signup: async (parent, args, context) => {
return await context.dataSources.usersDataSrc.signup(args.name, args.email, args.password);
}
}
};
Expand Down
76 changes: 42 additions & 34 deletions backend/src/schema.js
Original file line number Diff line number Diff line change
@@ -1,39 +1,47 @@
const {gql } = require('apollo-server');
const {gql} = require('apollo-server');

const typeDefs = gql`
type Post {
id: ID!
title: String!
votes: Int!
author: User!
voters:[User]
}

type User {
name: ID!
posts: [Post]
}

type Query {
posts: [Post]
users: [User]
}

type Mutation {
write(post: PostInput!): Post
delete(id: ID!): Post
upvote(id: ID!, voter: UserInput!): Post
downvote(id: ID!, voter: UserInput!): Post
}

input PostInput {
title: String!
author: UserInput!
}

input UserInput {
name: String!
}
type Post {
id: ID!
title: String!
votes: Int!
author: User!
}

type User {
# ⚠️ attributes 'id' and 'name' have changed!
# 'id' now represents a randomly generated string, similar to 'Post.id'
id: ID!
name: String!
email: String!
posts: [Post]
}

type Query {
posts: [Post]
users: [User]
}

type Mutation {
write(post: PostInput!): Post
upvote(id: ID!): Post
downvote(id: ID!): Post
delete(id: ID!): Post

"""
returns a signed JWT or null
"""
login(email: String!, password: String!): String

"""
returns a signed JWT or null
"""
signup(name: String!, email: String!, password: String!): String
}

input PostInput {
title: String!
}
`;

module.exports = typeDefs