-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
2077 lines (2060 loc) · 94.7 KB
/
Program.cs
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Net;
using System.Text;
using Newtonsoft.Json;
using System.Data.SQLite;
using System.Data;
using System.Security;
using System.Dynamic;
using System.Net.Mime;
using System.Windows.Markup;
using System.CodeDom;
class MessageServer
{
// Global constants:
const string typeJson = "application/json"; // For ease of use when sending a response.
static readonly string logPath = @"logs\Server_" + DateTime.Now.ToString("yyyy-MM-dd_HH.mm.ss") + ".log"; // Cannot use a const because the time can't be calculated at compilation.
const string connectionString = "Data Source=data.db; Version=3; New=True; Compress=True;";
const bool logAllRequests = true;
const int owner = 5;
const int admin = 4;
const int unprivileged = 3;
const int readWrite = 3;
const int readOnly = 2;
const int notInChannel = 1;
const int notInGuild = 1;
const int channelNotExist = 0;
const int guildNotExist = 0;
static void Main(string[] args)
{
using (var con = new SQLiteConnection(connectionString))
{
con.Open();
log("DEBUG", "Using SQLite version: " + con.ServerVersion);
}
createDB(connectionString);
const string url = "http://localhost:8080/"; // Sets up http server
HttpListener listener = new HttpListener();
listener.Prefixes.Add(url);
try
{
listener.Start();
}
catch (Exception ex)
{
Console.WriteLine("Failed to start server, the port is likeley already in use or the address has been reserved by the system.");
log("ERROR", "Server failed to start. Error: ", ex);
Environment.Exit(-1);
}
Console.WriteLine("Listening for requests on " + url);
log("INFO", "Started server at " + url);
while (true)
{
HttpListenerContext context = listener.GetContext();
Uri uri = new Uri(context.Request.Url.ToString());
if (logAllRequests) {log("INFO", context.Request.UserHostAddress.ToString() + " accessed " + uri.AbsolutePath.ToString());}
string responseMessage;
try // This try catch should hopefully never run, but if needed it will stop the server from crashing.
{
switch (uri.AbsolutePath) // Calls function used for each api endpoint
{
case "/api/content/getMessages": apiGetMessages(context); break; //Get
case "/api/content/sendMessage": apiSendMessage(context); break; //Post
case "/api/user/getInfo": apiGetUserInfo(context); break; //Get
//case "/api/directMessage/create": apiCreateChannel(context, true); break; //Post Unfinished
case "/api/guild/channel/create": apiCreateChannel(context, false); break; //Post
case "/api/guild/channel/rename": apiRenameChannel(context); break; //Post
case "/api/guild/channel/delete": apiDeleteChannel(context); break; //Post
case "/api/guild/channel/setPermissions": apiSetChannelPermissions(context); break;
case "/api/guild/create": apiCreateGuild(context); break; //Post
case "/api/guild/listGuilds": apiListGuilds(context); break; //Get
case "/api/guild/fetchDetails": apiFetchGuildDetails(context); break; //Get
case "/api/guild/setDetails": apiSetGuildDetails(context); break; //Post
case "/api/guild/invite/create": apiCreateInvite(context); break; //Get
case "/api/guild/invite/list": apiListInvites(context); break; //Get
case "/api/guild/join": apiJoinGuildFromCode(context); break; //Post
case "/api/guild/leave": apiLeaveGuild(context); break; //Post
case "/api/account/create": apiCreateUser(context); break; //Post
case "/api/account/login": apiLogin(context); break; //Post
case "/api/account/userID": apiReturnUserIDFromToken(context); break; //Get
case "/api/account/setPicture": apiSetPicture(context); break; //Post
case "/api/guild/key/request": apiRequestKeys(context); break; //Post
case "/api/guild/key/listRequests": apiGetKeyRequests(context); break; //Get
case "/api/guild/key/submit": apiSubmitKey(context); break; //Post
case "/api/guild/users/togglePerms": apiToggleUserPerms(context); break; //Post
case "/api/guild/users/list": apiListGuildUsers(context); break; //Get
case "/api/guild/users/kick": apiKickGuildUser(context); break; //Post
default:
{
var responseJson = new
{
error = "Unrecognised request",
errcode = "UNRECOGNISED_URL"
};
responseMessage = JsonConvert.SerializeObject(responseJson);
sendResponse(context, typeJson, 404, responseMessage);
Console.WriteLine(uri.AbsolutePath);
}break;
}
}
catch (Exception ex)
{
log("ERROR", ex.GetType() + "Error: \n", ex);
var responseJson = new { error = "Internal Server Error (500)", errcode = "UNKNOWN" };
responseMessage = JsonConvert.SerializeObject(responseJson);
sendResponse(context, typeJson, 500, responseMessage);
}
}
}
static void createDB(string connectionString) // Opens connection to SQLite and creates the tables required
{
using (var con = new SQLiteConnection(connectionString))
using (var cmd = new SQLiteCommand(con))
{
con.Open();
cmd.CommandText = "";
cmd.CommandText = @"CREATE TABLE IF NOT EXISTS 'tblUsers' (
'UserID' CHAR(36),
'UserName' VARCHAR(20),
'PassHash' VARCHAR(64),
'PublicKey' TEXT,
'Picture' CHAR(36),
'Description' CHAR(36),
PRIMARY KEY('UserID')
);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"CREATE TABLE IF NOT EXISTS 'tblChannels' (
'ChannelID' CHAR(36),
'ChannelName' VARCHAR(20),
'ChannelType' INTEGER,
'ChannelDesc' VARCHAR(100),
'IsDM' BOOL,
'GuildID' CHAR(36),
PRIMARY KEY('ChannelID')
);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"CREATE TABLE IF NOT EXISTS 'tblMessages' (
'ChannelID' CHAR(36),
'TimeSent' REAL,
'MessageID' CHAR(36),
'UserID' CHAR(36),
'Type' INTEGER,
'MessageContent' TEXT,
'IV' CHAR(32),
FOREIGN KEY('UserID') REFERENCES 'tblUsers'('UserID'),
FOREIGN KEY('ChannelID') REFERENCES 'tblChannels'('ChannelID'),
PRIMARY KEY('MessageID')
);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"CREATE TABLE IF NOT EXISTS 'tblGuildConnections' (
'UserID' CHAR(36),
'GuildID' CHAR(36),
'Admin' BOOL,
FOREIGN KEY('UserID') REFERENCES 'tblUsers'('UserID'),
FOREIGN KEY('GuildID') REFERENCES 'tblGuilds'('GuildID'),
PRIMARY KEY('UserID', 'GuildID')
)";
cmd.ExecuteNonQuery();
cmd.CommandText = @"CREATE TABLE IF NOT EXISTS 'tblDMConnections' (
'UserID' CHAR(36),
'ChannelID' CHAR(36),
FOREIGN KEY('UserID') REFERENCES 'tblUsers'('UserID'),
FOREIGN KEY('ChannelID') REFERENCES 'tblChannels'('ChannelID'),
PRIMARY KEY('UserID', 'ChannelID')
);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"CREATE TABLE IF NOT EXISTS 'tblTokens' (
'Token' CHAR(36),
'UserID' CHAR(36),
PRIMARY KEY('Token'),
FOREIGN KEY('UserID') REFERENCES 'tblUsers'('UserID')
);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"CREATE TABLE IF NOT EXISTS 'tblGuilds' (
'GuildID' CHAR(36),
'GuildName' VARCHAR(36),
'OwnerID' CHAR(36),
'GuildDesc' VARCHAR(100),
'GuildKeyDigest' CHAR(32),
PRIMARY KEY('GuildID'),
FOREIGN KEY('OwnerID') REFERENCES 'tblUsers'('UserID')
);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"CREATE TABLE IF NOT EXISTS 'tblKeyRequests' (
'RequesterID' CHAR(36),
'GuildID' CHAR(36),
'EncryptedKey' TEXT,
'ResponderID' CHAR(36),
FOREIGN KEY('RequesterID') REFERENCES 'tblUsers'('UserID'),
FOREIGN KEY('GuildID') REFERENCES 'tblGuilds'('GuildID'),
PRIMARY KEY('RequesterID', 'GuildID')
);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"CREATE TABLE IF NOT EXISTS 'tblInvites' (
'Code' CHAR(8),
'GuildID' CHAR(36),
PRIMARY KEY('Code'),
FOREIGN KEY('GuildID') REFERENCES 'tblGuilds'('GuildID')
);";
cmd.ExecuteNonQuery();
}
}
static void sendResponse(HttpListenerContext context, string type, int code, string? responseMessage = null) // Sends data in response to a call from a client
{
try
{
if (string.IsNullOrEmpty(responseMessage))
{
context.Response.Headers.Clear();
context.Response.StatusCode = code;
context.Response.Close();
}
else
{
byte[] responseBytes = Encoding.UTF8.GetBytes(responseMessage);
context.Response.ContentLength64 = responseBytes.Length;
context.Response.ContentType = type;
context.Response.StatusCode = code;
Stream outputStream = context.Response.OutputStream;
outputStream.Write(responseBytes, 0, responseBytes.Length);
outputStream.Close();
}
if (logAllRequests && context.Request.Url.AbsolutePath.ToString() != "/api/content/getMessages")
{
Console.WriteLine("Sent response: " + responseMessage);
}
}
catch(Exception ex) { log("ERROR", "Failed to send response", ex); }
}
static void log(string type, string desc, Exception ex = null)
{
string time = DateTime.Now.ToString("MM/dd HH:mm:ss.fff");
if(!Directory.Exists("logs"))
{
Directory.CreateDirectory("logs");
}
switch (type)
{
case "ERROR":
{
Console.WriteLine("[!ERROR] " + ex.GetType() + " exeption, see logs for details");
File.AppendAllText(logPath, time + " [!ERROR] " + desc + ex.ToString() + "\n\n");
}break;
case "WARNING":
{
Console.WriteLine("[WARNING] " + desc);
File.AppendAllText(logPath, time + " [WARNING] " + desc + "\n\n");
}break;
case "INFO":
{
File.AppendAllText(logPath, time + " [INFO] " + desc + "\n");
}break;
case "DEBUG":
{
File.AppendAllText(logPath, time + " [DEBUG] " + desc + "\n");
}break;
}
}
static dynamic parsePost(HttpListenerContext context)
{
string bodyContent;
var request = context.Request;
if (request.HttpMethod == "POST" && request.ContentType != null)
{
using (var body = request.InputStream)
using (var reader = new StreamReader(body, request.ContentEncoding))
{
bodyContent = reader.ReadToEnd();
}
}
else { bodyContent = null; }
return bodyContent;
}
static dynamic parseJsonPost(HttpListenerContext context)
{
var request = context.Request;
dynamic jsonBodyObject;
if (request.HttpMethod == "POST" && request.ContentType != null && request.ContentType.Contains(typeJson))
{
var JsonBody = parsePost(context);
jsonBodyObject = JsonConvert.DeserializeObject<dynamic>(JsonBody);
}
else { jsonBodyObject = null; }
return jsonBodyObject;
}
static void returnInvalidTokenError(out string responseMessage, out int code)
{
var responseJson = new { error = "Invalid token", errcode = "INVALID_TOKEN" };
responseMessage = JsonConvert.SerializeObject(responseJson);
code = 401;
}
static void returnMissingParameterError(out string responseMessage, out int code)
{
var responseJson = new { error = "Missing a required parameter", errcode = "MISSING_PARAMETER"};
responseMessage = JsonConvert.SerializeObject(responseJson);
code = 400;
}
static void apiGetMessages(HttpListenerContext context) // Fetches message data from db if user has permission, and returns it as a json array.
{
List<Message> messages = new List<Message>();
int code;
string responseMessage;
string? channelID = context.Request.QueryString["channelID"];
string? afterMessageID = context.Request.QueryString["afterMessageID"];
string? beforeMessageID = context.Request.QueryString["beforeMessageID"];
string? token = context.Request.QueryString["token"];
if (string.IsNullOrEmpty(channelID) | string.IsNullOrEmpty(token)) returnMissingParameterError(out responseMessage, out code);
else if (!tokenValid(token)) returnInvalidTokenError(out responseMessage, out code);
else
{
string userID = getUserIDFromToken(token);
if (checkUserChannelPerms(channelID, userID) > notInChannel) // Has to have read permissions
{
using (var con = new SQLiteConnection(connectionString))
using (var cmd = new SQLiteCommand(con))
{
con.Open();
// Will return all messages in a channel if AfterMessageID is null, otherwise it will return only the messages after the message specified.
cmd.CommandText = @"SELECT * FROM
(
SELECT tblUsers.UserID, UserName, MessageID, TimeSent, MessageContent, IV, Type
FROM tblMessages, tblUsers
WHERE tblMessages.ChannelID = @ChannelID
AND tblMessages.UserID = tblUsers.UserID
AND (
CASE
WHEN @AfterMessageID IS NOT NULL AND tblMessages.TimeSent > (
SELECT TimeSent
FROM tblMessages
WHERE MessageID = @AfterMessageID
)
OR @BeforeMessageID IS NOT NULL AND tblMessages.TimeSent < (
SELECT TimeSent
FROM tblMessages
WHERE MessageID = @BeforeMessageID
)
OR (@AfterMessageID IS NULL AND @BeforeMessageID IS NULL)
THEN true
ELSE false
END
)
ORDER BY TimeSent desc
LIMIT 50
)
ORDER BY TimeSent ASC;";
cmd.Parameters.AddWithValue("AfterMessageID", afterMessageID);
cmd.Parameters.AddWithValue("BeforeMessageID", beforeMessageID);
cmd.Parameters.AddWithValue("ChannelID", channelID);
using (SQLiteDataReader reader = cmd.ExecuteReader())
{
while (reader.Read()) // Loops through each message and adds it to the message list
{
Message responseRow = new Message
{
UserID = reader.GetString(0),
UserName = reader.GetString(1),
ID = reader.GetString(2),
ChannelID = channelID,
Time = reader.GetDouble(3),
Content = reader.GetString(4),
IV = reader.GetString(5),
Type = reader.GetInt32(6)
};
messages.Add(responseRow);
}
}
}
}
else
{
var responseJson = new { error = "You do not have permission to read messages in this channel", errcode = "FORBIDDEN" };
responseMessage = JsonConvert.SerializeObject(responseJson);
code = 403;
sendResponse(context, typeJson, code, responseMessage);
return;
}
responseMessage = JsonConvert.SerializeObject(messages);
code = 200;
}
sendResponse(context, typeJson, code, responseMessage);
}
static void apiSendMessage(HttpListenerContext context)
{
Message message;
string token;
dynamic jsonBodyObject = parseJsonPost(context);
int code;
string? responseMessage;
if (jsonBodyObject == null)
{
var responseJson = new { error = "Incorrectly formatted request", errcode = "FORMATTING_ERROR"};
responseMessage = JsonConvert.SerializeObject(responseJson);
sendResponse(context, typeJson, 400, responseMessage);
return;
}
else
{
token = jsonBodyObject.token;
}
if (string.IsNullOrEmpty((string)jsonBodyObject.channelID) | string.IsNullOrEmpty((string)jsonBodyObject.content) | string.IsNullOrEmpty(token))
{returnMissingParameterError(out responseMessage, out code);}
else if (!tokenValid(token)) returnInvalidTokenError(out responseMessage, out code);
else
{
message = new Message
{
ID = Guid.NewGuid().ToString(),
ChannelID = jsonBodyObject.channelID,
Type = jsonBodyObject.type,
Content = jsonBodyObject.content,
IV = jsonBodyObject.iv,
};
message.UserID = getUserIDFromToken(token);
if (checkUserChannelPerms(message.ChannelID, message.UserID) >= checkChannelMimimumPerms(message.ChannelID)) // Has to have higher privilages than the minimum
{
using (var con = new SQLiteConnection(connectionString))
using (var cmd = new SQLiteCommand(con))
{
con.Open();
cmd.CommandText = @"INSERT INTO tblMessages (ChannelID, TimeSent, MessageID, UserID, Type, MessageContent, IV)
VALUES (@ChannelID, unixepoch('subsec'), @MessageID, @UserID, @Type, @MessageContent, @IV);";
cmd.Parameters.AddWithValue("ChannelID", message.ChannelID);
cmd.Parameters.AddWithValue("MessageID", message.ID);
cmd.Parameters.AddWithValue("UserID", message.UserID);
cmd.Parameters.AddWithValue("Type", message.Type);
cmd.Parameters.AddWithValue("MessageContent", message.Content);
cmd.Parameters.AddWithValue("IV", message.IV);
cmd.ExecuteNonQuery();
cmd.CommandText = @"SELECT Username
FROM tblUsers
WHERE UserID = @UserID";
cmd.Parameters.AddWithValue("UserID", message.UserID);
message.UserName = (string)cmd.ExecuteScalar();
cmd.CommandText = @"SELECT TimeSent
FROM tblMessages
WHERE MessageID = @MessageID";
cmd.Parameters.AddWithValue("MessageID", message.ID);
message.Time = (double)cmd.ExecuteScalar();
responseMessage = JsonConvert.SerializeObject(message);
code = 200;
}
}
else
{
var responseJson = new { error = "You do not have permission to post in this channel", errcode = "FORBIDDEN" };
responseMessage = JsonConvert.SerializeObject(responseJson);
code = 403;
}
}
sendResponse(context, typeJson, code, responseMessage);
}
private static void apiListGuildUsers(HttpListenerContext context)
{
string? token = context.Request.QueryString["token"];
string? guildID = context.Request.QueryString["guildID"];
string responseMessage;
int code;
if (string.IsNullOrEmpty(guildID) | string.IsNullOrEmpty(token)) returnMissingParameterError(out responseMessage, out code);
else if (!tokenValid(token)) returnInvalidTokenError(out responseMessage, out code);
else
{
string requesterUserID = getUserIDFromToken(token);
if (checkUserGuildPerms(guildID, requesterUserID) > notInGuild) // Has to have read permissions
{
List<string> users = new List<string>{ };
using (var con = new SQLiteConnection(connectionString))
using (var cmd = new SQLiteCommand(con))
{
con.Open();
cmd.CommandText = @"SELECT UserID
FROM tblGuildConnections
WHERE GuildID = @GuildID;";
cmd.Parameters.AddWithValue("GuildID", guildID);
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
users.Add(reader.GetString(0));
}
}
}
Dictionary<string, object> responseJson = new();
foreach (string userID in users)
{
int permissions = checkUserGuildPerms(guildID, userID);
User user = getUserInfoFromID(userID);
responseJson.Add(
userID,
new {
permissions = permissions,
userName = user.Name
}
);
}
responseMessage = JsonConvert.SerializeObject(responseJson);
code = 200;
}
else
{
var responseJson = new { error = "You do not have permission to send messages in this channel", errcode = "FORBIDDEN" };
responseMessage = JsonConvert.SerializeObject(responseJson);
code = 403;
}
}
sendResponse(context, typeJson, code, responseMessage);
}
private static void apiKickGuildUser(HttpListenerContext context)
{
string token;
string guildID;
string userID;
dynamic jsonBodyObject = parseJsonPost(context);
int code;
string? responseMessage;
if (jsonBodyObject == null)
{
var responseJson = new { error = "Incorrectly formatted request", errcode = "FORMATTING_ERROR"};
responseMessage = JsonConvert.SerializeObject(responseJson);
sendResponse(context, typeJson, 400, responseMessage);
return;
}
else
{
token = jsonBodyObject.token;
guildID = jsonBodyObject.guildID;
userID = jsonBodyObject.userID;
}
if (string.IsNullOrEmpty((string)jsonBodyObject.guildID) | string.IsNullOrEmpty((string)jsonBodyObject.userID) | string.IsNullOrEmpty((string)jsonBodyObject.token))
{returnMissingParameterError(out responseMessage, out code);}
else if (!tokenValid(token)) returnInvalidTokenError(out responseMessage, out code);
else
{
string requesterUserID = getUserIDFromToken(token);
int requesterPerms = checkUserGuildPerms(guildID, requesterUserID);
if (requesterPerms >= admin) // Has to have admin permissions
{
removeUserFromGuild(userID, guildID);
responseMessage = null;
code = 200;
}
else
{
var responseJson = new { error = "You do not have permission to remove a user from this guild", errcode = "FORBIDDEN" };
responseMessage = JsonConvert.SerializeObject(responseJson);
code = 403;
}
}
sendResponse(context, typeJson, code, responseMessage);
}
private static void apiLeaveGuild(HttpListenerContext context)
{
string token;
string guildID;
dynamic jsonBodyObject = parseJsonPost(context);
int code;
string? responseMessage;
if (jsonBodyObject == null)
{
var responseJson = new { error = "Incorrectly formatted request", errcode = "FORMATTING_ERROR"};
responseMessage = JsonConvert.SerializeObject(responseJson);
sendResponse(context, typeJson, 400, responseMessage);
return;
}
else
{
token = jsonBodyObject.token;
guildID = jsonBodyObject.guildID;
}
if (string.IsNullOrEmpty((string)jsonBodyObject.guildID) | string.IsNullOrEmpty((string)jsonBodyObject.token))
{returnMissingParameterError(out responseMessage, out code);}
else if (!tokenValid(token)) returnInvalidTokenError(out responseMessage, out code);
else
{
string userID = getUserIDFromToken(token);
if (checkUserGuildPerms(guildID, userID) > notInGuild) // Has to have admin permissions
{
removeUserFromGuild(userID, guildID);
responseMessage = null;
code = 200;
}
else
{
var responseJson = new { error = "You do not have permission to leave this guild", errcode = "FORBIDDEN" };
responseMessage = JsonConvert.SerializeObject(responseJson);
code = 403;
}
}
sendResponse(context, typeJson, code, responseMessage);
}
private static void removeUserFromGuild(string userID, string guildID)
{
using (var con = new SQLiteConnection(connectionString))
using (var cmd = new SQLiteCommand(con))
{
con.Open();
cmd.CommandText = @"DELETE FROM tblGuildConnections
WHERE UserID = @UserID
AND GuildID = @GuildID";
cmd.Parameters.AddWithValue("GuildID", guildID);
cmd.Parameters.AddWithValue("UserID", userID);
cmd.ExecuteNonQuery();
}
}
private static int checkUserGuildPerms(string guildID, string userID)
{
/* Returns:
- 5 for Owner
- 4 for Admin
- 3 for unprivileged user
- 1 for not in guild
- 0 if guild does not exist
*/
if (!checkGuildExists(guildID)) {return guildNotExist;}
using (var con = new SQLiteConnection(connectionString))
using (var cmd = new SQLiteCommand(con))
{
con.Open();
// Check if server is in guild
cmd.CommandText = @"SELECT EXISTS(
SELECT 1
FROM tblGuildConnections
WHERE UserID = @UserID
AND GuildID = @GuildID
);";
cmd.Parameters.AddWithValue("UserID", userID);
cmd.Parameters.AddWithValue("GuildID", guildID);
bool inGuild = (Int64)cmd.ExecuteScalar() > 0;
if (!inGuild) {return notInGuild;}
// Check if user is the owner
cmd.CommandText = @"SELECT OwnerID
FROM tblGuilds
WHERE GuildID = @GuildID;";
cmd.Parameters.AddWithValue("GuildID", guildID);
bool isOwner = (string)cmd.ExecuteScalar() == userID;
if (isOwner) {return owner;}
// Check if user has admin
cmd.CommandText = @"SELECT Admin
FROM tblGuildConnections
JOIN tblGuilds ON tblGuilds.GuildID = tblGuildConnections.GuildID
WHERE UserID = @UserID
AND tblGuilds.GuildID = @GuildID;";
cmd.Parameters.AddWithValue("UserID", userID);
cmd.Parameters.AddWithValue("GuildID", guildID);
bool isAdmin = (bool)cmd.ExecuteScalar();
if (isAdmin) {return admin;}
// If the user is in the guild and is not the owner of an admin then the user has no extra permissions.
return unprivileged;
}
}
private static int checkUserChannelPerms(string channelID, string userID) // Gets the permissions of the user. 0 is not in channel, 1 is a read only channel, 2 is a normal user, 3 is administrator, 4 is owner.
{
/* Used to check the permissions a user has in a guild.
Returns:
- 5 for Owner
- 4 for Admin
- 3 if user has read and message permission
- 2 if read only (used for announcement or rule channels for example)
- 1 if not in channel
- 0 if channel does not exist
*/
bool inDM;
bool isDM;
int guildPerms;
using (var con = new SQLiteConnection(connectionString))
using (var cmd = new SQLiteCommand(con))
{
con.Open();
cmd.CommandText = @"SELECT GuildID
FROM tblChannels
WHERE ChannelID = @ChannelID";
cmd.Parameters.AddWithValue("ChannelID", channelID);
var result = cmd.ExecuteScalar(); // Get the guildID to check the permissions
if (result == null) // If the channel is in a DM, or doesn't exist
{
cmd.CommandText = @"SELECT IsDM
FROM tblChannels
WHERE ChannelID = @ChannelID;";
cmd.Parameters.AddWithValue("ChannelID", channelID);
isDM = (bool)cmd.ExecuteScalar();
if (!isDM) {return notInChannel;} // The channel does not exist
cmd.CommandText = @"SELECT EXISTS(
SELECT 1
FROM tblDMConnections, tblChannels
WHERE tblDMConnections.UserID = @UserID
AND tblDMConnections.ChannelID = @ChannelID
);"; // Returns true if user is in the supplied Channel or DM
cmd.Parameters.AddWithValue("UserID", userID);
cmd.Parameters.AddWithValue("ChannelID", channelID);
inDM = (Int64)cmd.ExecuteScalar() > 0; // Convert integer 1 or 0 into boolean
if (inDM) {return readWrite;} // If in the DM the user will always have admin permissions.
return channelNotExist; // If none of the other possibilities are true, the channel does not exist
}
else // If the channel is in a guild
{
string guildID = (string)result;
guildPerms = checkUserGuildPerms(guildID, userID);
if (guildPerms == unprivileged) // Normal user
{
cmd.CommandText = @"SELECT ChannelType
FROM tblChannels
WHERE ChannelID = @ChannelID";
cmd.Parameters.AddWithValue("@ChannelID", channelID);
Int64 channelType = (Int64)cmd.ExecuteScalar();
return channelType == 1 ? readWrite : readOnly; // Return 2 if the channel is read only, 3 if read/write
}
else
{
return guildPerms;
}
}
}
}
private static int checkChannelMimimumPerms(string channelID)
{
/* Returns:
- 5 for Owner
- 4 for Admin
- 3 for Unpriviliged user
- 10 if channel does not exist (needs to be higher than owner to stop messages being sent)
*/
int requiredPermission;
using (var con = new SQLiteConnection(connectionString))
using (var cmd = new SQLiteCommand(con))
{
// Check if channel exists
con.Open();
cmd.CommandText = @"SELECT EXISTS(
SELECT 1
FROM tblChannels
WHERE tblChannels.ChannelID = @ChannelID
);";
cmd.Parameters.AddWithValue("ChannelID", channelID);
bool channelExists = (Int64)cmd.ExecuteScalar() > 0;
if (!channelExists) requiredPermission = 10;
else
{
cmd.CommandText = @"SELECT ChannelType
FROM tblChannels
WHERE ChannelID = @ChannelID";
cmd.Parameters.AddWithValue("@ChannelID", channelID);
long channelType = (long)cmd.ExecuteScalar();
switch (channelType)
{
case 1: requiredPermission = unprivileged; break;
case 2: requiredPermission = admin; break;
case 3: requiredPermission = owner; break;
default: requiredPermission = 10; break;
}
}
}
return requiredPermission;
}
static void apiGetUserInfo(HttpListenerContext context)
{
string? token = context.Request.QueryString["token"];
string? requestedUserID = context.Request.QueryString["userID"];
int code;
string responseMessage;
if (string.IsNullOrEmpty(token) | string.IsNullOrEmpty(requestedUserID)) returnMissingParameterError(out responseMessage, out code);
else if (!tokenValid(token)) returnInvalidTokenError(out responseMessage, out code);
else
{
User user = getUserInfoFromID(requestedUserID);
if (user == null)
{
var responseJson = new { error = "That UserID does not exist", errcode = "NOT_FOUND" };
responseMessage = JsonConvert.SerializeObject(responseJson);
code = 400;
}
else
{
responseMessage = JsonConvert.SerializeObject(user);
code = 200;
}
}
sendResponse(context, typeJson, code, responseMessage);
}
static void apiCreateUser(HttpListenerContext context) // Checks if user exists before adding them to the database. Will respond with an error if the user allready exists.
{
string responseMessage;
int code;
string? userName;
string? passHash;
string? publicKey;
dynamic jsonBodyObject = parseJsonPost(context);
if (jsonBodyObject == null)
{
var responseJson = new { error = "Incorrectly formatted request", errcode = "FORMATTING_ERROR"};
responseMessage = JsonConvert.SerializeObject(responseJson);
sendResponse(context, typeJson, 400, responseMessage);
return;
}
else
{
userName = jsonBodyObject.userName;
publicKey = jsonBodyObject.publicKey;
passHash = jsonBodyObject.passHash;
}
if (string.IsNullOrEmpty(userName) | string.IsNullOrEmpty(publicKey) | string.IsNullOrEmpty(passHash)) {
returnMissingParameterError(out responseMessage, out code);
}
else
{
using (var con = new SQLiteConnection(connectionString))
using (var cmd = new SQLiteCommand(con))
{
con.Open();
cmd.CommandText = @"
SELECT EXISTS(
SELECT 1
FROM tblUsers
WHERE UserName = @UserName
)";
cmd.Parameters.AddWithValue("UserName", userName);
bool userTaken = (Int64)cmd.ExecuteScalar() > 0;
if (userTaken)
{
var responseJson = new { error = "User with that name already exists", errcode = "NAME_IN_USE"};
responseMessage = JsonConvert.SerializeObject(responseJson);
code = 400;
}
else
{
string userID = Guid.NewGuid().ToString();
cmd.CommandText = @"INSERT INTO tblUsers (UserID, UserName, PassHash, PublicKey, Picture)
VALUES (@UserID, @UserName, @PassHash, @PublicKey, '')";
cmd.Parameters.AddWithValue("UserID", userID);
cmd.Parameters.AddWithValue("UserName", userName);
cmd.Parameters.AddWithValue("PassHash", passHash);
cmd.Parameters.AddWithValue("PublicKey", publicKey);
cmd.ExecuteNonQuery();
var responseJson = new { token = createToken(userID) };
responseMessage = JsonConvert.SerializeObject(responseJson);
code = 200;
}
}
}
sendResponse(context, typeJson, code, responseMessage);
}
static void apiSetPicture(HttpListenerContext context)
{
string responseMessage;
int code;
string? token;
string? imageBase64;
dynamic jsonBodyObject = parseJsonPost(context);
if (jsonBodyObject == null)
{
var responseJson = new { error = "Incorrectly formatted request", errcode = "FORMATTING_ERROR"};
responseMessage = JsonConvert.SerializeObject(responseJson);
sendResponse(context, typeJson, 400, responseMessage);
return;
}
else
{
token = jsonBodyObject.token;
imageBase64 = jsonBodyObject.image;
}
if (string.IsNullOrEmpty(imageBase64)) returnMissingParameterError(out responseMessage, out code);
else if (!tokenValid(token)) returnInvalidTokenError(out responseMessage, out code);
else
{
string userID = getUserIDFromToken(token);
using (var con = new SQLiteConnection(connectionString))
using (var cmd = new SQLiteCommand(con))
{
con.Open();
cmd.CommandText = @"UPDATE tblUsers
SET Picture = @Picture
WHERE UserID = @UserID";
cmd.Parameters.AddWithValue("UserID", userID);
cmd.Parameters.AddWithValue("Picture", imageBase64);
cmd.ExecuteNonQuery();
code = 200;
responseMessage = null;
}
}
sendResponse(context, typeJson, code, responseMessage);
}
static void apiLogin(HttpListenerContext context) // Checks if the supplied username and password are correct, and returns a token if they are
{
string responseMessage;
int code;
string? userName;
string? passHash;
dynamic jsonBodyObject = parseJsonPost(context);
if (jsonBodyObject == null)
{
var responseJson = new { error = "Incorrectly formatted request", errcode = "FORMATTING_ERROR"};
responseMessage = JsonConvert.SerializeObject(responseJson);
sendResponse(context, typeJson, 400, responseMessage);
return;
}
else
{
userName = jsonBodyObject.userName;
passHash = jsonBodyObject.passHash;
}
if (string.IsNullOrEmpty(userName) | string.IsNullOrEmpty(passHash)) returnMissingParameterError(out responseMessage, out code);
else
{
using (var con = new SQLiteConnection(connectionString))
using (var cmd = new SQLiteCommand(con))
{
con.Open();
cmd.CommandText = @"SELECT UserID
FROM tblUsers
WHERE UserName = @UserName AND PassHash = @PassHash;";
cmd.Parameters.AddWithValue("UserName", userName);
cmd.Parameters.AddWithValue("PassHash", passHash);
object temp = cmd.ExecuteScalar();
string userID = temp == null ? null : (string)temp; // If the select returns null, store string as null, otherwise as a string.
bool correctCredentials = !string.IsNullOrEmpty(userID);
if (correctCredentials)
{
var responseJson = new { token = createToken(userID) };
responseMessage = JsonConvert.SerializeObject(responseJson);
code = 200;
}
else
{
var responseJson = new { error = "Incorrect username or password.", errcode = "FORBIDDEN" };
responseMessage = JsonConvert.SerializeObject(responseJson);
code = 403;
}
}
}
sendResponse(context, typeJson, code, responseMessage);
}
static void apiCreateChannel(HttpListenerContext context, bool isDM)
{
string? channelName;
string? token;
string? guildID;
string? userID2;
string? responseMessage;
int code;
int? channelType;
dynamic jsonBodyObject = parseJsonPost(context);
if (jsonBodyObject == null)
{
var responseJson = new { error = "Incorrectly formatted request", errcode = "FORMATTING_ERROR"};
responseMessage = JsonConvert.SerializeObject(responseJson);
sendResponse(context, typeJson, 400, responseMessage);
return;
}
else
{
token = jsonBodyObject.token;
channelName = jsonBodyObject.channelName;
guildID = jsonBodyObject.guildID;
userID2 = getUserIDFromUsername(jsonBodyObject.userToAdd);
}
if (!isDM)
{
channelType = 1;
}
else
{
channelType = null;
}
if (string.IsNullOrEmpty(channelName) | string.IsNullOrEmpty(token) | (isDM & string.IsNullOrEmpty(userID2)) | (!isDM & string.IsNullOrEmpty(guildID))) {
returnMissingParameterError(out responseMessage, out code);
}
else if (!tokenValid(token)) returnInvalidTokenError(out responseMessage, out code);
else
{
string userID1 = getUserIDFromToken(token);
if (isDM)
{
if (userID1 != userID2)
{
createDM(userID1, userID2);
responseMessage = null;
code = 200;
}
else
{
var responseJson = new { error = "You cannot add yourself to your own DM", errcode = "INVALID_DM" };
responseMessage = JsonConvert.SerializeObject(responseJson);
code = 400;
}
}
else
{
int userPermission = checkUserGuildPerms(guildID, userID1);
if (userPermission <= guildNotExist)
{
var responseJson = new { error = "Invalid GuildID", errcode = "INVALID_GUILDID" };
responseMessage = JsonConvert.SerializeObject(responseJson);
code = 400;
}
else if (userPermission < admin) // Reject the request if the user has lower permissions than admin