internal ValidateUserResponse ValidatUser(ValidateUserRequest validateUserRequest) { logger.Debug("Recived validate user request"); ValidateUserResponse ValidateUserResponse; try { validateUserRequest.email = Decryptor.Decrypt(validateUserRequest.email).Split('|')[1]; validateUserRequest.username = Decryptor.Decrypt(validateUserRequest.username).Split('|')[1]; int usersWithEmail, UsersWithUserName = 0; using (var ctx = new PetWhizzEntities()) { usersWithEmail = ctx.users.Where(a => a.eMail.ToLower().Equals(validateUserRequest.email.ToLower())).Count(); UsersWithUserName = ctx.users.Where(a => a.userName.ToLower().Equals(validateUserRequest.username.ToLower())).Count(); } if (usersWithEmail > 0 || UsersWithUserName > 0) { logger.Error("Email or Username Already Exist userName - " + validateUserRequest.username + " email - " + validateUserRequest.email); throw new CustomException("Email or Username Already Exist", (int)ErrorCode.EMAILORUSERNAMEALREADYEXIST); } ValidateUserResponse = new ValidateUserResponse() { messege = "Success" }; } catch (CustomException) { throw; } catch (Exception ex) { logger.Error(MethodBase.GetCurrentMethod().Name + ": exception: " + ex.Message + ", " + ex.InnerException); throw new CustomException("SystemError", ex, (int)ErrorCode.PROCEESINGERROR); throw; } return(ValidateUserResponse); }
internal void LogoutUser() { logger.Debug("Recived log out request"); try { CurrentUser currentUser = (CurrentUser)HttpContext.Current.User; if (String.IsNullOrEmpty(currentUser.token)) { logger.Error("token is empty for user"); throw new CustomException("token is empty for user", (int)ErrorCode.UNAUTHORIZED); } using (var ctx = new PetWhizzEntities()) { userToken currentToken = ctx.userTokens.Where(a => a.token.Equals(currentUser.token)).FirstOrDefault(); if (currentToken == null) { logger.Error("token is not found on DB"); throw new CustomException("token is not found on DB", (int)ErrorCode.UNAUTHORIZED); } ctx.userTokens.Attach(currentToken); currentToken.expiryTime = null; ctx.SaveChanges(); logger.Debug("successfully logout user - " + currentUser.username); } } catch (CustomException) { throw; } catch (Exception ex) { logger.Error(MethodBase.GetCurrentMethod().Name + ": exception: " + ex.Message + ", " + ex.InnerException); throw new CustomException("SystemError", ex, (int)ErrorCode.PROCEESINGERROR); throw; } }
private void UpdateLogMessage(string correlationId, string requestInfo, byte[] message) { try { using (var ctx = new PetWhizzEntities()) { ioLogger ioLogger = new ioLogger() { json = Encoding.UTF8.GetString(message), triggeredTime = DateTime.Now, type = "Request", url = requestInfo, userName = "" }; ctx.ioLoggers.Add(ioLogger); ctx.SaveChanges(); } } catch (DbEntityValidationException e) { foreach (var eve in e.EntityValidationErrors) { Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); } } // throw; } catch (Exception e) { } }
internal void DeleteUser(string userName) { try { userName = Decryptor.Decrypt(userName).Split('|')[1]; using (var ctx = new PetWhizzEntities()) { user User = ctx.users.Where(a => a.userName == userName).FirstOrDefault(); List <userDevice> UserDevices = ctx.userDevices.Where(a => a.userId == User.id).ToList(); foreach (userDevice device in UserDevices) { ctx.userTokens.RemoveRange(device.userTokens); } ctx.userDevices.RemoveRange(UserDevices); ctx.userVerifications.RemoveRange(User.userVerifications); ctx.users.Remove(User); ctx.SaveChanges(); } } catch (CustomException) { throw; } catch (Exception ex) { logger.Error(MethodBase.GetCurrentMethod().Name + ": exception: " + ex.Message + ", " + ex.InnerException); throw new CustomException("SystemError", ex, (int)ErrorCode.PROCEESINGERROR); } }
internal UserLoginResponse TokenLogin() { logger.Debug("Recived token login request"); UserLoginResponse UserLoginResponse; try { CurrentUser currentUser = (CurrentUser)HttpContext.Current.User; if (String.IsNullOrEmpty(currentUser.token)) { logger.Error("token is empty for user"); throw new CustomException("token is empty for user", (int)ErrorCode.UNAUTHORIZED); } user User = new user(); using (var ctx = new PetWhizzEntities()) { User = ctx.users.Where(a => a.id == currentUser.userId).FirstOrDefault(); if (User == null) { logger.Error("User record is not found for userId - " + currentUser.userId); throw new CustomException("User record is not found", (int)ErrorCode.UNAUTHORIZED); } var currentToken = ctx.userTokens.Where(a => a.token.Equals(currentUser.token)).FirstOrDefault(); if (currentToken != null && currentToken.expiryTime >= DateTime.Now) { ctx.userTokens.Attach(currentToken); currentToken.expiryTime = DateTime.Now.AddSeconds(TokenExpiryTime); ctx.SaveChanges(); } else { logger.Error("token is invalid or expired"); throw new CustomException("token is invalid or expired", (int)ErrorCode.UNAUTHORIZED); } } UserLoginResponse = new UserLoginResponse() { email = Encryptor.Encrypt(DateTime.Now.ToString("M/d/yyyy h:mm:ss tt") + "|" + User.eMail), status = Encryptor.Encrypt(DateTime.Now.ToString("M/d/yyyy h:mm:ss tt") + "|" + User.status), token = Encryptor.Encrypt(DateTime.Now.ToString("M/d/yyyy h:mm:ss tt") + "|" + currentUser.token), username = Encryptor.Encrypt(DateTime.Now.ToString("M/d/yyyy h:mm:ss tt") + "|" + User.userName), userId = Encryptor.Encrypt(DateTime.Now.ToString("M/d/yyyy h:mm:ss tt") + "|" + User.id.ToString()) }; logger.Debug("Token login successfull for token - " + currentUser.token); } catch (CustomException) { throw; } catch (Exception ex) { logger.Error(MethodBase.GetCurrentMethod().Name + ": exception: " + ex.Message + ", " + ex.InnerException); throw new CustomException("SystemError", ex, (int)ErrorCode.PROCEESINGERROR); throw; } return(UserLoginResponse); }
internal void VerifyEmail(string token) { logger.Debug("Recived verify email request for token - " + token); try { int UserId = Convert.ToInt32(Decryptor.Decrypt(token).Split('|')[1]); int RandomCode = Convert.ToInt32(Decryptor.Decrypt(token).Split('|')[0]); logger.Debug("Recived verify email request for userId - " + UserId.ToString() + " and code - " + RandomCode.ToString()); userVerification _currentVerification; using (var ctx = new PetWhizzEntities()) { _currentVerification = ctx.userVerifications .Where(a => a.userId == UserId && a.code == RandomCode.ToString() && a.verificationType == "EMAILVERIFY" && a.expiryTime >= DateTime.Now && a.isValid == true).FirstOrDefault(); if (_currentVerification != null) { using (var dbContextTransaction = ctx.Database.BeginTransaction()) { try { ctx.userVerifications.Attach(_currentVerification); _currentVerification.isValid = false; ctx.users.Attach(_currentVerification.user); _currentVerification.user.status = "VERIFIED"; ctx.SaveChanges(); dbContextTransaction.Commit(); } catch (Exception) { dbContextTransaction.Rollback(); dbContextTransaction.Dispose(); logger.Error("verification details update failed for userId - " + UserId.ToString() + " and code - " + RandomCode.ToString()); throw new CustomException("verification details update failed", (int)ErrorCode.PROCEESINGERROR); } } } else { ctx.Dispose(); logger.Error("verification details not for userId - " + UserId.ToString() + " and code - " + RandomCode.ToString()); throw new CustomException("Verification details not found", (int)ErrorCode.PROCEESINGERROR); } } } catch (CustomException) { throw; } catch (Exception) { logger.Error("Error occured while user verification token - " + token); throw; } }
internal void ForgotPassword(ForgotPasswordRequest changePasswordRequest) { logger.Debug("Recived forgotPassword request for encrypted string - " + changePasswordRequest.email); try { changePasswordRequest.email = Decryptor.Decrypt(changePasswordRequest.email).Split('|')[1]; logger.Debug("Recived forgotPassword request for email = " + changePasswordRequest.email); if (!String.IsNullOrEmpty(changePasswordRequest.email)) { user User; using (var ctx = new PetWhizzEntities()) { User = ctx.users.Where(a => a.eMail.ToLower() == changePasswordRequest.email.ToLower()).FirstOrDefault(); } if (User == null) { logger.Error("User not found for given email - " + changePasswordRequest.email); throw new CustomException("User not found for given email", (int)ErrorCode.USERNOTFOUND); } int GeneratedCode = new Random().Next(100000, 999999); var userVerificationInfo = new userVerification() { code = GeneratedCode.ToString(), generatedTime = DateTime.Now, expiryTime = DateTime.Now.AddSeconds(VerificationCodeExpiryTime), isValid = true, userId = User.id, verificationType = "RESETPASSWORD", }; using (var ctx = new PetWhizzEntities()) { ctx.userVerifications.Add(userVerificationInfo); ctx.SaveChanges(); } SendResetPasswordEmail(User.eMail, User.id, User.userName, GeneratedCode); } else { logger.Error("ForgotPassword request email is empty"); throw new CustomException("Email is empty", (int)ErrorCode.VALIDATIONFAILED); } } catch (CustomException) { throw; } catch (Exception ex) { logger.Error(MethodBase.GetCurrentMethod().Name + ": exception: " + ex.Message + ", " + ex.InnerException); throw new CustomException("SystemError", ex, (int)ErrorCode.PROCEESINGERROR); } }
internal void UpdatePet(PetUpdateRequest PetUpdateRequest) { logger.Trace("Recived pet update request"); try { CurrentUser currentUser = (CurrentUser)HttpContext.Current.User; if (PetUpdateRequest == null || PetUpdateRequest.id <= 0 || String.IsNullOrEmpty(PetUpdateRequest.petName)) { logger.Error("Pet update Request body is empty or required fields not found"); throw new CustomException("Pet update request invalid", (int)ErrorCode.VALIDATIONFAILED); } using (var ctx = new PetWhizzEntities()) { pet Pet = ctx.pets.Where(a => a.id == PetUpdateRequest.id).FirstOrDefault(); if (Pet == null) { logger.Error("Pet record is not fount for petId - " + PetUpdateRequest.id.ToString()); throw new CustomException("Pet object not found", (int)ErrorCode.NORECORDFOUND); } //looking for authorization if (Pet.petOwners.Where(a => a.userId == currentUser.userId).FirstOrDefault() == null) { logger.Error("Pet record is not fount for petId - " + PetUpdateRequest.id.ToString() + " and userId - " + currentUser.userId); throw new CustomException("Pet object not found for user", (int)ErrorCode.UNAUTHORIZED); } //update pet ctx.pets.Attach(Pet); Pet.breedId = PetUpdateRequest.breedId; Pet.birthDay = PetUpdateRequest.birthDay; Pet.coverImage = PetUpdateRequest.coverImage; Pet.isActive = PetUpdateRequest.isActive; Pet.lastUpdatedBy = currentUser.username; Pet.lastUpdatedTime = DateTime.Now; Pet.petName = PetUpdateRequest.petName; Pet.profileImage = PetUpdateRequest.profileImage; Pet.sex = PetUpdateRequest.sex; ctx.SaveChanges(); logger.Trace("Successfully updated Pet id - " + Pet.id + " by - " + currentUser.username); } } catch (CustomException) { throw; } catch (Exception ex) { logger.Error(MethodBase.GetCurrentMethod().Name + ": exception: " + ex.Message + ", " + ex.InnerException); throw new CustomException("SystemError", ex, (int)ErrorCode.PROCEESINGERROR); } }
internal void ConfirmPetSharingRequest(string token) { logger.Trace("Recived Confirm Pet share request"); try { if (String.IsNullOrEmpty(token)) { logger.Error("Recived Confirm Pet share request token is empty"); throw new CustomException("Recived Confirm Pet share request token is empty", (int)ErrorCode.VALIDATIONFAILED); } var userId = Decryptor.Decrypt(token).Split('|')[0]; var petId = Decryptor.Decrypt(token).Split('|')[1]; var sharedUserId = Decryptor.Decrypt(token).Split('|')[2]; if (String.IsNullOrEmpty(userId) || String.IsNullOrEmpty(petId) || String.IsNullOrEmpty(sharedUserId)) { logger.Error("Recived Confirm Pet share request some of the properties empty"); throw new CustomException("Recived Confirm Pet share request some of the properties empty", (int)ErrorCode.VALIDATIONFAILED); } int iUserId = int.Parse(userId); Int64 ipetId = Int64.Parse(petId); int isharedUserId = int.Parse(sharedUserId); using (var ctx = new PetWhizzEntities()) { petOwner PetOwner = ctx.petOwners.Where(a => a.userId == iUserId && a.petId == ipetId && a.sharedUserId == isharedUserId).FirstOrDefault(); if (PetOwner == null) { logger.Error("No Owner request found for userId -" + userId + " & petId -" + petId + " by userId- " + sharedUserId); throw new CustomException("Recived Confirm Pet share request some of the properties empty", (int)ErrorCode.NORECORDFOUND); } ctx.petOwners.Attach(PetOwner); PetOwner.isActive = true; PetOwner.acceptedTime = DateTime.Now; PetOwner.isMainOwner = false; ctx.SaveChanges(); logger.Trace("Confirm Pet share request completed successfully"); } } catch (CustomException) { throw; } catch (Exception ex) { logger.Error(MethodBase.GetCurrentMethod().Name + ": exception: " + ex.Message + ", " + ex.InnerException); throw new CustomException("SystemError", ex, (int)ErrorCode.PROCEESINGERROR); } }
internal AnimalBreedFilterResponse AnimalBreedFilter(AnimalBreedFilterRequest animalBreedFilterRequest) { logger.Trace("Recived AnimalBreedFilter request"); AnimalBreedFilterResponse AnimalBreedFilterResponse = new AnimalBreedFilterResponse(); try { if (String.IsNullOrEmpty(animalBreedFilterRequest.animalType)) { logger.Error("Recived Animal Breed Filter request Animal Type is empty"); throw new CustomException("Animal type is empty", (int)ErrorCode.VALIDATIONFAILED); } using (var ctx = new PetWhizzEntities()) { var animals = ctx.animals.Where(a => a.animalName.ToLower() == animalBreedFilterRequest.animalType.ToLower() && a.isActive == true).FirstOrDefault(); if (animals != null) { if (!String.IsNullOrEmpty(animalBreedFilterRequest.filterQuery)) { AnimalBreedFilterResponse.AnimalBreedList = animals.animalBreeds.Where(a => a.breedName.ToLower().Contains(animalBreedFilterRequest.filterQuery.ToLower()) && a.isActive == true) .Take(10) .Select(a => new { a.id, a.breedName }).ToArray(); } } else { logger.Error("No animal found for type - " + animalBreedFilterRequest.animalType); throw new CustomException("No animal found for type", (int)ErrorCode.NORECORDFOUND); } } } catch (CustomException) { throw; } catch (Exception ex) { logger.Error(MethodBase.GetCurrentMethod().Name + ": exception: " + ex.Message + ", " + ex.InnerException); throw new CustomException("SystemError", ex, (int)ErrorCode.PROCEESINGERROR); } return(AnimalBreedFilterResponse); }
internal PetUserResponse GetUsersByPet(PetUserRequest petUserRequest) { logger.Trace("Recived Get Users By Pet request"); PetUserResponse PetUserResponse = new PetUserResponse(); try { CurrentUser currentUser = (CurrentUser)HttpContext.Current.User; if (petUserRequest.petId <= 0) { logger.Error("Get users by pet petId is invalid"); throw new CustomException("Get users by pet petId is invalid", (int)ErrorCode.VALIDATIONFAILED); } using (var ctx = new PetWhizzEntities()) { pet Pet = ctx.pets.Where(a => a.id == petUserRequest.petId).FirstOrDefault(); if (Pet == null) { logger.Error("No pet found for given Id"); throw new CustomException("No pet found for given Id", (int)ErrorCode.NORECORDFOUND); } List <petOwner> petOwnerList = Pet.petOwners.Where(a => a.userId != currentUser.userId).ToList(); PetUserResponse.PetUserList = new List <PetUser>(); foreach (petOwner owner in petOwnerList) { PetUserResponse.userCount++; PetUser PetUser = new PetUser() { isConfirmed = owner.isActive, profilePic = owner.user.profilePic, userId = owner.userId, userName = owner.user.userName }; PetUserResponse.PetUserList.Add(PetUser); } } } catch (CustomException) { throw; } catch (Exception ex) { logger.Error(MethodBase.GetCurrentMethod().Name + ": exception: " + ex.Message + ", " + ex.InnerException); throw new CustomException("SystemError", ex, (int)ErrorCode.PROCEESINGERROR); } return(PetUserResponse); }
internal RefreshTokenResponse RefreshToken(RefreshTokenRequest refreshTokenRequest) { logger.Debug("Recived RefreshToken request"); RefreshTokenResponse RefreshTokenResponse; try { if (String.IsNullOrEmpty(refreshTokenRequest.token)) { logger.Error("Refresh token validation failed"); throw new CustomException("Refresh token validation failed.Token is null", (int)ErrorCode.VALIDATIONFAILED); } refreshTokenRequest.token = Decryptor.Decrypt(refreshTokenRequest.token).Split('|')[1]; String NewToken = Guid.NewGuid().ToString(); using (var ctx = new PetWhizzEntities()) { userToken UserToken = ctx.userTokens.Where(a => a.token == refreshTokenRequest.token && a.tokenType == "AUTHTOKEN").FirstOrDefault(); if (UserToken == null) { logger.Error("token is invalid"); throw new CustomException(" token is invalid", (int)ErrorCode.UNAUTHORIZED); } //update existing token ctx.userTokens.Attach(UserToken); UserToken.generatedTime = DateTime.Now; UserToken.token = NewToken; UserToken.expiryTime = DateTime.Now.AddSeconds(TokenExpiryTime); ctx.SaveChanges(); RefreshTokenResponse = new RefreshTokenResponse() { token = Encryptor.Encrypt(DateTime.Now.ToString("M/d/yyyy h:mm:ss tt") + "|" + NewToken), }; } } catch (CustomException) { throw; } catch (Exception ex) { logger.Error(MethodBase.GetCurrentMethod().Name + ": exception: " + ex.Message + ", " + ex.InnerException); throw new CustomException("SystemError", ex, (int)ErrorCode.PROCEESINGERROR); } return(RefreshTokenResponse); }
internal void UpdateUser(UserUpdateRequest UserUpdateRequest) { logger.Debug("Recived update user request"); try { UserUpdateRequest.email = Decryptor.Decrypt(UserUpdateRequest.email); if (String.IsNullOrEmpty(UserUpdateRequest.email)) { logger.Error("User update required user email"); throw new CustomException("User update required user email", (int)ErrorCode.VALIDATIONFAILED); } CurrentUser currentUser = (CurrentUser)HttpContext.Current.User; if (currentUser.userId >= 0) { logger.Error("User is not found on the session"); throw new CustomException("User is not found on the session", (int)ErrorCode.UNAUTHORIZED); } using (var ctx = new PetWhizzEntities()) { user User = ctx.users.Where(a => a.id == currentUser.userId).FirstOrDefault(); ctx.users.Attach(User); User.addressLine1 = UserUpdateRequest.addressLine1; User.addressLine2 = UserUpdateRequest.addressLine2; User.dateOfBirth = UserUpdateRequest.dateOfBirth; User.eMail = UserUpdateRequest.email; User.firstName = UserUpdateRequest.firstName; User.lastName = UserUpdateRequest.lastName; User.lastUpdatedDate = DateTime.Now; User.middleName = UserUpdateRequest.middleName; User.mobileNumber = UserUpdateRequest.mobileNumber; User.profilePic = UserUpdateRequest.profilePic; ctx.SaveChanges(); } logger.Debug("Successfully updated user - " + currentUser.userId); } catch (CustomException) { throw; } catch (Exception ex) { logger.Error(MethodBase.GetCurrentMethod().Name + ": exception: " + ex.Message + ", " + ex.InnerException); throw new CustomException("SystemError", ex, (int)ErrorCode.PROCEESINGERROR); throw; } }
internal PetsResponse Pets() { PetsResponse PetsResponse = new PetsResponse(); logger.Trace("Recived get pets request"); try { CurrentUser currentUser = (CurrentUser)HttpContext.Current.User; using (var ctx = new PetWhizzEntities()) { PetsResponse.petList = ctx.petOwners .Where(a => a.userId == currentUser.userId && a.isActive == true) .Select(b => new { b.pet.id, b.pet.petName, birthDay = b.pet.birthDay.ToString(), b.pet.breedId, b.pet.sex, b.pet.animalBreed.breedName, b.pet.animalBreed.animal.animalName, b.pet.profileImage, b.pet.coverImage, b.pet.isActive, b.pet.isDeleted, userCount = b.pet.petOwners.Count }).ToArray(); }; } catch (CustomException) { throw; } catch (Exception ex) { logger.Error(MethodBase.GetCurrentMethod().Name + ": exception: " + ex.Message + ", " + ex.InnerException); throw new CustomException("SystemError", ex, (int)ErrorCode.PROCEESINGERROR); } return(PetsResponse); }
internal string ValidateResetPasswordToken(string token) { logger.Debug("Recived Validate ResetPassword Token request for token - " + token); String UserName = String.Empty; try { int UserId = Convert.ToInt32(Decryptor.Decrypt(token).Split('|')[1]); int RandomCode = Convert.ToInt32(Decryptor.Decrypt(token).Split('|')[0]); logger.Debug("Recived Validate ResetPassword Token request for userId - " + UserId.ToString() + " and code - " + RandomCode.ToString()); userVerification _currentVerification; using (var ctx = new PetWhizzEntities()) { _currentVerification = ctx.userVerifications .Where(a => a.userId == UserId && a.code == RandomCode.ToString() && a.verificationType == "RESETPASSWORD" && a.expiryTime >= DateTime.Now && a.isValid == true).FirstOrDefault(); if (_currentVerification != null) { UserName = _currentVerification.user.userName; UserName = char.ToUpper(UserName[0]) + UserName.Substring(1); } else { ctx.Dispose(); logger.Error("no verification details found for userId - " + UserId.ToString() + " and code - " + RandomCode.ToString()); throw new CustomException("Verification details not found", (int)ErrorCode.PROCEESINGERROR); } } } catch (CustomException) { throw; } catch (Exception) { logger.Error("Error occured while user verification token - " + token); throw; } return(UserName); }
internal bool ValidateAuthToken(string Token) { bool status = false; try { using (var ctx = new PetWhizzEntities()) { var userToken = ctx.userTokens.Where(a => a.token.Equals(Token)).FirstOrDefault(); if (userToken != null && userToken.expiryTime >= DateTime.Now) { status = true; HttpContext.Current.User = new CurrentUser(userToken.userDevice.user, Token); } } logger.Debug("Successfully validated the token with DB token -" + Token); } catch (Exception ex) { logger.Error("Error occured while validating the token with DB tokens -" + Token); throw; } return(status); }
internal void DeletePet(PetDeleteRequest petDeleteRequest) { logger.Trace("Recived get pets delete request"); try { CurrentUser currentUser = (CurrentUser)HttpContext.Current.User; petDeleteRequest.petId = Decryptor.Decrypt(petDeleteRequest.petId).Split('|')[1]; Int64 petId = Convert.ToInt64(petDeleteRequest.petId); if (String.IsNullOrEmpty(petDeleteRequest.petId)) { logger.Error("Pet id not found on request"); throw new CustomException("Pet id not found on request", (int)ErrorCode.VALIDATIONFAILED); } using (var ctx = new PetWhizzEntities()) { pet Pet = ctx.pets.Where(a => a.id == petId).FirstOrDefault(); if (Pet.petOwners.Where(a => a.userId == currentUser.userId && a.isActive == true && a.isMainOwner == true).FirstOrDefault() == null) { logger.Error("Requested user not belongs to the pet or not the main owner"); throw new CustomException("Requested user not belongs to the pet or not the main owner", (int)ErrorCode.UNAUTHORIZED); } //delete pet ctx.pets.Attach(Pet); Pet.isActive = false; Pet.isDeleted = true; ctx.SaveChanges(); logger.Trace("Pet successfully deleted"); } } catch (CustomException) { throw; } catch (Exception ex) { logger.Error(MethodBase.GetCurrentMethod().Name + ": exception: " + ex.Message + ", " + ex.InnerException); throw new CustomException("SystemError", ex, (int)ErrorCode.PROCEESINGERROR); } }
internal string ResetPassword(ResetPasswordRequest resetPasswordRequest) { logger.Debug("Recived ResetPassword request for token - " + resetPasswordRequest.token); String Status = String.Empty; try { if (!String.IsNullOrEmpty(resetPasswordRequest.token) && !String.IsNullOrEmpty(resetPasswordRequest.newPassowrd)) { int UserId = Convert.ToInt32(Decryptor.Decrypt(resetPasswordRequest.token).Split('|')[1]); int RandomCode = Convert.ToInt32(Decryptor.Decrypt(resetPasswordRequest.token).Split('|')[0]); logger.Debug("Recived ResetPassword request for userId - " + UserId.ToString() + " and code - " + RandomCode.ToString()); userVerification _currentVerification; using (var ctx = new PetWhizzEntities()) { _currentVerification = ctx.userVerifications .Where(a => a.userId == UserId && a.code == RandomCode.ToString() && a.verificationType == "RESETPASSWORD" && a.expiryTime >= DateTime.Now && a.isValid == true).FirstOrDefault(); if (_currentVerification != null) { using (var dbContextTransaction = ctx.Database.BeginTransaction()) { try { ctx.userVerifications.Attach(_currentVerification); _currentVerification.isValid = false; ctx.users.Attach(_currentVerification.user); _currentVerification.user.password = resetPasswordRequest.newPassowrd; ctx.SaveChanges(); dbContextTransaction.Commit(); Status = "success"; } catch (Exception) { dbContextTransaction.Rollback(); dbContextTransaction.Dispose(); logger.Error("verification details update failed for userId - " + UserId.ToString() + " and code - " + RandomCode.ToString()); throw new CustomException("verification details update failed", (int)ErrorCode.PROCEESINGERROR); } } } else { ctx.Dispose(); logger.Error("No ResetPassword found for userId - " + UserId.ToString() + " and code - " + RandomCode.ToString()); throw new CustomException("ResetPassword details not found", (int)ErrorCode.PROCEESINGERROR); } } } else { logger.Error("Recived ResetPassword request token or new password empty"); throw new CustomException("Recived ResetPassword request token or new password empty", (int)ErrorCode.VALIDATIONFAILED); } } catch (CustomException) { throw; } catch (Exception) { logger.Error("ResetPassword failed"); throw; } return(Status); }
internal void SendVerifyEmail() { logger.Debug("Recived SendVerifyEmail request"); try { CurrentUser currentUser = (CurrentUser)HttpContext.Current.User; if (String.IsNullOrEmpty(currentUser.token)) { logger.Error("Verify email token is invalid"); throw new CustomException(" token is invalid", (int)ErrorCode.UNAUTHORIZED); } using (var ctx = new PetWhizzEntities()) { using (var dbContextTransaction = ctx.Database.BeginTransaction()) { try { user User = ctx.users.Where(a => a.id == currentUser.userId).FirstOrDefault(); if (User == null) { logger.Error("Verify email user is invalid"); throw new CustomException("user is invalid", (int)ErrorCode.UNAUTHORIZED); } //inactive existing verifications for user List <userVerification> userVerificationList = ctx.userVerifications.Where(a => a.userId == User.id && a.verificationType == "EMAILVERIFY" && a.isValid == true).ToList(); foreach (userVerification userVerification in userVerificationList) { ctx.userVerifications.Attach(userVerification); userVerification.isValid = false; ctx.SaveChanges(); } int GeneratedCode = new Random().Next(100000, 999999); var userVerificationInfo = new userVerification() { code = GeneratedCode.ToString(), generatedTime = DateTime.Now, expiryTime = DateTime.Now.AddSeconds(VerificationCodeExpiryTime), isValid = true, userId = User.id, verificationType = "EMAILVERIFY", }; ctx.userVerifications.Add(userVerificationInfo); ctx.SaveChanges(); SendEmailVerification(User.eMail, User.userName, User.id, GeneratedCode.ToString()); dbContextTransaction.Commit(); } catch (Exception) { dbContextTransaction.Rollback(); dbContextTransaction.Dispose(); logger.Error("verification details update failed for userId - " + currentUser.userId.ToString()); throw new CustomException("verification details update failed", (int)ErrorCode.PROCEESINGERROR); } } } } catch (CustomException) { throw; } catch (Exception ex) { logger.Error(MethodBase.GetCurrentMethod().Name + ": exception: " + ex.Message + ", " + ex.InnerException); throw new CustomException("SystemError", ex, (int)ErrorCode.PROCEESINGERROR); } }
internal EnrollUserResponse EnrollUser(EnrollUserRequest EnrollUserRequest) { logger.Debug("Recived enroll user request"); EnrollUserResponse EnrollUserResponse; try { ValidateUserRequest ValidateUserRequest = new ValidateUserRequest() { email = EnrollUserRequest.email, username = EnrollUserRequest.username }; ValidatUser(ValidateUserRequest); EnrollUserRequest.username = Decryptor.Decrypt(EnrollUserRequest.username).Split('|')[1]; EnrollUserRequest.password = Decryptor.Decrypt(EnrollUserRequest.password).Split('|')[1]; EnrollUserRequest.email = Decryptor.Decrypt(EnrollUserRequest.email).Split('|')[1]; EnrollUserRequest.deviceId = Decryptor.Decrypt(EnrollUserRequest.deviceId).Split('|')[1]; String GeneratedToken = Guid.NewGuid().ToString(); int GeneratedCode = new Random().Next(100000, 999999); logger.Debug("Decrypted enroll user request details userName - " + EnrollUserRequest.username + " password - " + EnrollUserRequest.password + " email - " + EnrollUserRequest.email + " deviceId - " + EnrollUserRequest.deviceId); //validating details if (!String.IsNullOrEmpty(EnrollUserRequest.username) && !String.IsNullOrEmpty(EnrollUserRequest.password) && !String.IsNullOrEmpty(EnrollUserRequest.email) && !String.IsNullOrEmpty(EnrollUserRequest.deviceId)) { //setting up user details var user = new user() { createdDate = DateTime.Now, lastUpdatedDate = DateTime.Now, userName = EnrollUserRequest.username, password = EnrollUserRequest.password, eMail = EnrollUserRequest.email, status = "EMAILVERIFY" }; using (var ctx = new PetWhizzEntities()) { //saving user ctx.users.Add(user); ctx.SaveChanges(); //saving user device var userDevice = new userDevice() { deviceId = EnrollUserRequest.deviceId, // deviceName = EnrollUserRequest.deviceName, userId = user.id, }; ctx.userDevices.Add(userDevice); ctx.SaveChanges(); //saving user token var userToken = new userToken() { tokenType = "AUTHTOKEN", useCount = 0, generatedTime = DateTime.Now, userDeviceId = userDevice.id, expiryTime = DateTime.Now.AddSeconds(TokenExpiryTime), token = GeneratedToken, }; ctx.userTokens.Add(userToken); ctx.SaveChanges(); //user verification data var userVerificationInfo = new userVerification() { code = GeneratedCode.ToString(), generatedTime = DateTime.Now, expiryTime = DateTime.Now.AddSeconds(VerificationCodeExpiryTime), isValid = true, userId = user.id, verificationType = "EMAILVERIFY", }; ctx.userVerifications.Add(userVerificationInfo); ctx.SaveChanges(); } SendEmailVerification(user.eMail, user.userName, user.id, GeneratedCode.ToString()); EnrollUserResponse = new EnrollUserResponse() { token = Encryptor.Encrypt(DateTime.Now.ToString("M/d/yyyy h:mm:ss tt") + "|" + GeneratedToken), username = Encryptor.Encrypt(DateTime.Now.ToString("M/d/yyyy h:mm:ss tt") + "|" + user.userName), email = Encryptor.Encrypt(DateTime.Now.ToString("M/d/yyyy h:mm:ss tt") + "|" + user.eMail), status = Encryptor.Encrypt(DateTime.Now.ToString("M/d/yyyy h:mm:ss tt") + "|" + user.status), userId = Encryptor.Encrypt(DateTime.Now.ToString("M/d/yyyy h:mm:ss tt") + "|" + user.id) }; } else { logger.Error("Some of the properties in EnrollUserRequest is null or empty"); throw new CustomException("All propreties should contains a value", (int)ErrorCode.VALIDATIONFAILED); } } catch (CustomException) { throw; } catch (Exception ex) { logger.Error(MethodBase.GetCurrentMethod().Name + ": exception: " + ex.Message + ", " + ex.InnerException); throw new CustomException("SystemError", ex, (int)ErrorCode.PROCEESINGERROR); } return(EnrollUserResponse); }
internal void PetEnrollment(PetEnrollmentRequest petEnrollmentRequest) { logger.Trace("Recived pet enroll request"); try { CurrentUser currentUser = (CurrentUser)HttpContext.Current.User; if (String.IsNullOrEmpty(petEnrollmentRequest.petName) || petEnrollmentRequest.breedId == 0) { logger.Error("Required fiedls not found on pet emrollment reuest"); throw new CustomException("Breed or Pet Name is empty", (int)ErrorCode.VALIDATIONFAILED); } //creating pet object pet Pet = new pet() { profileImage = petEnrollmentRequest.profileImage, coverImage = petEnrollmentRequest.coverImage, sex = petEnrollmentRequest.sex, birthDay = petEnrollmentRequest.birthDay, breedId = petEnrollmentRequest.breedId, entryDate = DateTime.Now, isActive = true, isDeleted = false, petName = petEnrollmentRequest.petName }; using (var ctx = new PetWhizzEntities()) { using (var dbContextTransaction = ctx.Database.BeginTransaction()) { try { ctx.pets.Add(Pet); ctx.SaveChanges(); petOwner PetOwner = new petOwner() { enteryDate = DateTime.Now, petId = Pet.id, userId = currentUser.userId, isActive = true, isMainOwner = true }; ctx.petOwners.Add(PetOwner); ctx.SaveChanges(); dbContextTransaction.Commit(); } catch (Exception) { dbContextTransaction.Rollback(); logger.Error("DB error occure when enrolling Pet"); throw new CustomException("Pet Enrolling failed", (int)ErrorCode.PROCEESINGERROR); } } } } catch (CustomException) { throw; } catch (Exception ex) { logger.Error(MethodBase.GetCurrentMethod().Name + ": exception: " + ex.Message + ", " + ex.InnerException); throw new CustomException("SystemError", ex, (int)ErrorCode.PROCEESINGERROR); } }
internal UserLoginResponse UserLogin(UserLoginRequest userLoginRequest) { logger.Debug("Recived user login request"); UserLoginResponse UserLoginResponse; try { String GeneratedToken = Guid.NewGuid().ToString(); userLoginRequest.deviceId = Decryptor.Decrypt(userLoginRequest.deviceId).Split('|')[1]; userLoginRequest.username = Decryptor.Decrypt(userLoginRequest.username).Split('|')[1]; userLoginRequest.password = Decryptor.Decrypt(userLoginRequest.password).Split('|')[1]; logger.Debug("Recived user login request with username - " + userLoginRequest.username + " password - " + userLoginRequest.password + " deviceId - " + userLoginRequest.deviceId); if (!String.IsNullOrEmpty(userLoginRequest.deviceId) && !String.IsNullOrEmpty(userLoginRequest.username) && !String.IsNullOrEmpty(userLoginRequest.password)) { using (var ctx = new PetWhizzEntities()) { //checking for user user User = ctx.users.Where(a => a.userName.ToLower().Equals(userLoginRequest.username.ToLower()) && a.password == userLoginRequest.password).FirstOrDefault(); if (User == null) { logger.Error("Login failed for user - " + userLoginRequest.username); throw new CustomException("Username or Password Invalid", (int)ErrorCode.LOGINFAILURE); } UserLoginResponse = new UserLoginResponse() { email = Encryptor.Encrypt(DateTime.Now.ToString("M/d/yyyy h:mm:ss tt") + "|" + User.eMail), status = Encryptor.Encrypt(DateTime.Now.ToString("M/d/yyyy h:mm:ss tt") + "|" + User.status), token = Encryptor.Encrypt(DateTime.Now.ToString("M/d/yyyy h:mm:ss tt") + "|" + GeneratedToken), username = Encryptor.Encrypt(DateTime.Now.ToString("M/d/yyyy h:mm:ss tt") + "|" + User.userName), userId = Encryptor.Encrypt(DateTime.Now.ToString("M/d/yyyy h:mm:ss tt") + "|" + User.id.ToString()) }; //checking for device userDevice UserDevice = ctx.userDevices.Where(a => a.userId == User.id && a.deviceId == userLoginRequest.deviceId).FirstOrDefault(); if (UserDevice == null) { //new device var userDevice = new userDevice() { deviceId = userLoginRequest.deviceId, deviceName = "", userId = User.id, }; ctx.userDevices.Add(userDevice); ctx.SaveChanges(); //saving user token var userToken = new userToken() { tokenType = "AUTHTOKEN", useCount = 0, generatedTime = DateTime.Now, userDeviceId = userDevice.id, expiryTime = DateTime.Now.AddSeconds(TokenExpiryTime), token = GeneratedToken, }; ctx.userTokens.Add(userToken); ctx.SaveChanges(); } else { userToken userDBToken = ctx.userTokens.Where(a => a.userDeviceId == UserDevice.id).FirstOrDefault(); if (userDBToken == null) { var userToken = new userToken() { tokenType = "AUTHTOKEN", useCount = 0, generatedTime = DateTime.Now, userDeviceId = UserDevice.id, expiryTime = DateTime.Now.AddSeconds(TokenExpiryTime), token = GeneratedToken, }; ctx.userTokens.Add(userToken); ctx.SaveChanges(); } else { ctx.userTokens.Attach(userDBToken); userDBToken.expiryTime = DateTime.Now.AddSeconds(TokenExpiryTime); ctx.SaveChanges(); UserLoginResponse.token = Encryptor.Encrypt(DateTime.Now.ToString("M/d/yyyy h:mm:ss tt") + "|" + userDBToken.token); } } } } else { logger.Error("Some of the properties in userLoginRequest is null or empty"); throw new CustomException("All propreties should contains a value", (int)ErrorCode.VALIDATIONFAILED); } } catch (CustomException) { throw; } catch (Exception ex) { logger.Error(MethodBase.GetCurrentMethod().Name + ": exception: " + ex.Message + ", " + ex.InnerException); throw new CustomException("SystemError", ex, (int)ErrorCode.PROCEESINGERROR); } return(UserLoginResponse); }
internal void SharePet(PetShareRequest petShareRequest) { logger.Trace("Recived Pet share request"); try { if (String.IsNullOrEmpty(petShareRequest.username) || String.IsNullOrEmpty(petShareRequest.email) || petShareRequest.petId <= 0) { logger.Error("Recived Pet share request"); throw new CustomException("Pet share request dosent have required fields", (int)ErrorCode.VALIDATIONFAILED); } CurrentUser currentUser = (CurrentUser)HttpContext.Current.User; using (var ctx = new PetWhizzEntities()) { user User = ctx.users.Where(a => a.eMail.ToLower() == petShareRequest.email.ToLower()).FirstOrDefault(); if (User == null) { logger.Error("Requested user details not matching for Petwhizz user email - " + petShareRequest.email); throw new CustomException("Requested user details not matching for Petwhizz user", (int)ErrorCode.USERNOTFOUND); } if (User.userName.ToLower() != petShareRequest.username.ToLower()) { logger.Error("Requested user details not matching for Petwhizz user username - " + petShareRequest.username); throw new CustomException("Requested user details not matching for Petwhizz user username", (int)ErrorCode.VALIDATIONFAILED); } pet Pet = ctx.pets.Where(a => a.id == petShareRequest.petId).FirstOrDefault(); if (Pet.petOwners.Where(a => a.userId == currentUser.userId && a.isActive == true && a.isMainOwner == true).FirstOrDefault() == null) { logger.Error("Requested user not belongs to the pet or not the main owner"); throw new CustomException("Requested user not belongs to the pet or not the main owner", (int)ErrorCode.UNAUTHORIZED); } petOwner PetOwner = ctx.petOwners.Where(a => a.petId == petShareRequest.petId && a.userId == User.id).FirstOrDefault(); if (PetOwner != null && PetOwner.isActive == true) { logger.Error("Pet is already shared with requestd user"); throw new CustomException("Pet is already shared with requestd user", (int)ErrorCode.ALREADYEXIST); } else if (PetOwner != null && PetOwner.isActive == false) { logger.Error("Pet is already shared with this user but not yet confirmed."); throw new CustomException("Pet is already shared with this user but not yet confirmed.", (int)ErrorCode.NOTCONFIRMED); } else { //share pet PetOwner = new petOwner() { enteryDate = DateTime.Now, isActive = false, isMainOwner = false, petId = petShareRequest.petId, sharedTime = DateTime.Now, sharedUserId = currentUser.userId, acceptedTime = null, userId = User.id }; ctx.petOwners.Add(PetOwner); ctx.SaveChanges(); // var EmailService = new EmailService(); SendPetSharingEmail(PetOwner); } } } catch (CustomException) { throw; } catch (Exception ex) { logger.Error(MethodBase.GetCurrentMethod().Name + ": exception: " + ex.Message + ", " + ex.InnerException); throw new CustomException("SystemError", ex, (int)ErrorCode.PROCEESINGERROR); } }