public async void ResendCodeAsync([Bind(Include = "Code, Email")] ConfirmationCode cc) { if (ModelState.IsValid) { await EmailSender.Activate(cc.Email, cc.Code, "Reset your password"); } }
public async Task <ActionResult> SignUpAsync([Bind(Include = "Email, Pass")] User user) { if (ModelState.IsValid) { IUserRepo ur = new UserRepo(); if (!ur.CheckUserByEmail(user.Email) && Constants.ZXCVBN(user.Pass) > 1) { ur.AddUser(new User(user.Email, user.Pass)); IConfirmationCodeRepo cr = new ConfirmationCodeRepo(); ConfirmationCode cc; if (!cr.CheckConfirmationCodeByEmail(user.Email)) { cc = new ConfirmationCode(user.Email, false); cr.AddConfirmationCode(cc); await EmailSender.Activate(user.Email, cc.Code, "Activate your account"); } else { cc = cr.GetConfirmationCode(user.Email); } return(View("~/Views/User/ConfirmEmail.cshtml", cc)); } else { return(View("~/Views/Home/SignUp.cshtml")); } } else { return(View("~/Views/Home/SignUp.cshtml")); } }
/// <summary> /// Create a confirmation code /// </summary> /// <param name="input">The code input</param> /// <returns></returns> public Task <ConfirmationCode> Create(ConfirmationCode input) { // generate id if necessary input.Id ??= StdIdGenerator.Next(IdentityObjects.CNF)?.ToLowerInvariant(); return(this.dataOps.Connect().QueryFirst("Confirmation", "Create").ExecuteAsync <ConfirmationCode>(input)); }
public string PasswordConfirmation(AccountDto dto) { string code = ConfirmationCode.RandomString(); _mailService.SendPasswordUpdateConfirmation(dto.email, dto.firstName + " " + dto.lastName, code); return(code); }
public bool AddConfirmationCode(ConfirmationCode cc) { int conv; if (cc.IsPasswordReset) { conv = 1; } else { conv = 0; } string query = "insert into confirmationcode(code, email, ispasswordreset) values (@code, @email, @ispasswordreset)"; using (MySqlConnection connection = new MySqlConnection(Constants.Conn)) { MySqlCommand command = new MySqlCommand(query, connection); command.Parameters.AddWithValue("@code", cc.Code); command.Parameters.AddWithValue("@email", cc.Email); command.Parameters.AddWithValue("@ispasswordreset", conv); try { connection.Open(); command.ExecuteNonQuery(); } catch (Exception ex) { Console.WriteLine(ex.Message); return(false); } } return(true); }
/// <summary> /// Send the confirmation code /// </summary> /// <param name="confirmation">The confirmation object</param> /// <param name="code">The code to send</param> /// <returns></returns> private async Task <bool> SendConfirmationCode(ConfirmationCode confirmation, string code) { // stringify the creation time and make sha512 code var proof = confirmation.Created.ToString("O").ToSafeSha512(); // build confirmation URL var fullUrl = $"{selfSettings.ExternalBaseAddress}api-auth/email-confirmation/{confirmation.Link}/crypto-proof/{proof}"; // set of messages for format the email var messages = new Dictionary <string, string> { { "confirmation_url", fullUrl }, { "confirmation_code", code } }; // format template into final message var content = messages.Aggregate(CONFIRMATION_TEMPLATE, (current, message) => current.Replace($"{{{message.Key}}}", message.Value)); // send email and get result var result = await this.emailSender.SendAsync(new EmailMessage { Subject = "Please confirm your email!", To = new List <string> { confirmation.Email }, Body = content, Resources = new List <ContentResource>() }); // return result return(result.Sent); }
public async Task <string> Execute(string phoneNumber) { if (string.IsNullOrWhiteSpace(phoneNumber)) { throw new ArgumentNullException(nameof(phoneNumber)); } var confirmationCode = new ConfirmationCode { Value = await GetCode(), IssueAt = DateTime.UtcNow, ExpiresIn = 300, Subject = phoneNumber }; var message = string.Format(_smsAuthenticationOptions.Message, confirmationCode.Value); try { await _twilioClient.SendMessage(_smsAuthenticationOptions.TwilioSmsCredentials, phoneNumber, message); } catch (Exception ex) { _eventSource.Failure(ex); throw new IdentityServerException(ErrorCodes.UnhandledExceptionCode, "the twilio account is not properly configured"); } if (!await _confirmationCodeStore.Add(confirmationCode)) { throw new IdentityServerException(ErrorCodes.UnhandledExceptionCode, ErrorDescriptions.TheConfirmationCodeCannotBeSaved); } _eventSource.GetConfirmationCode(confirmationCode.Value); return(confirmationCode.Value); }
public void CreateBooking(CreateBookingDto createBooking) { try { VehicleBooking vehicle = _mapper.Map <VehicleBooking>(createBooking.vehicleBooking); vehicle.confirmationCode = ConfirmationCode.RandomString(); _repositoryFactory.VehicleBookingRepository.Create(vehicle); SendMail(vehicle); _logger.LogInformation("Vehicle booking created"); List <EquipmentBooking> equipmentBookings = _mapper.Map <List <EquipmentBooking> >(createBooking.equipmentBookings); foreach (var e in equipmentBookings) { e.vehicleBookingId = vehicle.id; } _repositoryFactory.EquipmentBookingRepository.CreateEquipmentBooking(equipmentBookings); _logger.LogInformation("Equipment booking created"); } catch (Exception ex) { _logger.LogWarning(ex.Message); throw ex; } }
/// <inheritdoc /> public async Task <bool> Add(ConfirmationCode confirmationCode, CancellationToken cancellationToken) { await using var session = _sessionFactory(); session.Store(confirmationCode); await session.SaveChangesAsync(cancellationToken).ConfigureAwait(false); return(true); }
public async Task <ConfirnmationResponse> ConfirmEmailAsync(ConfirnmationRequest request) { try { var confirmCode = ConfirmationCode.Generate(); var sent = await SendAndStoreConfirmationCode(confirmCode, request.Email); if (!sent) { return new ConfirnmationResponse { Status = new APIResponseStatus { IsSuccessful = false, Message = new APIResponseMessage { FriendlyMessage = "Unable to send mail!! please contact systems administrator" } } } } ; return(new ConfirnmationResponse { Status = new APIResponseStatus { IsSuccessful = true, Message = new APIResponseMessage { FriendlyMessage = "Please Check your email for email for confirnmation" } } }); } catch (Exception ex) { #region Log error var errorCode = ErrorID.Generate(4); _logger.Error($"ErrorID : {errorCode} Ex : {ex?.Message ?? ex?.InnerException?.Message} ErrorStack : {ex?.StackTrace}"); return(new ConfirnmationResponse { Status = new APIResponseStatus { IsSuccessful = false, Message = new APIResponseMessage { FriendlyMessage = "Error occured!! Please tyr again later", MessageId = errorCode, TechnicalMessage = $"ErrorID : {errorCode} Ex : {ex?.Message ?? ex?.InnerException?.Message} ErrorStack : {ex?.StackTrace}" } } }); #endregion } }
public Task <bool> Add(ConfirmationCode confirmationCode, CancellationToken cancellationToken) { if (confirmationCode == null) { throw new ArgumentNullException(nameof(confirmationCode)); } _confirmationCodes.Add(confirmationCode); return(Task.FromResult(true)); }
private ConfirmationCode RegisterConfirmationCode(int userId, string code) { CancelAllConfirmationCodes(userId); var codeDomain = new ConfirmationCode(); codeDomain.Code = code; codeDomain.CreationDate = DateTime.UtcNow; codeDomain.UserId = userId; _raterPriceContext.ConfirmationCodes.Add(codeDomain); _raterPriceContext.SaveChanges(); return(codeDomain); }
public async Task <IActionResult> ResetPassword([FromBody] string code, bool verify) { var confirmationCode = await _db.ConfirmationCodes.FirstOrDefaultAsync(ConfirmationCode.CanBeUsed(code, ConfirmationCode.Types.PasswordReset)); if (confirmationCode == null) { return(NotFound()); } return(Ok()); }
public async Task When_Code_Is_Not_Expired_Then_True_Is_Returned() { var confirmationCode = new ConfirmationCode { ExpiresIn = 200, IssueAt = DateTimeOffset.UtcNow }; _confirmationCodeStoreStub .Setup(c => c.Get(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <CancellationToken>())) .ReturnsAsync(confirmationCode); var result = await _validateConfirmationCodeAction.Execute("code", "test", CancellationToken.None) .ConfigureAwait(false); Assert.True(result); }
public async Task <ActionResult> SubmitEmailAsync([Bind(Include = "Email")] ConfirmationCode em) { if (ModelState.IsValid) { IUserRepo ur = new UserRepo(); if (ur.CheckUserByEmail(em.Email)) { IConfirmationCodeRepo cr = new ConfirmationCodeRepo(); ConfirmationCode cc = new ConfirmationCode(em.Email, true); cr.AddConfirmationCode(cc); await EmailSender.Activate(em.Email, cc.Code, "Reset your password"); } } return(View("~/Views/Home/ConfirmPasswordReset.cshtml", em)); }
public ActionResult SubmitCode([Bind(Include = "Code, Email")] ConfirmationCode en) { IUserRepo ur = new UserRepo(); IConfirmationCodeRepo cr = new ConfirmationCodeRepo(); ConfirmationCode cc = cr.GetConfirmationCode(en.Email); if (!cc.IsPasswordReset && en.Code.Equals(cc.Code)) { User u = ur.GetUserByEmail(en.Email); u.IsConfirmed = true; ur.UpdateUser(u); cr.DeleteConfirmationCode(en.Email); return(View("~/Views/Home/LogIn.cshtml")); } return(View()); }
public ConfirmationCode GenerateCode(ConfirmationCodeType type) { const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; var generator = new Generator(); var value = generator.GenerateString(chars); var experationDate = DateTime.Now.AddHours(12); var confirmationCode = new ConfirmationCode(); confirmationCode.ExpirationDate = experationDate; confirmationCode.Value = value; confirmationCode.IsActive = true; confirmationCode.Type = type; return(confirmationCode); }
public ActionResult SubmitCode([Bind(Include = "Code, Email")] ConfirmationCode en) { if (ModelState.IsValid) { IUserRepo ur = new UserRepo(); IConfirmationCodeRepo cr = new ConfirmationCodeRepo(); ConfirmationCode cc = cr.GetConfirmationCode(en.Email); if (cc.IsPasswordReset && en.Code.Equals(cc.Code)) { User u = ur.GetUserByEmail(en.Email); cr.DeleteConfirmationCode(en.Email); return(View("~/Views/Home/ResetPassword.cshtml", u)); } return(View("~/Views/Home/ConfirmPasswordReset.cshtml", en)); } return(View("~/Views/Home/ConfirmPasswordReset.cshtml", en)); }
public void ValidateCode(ConfirmationCode code) { if (code == null) { throw new CodeIsNotExistException("Code is not exist"); } if (!code.IsActive) { throw new CodeIsNotActiveException("Code is not active."); } if (DateTime.Now.Subtract(code.ExpirationDate.DateTime).Seconds > 0) { throw new CodeExpirationDateIsUpException("Code's Experation Date is up."); } }
public async Task <string> ExecuteAsync(string subject) { if (string.IsNullOrWhiteSpace(subject)) { throw new ArgumentNullException(nameof(subject)); } var resourceOwner = await _resourceOwnerRepository.GetAsync(subject); if (resourceOwner == null) { throw new IdentityServerException(ErrorCodes.UnhandledExceptionCode, ErrorDescriptions.TheRoDoesntExist); } if (string.IsNullOrWhiteSpace(resourceOwner.TwoFactorAuthentication)) { throw new IdentityServerException( ErrorCodes.UnhandledExceptionCode, ErrorDescriptions.TwoFactorAuthenticationIsNotEnabled); } var confirmationCode = new ConfirmationCode { Value = await GetCode(), IssueAt = DateTime.UtcNow, ExpiresIn = 300 }; var service = _twoFactorAuthenticationHandler.Get(resourceOwner.TwoFactorAuthentication); if (!resourceOwner.Claims.Any(c => c.Type == service.RequiredClaim)) { throw new ClaimRequiredException(service.RequiredClaim); } if (!await _confirmationCodeStore.Add(confirmationCode)) { throw new IdentityServerException(ErrorCodes.UnhandledExceptionCode, ErrorDescriptions.TheConfirmationCodeCannotBeSaved); } await _twoFactorAuthenticationHandler.SendCode(confirmationCode.Value, resourceOwner.TwoFactorAuthentication, resourceOwner); return(confirmationCode.Value); }
public async Task When_Code_Is_Not_Expired_Then_True_Is_Returned() { // ARRANGE var confirmationCode = new ConfirmationCode { ExpiresIn = 200, CreateDateTime = DateTime.UtcNow }; InitializeFakeObjects(); _confirmationCodeRepositoryStub.Setup(c => c.GetAsync(It.IsAny <string>())) .Returns(Task.FromResult(confirmationCode)); // ACT var result = await _validateConfirmationCodeAction.Execute("code"); // ASSERT Assert.True(result); }
public async Task When_Code_Is_Expired_Then_False_Is_Returned() { // ARRANGE var confirmationCode = new ConfirmationCode { ExpiresIn = 10, IssueAt = DateTime.UtcNow.AddDays(-2) }; InitializeFakeObjects(); _confirmationCodeStoreStub.Setup(c => c.Get(It.IsAny <string>())) .Returns(Task.FromResult(confirmationCode)); // ACT var result = await _validateConfirmationCodeAction.Execute("code"); // ASSERT Assert.False(result); }
public async Task SendEmailConfirmationAsync(User user) { var confirmationCode = new ConfirmationCode { UserId = user.Id, Type = ConfirmationCode.Types.EmailConfirmation }; await _db.ConfirmationCodes.AddAsync(confirmationCode); await _db.SaveChangesAsync(); var resource = CultureResources.EmailConfirmation(_userService.Culture); _ = _emailService.SendEmailAsync(user.Email, resource["subject"], GenerateMessageWithCode(beforeCode: resource["body_before_code"], code: confirmationCode.Code, afterCode: resource["body_after_code"])); }
public async Task <string> ExecuteAsync(string subject) { if (string.IsNullOrWhiteSpace(subject)) { throw new ArgumentNullException(nameof(subject)); } var resourceOwner = await _authenticateResourceOwnerService.AuthenticateResourceOwnerAsync(subject); if (resourceOwner == null) { throw new IdentityServerException( ErrorCodes.UnhandledExceptionCode, ErrorDescriptions.TheRoDoesntExist); } if (resourceOwner.TwoFactorAuthentication == TwoFactorAuthentications.NONE) { throw new IdentityServerException( ErrorCodes.UnhandledExceptionCode, ErrorDescriptions.TwoFactorAuthenticationIsNotEnabled); } var confirmationCode = new ConfirmationCode { Code = await GetCode(), CreateDateTime = DateTime.UtcNow, ExpiresIn = 300, IsConfirmed = false }; if (!await _confirmationCodeRepository.AddAsync(confirmationCode)) { throw new IdentityServerException( ErrorCodes.UnhandledExceptionCode, ErrorDescriptions.TheConfirmationCodeCannotBeSaved); } await _twoFactorAuthenticationHandler.SendCode(confirmationCode.Code, (int)resourceOwner.TwoFactorAuthentication, resourceOwner); return(confirmationCode.Code); }
public ActionResult LogIn([Bind(Include = "Email, Pass")] User user) { var response = Request["g-recaptcha-response"]; string secretKey = Constants.captchaSecret; var client = new WebClient(); var result = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secretKey, response)); var obj = JObject.Parse(result); var status = (bool)obj.SelectToken("success"); if (ModelState.IsValid && status) { IUserRepo ur = new UserRepo(); if (ur.CheckUserByEmail(user.Email)) { if (!ur.GetUserByEmail(user.Email).IsConfirmed) { IConfirmationCodeRepo cr = new ConfirmationCodeRepo(); ConfirmationCode cc = cr.GetConfirmationCode(user.Email); return(View("~/Views/User/ConfirmEmail.cshtml", cc)); } else { User u = ur.GetUserByEmail(user.Email); bool success = user.AuthUser(ur.GetUserByEmail(user.Email), user.Pass); if (success) { Session.Add("CurrentUser", u); return(RedirectToAction("Landing", "User")); } else { return(View("~/Views/Home/LogIn.cshtml")); } } } return(View("~/Views/Home/SignUp.cshtml")); } else { return(View("~/Views/Home/LogIn.cshtml")); } }
public async Task <bool> AddAsync(ConfirmationCode code) { using (var transaction = _context.Database.BeginTransaction()) { try { var record = code.ToModel(); _context.ConfirmationCodes.Add(record); await _context.SaveChangesAsync().ConfigureAwait(false);; transaction.Commit(); return(true); } catch (Exception ex) { transaction.Rollback(); _managerEventSource.Failure(ex); return(false); } } }
public async Task <IActionResult> ResetPassword([FromBody] UserModels.PasswordReset model) { var confirmationCode = await _db.ConfirmationCodes.FirstOrDefaultAsync(ConfirmationCode.CanBeUsed(model.Code, ConfirmationCode.Types.PasswordReset)); if (confirmationCode == null) { return(BadRequest()); } confirmationCode.IsConfirmed = true; var user = confirmationCode.User; user.Password = _userService.HashPassword(user, model.Password); await _db.SaveChangesAsync(); return(Ok()); }
public async Task When_Using_Password_Grant_Type_With_SMS_Then_Access_Token_Is_Returned() { // ARRANGE InitializeFakeObjects(); _httpClientFactoryStub.Setup(h => h.GetHttpClient()).Returns(_server.Client); _smsHttpClientFactoryStub.Setup(h => h.GetHttpClient()).Returns(_server.Client); // ACT ConfirmationCode confirmationCode = new ConfirmationCode(); _server.SharedCtx.ConfirmationCodeStore.Setup(c => c.Get(It.IsAny <string>())).Returns(() => { return(Task.FromResult((ConfirmationCode)null)); }); _server.SharedCtx.ConfirmationCodeStore.Setup(h => h.Add(It.IsAny <ConfirmationCode>())).Callback <ConfirmationCode>(r => { confirmationCode = r; }).Returns(() => { return(Task.FromResult(true)); }); await _sidSmsAuthenticateClient.Send(baseUrl, new Authenticate.SMS.Common.Requests.ConfirmationCodeRequest { PhoneNumber = "phone" }); _server.SharedCtx.ConfirmationCodeStore.Setup(c => c.Get(It.IsAny <string>())).Returns(Task.FromResult(confirmationCode)); var result = await _clientAuthSelector.UseClientSecretPostAuth("client", "client") .UsePassword("phone", confirmationCode.Value, new List <string> { "sms" }, new List <string> { "scim" }) .ResolveAsync(baseUrl + "/.well-known/openid-configuration"); // ASSERTS Assert.NotNull(result); Assert.False(result.ContainsError); Assert.NotEmpty(result.Content.AccessToken); }
public ConfirmationCode GetConfirmationCode(string email) { string query = "select * from confirmationcode where email = @email"; using (MySqlConnection connection = new MySqlConnection(Constants.Conn)) { MySqlCommand command = new MySqlCommand(query, connection); command.Parameters.AddWithValue("@email", email); try { connection.Open(); var read = command.ExecuteReader(); ConfirmationCode cc = new ConfirmationCode(); read.GetOrdinal("code"); read.GetOrdinal("email"); read.GetOrdinal("ispasswordreset"); read.GetOrdinal("date"); while (read.Read()) { cc.Code = read.GetString("code"); cc.Email = read.GetString("email"); cc.IsPasswordReset = Convert.ToBoolean(read.GetInt16("ispasswordreset")); cc.Date = read.GetDateTime("date"); } return(cc); } catch (Exception ex) { Console.WriteLine(ex.Message); return(null); } } }
public ConfirmationCode SendPassword(string Email, SendPassword Source) { _Connection.Sheet = "Fundraisers"; string to = Email; string from = "f"; //From address ConfirmationCode cd = new ConfirmationCode(); try { MailMessage message = new MailMessage(from, to); message.BodyEncoding = Encoding.UTF8; message.IsBodyHtml = true; string mailbody; SmtpClient client = new SmtpClient("smtp.gmail.com", 587); //Gmail smtp System.Net.NetworkCredential basicCredential1 = new System.Net.NetworkCredential(); client.EnableSsl = true; client.UseDefaultCredentials = false; client.Credentials = basicCredential1; switch (Source) { case Entities.SendPassword.ForgotPassword: var range = $"{_Connection.Sheet}!A:AP"; SpreadsheetsResource.ValuesResource.GetRequest request = _Connection.Service.Spreadsheets.Values.Get(_Connection.SpreadsheetId, range); var response = request.Execute(); IList <IList <object> > values = response.Values; if (values != null && values.Count > 0) { foreach (var row in values) { if (row.Count != 0) { if (row[8].ToString().ToLower() == Email.ToLower()) { mailbody = "Your password is: " + row[2].ToString(); message.Subject = "Your Password"; message.Body = mailbody; try { client.Send(message); cd.EmailStatus = Status.EmailSent; return(cd); } catch { cd.EmailStatus = Status.ProblemSending; return(cd); } } } } } cd.EmailStatus = Status.EmailNotFound; return(cd); case Entities.SendPassword.NewMember: Random rnd = new Random(); int length = 10; string rndPassword = ""; for (var i = 0; i < length; i++) { rndPassword += ((char)(rnd.Next(1, 26) + 64)).ToString(); } mailbody = "Your Confirmation Code is: " + rndPassword; message.Subject = "Confirmation Code"; message.Body = mailbody; try { client.Send(message); cd.EmailStatus = Status.EmailSent; cd.Code = rndPassword; return(cd); } catch { cd.EmailStatus = Status.ProblemSending; return(cd); } default: return(null); } } catch { cd.EmailStatus = Status.IncorrectFormat; return(cd); } }