private void ThrowIfEmailNotConfirmed(AppUser user) { if (!user.EmailConfirmed) { throw BankClientException.ThrowEmailNotConfirmed(); } }
//платеж по кредиту public void Add(string contractNumber, double sum) { var startPay = GlobalValues.BankDateTime.AddDays(ProjectConstants.DayCountForStartPay); var customerCredit = _iUnitOfWork.CustomerCreditRepository.GetByContractNumber(contractNumber); var currentPaymentPlan = customerCredit .CreditPaymentPlanItems .FirstOrDefault(x => !x.IsPaid && startPay > x.StartDate); if (currentPaymentPlan == null) { throw BankClientException.ThrowNotPayment(); } var destinationBill = _iUnitOfWork.BillRepository .GetByNumber(ConfigurationManager.AppSettings.Get("BankBillNumber")); destinationBill.Sum += sum; var payment = CalculatePayment(currentPaymentPlan, sum); payment.DestinationBillId = destinationBill.Id; _iUnitOfWork.CreditPaymentRepository.Add(payment); currentPaymentPlan.IsPaid = isPaid(currentPaymentPlan); _iUnitOfWork.SaveChanges(); }
private void ThrowIfNotRegistered(AppUser user) { if (user == null) { throw BankClientException.ThrowUserNotRegistered(); } }
private void ThrowIfInvalidEmployeeCredentials(AppUser user, string password) { var appUser = AppUserManagerFactory.Instance.Factory().Find(user.UserName, password); if (appUser == null) { throw BankClientException.ThrowInvalidCredentials(); } }
public DomainCustomerCredit GetByContractNumber(string contractNumber) { var userCredit = Uow.CustomerCreditRepository.GetByContractNumber(contractNumber); if (userCredit == null) { throw BankClientException.ThrowUserCreditNotFound(); } return(Mapper.Map <DomainCustomerCredit>(userCredit)); }
public static ResponseBase Unsuccessful(BankClientException ex) { return(new ResponseBase() { IsSuccess = false, ErrorMessage = new Error() { Code = ex.Code, Description = ex.Message } }); }
public static TResponse Unsuccessful <TResponse>(BankClientException ex) where TResponse : ResponseBase, new() { return(new TResponse() { IsSuccess = false, ErrorMessage = new Error() { Code = ex.Code, Description = ex.Message } }); }
public CustomPagedList <ShortCustomerCredit> GetAllByUser(string userId, int pageNumber, int pageSize) { var user = Uow.AppUserRepository.GetAll().FirstOrDefault(u => u.Id == userId); if (user == null) { throw BankClientException.ThrowUserNotRegistered(); } var credits = Uow.CustomerCreditRepository.GetAll().Where(cc => cc.CustomerId == user.CustomerId); var domainCredits = Mapper.Map <CustomPagedList <ShortCustomerCredit> >(credits.ToCustomPagedList(pageNumber, pageSize)); return(domainCredits); }
public override void OnActionExecuting(HttpActionContext actionContext) { try { var requestScope = actionContext.Request.GetDependencyScope(); var authenticationService = requestScope.GetService(typeof(IAuthenticationService)) as IAuthenticationService; if (authenticationService == null) { throw BankClientException.ThrowAutofacError("AuthenticationService is null"); } // var requestParams = ((AuthenticatedRequest)actionContext.ActionArguments.First().Value); var token = actionContext.Request.Headers.First(p => p.Key.ToLower() == "token").Value.First(); var parsedToken = authenticationService.CheckToken(token); actionContext.Request.Properties.Add("tokenObj", parsedToken); // requestParams.TokenObj = parsedToken; } catch (TokenExpiredException) { // var logService = actionContext.Request.GetDependencyScope().GetService(typeof(ILogService)) as ILogService; // if (logService == null) // { // throw BankClientException.ThrowAutofacError("LogService is null"); // } // logService.Log("Token expired", "CheckToken", LogType.Warning); actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, ResponseBase.TokenExpired()); } catch (BankClientException ex) { // var logService = actionContext.Request.GetDependencyScope().GetService(typeof(ILogService)) as ILogService; // if (logService == null) // { // throw BankClientException.ThrowAutofacError("LogService is null"); // } // logService.Log(ex.ToString(), "CheckToken", LogType.Error); actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, ResponseBase.Unsuccessful(ex)); } catch (Exception ex) { // var logService = actionContext.Request.GetDependencyScope().GetService(typeof(ILogService)) as ILogService; // if (logService == null) // { // throw BankClientException.ThrowAutofacError("LogService is null"); // } // logService.Log(ex.ToString(), "CheckToken", LogType.Error); actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, ResponseBase.Unsuccessful(ex)); } }
public DomainToken CheckToken(string token) { if (token == null) { throw BankClientException.ThrowInvalidToken(); } var decryptedToken = _iEncryptorService.Decrypt(token); var tokenParts = ParseToken(decryptedToken); var tokenObject = CheckTokenParts(tokenParts); CheckTokenValidity(tokenObject); return(tokenObject); }
private DomainToken CheckTokenParts(string[] tokenParts) { Guid guid; DateTime date; var isSuccessGuidParse = Guid.TryParse(tokenParts[0], out guid); var login = tokenParts[1]; var userId = tokenParts[2]; var isSuccessDateParse = DateTime.TryParse(tokenParts[3], out date); if (!isSuccessGuidParse || !isSuccessDateParse) { throw BankClientException.ThrowInvalidToken(); } return(new DomainToken(guid, login, userId, date)); }
private void ThrowIfLockout(AppUser user) { if (user.LockoutEnabled) { if (DateTime.UtcNow > user.LockoutEndDateUtc) { user.LockoutEnabled = false; user.AccessFailedCount = 0; _iUnitOfWork.SaveChanges(); } else { throw BankClientException.ThrowUserLockout(); } } }
public void SetStatus(string userId, int creditRequestId, CreditRequestStatusInfo statusInfo, string message) { var creditRequest = _iUnitOfWork.CreditRequestRepository.Get(creditRequestId); //не выдали ли уже кредит if (creditRequest.CustomerCredits.Any()) { throw BankClientException.ThrowCannotSetStatus(); } var chiefRoleName = AppRoles.CreditDepartmentChief.ToString(); //не обработал ли заяку начальник if (!AuthManagerService.UserManager.IsInRole(userId, chiefRoleName)) { if (creditRequest.CreditRequestStatuses.Any(s => AuthManagerService.UserManager.IsInRole(s.AppUserId, chiefRoleName))) { throw BankClientException.ThrowCannotSetStatus(); } } var existingStatus = creditRequest.CreditRequestStatuses.FirstOrDefault(cs => cs.AppUserId == userId); if (existingStatus != null) { if (statusInfo == CreditRequestStatusInfo.None) { _iUnitOfWork.CreditRequestStatusRepository.Delete(existingStatus.Id); } else { existingStatus.Info = statusInfo; existingStatus.Message = message; } } else { creditRequest.CreditRequestStatuses.Add(new CreditRequestStatus() { AppUserId = userId, Info = statusInfo, Message = message }); } _iUnitOfWork.SaveChanges(); }
public DomainToken GetParsedToken(IDictionary <string, object> requestProperties) { object tokenObj; requestProperties.TryGetValue("tokenObj", out tokenObj); if (tokenObj == null) { throw BankClientException.ThrowAuthorizationError(); } var token = tokenObj as DomainToken; if (token == null) { throw BankClientException.ThrowAuthorizationError(); } return(token); }
public void SignOut(string token) { if (token == null) { throw BankClientException.ThrowInvalidToken(); } var decryptedToken = _iEncryptorService.Decrypt(token); var tokenParts = ParseToken(decryptedToken); var tokenObject = CheckTokenParts(tokenParts); var databaseToken = _iUnitOfWork.TokenRepository.GetByGuid(tokenObject.Guid); if (databaseToken != null) { _iUnitOfWork.TokenRepository.Delete(databaseToken.Id); } _iUnitOfWork.SaveChanges(); }
private void ThrowIfInvalidCredentials(AppUser user, string password) { var appUser = AppUserManagerFactory.Instance.Factory().Find(user.UserName, password); if (appUser == null) { user.AccessFailedCount += 1; if (user.AccessFailedCount == 3) { user.LockoutEnabled = true; user.LockoutEndDateUtc = DateTime.UtcNow + TimeSpan.FromMinutes(15); _iEmailSender.SendLockoutNotification(user.Email, user.UserName); } _iUnitOfWork.SaveChanges(); throw BankClientException.ThrowInvalidCredentials(); } }
public void Add(int creditRequestId) { var creditRequest = Uow.CreditRequestRepository.Get(creditRequestId); var dateNow = GlobalValues.BankDateTime; var credit = new DomainCustomerCredit() { CreditId = creditRequest.CreditId, CreditSum = creditRequest.Sum, Currency = creditRequest.Currency, CustomerId = creditRequest.CustomerId, StartDate = dateNow.Date, EndDate = dateNow.Date.AddMonths(creditRequest.MonthCount), ContractNumber = GenerateContractNumber(), Bill = new DomainBill() { Number = GenerateBillNumber(), CustomerId = creditRequest.CustomerId, Sum = creditRequest.Sum }, CreditRequestId = creditRequestId }; var bankBill = Uow.BillRepository.GetByNumber(ConfigurationManager.AppSettings.Get("BankBillNumber")); if (bankBill.Sum - creditRequest.Sum < 0) { throw BankClientException.ThrowNotHaveMoney(); } bankBill.Sum -= creditRequest.Sum; var paymentPlan = new CalculationCreditService().CalculatePaymentPlan(credit.CreditSum, creditRequest.Credit.PercentRate, creditRequest.MonthCount, credit.StartDate).ToList(); credit.CreditPaymentPlanItems = paymentPlan; Uow.CustomerCreditRepository.Add(Mapper.Map <CustomerCredit>(credit)); Uow.SaveChanges(); credit.Customer = Mapper.Map <DomainCustomer>(Uow.CustomerRepository.Get(credit.CustomerId)); credit.Credit = Mapper.Map <DomainCredit>(Uow.CreditRepository.Get(credit.CreditId)); new CreditDocService().FillConcreteContract(credit); }
private void Validate(DomainCustomerDeposit customerDeposit, DomainDeposit deposit, int monthCount) { if (customerDeposit.InitialSum < deposit.MinSum) { throw BankClientException.ThrowSumLessThanMin(); } if (customerDeposit.InitialSum > deposit.MaxSum) { throw BankClientException.ThrowSumMoreThanMax(); } if (monthCount < deposit.MinMonthPeriod) { throw BankClientException.ThrowMonthLessThanMin(); } if (monthCount > deposit.MaxMonthPeriod) { throw BankClientException.ThrowMonthMoreThanMax(); } }
public override void OnActionExecuting(HttpActionContext actionContext) { try { var requestScope = actionContext.Request.GetDependencyScope(); var authenticationService = requestScope.GetService(typeof(IAuthenticationService)) as IAuthenticationService; if (authenticationService == null) { throw BankClientException.ThrowAutofacError("AuthenticationService is null"); } var token = actionContext.Request.Headers.First(p => p.Key.ToLower() == "token").Value.First(); var parsedToken = authenticationService.CheckToken(token); actionContext.Request.Properties.Add("tokenObj", parsedToken); if (Roles != null) { var userManager = Startup.UserManagerFactory(); var tokenObj = new ParsedTokenHelper().GetParsedToken(actionContext.Request.Properties); var userId = tokenObj.UserId; if (Roles.Any(role => userManager.IsInRole(userId, role.ToString()))) { return; } actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized); } } catch (TokenExpiredException) { // var logService = actionContext.Request.GetDependencyScope().GetService(typeof(ILogService)) as ILogService; // if (logService == null) // { // throw BankClientException.ThrowAutofacError("LogService is null"); // } // logService.Log("Token expired", "CheckToken", LogType.Warning); actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, ResponseBase.TokenExpired()); } catch (BankClientException ex) { // var logService = actionContext.Request.GetDependencyScope().GetService(typeof(ILogService)) as ILogService; // if (logService == null) // { // throw BankClientException.ThrowAutofacError("LogService is null"); // } // logService.Log(ex.ToString(), "CheckToken", LogType.Error); actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, ResponseBase.Unsuccessful(ex)); } catch (Exception ex) { // var logService = actionContext.Request.GetDependencyScope().GetService(typeof(ILogService)) as ILogService; // if (logService == null) // { // throw BankClientException.ThrowAutofacError("LogService is null"); // } // logService.Log(ex.ToString(), "CheckToken", LogType.Error); actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, ResponseBase.Unsuccessful(ex)); } }
public async Task <IHttpActionResult> Register(RegisterBindingModel request) { try { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var user = new AppUser() { Email = request.Email, UserName = request.UserName }; var customer = _iUnitOfWork.CustomerRepository.GetAll() .FirstOrDefault(c => c.IdentificationNumber == request.IdentificationNumber); if (customer == null) { throw BankClientException.ThrowIdentificationNumberNotFound(); } if (request.Code != customer.SecretCode) { throw BankClientException.ThrowSuperSecretCodeIsIncorrect(); } // else // { // customer = Mapper.Map<Customer>(request); // _iUnitOfWork.CustomerRepository.Add(customer); // _iUnitOfWork.SaveChanges(); // } user.CustomerId = customer.Id; var result = await UserManager.CreateAsync(user, request.Password); if (result.Succeeded) { UserManager.AddToRole(user.Id, AppRoles.User.ToString()); var baseUrl = String.Format("{0}://{1}", Request.RequestUri.Scheme, Request.RequestUri.Authority); _iEmailSender.SendVerifyToEmail(user.Email, user.Id, baseUrl); } var errorResult = GetErrorResult(result); if (errorResult != null) { return(errorResult); } return(Ok()); } catch (BankClientException ex) { return(BadRequest(ex.Message)); } catch (Exception ex) { return(InternalServerError(ex)); } }