Commit 9b4cad9d by qiuzhi99

check-auth createpost deletepost

1 parent ddb977b9
......@@ -6,6 +6,7 @@ module.exports = {
...postsResolvers.Query
},
Mutation: {
...usersResolvers.Mutation
...usersResolvers.Mutation,
...postsResolvers.Mutation
}
};
const Post = require("../../models/Post");
const checkAuth = require("../../util/check-auth");
const { AuthenticationError } = require("apollo-server");
module.exports = {
Query: {
async getPosts() {
try {
const posts = await Post.find();
const posts = await Post.find().sort({ createdAt: -1 });
return posts;
} catch (err) {
throw new Error(err);
}
},
async getPost(_, { postId }) {
try {
const post = await Post.findById(postId);
if (post) {
return post;
} else {
throw new Error("Post not found");
}
} catch (err) {
throw new Error(err);
}
}
},
Mutation: {
async createPost(_, { body }, context) {
const user = checkAuth(context);
const newPost = new Post({
body,
username: user.username,
createdAt: new Date().toISOString(),
user: user.id
});
const post = await newPost.save();
return post;
},
async deletePost(_, { postId }, context) {
const user = checkAuth(context);
try {
const post = await Post.findById(postId);
if (user.username === post.username) {
await post.delete();
return "Post deleted successfully";
} else {
throw new AuthenticationError("Action not allowed");
}
} catch (err) {
throw new Error(err);
}
}
}
};
......@@ -10,6 +10,7 @@ module.exports = gql`
type Query {
getPosts: [Post]
getPost(postId: ID!): Post
}
type User {
......@@ -30,5 +31,7 @@ module.exports = gql`
type Mutation {
register(registerInput: RegisterInput): User!
login(username: String!, password: String!): User!
createPost(body: String!): Post!
deletePost(postId: ID!): String!
}
`;
......@@ -9,7 +9,8 @@ const resolvers = require("./graphql/resolvers");
const server = new ApolloServer({
typeDefs,
resolvers
resolvers,
context: ({ req }) => ({ req })
});
mongoose
......
const jwt = require("jsonwebtoken");
const { SECRET_KEY } = require("../config");
const { AuthenticationError } = require("apollo-server");
module.exports = context => {
const authHeader = context.req.headers.authorization;
if (authHeader) {
const token = authHeader.split("Bearer ")[1];
if (token) {
try {
const user = jwt.verify(token, SECRET_KEY);
return user;
} catch (error) {
throw new AuthenticationError("Invalid/Expired token");
}
}
throw new Error("Authentication token must be 'Bearer [token]");
}
throw new Error("Authorization header must be provided");
};
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!