-
Notifications
You must be signed in to change notification settings - Fork 19
/
PermissionRepository.cs
599 lines (502 loc) · 21.5 KB
/
PermissionRepository.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
using System;
using System.Linq;
using Microsoft.Extensions.Caching.Distributed;
using Arda.Common.Utils;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Net.Http;
using Arda.Permissions.Models;
using Arda.Permissions.Models.Repositories;
using Arda.Permissions.ViewModels;
namespace Arda.Permissions.Repositories
{
//TODO: Splits in User and Permission Repository
public class PermissionRepository : IPermissionRepository
{
private PermissionsContext _context;
private IDistributedCache _cache;
public PermissionRepository(PermissionsContext context, IDistributedCache cache)
{
_context = context;
_cache = cache;
}
CacheViewModel GetUserPermissionsAndCode(string uniqueName, string code)
{
var userPermissions = (from u in _context.Users
join up in _context.UsersPermissions on u.UniqueName equals up.UniqueName
join r in _context.Resources on up.ResourceID equals r.ResourceID
join m in _context.Modules on r.ModuleID equals m.ModuleID
where up.UniqueName == uniqueName && r.ResourceSequence > 0
orderby r.CategorySequence, r.ResourceSequence
select new PermissionsToBeCachedViewModel
{
Endpoint = m.Endpoint,
Module = m.ModuleName,
Resource = r.ResourceName,
Category = r.Category,
DisplayName = r.DisplayName
}).ToList();
return new CacheViewModel(code, userPermissions);
}
public bool SetUserPermissionsAndCode(string uniqueName, string code)
{
var userPermissions = (from u in _context.Users
join up in _context.UsersPermissions on u.UniqueName equals up.UniqueName
join r in _context.Resources on up.ResourceID equals r.ResourceID
join m in _context.Modules on r.ModuleID equals m.ModuleID
where up.UniqueName == uniqueName && r.ResourceSequence > 0
orderby r.CategorySequence, r.ResourceSequence
select new PermissionsToBeCachedViewModel
{
Endpoint = m.Endpoint,
Module = m.ModuleName,
Resource = r.ResourceName,
Category = r.Category,
DisplayName = r.DisplayName
}).ToList();
var propertiesToCache = new CacheViewModel(code, userPermissions);
//_cache.Set(uniqueName, Util.GetBytes(propertiesToCache.ToString()));
return true;
}
//Updates permissions on database and cache
public bool UpdateUserPermissions(string uniqueName, PermissionsViewModel newUserPermissions)
{
//Delete old permissions from the database:
var oldPermissions = _context.UsersPermissions.Where(up => up.UniqueName == uniqueName);
_context.UsersPermissions.RemoveRange(oldPermissions);
//_context.SaveChanges();
//Update the database
//Permissions:
foreach (var permissionToQuery in newUserPermissions.permissions)
{
var resourceReturned = _context.Resources.First(r => r.Category == permissionToQuery.category && r.DisplayName == permissionToQuery.resource);
_context.UsersPermissions.Add(new UsersPermission()
{
UniqueName = uniqueName,
ResourceID = resourceReturned.ResourceID
});
}
//User:
var user = _context.Users.First(u => u.UniqueName == uniqueName);
if (newUserPermissions.permissions.Count > 0)
{
user.Status = PermissionStatus.Permissions_Granted;
}
else
{
user.Status = PermissionStatus.Permissions_Denied;
}
_context.SaveChanges();
//Update the cache
CacheViewModel propertiesToCache = new CacheViewModel();
byte[] arrPropertiesSerializedCached = null;
try
{
// may raise exception
//arrPropertiesSerializedCached = _cache.Get(uniqueName);
// if data is not cached
if (arrPropertiesSerializedCached != null)
{
string propertiesSerializedCached = Util.GetString(arrPropertiesSerializedCached);
propertiesToCache = new CacheViewModel(propertiesSerializedCached);
}
}
catch (StackExchange.Redis.RedisConnectionException)
{
// Ignore transient network errors
}
var userPermissions = (from up in _context.UsersPermissions
join r in _context.Resources on up.ResourceID equals r.ResourceID
join m in _context.Modules on r.ModuleID equals m.ModuleID
where up.UniqueName == uniqueName && r.ResourceSequence > 0
orderby r.CategorySequence, r.ResourceSequence
select new PermissionsToBeCachedViewModel
{
Endpoint = m.Endpoint,
Module = m.ModuleName,
Resource = r.ResourceName,
Category = r.Category,
DisplayName = r.DisplayName
}).ToList();
if (userPermissions != null)
{
propertiesToCache.Permissions = userPermissions;
//_cache.Set(uniqueName, Util.GetBytes(propertiesToCache.ToString()));
return true;
}
else
{
return false;
}
}
//Updates user photo
public bool UpdateUserPhoto(string uniqueName, string photo)
{
var user = _context.Users.First(u => u.UniqueName == uniqueName);
if (user != null && photo != null)
{
//Save on database:
user.PhotoBase64 = photo;
_context.SaveChanges();
//Cache it:
CacheUserPhoto(uniqueName, photo);
return true;
}
else
{
return false;
}
}
//Cache User Photo:
public void CacheUserPhoto(string uniqueName, string PhotoBase64)
{
var key = "photo_" + uniqueName;
//_cache.Set(key, Util.GetBytes(PhotoBase64.ToString()));
}
//Updates user info
public bool UpdateUser(string uniqueName, UserMainViewModel userToBeUpdated)
{
var user = _context.Users.First(u => u.UniqueName == uniqueName);
if (user != null)
{
user.Name = userToBeUpdated.Name;
user.GivenName = userToBeUpdated.GivenName;
user.Surname = userToBeUpdated.Surname;
user.JobTitle = userToBeUpdated.JobTitle;
user.ManagerUniqueName = userToBeUpdated.ManagerUniqueName;
_context.SaveChanges();
return true;
}
else
{
return false;
}
}
public void DeleteUserPermissions(string uniqueName)
{
//_cache.Remove(uniqueName);
}
public void DeleteUser(string uniqueName)
{
//From Cache:
//_cache.Remove(uniqueName);
//From Context:
var userPermissions = (from up in _context.UsersPermissions
where up.UniqueName == uniqueName
select up).ToList();
var user = (from u in _context.Users
where u.UniqueName == uniqueName
select u).First();
_context.UsersPermissions.RemoveRange(userPermissions);
_context.Users.Remove(user);
_context.SaveChanges();
//From Kanban:
var res = Util.ConnectToRemoteService(HttpMethod.Delete, Util.KanbanURL + "api/user/delete?userID=" + uniqueName, "kanban", "kanban").Result;
if (!res.IsSuccessStatusCode)
{
throw new Exception();
}
}
CacheViewModel GetUserPermissionsCached(string uniqueName)
{
CacheViewModel cachedView = null;
byte[] arraySerializedCached = null;
if (uniqueName == null)
throw new ArgumentNullException("GetUserPermissionsCached(uniqueName: null)");
//try
//{
// arraySerializedCached = _cache.Get(uniqueName);
//}
//catch(StackExchange.Redis.RedisConnectionException)
//{
// // Ignore transient network issues
//}
if (arraySerializedCached != null)
{
var propertiesSerializedCached = Util.GetString(arraySerializedCached);
cachedView = new CacheViewModel(propertiesSerializedCached);
}
return cachedView;
}
public bool VerifyUserAccessToResource(string uniqueName, string module, string resource)
{
// THIS IMPLEMENTATION IS WRONG!
// If the cache is clean, then it will not properly verify the user access
//try
//{
// var propertiesSerializedCached = Util.GetString(_cache.Get(uniqueName));
// if (propertiesSerializedCached != null)
// {
// var permissions = new CacheViewModel(propertiesSerializedCached).Permissions;
// var perm = (from p in permissions
// where p.Resource.ToLower().Equals(resource) && p.Module.ToLower().Equals(module)
// select p).First();
// return (perm != null);
// }
// else
// {
// return false;
// }
//}
//catch (Exception ex)
//{
// if (ex.Message == "Sequence contains no elements")
// {
// return false;
// }
// else
// {
// throw;
// }
//}
var cachedView = GetUserPermissionsCached(uniqueName);
if (cachedView != null)
{
var permissions = cachedView.Permissions;
var perm = (from p in permissions
where p.Resource.ToLower().Equals(resource) && p.Module.ToLower().Equals(module)
select p).First();
return (perm != null);
}
return false;
}
public bool VerifyIfUserIsInUserPermissionsDatabase(string uniqueName)
{
var response = _context.Users.SingleOrDefault(u => u.UniqueName == uniqueName);
if (response == null)
{
return false;
}
else
{
return true;
}
}
public bool SendNotificationOfNewUserByEmail(string uniqueName)
{
return true;
//EmailLogic clientEmail = new EmailLogic();
//// Mounting parameters and message.
//var Configuration = new ConfigurationBuilder().AddJsonFile("secrets.json").Build();
//var admin = Configuration["Email:Administrator"];
//string ToName = "Arda Administrator";
//string ToEmail = admin;
//string Subject = "[ARDA] A new user has been logged @ Arda";
//StringBuilder StructureModified = new StringBuilder();
//StructureModified = EmailMessages.GetEmailMessageStructure();
//// Replacing the generic title by the customized.
//StructureModified.Replace("[MessageTitle]", "Hi " + ToName + ", someone requested access to the system");
//// Replacing the generic subtitle by the customized.
//StructureModified.Replace("[MessageSubtitle]", "Who did the request was <strong>" + uniqueName + "</strong>. If you deserve, can access 'Users' area and distribute the appropriated permissions.");
//// Replacing the generic message body by the customized.
//StructureModified.Replace("[MessageBody]", "Details about the request: </br></br><ul><li>Email: " + uniqueName + "</li><li>Date/time access: " + DateTime.Now + "</li></ul>");
//// Replacing the generic callout box.
//StructureModified.Replace("[MessageCallout]", "For more details about the request, send a message to <strong>arda@microsoft.com</strong>.");
//// Creating a object that will send the message.
//EmailLogic EmailObject = new EmailLogic();
//try
//{
// var EmailTask = EmailObject.SendEmailAsync(ToName, ToEmail, Subject, StructureModified.ToString());
// return true;
//}
//catch (Exception)
//{
// return false;
//}
}
// Generate initial and basic permissions set to new users.
public User CreateNewUserAndSetInitialPermissions(string uniqueName, string name)
{
var user = new User()
{
UniqueName = uniqueName,
Name = name,
Status = PermissionStatus.Waiting_Review,
UserPermissions = new List<UsersPermission>()
};
//Save on Permissions
_context.Users.Add(user);
_context.SaveChanges();
return user;
}
public string GetUserMenuSerialized(string uniqueName)
{
var menu = new List<Tuple<string, Tuple<string, string, string>>>();
string propertiesSerializedCached = null;
byte[] arraySerializedCached = null;
//try
//{
// arraySerializedCached = _cache.Get(uniqueName);
//}
//catch (StackExchange.Redis.RedisConnectionException)
//{
// // Ignore transient network failures
//}
if (arraySerializedCached != null)
{
propertiesSerializedCached = Util.GetString(arraySerializedCached);
}
else
{
var cachedView = GetUserPermissionsAndCode(uniqueName, string.Empty);
propertiesSerializedCached = cachedView.ToString();
}
//try
//{
// _cache.Set(uniqueName, Util.GetBytes(propertiesSerializedCached));
//}
//catch (StackExchange.Redis.RedisConnectionException)
//{
// // Ignore transient network failures
//}
//try
//{
// propertiesSerializedCached = Util.GetString(_cache.Get(uniqueName));
//}
//catch (Exception)
//{
// SetUserPermissionsAndCode(uniqueName, string.Empty);
// propertiesSerializedCached = Util.GetString(_cache.Get(uniqueName));
//}
var permissions = new CacheViewModel(propertiesSerializedCached).Permissions;
foreach (var p in permissions)
{
if (!p.Endpoint.Contains("/api"))
{
string category = p.Category;
string display = p.DisplayName;
string controller = p.Module;
string action = p.Resource;
//string url = p.Endpoint + "/" + p.Module + "/" + p.Resource;
menu.Add(Tuple.Create(category, Tuple.Create(display, controller, action)));
}
}
var menuGrouped = (from m in menu
group m.Item2 by m.Item1 into g
select new
{
Category = g.Key,
Items = g.ToList()
}).ToList();
return JsonConvert.SerializeObject(menuGrouped);
}
public PermissionStatus GetUserStatus(string uniqueName)
{
return _context.Users.First(u => u.UniqueName == uniqueName).Status;
}
public bool VerifyIfUserAdmin(string uniqueName)
{
return true;
//var cache = _cache.Get(uniqueName);
//if(cache == null)
// return false;
//var propertiesSerializedCached = Util.GetString(cache);
//var permissions = new CacheViewModel(propertiesSerializedCached).Permissions;
//var permToReview = permissions.FirstOrDefault(p => p.Module == "Users" && p.Resource == "Review");
//if (permToReview != null)
//{
// return true;
//}
//else
//{
// return false;
//}
}
public int GetNumberOfUsersToApprove()
{
return _context.Users.Where(u => u.Status == PermissionStatus.Waiting_Review).Count();
}
public IEnumerable<UserMainViewModel> GetPendingUsers()
{
var data = from users in _context.Users
where users.Status == PermissionStatus.Waiting_Review
select new UserMainViewModel
{
Name = users.Name,
Email = users.UniqueName,
Status = (int)users.Status
};
return data.ToArray();
}
public IEnumerable<ResourcesViewModel> GetAllPermissions()
{
var data = (from r in _context.Resources
orderby r.CategorySequence, r.ResourceSequence
group r.DisplayName by r.Category into g
select new ResourcesViewModel
{
Category = g.Key,
Resources = g.ToList()
}).ToList();
return data;
}
public PermissionsViewModel GetUserPermissions(string uniqueName)
{
var data = (from up in _context.UsersPermissions
join r in _context.Resources on up.ResourceID equals r.ResourceID
where up.UniqueName == uniqueName
orderby r.CategorySequence, r.ResourceSequence
select new Permission
{
category = r.Category,
resource = r.DisplayName
}).ToList();
var permissions = new PermissionsViewModel()
{
permissions = data
};
return permissions;
}
public IEnumerable<UserMainViewModel> GetUsers()
{
var data = from users in _context.Users
select new UserMainViewModel
{
Name = users.Name,
Email = users.UniqueName,
Status = (int)users.Status
};
return data.ToArray();
}
public UserMainViewModel GetUser(string uniqueName)
{
var data = (from user in _context.Users
where user.UniqueName == uniqueName
select new UserMainViewModel
{
Name = user.Name,
Email = user.UniqueName,
Status = (int)user.Status
}).First();
return data;
}
public string GetUserPhotoFromCache(string uniqueName)
{
var user = _context.Users.First(u => u.UniqueName == uniqueName);
if (user != null)
{
var photo = user.PhotoBase64;
var arrr = Util.GetBytes(photo.ToString());
return Util.GetString(arrr);
}
return null;
}
public bool SaveUserPhotoOnCache(string uniqueName)
{
var user = _context.Users.First(u => u.UniqueName == uniqueName);
return true;
//if (user != null)
//{
// //Get photo from database:
// var photo = user.PhotoBase64;
// //Cache it:
// CacheUserPhoto(uniqueName, photo);
// return true;
//}
//else
//{
// return false;
//}
}
}
}