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; namespace AIAHTML5.API.Controllers { public class AuthenticateController : ApiController { // GET api/authenticate public IEnumerable 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(); inserExportImageDetail.UserId = jsonData["UserId"].Value(); inserExportImageDetail.ImageName = jsonData["ImageName"].Value(); inserExportImageDetail.OriginalFileName = jsonData["OriginalFileName"].Value(); inserExportImageDetail.Title = jsonData["Title"].Value(); inserExportImageDetail.ModuleName = jsonData["ModuleName"].Value(); 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; AIAHTML5.API.Models.Users.getLicenseIdForThisUser(userInfo.Id, out licenseId, out editionId); userInfo.LicenseId = licenseId; userInfo.EditionId = editionId; //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); } } 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; if (userInfo.LicenseSubscriptions != null) { isLicenseExpired = AIAHTML5.API.Models.Users.checkIfLicenseExpired(userInfo.LicenseSubscriptions, out expirationDate); } if (isLicenseExpired) { userInfo.IsSubscriptionExpired = isLicenseExpired; userInfo.SubscriptionExpirationDate = expirationDate; } 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; } // PUT api/authenticate/5 public void Put(int id, [FromBody]string value) { } // DELETE api/authenticate/5 public void Delete(int id) { } } }