Removed unused authentication and product code

This commit is contained in:
Riccardo
2022-07-15 23:12:37 +02:00
parent 36a945e175
commit 0ee1ce6fb8
14 changed files with 9 additions and 555 deletions

View File

@@ -1,133 +0,0 @@
import React, { useState } from 'react';
import { useHistory } from 'react-router';
import { useMutation, gql } from '@apollo/client';
import { AUTH_TOKEN } from '../constants';
const SIGNUP_MUTATION = gql`
mutation SignupMutation(
$email: String!
$password: String!
$name: String!
) {
signup(
email: $email
password: $password
username: $name
) {
token
}
}
`;
const LOGIN_MUTATION = gql`
mutation LoginMutation(
$email: String!
$password: String!
) {
login(email: $email, password: $password) {
token
}
}
`;
const Login = () => {
const history = useHistory();
const [formState, setFormState] = useState({
login: true,
email: '',
password: '',
name: ''
});
const [login] = useMutation(LOGIN_MUTATION, {
variables: {
email: formState.email,
password: formState.password
},
onCompleted: ({ login }) => {
localStorage.setItem(AUTH_TOKEN, login.token);
history.push('/');
}
});
const [signup] = useMutation(SIGNUP_MUTATION, {
variables: {
name: formState.name,
email: formState.email,
password: formState.password
},
onCompleted: ({ signup }) => {
localStorage.setItem(AUTH_TOKEN, signup.token);
history.push('/');
}
});
return (
<div>
<h4 className="mv3">
{formState.login ? 'Login' : 'Sign Up'}
</h4>
<div className="flex flex-column">
{!formState.login && (
<input
value={formState.name}
onChange={(e) =>
setFormState({
...formState,
name: e.target.value
})
}
type="text"
placeholder="Your name"
/>
)}
<input
value={formState.email}
onChange={(e) =>
setFormState({
...formState,
email: e.target.value
})
}
type="text"
placeholder="Your email address"
/>
<input
value={formState.password}
onChange={(e) =>
setFormState({
...formState,
password: e.target.value
})
}
type="password"
placeholder="Choose a safe password"
/>
</div>
<div className="flex mt3">
<button
className="pointer mr2 button"
onClick={formState.login ? login : signup}
>
{formState.login ? 'login' : 'create account'}
</button>
<button
className="pointer button"
onClick={(e) =>
setFormState({
...formState,
login: !formState.login
})
}
>
{formState.login
? 'need to create an account?'
: 'already have an account?'}
</button>
</div>
</div>
);
};
export default Login;

View File

@@ -1,14 +0,0 @@
import React from 'react';
const Product = (props) => {
const { product } = props;
return (
<div>
<div>
<b>{product.title}</b>: only {product.qty}!
</div>
</div>
);
};
export default Product;

View File

@@ -1,40 +0,0 @@
import React from 'react';
import Product from './Product';
import { useQuery, gql } from '@apollo/client';
const FEED_QUERY = gql`
{
allProducts{
title
qty
}
}
`;
const ProductList = () => {
const { data } = useQuery(FEED_QUERY);
console.log("Data:", data);
if (data !== undefined) {
return (
<div>
{
data.allProducts.map((product) => (
<Product key={product.id} product={product} />
))
}
</div>
);
} else {
return (
<div>
Rendering...
</div>
)
}
};
export default ProductList;

View File

