-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
292 lines (219 loc) · 7.52 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
const { ApolloServer, gql } = require('apollo-server');
//import { typeDefs } from './schema.js';
//import { resolvers } from './resolver.js';
//import { SECRET } from './secret.js';
//import { conToExport as con} from './createdb.js';
var mysql = require('mysql2');
var bcrypt = require('bcrypt')
var jwt = require('jsonwebtoken')
//var dotenv = require('dotenv');
//dotenv.config();
var con = mysql.createPool({
host: process.env.HOST,
user: process.env.USER,
password: process.env.PASSWORD,
database: process.env.DATABASE
});
const SECRET = process.env.SECRET;
const typeDefs = gql`
type Message {
message: String!
sentBy: String!
sendDate: String!
}
type Query {
user: String
getMessage(chatName: String): [Message]
}
type Mutation {
addMessage(text: String, chatName: String): Message
createChat(chatName: String otherUser: String): String
register(username: String! email: String!, password: String!): User!
login(username: String!, password: String!): String!
}
type User {
username: String
email: String
password: String
}
`;
const resolvers = {
Query: {
user(parent, args, context, info) {
if (!context.user) {
throw new Error("Please log in to view this information");
} else {
console.log(context.user.user)
return context.user.user
}
},
getMessage: async (parent, args, context, info) => {
/*async function checkValid(username, email) {
const result = await con.promise().query("SELECT * FROM users WHERE username=? OR email=?", [ username, email ])
return result[0]
}*/
if (!context.user) {
throw new Error("Please log in to view this information");
} else {
async function checkIfAllowed(table) {
const result = await con.promise().query(`SELECT * FROM ${context.user.user} WHERE chatName=?`, [table])
return result[0]
}
var theResult = await checkIfAllowed(args.chatName);
if (theResult.length < 1) {
throw new Error("You cannot access this information");
} else {
async function getMessages(table) {
const result = await con.promise().query(`SELECT * FROM ${table}`)
return result
}
var colMessages = await getMessages(args.chatName);
var collection = []
for (var i = 0; i < colMessages[0].length; i++) {
var singleMessage = {
message: colMessages[0][i].message,
sentBy: colMessages[0][i].sentBy,
sendDate: colMessages[0][i].date
}
collection.push(singleMessage)
}
console.log(collection)
return collection
}
}
},
},
Mutation: {
addMessage: async (parent, args, context, info) => {
if (!context.user) {
throw new Error("Please log in to view this information");
} else {
async function checkIfAllowed(table) {
const result = await con.promise().query(`SELECT * FROM ${context.user.user} WHERE chatName=?`, [table])
return result[0]
}
var theResult = await checkIfAllowed(args.chatName);
if (theResult.length < 1) {
throw new Error("You cannot access this information");
} else {
console.log(args.text)
var time = new Date().toISOString().slice(0, 19).replace('T', ' ');
var sql = `INSERT INTO ${args.chatName}(message, sentBy, date) VALUES ('${args.text}', '${context.user.user}', '${time}')`;
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Inserted");
});
const createdMessage = {
message: args.text,
sentBy: context.user.user,
sendDate: time
}
return createdMessage
}
}
},
register: async (parent, args) => {
var sql = `SELECT * FROM users WHERE username = '${args.username}'`
var theResult = 0;
async function checkValid(username, email) {
const result = await con.promise().query("SELECT * FROM users WHERE username=? OR email=?", [ username, email ])
return result[0]
}
theResult = await checkValid(args.username, args.email)
if (theResult.length > 0) {
throw new Error("Username or/and email already exists")
}
pass = await bcrypt.hash(args.password, 12);
var time = new Date().toISOString().slice(0, 19).replace('T', ' ');
var sql = `INSERT INTO users (username, email, password, creationDate) VALUES ('${args.username}', '${args.email}', '${pass}', '${time}')`;
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Inserted");
});
//var sql = `CREATE TABLE ${args.email}(chatName VARCHAR(255), otherUser VARCHAR(255), creationDate DATETIME)`;
var sql = `CREATE TABLE ${args.username}(chatName VARCHAR(255), otherUser VARCHAR(255), creationDate DATETIME)`;
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Created");
});
console.log("Success")
const user = {
username: args.username,
email: args.email,
password: pass
}
return user
},
login: async (parent, args, context) => {
var theResult = "";
async function get_info(username) {
const results = await con.promise().query(`SELECT * FROM users WHERE username = '${username}'`)
return results
//return results[0]
}
theResult = await get_info(args.username)
if (theResult[0].length < 1) {
throw new Error("Invalid username");
}
const isValid = await bcrypt.compare(args.password, theResult[0][0].password);
if (!isValid) {
throw new Error("Incorrect password");
}
const token = await jwt.sign(
{
user: args.username
},
SECRET,
{expiresIn: "5h" }
);
console.log(token)
return token;
},
createChat: async (parent, args, context) => {
if (!context.user) {
throw new Error("Please log in to view this information");
} else {
var time = new Date().toISOString().slice(0, 19).replace('T', ' ');
console.log(context.user.user + "BRUGH")
var sql = `INSERT INTO ${context.user.user} (chatName, otherUser, creationDate) VALUES ('${args.chatName}', '${args.otherUser}', '${time}')`;
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Inserted");
});
sql = `CREATE TABLE ${args.chatName}(message VARCHAR(8000), sentBy VARCHAR(255), date DATETIME)`;
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Inserted");
});
return time;
}
}
}
};
const server = new ApolloServer({
typeDefs,
resolvers,
context: async ({ req }) => {
const token = await req.headers["authentication"];
let user;
try {
user = await jwt.verify(token, SECRET);
} catch (error) {
console.log(`${error.message} caught`);
}
return {
user,
SECRET
};
}
});
con.getConnection(function(err) {
if (err) throw err;
console.log("Connected!");
server.listen({ port: process.env.PORT || 4000 }).then(({ url }) => {
console.log(`
🚀 Server is ready at ${url}
📭 Query at https://studio.apollographql.com/dev
`);
});
});