AuthenticateController.cs
25.8 KB
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
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using log4net;
using AIAHTML5.API.Constants;
using AIAHTML5.API.Models;
using System.Collections;
using System.Data.SqlClient;
using System.IO;
using System.Web.Hosting;
using System.Configuration;
namespace AIAHTML5.API.Controllers
{
public class AuthenticateController : ApiController
{
// GET api/authenticate
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/authenticate/5
public string Get(int id)
{
return "value";
}
// POST api/authenticate
public HttpResponseMessage Post([FromBody]JObject credentials)
{
ILog logger = log4net.LogManager.GetLogger((System.Reflection.MethodBase.GetCurrentMethod().DeclaringType));
logger.Debug("inside POST");
dynamic authenticationRepsonse;
DateTime blockTime;
bool isUserBlocked;
try
{
//01.get the user detail to autheticate the user
User userInfo = AIAHTML5.API.Models.Users.getUserDetails(credentials);
if (userInfo != null)
{
// 02 Check user is authenticated or not by login credential match
bool isUserAuthenticated = AIAHTML5.API.Models.Users.checkUserAuthenticity(credentials, userInfo);
if (isUserAuthenticated)
{
if (userInfo.IsActive)
{
//03. check if user is blocked
isUserBlocked = AIAHTML5.API.Models.Users.checkUserBlockStatus(userInfo.Id, out blockTime);
if (!isUserBlocked)
{
//04.delete past wrong login attempts of user
int wrongAttemptDeteledCount = AIAHTML5.API.Models.Users.deletePastWrongAttempts(userInfo.Id);
if (wrongAttemptDeteledCount < 0)
{
logger.Fatal("Unable to delete past wrong login attempts for userId= " + userInfo.Id);
}
//05.
GetModulesBasedOnUserType(userInfo);
// authenticationRepsonse = JsonConvert.SerializeObject(userInfo);
}
else
{
//compare block time of user with current time if user is blocked
DateTime blockDuration = blockTime.AddDays(1);
var difference = DateTime.Compare(DateTime.Now, blockDuration);
//check if credentials are valid credentials
//bool isCorrectLoginId, isCorrectPassword;
//AIAHTML5.API.Models.Users.isCredentialCorrect(credentials, userInfo, out isCorrectLoginId, out isCorrectPassword);
if (difference >= 0)
{
//means 24 hours block time is finished
userInfo.IsBlocked = false;
int wrongAttemptDeteledCount = AIAHTML5.API.Models.Users.deletePastWrongAttempts(userInfo.Id);
if (wrongAttemptDeteledCount < 0)
{
logger.Fatal("Unable to delete past wrong login attempts for userId= " + userInfo.Id);
}
//05. Now get the module list- for ADMIN (superadmin/ general admin) by default all module loads
GetModulesBasedOnUserType(userInfo);
}
else
{
userInfo.LoginFailureCauseId = ErrorHelper.E_USER_ID_BLOCKED_24_HRS;
}
}
}
else
{
//CODE REVIW: validate that is this tarnslated by UI because we need to show message to user if he is inactive
userInfo.LoginFailureCauseId = ErrorHelper.E_USER_NOT_ACTIVE;
//05.4 check the License expiration irespective of either user is active
//or not because on AIA, we shows the License expiration message
//for inactive users too
CheckLicenseStatus(userInfo);
}
}
else
{
//this come in picture when user input wrong passowrd
//get wrong attempt count of user
int previousIncorrectLoginAttempts = AIAHTML5.API.Models.Users.checkNoOfWrongAttempts(userInfo.Id);
userInfo.IncorrectLoginAttemptCount = previousIncorrectLoginAttempts + 1;
userInfo.LoginFailureCauseId = ErrorHelper.E_PASSWORD_NOT_MATCH;
//01. insert wrong attempt in dtabase
int updateCount = AIAHTML5.API.Models.Users.saveWrongAttemptOfUser(userInfo.Id, previousIncorrectLoginAttempts);
if (updateCount < 0)
{
//Put the log in log file
logger.Fatal("Unable to Update past wrong login attempts for userId= " + userInfo.Id);
}
//else
//{
if (userInfo.IncorrectLoginAttemptCount > 4)
{
userInfo.IsBlocked = true;
userInfo.LoginFailureCauseId = ErrorHelper.E_USER_ID_BLOCKED_24_HRS;
}
}
authenticationRepsonse = JsonConvert.SerializeObject(userInfo);
}
else
{
authenticationRepsonse = AIAConstants.USER_NOT_FOUND;
}
return new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StringContent(authenticationRepsonse) };
}
catch (SqlException e)
{
logger.Fatal("SqlException occured for loginId =" + credentials["username"].ToString() + " and password= " + credentials["password"].ToString() + "Exception= " + e.Message + ", STACKTRACE: " + e.StackTrace);
ArrayList supportMailList = UserUtility.GetSupportMailList();
string mailSubject = AIAConstants.SQL_CONNECTION_ERROR_MAIL_SUBJECT;
string mailBody = "MESSAGE: " + e.Message + ", STACKTRACE: " + e.StackTrace;
UserUtility.SendEmail(credentials, supportMailList, "", mailSubject, mailBody);
return new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent(AIAConstants.SQL_CONNECTION_ERROR) };
}
catch (Exception e)
{
logger.Fatal("Exception occured for loginId =" + credentials["username"].ToString() + " and password= " + credentials["password"].ToString() + "Exception= " + e.Message + ", STACKTRACE: " + e.StackTrace);
ArrayList supportMailList = UserUtility.GetSupportMailList();
string mailSubject = AIAConstants.EXCEPTION_IN_AIAHTML5_MAIL_SUBJECT;
string mailBody = "MESSAGE: " + e.Message + ", STACKTRACE: " + e.StackTrace;
UserUtility.SendEmail(credentials, supportMailList, "", mailSubject, mailBody);
return new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent(AIAConstants.EXCEPTION_OCCURED) };
}
}
[HttpPost]
[Route("api/ExportImage")]
public HttpResponseMessage InserExportImageDetail([FromBody]JObject jsonData)
{
int Status = 0;
dynamic responseData;
LicenseUserInsertImageDetail inserExportImageDetail = new LicenseUserInsertImageDetail();
try
{
inserExportImageDetail.LicenseId = jsonData["LicenseId"].Value<int>();
inserExportImageDetail.UserId = jsonData["UserId"].Value<int>();
inserExportImageDetail.ImageName = jsonData["ImageName"].Value<string>();
inserExportImageDetail.OriginalFileName = jsonData["OriginalFileName"].Value<string>();
inserExportImageDetail.Title = jsonData["Title"].Value<string>();
inserExportImageDetail.ModuleName = jsonData["ModuleName"].Value<string>();
Status = InsertExportImageDetail(inserExportImageDetail );
if (Status==-1)
{
if(inserExportImageDetail.LicenseId>0)
{
// for user
var getexportedImagedetail = GetLicenseExportImageDetail(inserExportImageDetail.LicenseId);
responseData = JsonConvert.SerializeObject(getexportedImagedetail);
}
else
{
// for admin
responseData = "ADMIN";
}
return new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StringContent(responseData) };
}
else
{
responseData = AIAConstants.EXPORTED_IMAGE_INSERT_FAILED;
return new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, Content = new StringContent(responseData) };
}
}
catch (Exception ex)
{
// Log exception code goes here
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message);
}
}
private static void GetModulesBasedOnUserType(User userInfo)
{
//based on old .net code(AIA flex), we get modules based on licenseId if licenseid>0.
//we verified in database that only superadmin has no licenseid so getting all modules for supeadmin
int licenseId, editionId, LicenseEditionId;
AIAHTML5.API.Models.Users.getLicenseIdForThisUser(userInfo.Id, out licenseId, out editionId,out LicenseEditionId);
userInfo.LicenseId = licenseId;
userInfo.EditionId = editionId;
userInfo.LicenseEditionId = LicenseEditionId;
userInfo.isSiteUser = false;
//if (userInfo.UserType == AIAHTML5.API.Models.User.SUPER_ADMIN)
if (userInfo.LicenseId == 0)
{
userInfo.Modules = AIAHTML5.API.Models.Users.getAllModulesList();
//Insert user login detail
AIAHTML5.API.Models.Users.insertLoginDetails(userInfo.Id);
}
else
{
CheckLicenseStatus(userInfo);
if (!userInfo.IsSubscriptionExpired)
{
GetModulesBasedOnLicense(userInfo, false);
}
// get exported image detail
userInfo.UserExportImageDetail = GetLicenseExportImageDetail(userInfo.LicenseId);
}
//get use settings
string skintone;
string modesty;
User us = AIAHTML5.API.Models.Users.GetUserSelectedSettings(userInfo.Id, false, out skintone, out modesty);
if (us != null)
{
userInfo.userselectedModesty = modesty;
userInfo.userSelectedSkintone = skintone;
userInfo.userLexicon = us.userLexicon;
}
else
{
userInfo.userselectedModesty = null;
userInfo.userSelectedSkintone = null;
userInfo.userLexicon = null;
}
}
private static void CheckLicenseStatus(User userInfo)
{
//05.1 For normal user need to get the license details, get the license id for authenticated user
//int licenseId, editionId;
//AIAHTML5.API.Models.Users.getLicenseIdForThisUser(userInfo.Id, out licenseId, out editionId);
//userInfo.LicenseId = licenseId;
//userInfo.EditionId = editionId;
//05.2 get license details
userInfo.LicenseInfo = AIAHTML5.API.Models.Users.getLicenseDetails(userInfo.LicenseId);
if (userInfo.LicenseInfo != null)
{
//05.3 get licenseSubscription details
userInfo.LicenseSubscriptions = AIAHTML5.API.Models.Users.getLicenseSubscriptionDetails(userInfo.LicenseId);
//05.4 check the License expiration irespective of either user is active or not because on AIA
//we shows the License expiration message for inactive users too
string expirationDate = null;
bool isLicenseExpired = false;
// validate license start date
string startDate = null;
bool isSubscriptionNotStart = false;
if (userInfo.LicenseSubscriptions != null)
{
isSubscriptionNotStart = AIAHTML5.API.Models.Users.checkIfLicenseNotStarted(userInfo.LicenseSubscriptions, out startDate);
isLicenseExpired = AIAHTML5.API.Models.Users.checkIfLicenseExpired(userInfo.LicenseSubscriptions, out expirationDate);
}
if (isLicenseExpired)
{
userInfo.IsSubscriptionExpired = isLicenseExpired;
userInfo.SubscriptionExpirationDate = expirationDate;
}
else if (isSubscriptionNotStart)
{
userInfo.IsSubscriptionNotStart = isSubscriptionNotStart;
userInfo.SubscriptionStartDate = startDate;
}
else
{
//check Modesty settings for this license
userInfo.IsModestyOn = AIAHTML5.API.Models.Users.IsModestyActiveForThisLicense(userInfo.LicenseId, Convert.ToInt16(userInfo.EditionId));
}
}
else
{
ILog logger = log4net.LogManager.GetLogger((System.Reflection.MethodBase.GetCurrentMethod().DeclaringType));
logger.Debug("userInfo.LicenseInfo is null for userInfo.LicenseId= " + userInfo.LicenseId);
}
}
private static void GetModulesBasedOnLicense(User userInfo, bool isLicenseExpired)
{
//05.6.1
if (userInfo.LicenseInfo.IsActive)
{
if (!userInfo.LicenseInfo.IsTermAccepted)
{
ArrayList termsList = AIAHTML5.API.Models.Users.getTermsAndConditions();
foreach (Hashtable item in termsList)
{
userInfo.TermsAndConditionsTitle = item[AIAConstants.KEY_TITLE].ToString();
userInfo.TermsAndConditionsText = item[AIAConstants.KEY_CONTENT].ToString();
}
}
else
{
userInfo.Modules = AIAHTML5.API.Models.Users.getModuleListByLicenseId(userInfo.LicenseId);
//Insert user login detail
AIAHTML5.API.Models.Users.insertLoginDetails(userInfo.Id);
}
}
else
{
userInfo.LoginFailureCauseId = ErrorHelper.E_LICENCE_IS_INACTIVE;
}
}
private static LicenseUserExportedImageDetail GetLicenseExportImageDetail(int licenseId)
{
LicenseUserExportedImageDetail exportedImageDetail = null;
exportedImageDetail = AIAHTML5.API.Models.Users.getExportedImageDetail(licenseId);
return exportedImageDetail;
}
private static int InsertExportImageDetail(LicenseUserInsertImageDetail imageDetail)
{
int insertImageResult = 0;
insertImageResult = AIAHTML5.API.Models.Users.InsertExportedImageDetail(imageDetail);
return insertImageResult;
}
private static int SaveAnimationFile(JArray JsonvidData)
{
int result = 0;
string Path = ConfigurationManager.AppSettings["ANIMATION_HOSTING_SERVER"];
foreach (JObject item in JsonvidData)
{
// string folderName = item.GetValue("folderNo").ToString();
string fileName = item.GetValue("FileName").ToString();
// DirectoryInfo di = Directory.CreateDirectory(Path);
string filePath = HostingEnvironment.MapPath(Path + fileName + ".mp4");
if (!File.Exists(filePath))
{
string data = item.GetValue("Data").ToString();
//Convert Base64 Encoded string to Byte Array.
byte[] imageBytes = Convert.FromBase64String(data);
//Save the Byte Array as Image File.
// string Path = HostingEnvironment.MapPath("~/../content/data/AnimationMp4/"+ folderName);
File.WriteAllBytes(filePath, imageBytes);
}
}
result = 1;
return result;
}
[HttpPost]
[Route("api/SaveUserSettings")]
public HttpResponseMessage SaveUserSettings([FromBody]JObject jsonData)
{
int Status = 0;
dynamic responseData;
User settings = new User();
UserLexicon userLexicon = new UserLexicon();
try
{
settings.userselectedModesty =jsonData["modesty"].Value<string>();
settings.userSelectedSkintone = jsonData["skintone"].Value<string>();
settings.userSelectedFont = null;
settings.Id= jsonData["userId"].Value<int>();
settings.LicenseEditionId = jsonData["LicenseEditionId"].Value<int>();
settings.isSiteUser = jsonData["isSiteUser"].Value<bool>();
userLexicon.primaryid= jsonData["primaryid"].Value<string>();
userLexicon.secondryids = jsonData["secondryids"].Value<string>();
settings.userLexicon= userLexicon;
Status = AIAHTML5.API.Models.Users.SaveUserSelectedSettings(settings);
if (Status == 1)
{
responseData = "1";
}
else
{
responseData = AIAConstants.SETTINGS_SAVE_FAILURE;
}
return new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StringContent(responseData) };
}
catch (Exception ex)
{
// Log exception code goes here
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message);
}
}
[HttpPost]
[Route("api/saveAnimationVideo")]
public HttpResponseMessage saveAnimationVideo([FromBody]JArray JsonvidData)
{
int Status = 0;
try
{
Status= SaveAnimationFile(JsonvidData);
if (Status == 1)
{
return new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StringContent("Save Sccuessful") };
}
else
{
return new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, Content = new StringContent("file not saved") };
}
}
catch (Exception ex)
{
// Log exception code goes here
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message);
}
}
[HttpPost]
[Route("api/ByPassLoginToOpenModule")]
public HttpResponseMessage ByPassLoginToOpenModule([FromBody]JObject sitedetail)
{
dynamic responseData;
BypassLogin objUser = null;
try
{
string loginId = sitedetail.GetValue("userId").ToString();
string accountNumber = sitedetail.GetValue("accountNumber").ToString();
objUser = AIAHTML5.API.Models.Users.ByPassLoginDetail(loginId, accountNumber);
responseData = JsonConvert.SerializeObject(objUser);
if (objUser != null)
{
return new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StringContent(responseData) };
}
else
{
return new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, Content = new StringContent(AIAConstants.USER_NOT_FOUND) };
}
}
catch (Exception ex)
{
// Log exception code goes here
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message);
}
}
[HttpPost]
[Route("api/ManageUserLoginStatus")]
public HttpResponseMessage ManageUserLoginStatus([FromBody]JObject jsonData)
{
string loginStatus = string.Empty;
try
{
int userId = jsonData["userId"].Value<int>();
string tagName = jsonData["tagName"].Value<string>();
long SessionId = jsonData["SessionId"].Value<long>();
bool isSiteUser = jsonData["isSiteUser"].Value<bool>();
bool isAdmin = jsonData["isAdmin"].Value<bool>();
loginStatus = AIAHTML5.API.Models.Users.GetUserLoginStatus(userId, tagName, SessionId, isSiteUser, isAdmin);
return new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StringContent(loginStatus) };
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message);
}
}
[HttpPost]
[Route("api/AodAuthentication")]
public HttpResponseMessage AodAuthentication([FromBody]JObject jsonData)
{
ILog logger = log4net.LogManager.GetLogger((System.Reflection.MethodBase.GetCurrentMethod().DeclaringType));
int requestStatus = 0;
try
{
string aodpasskey = jsonData["aiapasskey"].Value<string>();
long SessionId = jsonData["SessionId"].Value<long>();
string CourseId = jsonData["CourseId"].Value<string>();
logger.Debug("AOD request parameter: Session =" + SessionId +", aodkeypass="+ aodpasskey + ", CourseId=" + CourseId);
string aiaConfigKey= ConfigurationManager.AppSettings["aiapasskey"];
requestStatus = AIAHTML5.API.Models.Users.ValidateAodAthenticationStatus(SessionId, aiaConfigKey, aodpasskey, CourseId);
switch(requestStatus)
{
case 200:
{
return new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StringContent("authentication successful") };
}
case 401:
{
return new HttpResponseMessage { StatusCode = HttpStatusCode.Unauthorized, Content = new StringContent("passing key to api is not valid") };
}
case 404:
{
return new HttpResponseMessage { StatusCode = HttpStatusCode.NotFound, Content = new StringContent("session has expired or does not exist") };
}
default:
{
return new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent("server encountered an unexpected error.") };
}
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message);
}
}
[HttpGet]
[Route("api/GetAodCoursesList")]
public HttpResponseMessage GetAodCoursesList([FromUri] int LicenseId)
{
try
{
DBModel db = new DBModel();
List<AodCourse> courselist = db.GetSelectedCourseList(LicenseId);
if (courselist.Count>0)
return new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StringContent(JsonConvert.SerializeObject(courselist)) };
else
return new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StringContent(AIAConstants.NO_COURSE_FOUND) };
}
catch (Exception e)
{
return new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent(AIAConstants.ERROR_IN_FECTHING_DETAILS) };
}
}
// PUT api/authenticate/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/authenticate/5
public void Delete(int id)
{
}
}
}