@@ -11,10 +11,6 @@ const FEED_SEARCH_QUERY = gql`
title title
description description
type type
createdBy {
id
username
}
} }
} }
} }

View File

@@ -9,34 +9,6 @@ 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 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);
@@ -64,11 +36,7 @@ const server = new ApolloServer({
return { return {
...req, ...req,
mongoose, mongoose,
pubsub, pubsub
userId:
req && req.headers.authorization
? getUserId(req)
: null
} }
}, },
introspection: true, introspection: true,

View File

@@ -1,12 +0,0 @@
import mongoose from 'mongoose';
const Schema = mongoose.Schema;
const ProductSchema = new Schema({
title: {
type: String,
required: true
},
qty: {
type: Number
}
});
export default mongoose.model('product', ProductSchema);

View File

@@ -1,33 +0,0 @@
import mongoose from 'mongoose';
import bcrypt from 'bcrypt';
const Schema = mongoose.Schema;
const UserSchema = new Schema({
username: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
deleted: {
type: Boolean,
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

@@ -1,7 +1,4 @@
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 jwt from 'jsonwebtoken';
export const resolvers = { export const resolvers = {
Query: { Query: {
@@ -13,57 +10,11 @@ export const resolvers = {
_id: args._id _id: args._id
}); });
}, },
async allProducts() {
return await Product.find();
},
async allUsers() {
return await User.find();
},
}, },
Mutation: { Mutation: {
async signup(root, args, context, info) {
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);
return {
token,
user
};
},
async login(parent, args, context, info) {
console.log(context);
const { userId } = context;
console.log(userId);
const user = await User.findOne({
email: args.email
});
if (!user) {
throw new Error('No such user found');
}
if (!user.validPassword(args.password)) {
throw new Error('Invalid password');
}
const token = jwt.sign({ userId: user.id }, process.env.APP_SECRET);
return {
token,
user
};
},
async createAppointment(parent, args, context, info) { async createAppointment(parent, args, context, info) {
console.log(context); 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) {
@@ -77,27 +28,5 @@ export const resolvers = {
async deleteAppointment(parent, args, context, info) { async deleteAppointment(parent, args, context, info) {
return await Appointment.findOneAndUpdate({ _id: args._id }, { deleted: true }) return await Appointment.findOneAndUpdate({ _id: args._id }, { deleted: true })
}, },
async createProduct(root, {
input
}) {
return await Product.create(input);
},
async updateProduct(root, {
_id,
input
}) {
return await Product.findOneAndUpdate({
_id
}, input, {
new: true
})
},
async deleteProduct(root, {
_id
}) {
return await Product.findOneAndRemove({
_id
});
},
} }
}; };

View File

@@ -4,13 +4,6 @@ function createdBy(parent, args, context) {
.createdBy(); .createdBy();
} }
function follows(parent, args, context) {
return context.mongo.appointment
.findUnique({ where: { id: parent.id } })
.follows();
}
module.exports = { module.exports = {
createdBy, createdBy
follows
}; };

View File

@@ -1,16 +0,0 @@
function appointment(parent, args, context) {
return context.mongo.follow
.findUnique({ where: { id: parent.id } })
.appointment();
}
function user(parent, args, context) {
return context.mongo.follow
.findUnique({ where: { id: parent.id } })
.user();
}
module.exports = {
appointment,
user
};

View File

@@ -1,90 +1,14 @@
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { APP_SECRET } = require('../utils');
function createAppointment(parent, args, context, info) { function createAppointment(parent, args, context, info) {
const { userId } = context;
const newAppointment = context.mongo.appointment.create({ const newAppointment = context.mongo.appointment.create({
data: { data: {
title: args.title, title: args.title,
description: args.description, description: args.description
createdBy: { connect: { id: userId } }
} }
}); });
return newAppointment; return newAppointment;
} }
async function signup(parent, args, context, info) {
const password = await bcrypt.hash(args.password, 10);
const user = await context.mongo.user.create({
data: { ...args, password }
});
const token = jwt.sign({ userId: user.id }, APP_SECRET);
return {
token,
user
};
}
async function login(parent, args, context, info) {
const user = await context.mongo.user.findUnique({
where: { email: args.email }
});
if (!user) {
throw new Error('No such user found');
}
const valid = await bcrypt.compare(
args.password,
user.password
);
if (!valid) {
throw new Error('Invalid password');
}
const token = jwt.sign({ userId: user.id }, APP_SECRET);
return {
token,
user
};
}
async function follow(parent, args, context, info) {
const { userId } = context;
const follow = await context.mongo.follow.findUnique({
where: {
linkId_userId: {
linkId: Number(args.linkId),
userId: userId
}
}
});
if (Boolean(follow)) {
throw new Error(
`Already followed the appointment: ${args.linkId}`
);
}
const newFollow = context.mongo.follow.create({
data: {
user: { connect: { id: userId } },
link: { connect: { id: Number(args.linkId) } }
}
});
context.pubsub.publish('NEW_FOLLOW', newFollow);
return newFollow;
}
module.exports = { module.exports = {
createAppointment, createAppointment
signup,
login,
follow
}; };

View File

@@ -9,18 +9,6 @@ const newAppointment = {
}, },
} }
function newFollowSubscribe(parent, args, context, info) {
return context.pubsub.asyncIterator("NEW_FOLLOW")
}
const newFollow = {
subscribe: newFollowSubscribe,
resolve: payload => {
return payload
},
}
module.exports = { module.exports = {
newAppointment, newAppointment,
newFollow
} }

View File

@@ -6,13 +6,8 @@ type Query {
take: Int take: Int
orderBy: AppointmentOrderByInput orderBy: AppointmentOrderByInput
): Feed! ): Feed!
allProducts: [Product]
allAppointments: [Appointment] allAppointments: [Appointment]
oneAppointment( oneAppointment(_id: ID!): Appointment
_id: ID!
): Appointment
allUsers: [User]
users: [User!]!
} }
type Feed { type Feed {
@@ -31,7 +26,7 @@ type Mutation {
deleted: Boolean deleted: Boolean
): Appointment! ): Appointment!
updateAppointment( updateAppointment(
_id: ID!, _id: ID!
title: String! title: String!
description: String description: String
type: String! type: String!
@@ -39,55 +34,11 @@ type Mutation {
end: DateTime! end: DateTime!
deleted: Boolean deleted: Boolean
): Appointment ): Appointment
deleteAppointment( deleteAppointment(_id: ID!): Appointment
_id: ID!
) : Appointment
createProduct(
input: ProductInput
) : Product
updateProduct(
_id: ID!,
input: ProductInput
): Product
deleteProduct(
_id: ID!
) : Product
signup(
email: String!
password: String!
username: String!
): AuthPayload
login(
email: String!,
password: String!
): AuthPayload
follow(
appointmentId: ID!
): Follow
} }
type Subscription { type Subscription {
newAppointment: Appointment newAppointment: Appointment
newFollow: Follow
}
#User Schemas
type User {
_id: ID!
username: String!
email: String!
password: String!
# appointments: [Appointment!]!
}
input UserInput{
username: String!
email: String!
password: String!
# appointments: [Appointment!]!
}
type AuthPayload {
token: String
user: User
} }
# Appointment schemas # Appointment schemas
@@ -99,9 +50,6 @@ type Appointment {
start: DateTime! start: DateTime!
end: DateTime! end: DateTime!
deleted: Boolean deleted: Boolean
createdBy: User
# follows: [Follow!]!
# createdAt: DateTime!
} }
input AppointmentInput { input AppointmentInput {
title: String! title: String!
@@ -110,29 +58,10 @@ input AppointmentInput {
start: DateTime! start: DateTime!
end: DateTime! end: DateTime!
deleted: Boolean deleted: Boolean
} }
input AppointmentOrderByInput { input AppointmentOrderByInput {
title: Sort title: Sort
desc: Sort desc: Sort
# createdAt: Sort
}
# Product schemas
type Product {
_id: ID!
title: String!
qty: Int
}
input ProductInput {
title: String!
qty: Int
}
# Follow schemas
type Follow {
_id: ID!
appointment: Appointment!
user: User!
} }
# General-purpose schemas # General-purpose schemas

View File

@@ -1,30 +1,5 @@
import jwt from 'jsonwebtoken';
const APP_SECRET = 'GraphQL-is-aw3some'; 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');
}
module.exports = { module.exports = {
APP_SECRET, APP_SECRET
getUserId
}; };