/// <summary> /// Ghi đè phương thức dùng để lọc request. /// Author : TramHTD - 14/04/2018 - create /// </summary> /// <param name="actionContext"> /// Data của 1 request. /// </param> public override void OnAuthorization(HttpActionContext actionContext) { if (actionContext.Request.Headers.Authorization == null) { actionContext.Response = actionContext.Request.CreateResponse(System.Net.HttpStatusCode.Unauthorized, "Not allowed."); } else { string token = actionContext.Request.GetAuthorizationHeader(); var tokenInformation = JwtAuthenticationExtensions.ExtractTokenInformation(token); if (tokenInformation == null) { actionContext.Response = actionContext.Request.CreateResponse(System.Net.HttpStatusCode.Unauthorized, "Not allowed."); } else { var route = actionContext.RequestContext.RouteData; string controller = (string)route.Values["controller"]; string action = (string)route.Values["action"]; if (!AccountVerification.CheckAuthentication(token, controller, action)) { actionContext.Response = actionContext.Request.CreateResponse(System.Net.HttpStatusCode.NotAcceptable, "Not accept."); } } } }
public VerificationResponse SendAccountVerificationCode(string Email) { VerificationResponse response = new VerificationResponse(); if (Email == null || Email == "") { response.SetStatus(Constants.ResponseCode.FAILED); return(response); } User user = _userRepository.Get(t => t.Email == Email).FirstOrDefault(); if (user == null) { response.SetStatus(Constants.ResponseCode.FAILED); return(response); } AccountVerification accountVerification = CreateAccountVerificationCode(); MailRequest mailRequest = new MailRequest { ToMail = user.Email, ToName = user.FullName(), Subject = "B-Commerce E-Mail Onayı", Body = $"Merhaba {user.FullName()}\n Email onaylama kodunuz: {accountVerification.VerificationCode}", ProjectCode = "123456" }; HttpClient httpClient = new HttpClient(); httpClient.BaseAddress = new Uri(Constants.NOTIFICATION_API_BASE_URI); Task <HttpResponseMessage> httpResponse = httpClient.PostAsJsonAsync(Constants.NOTIFICATION_API_MAIL_URI, mailRequest); if (!httpResponse.Result.IsSuccessStatusCode) { response.SetStatus(Constants.ResponseCode.FAILED); return(response); } try { user.AccountVerifications.Add(accountVerification); _unitOfWork.SaveChanges(); response.SetStatus(Constants.ResponseCode.SUCCESS); return(response); } catch (Exception) { response.SetStatus(Constants.ResponseCode.SYSTEM_ERROR); return(response); } }
public HomeController(IConfiguration iconfiguration) { string con = iconfiguration.GetSection("ConnectionStrings").GetSection("connectionstring").Value; iappointmentContext = new AppointmentMsSqlContext(con); appointmentrepo = new AppointmentRepo(iappointmentContext); iaccountcontext = new AccountMsSqlContext(con); accountrepo = new AccountRepo(iaccountcontext); accVeri = new AccountVerification(); }
public AccountController(IConfiguration iconfiguration) { string con = iconfiguration.GetSection("ConnectionStrings").GetSection("connectionstring").Value; iaccountcontext = new AccountMsSqlContext(con); accountrepo = new AccountRepo(iaccountcontext); inotificationcontext = new NotificationMsSqlContext(con); notificationrepo = new NotificationRepo(inotificationcontext); accVeri = new AccountVerification(); }
public void OnGet_GivenPageModelIsNull_ExpectTokenSetInPageModel() { var mediator = new Mock <IMediator>(); var page = new AccountVerification(mediator.Object) { Token = "token" }; page.OnGet(); Assert.NotNull(page.PageModel); Assert.Equal("token", page.PageModel.Token); }
public void OnGet_GivenPageModelNotNull_ExpectTokenToBeIgnored() { var mediator = new Mock <IMediator>(); var page = new AccountVerification(mediator.Object) { Token = "token", PageModel = new AccountVerification.Model { Token = "model-token" }, }; page.OnGet(); Assert.Equal("model-token", page.PageModel.Token); }
public void Post([FromBody] UserDto userDto) { if (userDto != null) { try { var encryptedPassword = PasswordManager.CreateHash(userDto.Password); IUserBo userBo = new UserBo(); if (userBo.Save(userDto.Username, encryptedPassword, userDto.Email, userDto.DomainId, userDto.RoleId)) { var verCode = AccountVerification.GenerateVerificationCode(); if (userBo.SaveVerificationCode(verCode, userDto.Username)) { try { EmailManager.SendEmail(userDto.Email, AccountVerification.SignUpConfirmationSubject, AccountVerification.GetVerificationMessage(verCode)); } catch (Exception exception) { var message = new HttpResponseMessage(HttpStatusCode.ServiceUnavailable) { Content = new StringContent("Error Sending Verification Email") }; Logger.Error("API LAYER: ERROR IN CLASS: UserController, METHOD: POST =>> EXCEPTION MESSAGE: " + exception.Message); throw new HttpResponseException(message); } } } } catch (Exception exception) { var message = new HttpResponseMessage(HttpStatusCode.ServiceUnavailable) { Content = new StringContent(exception.Message) }; Logger.Error("API LAYER: ERROR IN CLASS: UserController, METHOD: POST =>> EXCEPTION MESSAGE: " + exception.Message); throw new HttpResponseException(message); } } else { throw new HttpResponseException(HttpStatusCode.BadRequest); } }
public async Task OnPost_GivenValidModelStateAndCommandDoesNotExecute_ExpectRedirectToPageResultAndPrgStateSetToFailed() { var mediator = new Mock <IMediator>(); mediator.Setup(x => x.Send(It.IsAny <VerifyAccountAndSetPasswordCommand>(), It.IsAny <CancellationToken>())) .ReturnsAsync(ResultWithError.Fail(new ErrorData(ErrorCodes.SavingChanges))); var page = new AccountVerification(mediator.Object) { PageModel = new AccountVerification.Model(), }; var result = await page.OnPostAsync(); Assert.IsType <RedirectToPageResult>(result); Assert.Equal(PrgState.Failed, page.PrgState); }
public async Task OnPost_GivenValidModelStateAndCommandExecutes_ExpectRedirectToPageResultAndPrgStateSetToSuccess() { var mediator = new Mock <IMediator>(); mediator.Setup(x => x.Send(It.IsAny <VerifyAccountAndSetPasswordCommand>(), It.IsAny <CancellationToken>())) .ReturnsAsync(ResultWithError.Ok <ErrorData>); var page = new AccountVerification(mediator.Object) { PageModel = new AccountVerification.Model(), }; var result = await page.OnPostAsync(); Assert.IsType <RedirectToPageResult>(result); Assert.Equal(PrgState.Success, page.PrgState); }
public async Task OnPost_GivenInvalidModelState_ExpectRedirectToPageResult() { var mediator = new Mock <IMediator>(); var page = new AccountVerification(mediator.Object) { PageModel = new AccountVerification.Model { Token = "token", }, }; page.ModelState.AddModelError("Error", "Error"); var result = await page.OnPostAsync(); Assert.IsType <RedirectToPageResult>(result); }
public BaseResponse CheckVerificationCode(string email, string code) { User user = _userRepository.Get(t => t.Email == email).FirstOrDefault(); AccountVerification accountVerification = user.AccountVerifications.FirstOrDefault(t => t.VerificationCode == code); BaseResponse verificationResponse = new BaseResponse(); if (accountVerification == null) { user.IsVerified = false; verificationResponse.SetStatus(Constants.ResponseCode.FAILED); return(verificationResponse); } if (accountVerification.ExpireTime < DateTime.Now) { user.IsVerified = false; verificationResponse.SetStatus(Constants.ResponseCode.EXPIRED_CODE); return(verificationResponse); } user.IsVerified = true; try { if (_unitOfWork.SaveChanges() > 0) { verificationResponse.SetStatus(Constants.ResponseCode.SUCCESS); } else { verificationResponse.SetStatus(Constants.ResponseCode.SYSTEM_ERROR); } } catch (Exception ex) { //mongodb log at. verificationResponse.SetStatus(Constants.ResponseCode.SYSTEM_ERROR); } return(verificationResponse); }
public RegisterResponse UserRegistry(User user) { RegisterResponse registerResponse = new RegisterResponse(); try { if (_userRepository.Get(t => t.Email == user.Email).FirstOrDefault() != null) { registerResponse.SetStatus(Constants.ResponseCode.EMAIL_IN_USE); return(registerResponse); } string passwordNotHash = user.Password; user.Password = Cryptor.sha512encrypt(user.Password); //şifreleme //*** dikkat user repoya eklenmeden bağlı tablolarına veri eklenirse bu tabloların takibi sağlamaz //kullanıcıyı olusturtur depoya ekle sonra bağlı tablolarını ekle _userRepository.Add(user); if (user.SocialInfos.Count != 0) { user.SocialInfos.Add(user.SocialInfos.FirstOrDefault()); } //default olarak her kullanıcı 1 enduser rolune sahip olmalı user.UserRoles.Add(new UserRole { RoleID = (int)Constants.UserRole.EndUserRole }); AccountVerification accountVerification = new AccountVerification(); if (user.SocialInfos.Count == 0) { accountVerification = CreateAccountVerificationCode(); user.AccountVerifications.Add(accountVerification); } if (_unitOfWork.SaveChanges() > 0) { if (!user.IsVerified) { MailRequest mailRequest = new MailRequest { ToMail = user.Email, ToName = user.FullName(), Subject = "B-Commerce E-Mail Onayı", Body = $"Merhaba {user.FullName()}\n Email onaylama kodunuz: {accountVerification.VerificationCode}", ProjectCode = "123456" }; HttpClient httpClient = new HttpClient(); httpClient.BaseAddress = new Uri(Constants.NOTIFICATION_API_BASE_URI); Task <HttpResponseMessage> httpResponse = httpClient.PostAsJsonAsync(Constants.NOTIFICATION_API_MAIL_URI, mailRequest); if (!httpResponse.Result.IsSuccessStatusCode) { registerResponse.SetStatus(Constants.ResponseCode.FAILED); return(registerResponse); } } registerResponse.SetStatus(Constants.ResponseCode.SUCCESS); registerResponse.Username = user.Username; registerResponse.Email = user.Email; } } catch (Exception ex) { registerResponse.SetStatus(Constants.ResponseCode.SYSTEM_ERROR); } return(registerResponse); }
public static EntityMock<AccountVerification> CreateValidAccountVerification() { var accountVerification = new AccountVerification() { Id = "id", Usage = "usage", Amount = 1, Currency = Iso4217CurrencyCodes.USD, RemoteIp = "255.10.100.10", CardHolder = "card holder", ExpirationMonth = 1, ExpirationYear = 2025, CustomerEmail = "*****@*****.**", CustomerPhone = "phone number", CardNumber = CardsNumbers.Visa3dSecureEnrolled, Cvv = "123", BillingAddress = new Address() { Address1 = "billing address1", Address2 = "billing address2", City = "billing city", Country = Iso3166CountryCodes.BG, FirstName = "billing first name", LastName = "billing last name", State = "BS", ZipCode = "1000" }, ShippingAddress = new Address() { Address1 = "shipping address1", Address2 = "shipping address2", City = "shipping city", Country = Iso3166CountryCodes.BG, FirstName = "shipping first name", LastName = "shipping last name", State = "BS", ZipCode = "1000" }, RiskParams = new RiskParams() { Email = "*****@*****.**", MacAddress = "mac address", Phone = "phone", RemoteIp = "255.10.100.10", SerialNumber = "serial number", SessionId = "session id", Ssn = "ssn", UserId = "user id", UserLevel = "user level" } }; var xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<payment_transaction xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"AccountVerification\">" + "<transaction_type>account_verification</transaction_type>" + "<transaction_id>id</transaction_id>" + "<usage>usage</usage>" + "<amount>100</amount>" + "<currency>USD</currency>" + "<remote_ip>255.10.100.10</remote_ip>" + "<card_holder>card holder</card_holder>" + "<expiration_month>01</expiration_month>" + "<expiration_year>2025</expiration_year>" + "<customer_email>[email protected]</customer_email>" + "<customer_phone>phone number</customer_phone>" + "<card_number>4711100000000000</card_number>" + "<cvv>123</cvv>" + "<billing_address>" + "<first_name>billing first name</first_name>" + "<last_name>billing last name</last_name>" + "<address1>billing address1</address1>" + "<address2>billing address2</address2>" + "<zip_code>1000</zip_code>" + "<city>billing city</city>" + "<state>BS</state>" + "<country>BG</country>" + "</billing_address>" + "<shipping_address>" + "<first_name>shipping first name</first_name>" + "<last_name>shipping last name</last_name>" + "<address1>shipping address1</address1>" + "<address2>shipping address2</address2>" + "<zip_code>1000</zip_code>" + "<city>shipping city</city>" + "<state>BS</state>" + "<country>BG</country>" + "</shipping_address>" + "<risk_params>" + "<ssn>ssn</ssn>" + "<mac_address>mac address</mac_address>" + "<session_id>session id</session_id>" + "<user_id>user id</user_id>" + "<user_level>user level</user_level>" + "<email>[email protected]</email>" + "<phone>phone</phone>" + "<remote_ip>255.10.100.10</remote_ip>" + "<serial_number>serial number</serial_number>" + "</risk_params>" + "</payment_transaction>"; return new EntityMock<AccountVerification>(accountVerification, xml); }