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

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

View File

@@ -9,6 +9,36 @@ import './utils/db.js';
import fs from 'fs';
import path from 'path';
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 __dirname = path.dirname(moduleURL.pathname);
@@ -19,12 +49,6 @@ dotenv.config();
app.use(cors());
// app.get('/', (req, res) => {
// res.json({
// msg: 'GraphQL home!'
// })
// });
app.use('/djhb58fytkh476dk45yh49', graphqlHTTP({
schema: schema,
validationRules: [depthLimit(3)],
@@ -39,7 +63,7 @@ const server = new ApolloServer({
// schema,
cors: true,
playground: process.env.NODE_ENV === 'development' ? true : false,
context: async ({ req }) => {
context: ({ req }) => {
// if (!db) {
// try {
// if (!dbClient.isConnected()) await dbClient.connect()
@@ -53,10 +77,10 @@ const server = new ApolloServer({
...req,
mongoose,
pubsub,
// userId:
// req && req.headers.authorization
// ? getUserId(req)
// : null
userId:
req && req.headers.authorization
? getUserId(req)
: null
}
},
// 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 mongoose = require("mongoose");
// const graphqlSchema = require("./graphql/schema/schema")
@@ -129,10 +144,6 @@ app.listen({ port: process.env.PORT }, () => {
// const path = require('path');
// const { getUserId } = require('./utils');
// const pubsub = new PubSub();
// const app = express()
// const graphqlResolvers = {
// appointmentResolvers,
// userResolvers

View File

@@ -1,4 +1,5 @@
import mongoose from 'mongoose';
import bcrypt from 'bcrypt';
const Schema = mongoose.Schema;
const UserSchema = new Schema({
username: {
@@ -18,4 +19,15 @@ const UserSchema = new Schema({
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);

View File

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

View File

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

View File

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