//[ValidateAntiForgeryToken] public async Task <ActionResult> Register(RegisterViewModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState.ValidationState)); } var isExist = this.myContext.Users.Where(Q => Q.Email == model.Email).Any(); if (isExist) { return(BadRequest("Email Already Registered !")); } var hashedPassword = BCrypt.Net.BCrypt.HashPassword(model.Password, 12); var role = this.myContext.Roles.Where(Q => Q.Name == "SALES").FirstOrDefault(); if (role == null) { return(BadRequest("Default Role Data Not Exist !")); } var userId = Guid.NewGuid().ToString(); var rand = new Random(); var emailRandomCode = rand.Next(0, 9999).ToString("D4"); sendEmailService.SendEmail(model.Email, emailRandomCode); User user = new User() { Id = model.Id, UserName = model.Email, Email = model.Email, NormalizedEmail = model.Email.ToUpper(), SecurityStamp = emailRandomCode, EmailConfirmed = false, PasswordHash = hashedPassword, PhoneNumber = null, PhoneNumberConfirmed = false, TwoFactorEnabled = false, LockoutEnabled = false, AccessFailedCount = 0 }; UserRole userRole = new UserRole() { UserId = model.Id, RoleId = role.Id }; this.myContext.Users.Add(user); this.myContext.UserRoles.Add(userRole); var result = await this.myContext.SaveChangesAsync(); if (result == 0) { return(BadRequest("Server Error !")); } return(Ok("Successfully Created")); }
/// <summary>This method should send the message</summary> /// <param name="message"></param> /// <returns></returns> public Task SendAsync(IdentityMessage message) { // Plug in your email service here to send an email. var emailService = new SendEmailService(); emailService.SendEmail(message); return(Task.FromResult(0)); }
public async Task <IActionResult> ResetPasswordConfirmationPage(ResetPasswordModel model) { if (model != null) { var user = await UserManager.FindByEmailAsync(model.EmailAddress); if (user != null) { if (user.EmailConfirmed) { var token = await UserManager.GeneratePasswordResetTokenAsync(user); var url = Url.Action("ResetPassword", "Account", new { UserId = user.Id, Token = token }, Request.Scheme); await SendEmailService.SendEmail(new ServiceEmail { EmailHtmlText = $"<strong>Hello, {user.UserName}, here is your password reset link - {url}</strong>", EmailSubject = "Password reset", EmailText = $"Hello, {user.UserName}, here is your password reset link - {url}", FromEmail = "*****@*****.**", FromName = "Yevhen", ToEmail = user.Email, ToName = user.UserName }); Trace.WriteLine($"Email was send to customer {user.Id} - id"); } else { ModelState.AddModelError("", DefaultResponseMessages.EmailIsNotVerified); Trace.WriteLine($"Email was not verified for customer {user.Id} - id"); } } else { ModelState.AddModelError("", DefaultResponseMessages.CustomerIsNotFoundInDb); Trace.WriteLine($"Wrong login attempt for email {model.EmailAddress}"); } return(View("ResetPasswordConfirmationPage", model.EmailAddress)); } else { ModelState.AddModelError("", DefaultResponseMessages.EmailIsNotProvided); } return(View()); }
public IActionResult Create(Temperature temperature) { var employee = _context.Employees.Include("User").SingleOrDefault(x => x.EmployeeId == temperature.EmployeeId); var suhu = temperature.EmployeeTemperature; var suhus = Convert.ToDouble(suhu); if (suhus >= 37.3) { _sendEmailService.SendEmail(employee.User.Email, suhus, employee); } temperature.Date = DateTimeOffset.Now; _context.Temperatures.Add(temperature); _context.SaveChanges(); return(Ok("Data Created Successfully")); }
public async Task <BookLogForCreateUpdateReturnModel> BookLog_Set(BookLogForCreateModel model, string uri) { var result = await _repo.BookLog_Set(model); var emailRecipients = await _emails.EmailRecipientList_Get(); if (result != null) { if (model.BookingTypeID == 3) { if (model.AmenityID == 3 || model.AmenityID == 4) { foreach (var recipient in emailRecipients) { result.Recipient = recipient; await _send.SendEmail(_send.BookLogForEmailParam(result, "Add-Admin-Booking-Template", uri, true)); } await _send.SendEmail(_send.BookLogForEmailParam(result, "Confirm-Booking-Conference-Template", uri, false)); } else { foreach (var recipient in emailRecipients) { result.Recipient = recipient; await _send.SendEmail(_send.BookLogForEmailParam(result, "Add-Admin-Booking-Template", uri, true)); } await _send.SendEmail(_send.BookLogForEmailParam(result, "Confirm-Booking-Template", uri, false)); } } } var modelForReturn = _mapper.Map <BookLogForCreateUpdateReturnModel>(result); return(modelForReturn); }
public Result SendEmail(MailAddress from, List <MailAddress> lTo, string subject, string body, IEnumerable <Attachment> lAttachFiles, bool isHtml = true) { try { if (from == null || string.IsNullOrEmpty(from.Address)) { from = new MailAddress(ConfigurationManager.AppSettings["RMS.KTB.SMTP.From"]); } if (string.IsNullOrEmpty(from.Address)) { throw new ArgumentNullException("from", "Please check database and Web.config > appSettings > RMS.KTB.SMTP.From "); } if (isHtml) { body = body.Replace(Environment.NewLine, "<br/>"); } var emailService = new SendEmailService(); var result = emailService.SendEmail(@from, lTo, subject, body, lAttachFiles, isHtml); if (result.IsSuccess) { return(new Result { IsSuccess = true }); } else { return(new Result { IsSuccess = false, ErrorMessage = result.ErrorMessage }); } } catch (Exception ex) { return(new Result { IsSuccess = false, ErrorMessage = ex.Message }); } }
public async Task <string> Register(RegisterVM registerVM) { var isEmailExist = await _myContext.Users.Where(Q => Q.Email == registerVM.Email).AnyAsync(); if (isEmailExist) { return("Email Already Registered !"); } var isPhoneNumberExist = await _myContext.Users.Where(Q => Q.PhoneNumber == registerVM.PhoneNumber).AnyAsync(); if (isPhoneNumberExist) { return("Phone Number Already Registered !"); } var isUserNameExist = await _myContext.Users.Where(Q => Q.UserName == registerVM.UserName).AnyAsync(); if (isUserNameExist) { return("User Name Already Registered !"); } var hashedPassword = BCrypt.Net.BCrypt.HashPassword(registerVM.Password, 12); var role = _myContext.Roles.Where(Q => Q.Name == "EMPLOYEE").FirstOrDefault(); if (role == null) { return("Default Role Data Not Exist !"); } var division = _myContext.Divisions.Where(Q => Q.Name == "NOT PLACED YET").FirstOrDefault(); if (division == null) { return("Default Division Data Not Exist !"); } var userId = Guid.NewGuid().ToString(); var rand = new Random(); var emailRandomCode = rand.Next(0, 9999).ToString("D4"); _sendEmailService.SendEmail(registerVM.Email, emailRandomCode); Employee employee = new Employee() { EmployeeId = userId, FirstName = registerVM.FirstName, LastName = registerVM.LastName, IsActive = true, PhoneNumber = registerVM.PhoneNumber, Salary = 0, DivisionId = division.Id }; User user = new User() { Id = userId, UserName = registerVM.UserName, Email = registerVM.Email, NormalizedEmail = registerVM.Email.ToUpper(), SecurityStamp = emailRandomCode, EmailConfirmed = false, PasswordHash = hashedPassword, PhoneNumber = registerVM.PhoneNumber, PhoneNumberConfirmed = false, TwoFactorEnabled = false, LockoutEnabled = false, AccessFailedCount = 0 }; UserRole userRole = new UserRole() { UserId = userId, RoleId = role.Id }; _myContext.Employees.Add(employee); _myContext.Users.Add(user); _myContext.UserRoles.Add(userRole); var result = await _myContext.SaveChangesAsync(); if (result == 0) { return("Server Error !"); } return(null); }
/// <summary> /// Method to perform customer registration in case, that he provided correct data to us /// </summary> /// <returns></returns> public async Task <DefaultServiceResponse> CompleteRegistration(CustomerViewModel customer) { var responseCheckData = new DefaultServiceResponse { ActionName = "Index", ControllerName = "HomePage", ResponseData = null, StatusCode = StatusCodesEnum.BadDataProvided, ValidationErrors = new List <string>() }; var userSearchResult = await UserManager.FindByEmailAsync(customer.EmailAddress); if (userSearchResult == null) // customer has no data in our DB --> he can be registered { var user = new ServiceUser { Email = customer.EmailAddress, UserName = customer.FirstName }; var result = await UserManager.CreateAsync(user, customer.Password); if (result.Succeeded) // errors will be displayed on validation-summary { Logger.LogInformation($"Customer created, account data - {user.Email} - email, {user.UserName} - username"); if (CheckIfWeHaveRole("User")) { await UserManager.AddToRoleAsync(user, "User"); } else { await RoleManager.CreateAsync(new IdentityRole { Id = new Guid().ToString(), Name = "User" }); await UserManager.AddToRoleAsync(user, "User"); } Logger.LogInformation($"Roles added for the user - {user.UserName}"); var currentUser = await UserManager.FindByEmailAsync(user.Email); var claims = CustomerContext.UserClaims.Select(x => x).ToList(); var newClaimId = claims.Count > 0 ? claims.Last().Id + 1 : 1; CustomerContext.UserClaims.Add(new IdentityUserClaim <string> { Id = newClaimId, ClaimType = "UploadPhoto", ClaimValue = "true", UserId = currentUser.Id }); await CustomerContext.SaveChangesAsync(); Logger.LogInformation($"Claims added for the user - {user.UserName}"); var token = await UserManager.GenerateEmailConfirmationTokenAsync(currentUser); var emailUrlConfirmation = UrlHelper.Action("ConfirmEmail", "Account", new { Token = token, UserId = currentUser.Id }, Context.HttpContext.Request.Scheme); var response = await SendEmailService.SendEmail(new ServiceEmail //todo - add there logging to get the response about loggined customers { FromEmail = "*****@*****.**", FromName = "Yevhen", ToEmail = currentUser.Email, ToName = currentUser.UserName, EmailSubject = "Thank you for register!!!", EmailHtmlText = $"<strong>Hello there! Thank you for registering, please confirm your email using this link : {emailUrlConfirmation}</strong>", EmailText = $"Hello there! Thank you for registering, please confirm your email using this link : {emailUrlConfirmation}", }); responseCheckData.ResponseData = customer.FirstName; responseCheckData.ActionName = "ConfirmationPage"; responseCheckData.ControllerName = "Registration"; responseCheckData.StatusCode = StatusCodesEnum.RedirectNeeded; return(responseCheckData); } else { foreach (var error in result.Errors) { responseCheckData.ValidationErrors.Add(error.Description); } responseCheckData.StatusCode = StatusCodesEnum.BadDataProvided; return(responseCheckData); } } else { responseCheckData.ValidationErrors.Add(DefaultResponseMessages.AllreadyHasAccount); responseCheckData.StatusCode = StatusCodesEnum.BadDataProvided; return(responseCheckData); } }
/// <summary> /// Method to perform login of the external customer /// </summary> /// <param name="returnUrl"></param> /// <param name="remoteError"></param> /// <returns></returns> public async Task <DefaultServiceResponse> ExternalLoginCallBack(string returnUrl = null, string remoteError = null) { var loginCallBackResult = new DefaultServiceResponse { ActionName = "Index", ControllerName = "HomePage", ResponseData = null, StatusCode = StatusCodesEnum.Ok, ValidationErrors = new List <string>() }; if (remoteError == null) { var accountDetailsFromProvider = await SignInManager.GetExternalLoginInfoAsync(); #region Check, that data is provided if (accountDetailsFromProvider != null) { // Search for the customer in our db var accountData = await UserManager.FindByEmailAsync(accountDetailsFromProvider.Principal.FindFirstValue(ClaimTypes.Email)); #region New account for our DB if (accountData == null) // new account { var serviceUser = new ServiceUser { Email = accountDetailsFromProvider.Principal.FindFirstValue(ClaimTypes.Email), UserName = accountDetailsFromProvider.Principal.FindFirstValue(ClaimTypes.GivenName) }; var userResponse = await UserManager.CreateAsync(serviceUser); #region Customer created without any error --> send him email to verify email and add password ( or not ) if (userResponse.Succeeded) { if (CheckIfWeHaveRole("User")) { await UserManager.AddToRoleAsync(serviceUser, "User"); } else { await RoleManager.CreateAsync(new IdentityRole { Id = new Guid().ToString(), Name = "User", NormalizedName = "USER" }); await UserManager.AddToRoleAsync(serviceUser, "User"); } var claims = CustomerContext.UserClaims.Select(x => x).ToList(); var newClaimId = claims.Count > 0 ? claims.Last().Id + 1 : 1; CustomerContext.UserClaims.Add(new IdentityUserClaim <string> { Id = newClaimId, ClaimType = "UploadPhoto", ClaimValue = "true", UserId = serviceUser.Id }); await CustomerContext.SaveChangesAsync(); await UserManager.AddLoginAsync(serviceUser, accountDetailsFromProvider); // Creates point in AspNetUserLogins var token = await UserManager.GenerateEmailConfirmationTokenAsync(serviceUser); var emailUrlConfirmation = UrlHelper.Action("ConfirmEmail", "Account", new { Token = token, UserId = serviceUser.Id }, Context.HttpContext.Request.Scheme); await SendEmailService.SendEmail(new ServiceEmail { FromEmail = "*****@*****.**", FromName = "Yevhen", ToEmail = serviceUser.Email, ToName = serviceUser.UserName, EmailSubject = "Thank you for register!!!", EmailHtmlText = $"<strong>Hello, {serviceUser.UserName}! Thank you for registering, please confirm your email using this link : {emailUrlConfirmation}</strong>", EmailText = $"Hello there! Thank you for registering, please confirm your email using this link : {emailUrlConfirmation}", }); loginCallBackResult.ActionName = "ConfirmPartnerRegister"; loginCallBackResult.ControllerName = "Registration"; loginCallBackResult.ResponseData = serviceUser.UserName; loginCallBackResult.StatusCode = StatusCodesEnum.RedirectNeeded; return(loginCallBackResult); } #endregion else { loginCallBackResult.ValidationErrors.Add(DefaultResponseMessages.ExternalLoginFailed); loginCallBackResult.StatusCode = StatusCodesEnum.BadDataProvided; return(loginCallBackResult); } } #endregion else { #region Customer already has account on our db, but email is not confirmed if (!accountData.EmailConfirmed) { var loginsData = await UserManager.GetLoginsAsync(accountData); if (loginsData == null) { await UserManager.AddLoginAsync(accountData, accountDetailsFromProvider); } var token = await UserManager.GenerateEmailConfirmationTokenAsync(accountData); var emailUrlConfirmation = UrlHelper.Action("ConfirmEmail", "Account", new { Token = token, UserId = accountData.Id }, Context.HttpContext.Request.Scheme); await SendEmailService.SendEmail(new ServiceEmail { FromEmail = "*****@*****.**", FromName = "Yevhen", ToEmail = accountData.Email, ToName = accountData.UserName, EmailSubject = "Thank you for register!!!", EmailHtmlText = $"<strong>Hello, {accountData.UserName}! Thank you for registering, please confirm your email using this link : {emailUrlConfirmation}</strong>", EmailText = $"Hello there! Thank you for registering, please confirm your email using this link : {emailUrlConfirmation}", }); loginCallBackResult.StatusCode = StatusCodesEnum.RedirectNeeded; loginCallBackResult.ResponseData = accountData.UserName; loginCallBackResult.ActionName = "ConfirmPartnerRegister"; loginCallBackResult.ControllerName = "Registration"; return(loginCallBackResult); } #endregion #region Email is confirmed but we need to check, that customer has row in ASPNETUSERLOGINS else { var loginReponse = await SignInManager.ExternalLoginSignInAsync(accountDetailsFromProvider.LoginProvider, accountDetailsFromProvider.ProviderKey, false); if (loginReponse.Succeeded) { loginCallBackResult.StatusCode = StatusCodesEnum.Ok; } else { await UserManager.AddLoginAsync(accountData, accountDetailsFromProvider); await SignInManager.SignInAsync(accountData, false); } loginCallBackResult.ActionName = "Index"; loginCallBackResult.ControllerName = "HomePage"; return(loginCallBackResult); } #endregion } } #endregion #region No data provided from external provider else { loginCallBackResult.ValidationErrors.Add(DefaultResponseMessages.ExternalLoginFailed); loginCallBackResult.StatusCode = StatusCodesEnum.BadDataProvided; return(loginCallBackResult); } #endregion } #region Error from external provider else { loginCallBackResult.ValidationErrors.Add(DefaultResponseMessages.ExternalLoginFailed); loginCallBackResult.StatusCode = StatusCodesEnum.RedirectNeeded; loginCallBackResult.ActionName = "Login"; loginCallBackResult.ControllerName = "Account"; return(loginCallBackResult); } #endregion }