This commit is contained in:
Riccardo
2021-01-07 11:01:36 +01:00
parent 12b19e889f
commit 28014b2850
8 changed files with 73 additions and 84 deletions

View File

@@ -11,19 +11,19 @@ const FEED_SEARCH_QUERY = gql`
id id
links { links {
id id
url title
description description
createdAt type
createdBy { createdBy {
id id
name username
}
follows {
id
user {
id
}
} }
# follows {
# id
# user {
# id
# }
# }
} }
} }
} }

View File

@@ -30,7 +30,6 @@ const authLink = setContext((_, { headers }) => {
const client = new ApolloClient({ const client = new ApolloClient({
link: authLink.concat(httpLink), link: authLink.concat(httpLink),
// link: httpLink,
cache: new InMemoryCache() cache: new InMemoryCache()
}); });
@@ -45,34 +44,14 @@ ReactDOM.render(
// serviceWorker.unregister(); // serviceWorker.unregister();
// import { setContext } from '@apollo/client/link/context';
// import { AUTH_TOKEN } from './constants';
// import { split } from '@apollo/client'; // import { split } from '@apollo/client';
// import { WebSocketLink } from '@apollo/client/link/ws'; // import { WebSocketLink } from '@apollo/client/link/ws';
// import { getMainDefinition } from '@apollo/client/utilities'; // import { getMainDefinition } from '@apollo/client/utilities';
// // import AppointmentList from './components/AppointmentList'; // // import AppointmentList from './components/AppointmentList';
// // class App extends Component {
// // render() {
// // return <AppointmentList />;
// // }
// // }
// // export default App; // // export default App;
// // attach the auth_token to all requests to GraphQL server
// const authLink = setContext((_, { headers }) => {
// const token = localStorage.getItem(AUTH_TOKEN);
// return {
// headers: {
// ...headers,
// authorization: token ? `Bearer ${token}` : ''
// }
// };
// });
// const wsLink = new WebSocketLink({ // const wsLink = new WebSocketLink({
// uri: `ws://localhost:4000/graphql`, // uri: `ws://localhost:4000/graphql`,
// options: { // options: {
@@ -95,13 +74,4 @@ ReactDOM.render(
// authLink.concat(httpLink) // authLink.concat(httpLink)
// ); // );
// // 3
// const client = new ApolloClient({
// link,
// cache: new InMemoryCache()
// });
// // If you want to start measuring performance in your app, pass a function
// // to log results (for example: reportWebVitals(console.log))
// // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
// // reportWebVitals(); // // reportWebVitals();

View File

@@ -15,6 +15,7 @@
"apollo-engine": "^1.1.2", "apollo-engine": "^1.1.2",
"apollo-server": "^2.19.0", "apollo-server": "^2.19.0",
"apollo-server-express": "^2.19.1", "apollo-server-express": "^2.19.1",
"bcrypt": "^5.0.0",
"bcryptjs": "2.4.3", "bcryptjs": "2.4.3",
"body-parser": "^1.19.0", "body-parser": "^1.19.0",
"chai": "^4.2.0", "chai": "^4.2.0",

View File

@@ -9,6 +9,36 @@ import './utils/db.js';
import fs from 'fs'; import fs from 'fs';
import path from 'path'; import path from 'path';
import cors from 'cors'; import cors from 'cors';
// import getUserId from './utils';
import jwt from 'jsonwebtoken';
const APP_SECRET = 'GraphQL-is-aw3some';
function getTokenPayload(token) {
return jwt.verify(token, APP_SECRET);
}
function getUserId(req, authToken) {
if (req) {
const authHeader = req.headers.authorization;
if (authHeader) {
const token = authHeader.replace('Bearer ', '');
if (!token) {
throw new Error('No token found');
}
const { userId } = getTokenPayload(token);
return userId;
}
} else if (authToken) {
const { userId } = getTokenPayload(authToken);
return userId;
}
throw new Error('Not authenticated');
}
const moduleURL = new URL(import.meta.url); const moduleURL = new URL(import.meta.url);
const __dirname = path.dirname(moduleURL.pathname); const __dirname = path.dirname(moduleURL.pathname);
@@ -19,12 +49,6 @@ dotenv.config();
app.use(cors()); app.use(cors());
// app.get('/', (req, res) => {
// res.json({
// msg: 'GraphQL home!'
// })
// });
app.use('/djhb58fytkh476dk45yh49', graphqlHTTP({ app.use('/djhb58fytkh476dk45yh49', graphqlHTTP({
schema: schema, schema: schema,
validationRules: [depthLimit(3)], validationRules: [depthLimit(3)],
@@ -39,7 +63,7 @@ const server = new ApolloServer({
// schema, // schema,
cors: true, cors: true,
playground: process.env.NODE_ENV === 'development' ? true : false, playground: process.env.NODE_ENV === 'development' ? true : false,
context: async ({ req }) => { context: ({ req }) => {
// if (!db) { // if (!db) {
// try { // try {
// if (!dbClient.isConnected()) await dbClient.connect() // if (!dbClient.isConnected()) await dbClient.connect()
@@ -53,10 +77,10 @@ const server = new ApolloServer({
...req, ...req,
mongoose, mongoose,
pubsub, pubsub,
// userId: userId:
// req && req.headers.authorization req && req.headers.authorization
// ? getUserId(req) ? getUserId(req)
// : null : null
} }
}, },
// subscriptions: { // subscriptions: {
@@ -102,15 +126,6 @@ app.listen({ port: process.env.PORT }, () => {
}); });
// const { ApolloServer, PubSub } = require('apollo-server');
// // const { Cors } = require('cors');
// // const { Express } = require('express');
// const express = require("express");
// const { graphqlHTTP } = require('express-graphql'); // const { graphqlHTTP } = require('express-graphql');
// const mongoose = require("mongoose"); // const mongoose = require("mongoose");
// const graphqlSchema = require("./graphql/schema/schema") // const graphqlSchema = require("./graphql/schema/schema")
@@ -129,10 +144,6 @@ app.listen({ port: process.env.PORT }, () => {
// const path = require('path'); // const path = require('path');
// const { getUserId } = require('./utils'); // const { getUserId } = require('./utils');
// const pubsub = new PubSub();
// const app = express()
// const graphqlResolvers = { // const graphqlResolvers = {
// appointmentResolvers, // appointmentResolvers,
// userResolvers // userResolvers

View File

@@ -1,4 +1,5 @@
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import bcrypt from 'bcrypt';
const Schema = mongoose.Schema; const Schema = mongoose.Schema;
const UserSchema = new Schema({ const UserSchema = new Schema({
username: { username: {
@@ -18,4 +19,15 @@ const UserSchema = new Schema({
required: false required: false
} }
}); });
// hash the password
UserSchema.methods.generateHash = function (password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
// checking if password is valid
UserSchema.methods.validPassword = function (password) {
return bcrypt.compareSync(password, this.password);
};
export default mongoose.model('user', UserSchema); export default mongoose.model('user', UserSchema);

View File

@@ -3,7 +3,7 @@ import Product from './models/product.js';
import Appointment from './models/appointment.js'; import Appointment from './models/appointment.js';
import User from './models/user.js' import User from './models/user.js'
// import { createAppointment } from './resolvers/Mutation.js'; // import { createAppointment } from './resolvers/Mutation.js';
import bcrypt from 'bcryptjs'; import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken'; import jwt from 'jsonwebtoken';
import dotenv from 'dotenv'; import dotenv from 'dotenv';
@@ -27,18 +27,12 @@ export const resolvers = {
}, },
Mutation: { Mutation: {
async signup(root, args, context, info) { async signup(root, args, context, info) {
console.log(args, args.password); var user = await User.create(args);
user.password = user.generateHash(args.password);
args.password = await bcrypt.hash(args.password, 10); user.save();
console.log("pre ", args.password)
const user = await User.create(args);
const token = jwt.sign({ userId: user.id }, process.env.APP_SECRET); const token = jwt.sign({ userId: user.id }, process.env.APP_SECRET);
console.log("post", user.password);
return { return {
token, token,
user user
@@ -46,7 +40,10 @@ export const resolvers = {
}, },
async login(parent, args, context, info) { async login(parent, args, context, info) {
console.log(args); console.log(context);
const { userId } = context;
console.log(userId);
const user = await User.findOne({ const user = await User.findOne({
email: args.email email: args.email
}); });
@@ -54,17 +51,11 @@ export const resolvers = {
throw new Error('No such user found'); throw new Error('No such user found');
} }
console.log(user.password); if (!user.validPassword(args.password)) {
const valid = await bcrypt.compare(
args.password,
user.password
);
if (!valid) {
throw new Error('Invalid password'); throw new Error('Invalid password');
} }
const token = jwt.sign({ userId: user.id }, APP_SECRET); const token = jwt.sign({ userId: user.id }, process.env.APP_SECRET);
return { return {
token, token,
@@ -73,7 +64,11 @@ export const resolvers = {
}, },
async createAppointment(parent, args, context, info) { async createAppointment(parent, args, context, info) {
console.log(context);
const { userId } = context;
console.log("userID", userId);
args.deleted = false; args.deleted = false;
args.createdBy = userId;
return await Appointment.create(args); return await Appointment.create(args);
}, },
async updateAppointment(parent, args, context, info) { async updateAppointment(parent, args, context, info) {

View File

@@ -99,7 +99,7 @@ type Appointment {
start: DateTime! start: DateTime!
end: DateTime! end: DateTime!
deleted: Boolean deleted: Boolean
# createdBy: User createdBy: User
# follows: [Follow!]! # follows: [Follow!]!
# createdAt: DateTime! # createdAt: DateTime!
} }

View File

@@ -1,4 +1,4 @@
const jwt = require('jsonwebtoken'); import jwt from 'jsonwebtoken';
const APP_SECRET = 'GraphQL-is-aw3some'; const APP_SECRET = 'GraphQL-is-aw3some';
function getTokenPayload(token) { function getTokenPayload(token) {