public async Task <IActionResult> Register(AddUserViewModel modelo) { if (ModelState.IsValid) { var role = "Owner"; if (modelo.RoleId == 1) { role = "Lessee"; } var user = await _userHelper.AddUser(modelo, role); if (user == null) { ModelState.AddModelError(string.Empty, "This email is already used."); return(View(modelo)); } if (modelo.RoleId == 1) { var lessee = new Lessee { Contracts = new List <Contract>(), User = user }; _dataContext.Lessees.Add(lessee); //await _dataContext.SaveChangesAsync(); } else { var owner = new Owner { Contracts = new List <Contract>(), Properties = new List <Property>(), User = user }; _dataContext.Owners.Add(owner); //await _dataContext.SaveChangesAsync(); } await _dataContext.SaveChangesAsync(); var myToken = await _userHelper.GenerateEmailConfirmationTokenAsync(user); var tokenLink = Url.Action("ConfirmEmail", "Account", new { userid = user.Id, token = myToken }, protocol: HttpContext.Request.Scheme); _mailHelper.SendMail(modelo.Username, "Email confirmation", $"<h1>Email Confirmation</h1>" + $"To allow the user, " + $"plase click in this link:</br></br><a href = \"{tokenLink}\">Confirm Email</a>"); ViewBag.Message = "The instructions to allow your user has been sent to email."; return(View(modelo)); } modelo.Roles = _combosHelpers.GetComboRoles(); return(View(modelo)); }
public async Task <IActionResult> Create(AddUserViewModel model) { if (ModelState.IsValid) { var user = new User { Address = model.Address, Document = model.Document, Email = model.Username, FirstName = model.FirstName, LastName = model.LastName, PhoneNumber = model.PhoneNumber, UserName = model.Username }; var response = await _userHelper.AddUserAsync(user, model.Password); if (response.Succeeded) { var userInDB = await _userHelper.GetUserByEmailAsync(model.Username); await _userHelper.AddUserToRoleAsync(userInDB, "Customer"); var owner = new Owner { Agendas = new List <Agenda>(), Pets = new List <Pet>(), User = userInDB }; _dataContext.Owners.Add(owner); try { await _dataContext.SaveChangesAsync(); var myToken = await _userHelper.GenerateEmailConfirmationTokenAsync(user); var tokenLink = Url.Action("ConfirmEmail", "Account", new { userid = user.Id, token = myToken }, protocol: HttpContext.Request.Scheme); _mailHelper.SendMail(model.Username, "Email confirmation", $"<h1>Email Confirmation</h1>" + $"To allow the user, " + $"plase click in this link:</br></br><a href = \"{tokenLink}\">Confirm Email</a>"); return(RedirectToAction(nameof(Index))); } catch (Exception ex) { ModelState.AddModelError(string.Empty, ex.ToString()); return(View(model)); } } ModelState.AddModelError(string.Empty, response.Errors.FirstOrDefault().Description); } return(View(model)); }
public async Task <IActionResult> PostUser([FromBody] UserRequest request) { var identity = HttpContext.User.Identity as ClaimsIdentity; IList <Claim> claims = identity.Claims.ToList(); var userName = claims[0].Value; User user = await _userHelper.GetUserAsyncByEmail(userName); if (user == null) { return(BadRequest(new Response { IsSuccess = false, Message = "User does not exist" })); } IList <string> roles = await _userHelper.GetUserRolAsync(user); if (!roles.Contains("Administrador")) { return(NotFound(new Response { IsSuccess = false, Message = "You do not have permissions to create users" })); } if (!ModelState.IsValid) { return(BadRequest(new Response { IsSuccess = false, Message = "Bad request", Result = ModelState })); } user = await _userHelper.GetUserAsyncByEmail(request.Email); if (user != null) { return(BadRequest(new Response { IsSuccess = false, Message = "A user with that email is already registered." })); } user = new User { FirstName = request.FirstName, LastName = request.LastName, IsActive = true, UserName = request.Email, Email = request.Email, UserType = UserType.Operador }; IdentityResult result = await _userHelper.AddUserAsync(user, request.Password); if (result != IdentityResult.Success) { return(BadRequest(result.Errors.FirstOrDefault().Description)); } User userNew = await _userHelper.GetUserAsyncByEmail(request.Email); await _userHelper.AddUserToRoleAsync(userNew, user.UserType.ToString()); EmailMessageModel message = new() { To = request.Email, Subject = "Email Confirmation", Content = $"<h1>Email Confirmation</h1> " + $"<h1>Below you will find the access data:</h1> " + $"<h3>UserName: {request.Email}</h3> " + $"<h3>Password: {request.Password}</h3> " }; _mailHelper.SendMail(message); return(Ok(new Response { IsSuccess = true, Message = "User created successfully", Result = userNew })); }
public async Task <IActionResult> PostUser([FromBody] UserRequest request) { if (!ModelState.IsValid) { return(BadRequest(new Response <object> { IsSuccess = false, Message = "Bad request" })); } var user = await _userHelper.GetUserByEmailAsync(request.Email); if (user != null) { return(BadRequest(new Response <object> { IsSuccess = false, Message = "This email is already registered." })); } user = new User { Address = request.Address, Document = request.Document, Email = request.Email, FirstName = request.FirstName, LastName = request.LastName, PhoneNumber = request.Phone, UserName = request.Email }; var result = await _userHelper.AddUserAsync(user, request.Password); if (result != IdentityResult.Success) { return(BadRequest(result.Errors.FirstOrDefault().Description)); } var userNew = await _userHelper.GetUserByEmailAsync(request.Email); await _userHelper.AddUserToRoleAsync(userNew, "Customer"); _dataContext.Owners.Add(new Owner { User = userNew }); await _dataContext.SaveChangesAsync(); var myToken = await _userHelper.GenerateEmailConfirmationTokenAsync(user); var tokenLink = Url.Action("ConfirmEmail", "Account", new { userid = user.Id, token = myToken }, protocol: HttpContext.Request.Scheme); _mailHelper.SendMail(request.Email, "Email confirmation", $"<h1>Email Confirmation</h1>" + $"To allow the user, " + $"please click on this link:</br></br><a href = \"{tokenLink}\">Confirm Email</a>"); return(Ok(new Response <object> { IsSuccess = true, Message = "A Confirmation email was sent. Please confirm your account and log into the App." })); }
public async Task <IActionResult> PostUserGroup([FromBody] AddUserGroupRequest request) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } CultureInfo cultureInfo = new CultureInfo(request.CultureInfo); Resource.Culture = cultureInfo; UserEntity proposalUser = await _userHelper.GetUserAsync(request.UserId); if (proposalUser == null) { return(BadRequest(Resource.UserNotFoundError)); } UserEntity requiredUser = await _userHelper.GetUserAsync(request.Email); if (requiredUser == null) { return(BadRequest(Resource.UserNotFoundError)); } UserGroupEntity userGroup = await _context.UserGroups .Include(ug => ug.Users) .ThenInclude(u => u.User) .FirstOrDefaultAsync(ug => ug.User.Id == request.UserId.ToString()); if (userGroup != null) { UserGroupDetailEntity user = userGroup.Users.FirstOrDefault(u => u.User.Email == request.Email); if (user != null) { return(BadRequest(Resource.UserAlreadyBelogToGroup)); } } UserGroupRequestEntity userGroupRequest = new UserGroupRequestEntity { ProposalUser = proposalUser, RequiredUser = requiredUser, Status = UserGroupStatus.Pending, Token = Guid.NewGuid() }; try { _context.UserGroupRequests.Add(userGroupRequest); await _context.SaveChangesAsync(); } catch (Exception ex) { return(BadRequest(ex.Message)); } string linkConfirm = Url.Action("ConfirmUserGroup", "Account", new { requestId = userGroupRequest.Id, token = userGroupRequest.Token }, protocol: HttpContext.Request.Scheme); string linkReject = Url.Action("RejectUserGroup", "Account", new { requestId = userGroupRequest.Id, token = userGroupRequest.Token }, protocol: HttpContext.Request.Scheme); Response response = _mailHelper.SendMail( request.Email, Resource.RequestJoinGroupSubject, $"<h1>{Resource.RequestJoinGroupSubject}</h1>" + $"<hr><br><br>{Resource.TheUser}: {proposalUser.FullName} ({proposalUser.Email}), {Resource.RequestJoinGroupBody}" + $"<br>{Resource.WishToAccept} <a href = \"{linkConfirm}\">{Resource.Confirm}</a> <br>" + $"{Resource.WishToReject} <a href = \"{linkReject}\">{Resource.Reject}</a>"); if (!response.IsSuccess) { return(BadRequest(response.Message)); } return(Ok(Resource.RequestJoinGroupEmailSent)); }
public async Task <IActionResult> Create(RegisterNewViewModel model) { if (ModelState.IsValid) { var user = new User { Address = model.Address, Email = model.UserName, FirstName = model.FirstName, LastName = model.LastName, PhoneNumber = model.PhoneNumber, UserName = model.UserName }; var response = await _userHelper.AddUserAsync(user, model.Password); if (response.Succeeded) { var userInDB = await _userHelper.GetUserByEmailAsync(model.UserName); await _userHelper.AddUSerToRoleAsync(userInDB, "Customer"); var creator = await _userHelper.GetUserByEmailAsync(User.Identity.Name); var owner = new Owner { Appointments = new List <Appointment>(), Pets = new List <Pet>(), User = userInDB, CreatedBy = creator, ModifiedBy = creator, CreateDate = DateTime.Now, UpdateDate = DateTime.Now }; await _ownerRepository.CreateAsync(owner); try { var myToken = await _userHelper.GenerateEmailConfirmationTokenAsync(userInDB); var tokenLink = Url.Action("ConfirmEmail", "Account", new { userid = userInDB.Id, token = myToken }, protocol: HttpContext.Request.Scheme); _mailHelper.SendMail(model.UserName, "Email confirmation", $"<h1>Email Confirmation</h1>" + $"To allow the user, " + $"please click in this link:</br></br><a href = \"{tokenLink}\">Confirm Email</a>"); return(RedirectToAction(nameof(Index))); } catch (Exception ex) { ModelState.AddModelError(string.Empty, ex.ToString()); return(View(model)); } } ModelState.AddModelError(string.Empty, response.Errors.FirstOrDefault().Description); } return(View(model)); }
public async Task <IActionResult> Register(AddUserViewModel model) { if (ModelState.IsValid) { var modelr = new AddUserViewModel { Document = model.Document, FirstName = model.FirstName, LastName = model.LastName, PhoneNumber = model.PhoneNumber, Gender = model.Gender }; var role = "turista"; var user = await _userHelper.AddUser(model, role); if (user == null) { ModelState.AddModelError(string.Empty, "Este email ya esta registrado."); return(View(modelr)); } var turista = new Tourist { user = user }; _dataContext.Tourists.Add(turista); await _dataContext.SaveChangesAsync(); var myToken = await _userHelper.GenerateEmailConfirmationTokenAsync(user); var tokenLink = Url.Action("ConfirmEmail", "Account", new { userid = user.Id, token = myToken }, protocol: HttpContext.Request.Scheme); _mailHelper.SendMail(model.Username, "Email de confirmación Tropical beach", $"<table style = 'max-width: 600px; padding: 10px; margin:0 auto; border-collapse: collapse;'>" + $" <tr>" + $" <td style = 'background-color: #34495e; text-align: center; padding: 0'>" + $" <a href = 'https://www.facebook.com' >" + $" Bienvenido" + $" </a>" + $" </td>" + $" </tr>" + $" <tr>" + $" </tr>" + $"<tr>" + $" <td style = 'background-color: #ecf0f1'>" + $" <div style = 'color: #34495e; margin: 4% 10% 2%; text-align: justify;font-family: sans-serif'>" + $" <h1 style = 'color: #e67e22; margin: 0 0 7px' > Hola " + model.FirstName + " </h1>" + $" <p style = 'margin: 2px; font-size: 15px'>" + $"Bienvenido a nuestra pagina, este es un mensaje de confirmación, esperamos que disfrutes nuestro Resort " + $" Estaremos atentos a tus inquietudes e inconvenientes." + $"Nuestros servicios:" + $"</p>" + $" <ul style = 'font-size: 15px; margin: 10px 0'>" + $" <li> Alquiler de habitaciones.</li>" + $" <li> Alquiler de cabañas.</li>" + $" </ul>" + $" <div style = 'width: 100%;margin:20px 0; display: inline-block;text-align: center'>" + $" <img style = 'padding: 0; width: 200px; margin: 5px' src = 'https://veterinarianuske.com/wp-content/uploads/2018/07/tarjetas.png'>" + $" </div>" + $" <div style = 'width: 100%; text-align: center'>" + $" <h2 style = 'color: #e67e22; margin: 0 0 7px' >Confirmación de email </h2>" + $" Para verificar tu cuenta por favor dar click en el siguiente link:</ br ></ br > " + $" <a style ='text-decoration: none; border-radius: 5px; padding: 11px 23px; color: white; background-color: #3498db' href = \"{tokenLink}\">Confirmar Email</a>" + $" <p style = 'color: #b3b3b3; font-size: 12px; text-align: center;margin: 30px 0 0' > Concesionario Chevrolet </p>" + $" </div>" + $" </td >" + $"</tr>" + $"</table>"); ViewBag.Message = "Se ha enviado un correo de confirmación."; return(View(model)); } return(View(model)); }
public async Task <IActionResult> PostUserGroup([FromBody] AddUserGroupRequest request) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } //CultureInfo cultureInfo = new CultureInfo(request.CultureInfo); //Resource.Culture = cultureInfo; UserEntity proposalUser = await _userHelper.GetUserAsync(request.UserId); if (proposalUser == null) { return(BadRequest(new Response { IsSuccess = false, Message = "User not found" })); } UserEntity requiredUser = await _userHelper.GetUserAsync(request.Email); if (requiredUser == null) { return(BadRequest(new Response { IsSuccess = false, Message = "User not found" })); } UserGroupEntity userGroup = await _context.UserGroups .Include(ug => ug.Users) .ThenInclude(u => u.User) .FirstOrDefaultAsync(ug => ug.User.Id == request.UserId.ToString()); if (userGroup != null) { UserGroupDetailEntity user = userGroup.Users.FirstOrDefault(u => u.User.Email == request.Email); if (user != null) { return(BadRequest(new Response { IsSuccess = false, Message = "User already belongs to a group" })); } } UserGroupRequestEntity userGroupRequest = new UserGroupRequestEntity { ProposalUser = proposalUser, RequiredUser = requiredUser, Status = UserGroupStatus.Pending, Token = Guid.NewGuid() }; try { _context.UserGroupRequests.Add(userGroupRequest); await _context.SaveChangesAsync(); } catch (Exception ex) { return(BadRequest(ex.Message)); } string linkConfirm = Url.Action("ConfirmUserGroup", "Account", new { requestId = userGroupRequest.Id, token = userGroupRequest.Token }, protocol: HttpContext.Request.Scheme); string linkReject = Url.Action("RejectUserGroup", "Account", new { requestId = userGroupRequest.Id, token = userGroupRequest.Token }, protocol: HttpContext.Request.Scheme); Response response = _mailHelper.SendMail(request.Email, "Request To Join Group", $"<h1>{"Invitation to join a user group"}</h1>" + $"{"User"}: {proposalUser.FullName} ({proposalUser.Email}), {" Has Invite you to join a user group for the Taxi Survey Application."}" + $"</hr></br></br>{"If you wish to accept, clik here"} <a href = \"{linkConfirm}\">{"Confirm"}</a>" + $"</hr></br></br>{"If you wish To Reject, clck here"} <a href = \"{linkReject}\">{"Not Inerested"}</a>"); if (!response.IsSuccess) { return(BadRequest(response.Message)); } return(Ok("Request To Join a Group EmailSent")); }
public async Task <IActionResult> Register(AddUserViewModel model) { if (ModelState.IsValid) { string path = string.Empty; if (model.PictureFile != null) { path = await _imageHelper.UploadImageAsync(model.PictureFile, "Users"); } Data.Entities.UserEntity user = await _userHelper.AddUserAsync(model, path); if (user == null) { ModelState.AddModelError(string.Empty, "Este correo ya se encuentra registrado."); model.UserTypes = _combosHelper.GetComboRoles(); return(View(model)); } var myToken = await _userHelper.GenerateEmailConfirmationTokenAsync(user); var tokenLink = Url.Action("ConfirmEmail", "Account", new { userid = user.Id, token = myToken }, protocol: HttpContext.Request.Scheme); var response = _mailHelper.SendMail(model.Username, "Confirmación de correo electrónico", $"<h1>Correo de confirmación</h1>" + $"Para permitir al usuario, " + $"Por favor presione click en este enlace:" + $"</br></br><a href = \"{tokenLink}\">Confirmar Email</a>"); if (response.IsSuccess) { ViewBag.Message = "Se han enviado las instrucciones al correo."; return(View(model)); } ModelState.AddModelError(string.Empty, response.Message); LoginViewModel loginViewModel = new LoginViewModel { Password = model.Password, RememberMe = false, Username = model.Username }; Microsoft.AspNetCore.Identity.SignInResult result2 = await _userHelper.LoginAsync(loginViewModel); if (result2.Succeeded) { return(RedirectToAction("Index", "Home")); } } model.UserTypes = _combosHelper.GetComboRoles(); return(View(model)); }
public async Task <IActionResult> PostUser([FromBody] UserRequest request) { if (!ModelState.IsValid) { return(BadRequest(new Response <object> { IsSuccess = false, Message = "Bad Request" })); } var user = await _userHelper.GetUserByEmailAsync(request.Email); if (user != null) { return(BadRequest(new Response <object> { IsSuccess = false, Message = "Este correo ya está registrado" })); } user = new User { Address = request.Address, Document = request.Document, Email = request.Email, FirstName = request.FirstName, LastName = request.LastName, PhoneNumber = request.Phone, UserName = request.Email }; var result = await _userHelper.AddUserAsync(user, request.Password); if (result != IdentityResult.Success) { return(BadRequest(result.Errors.FirstOrDefault().Description)); } var userNew = await _userHelper.GetUserByEmailAsync(request.Email); await _userHelper.AddUserToRoleAsync(userNew, "Customer"); _dataContext.Owners.Add(new Owner { user = userNew }); await _dataContext.SaveChangesAsync(); var myToken = await _userHelper.GenerateEmailConfirmationTokenAsync(user); var tokenLink = Url.Action("ConfirmEmail", "Account", new { userid = user.Id, token = myToken }, protocol: HttpContext.Request.Scheme); _mailHelper.SendMail(request.Email, "Confirmación de Correo", $"<h1>Veterinaria Zulu - Confirmación de Correo</h1>" + $"Para activar su usuario, " + $"por favor haga click en este link:</br></br><a href = \"{tokenLink}\">Confirmar</a>"); return(Ok(new Response <object> { IsSuccess = true, Message = "Una confirmación de fue enviada a su correo. Por favor confirme su usuario e ingrese a la App." })); }
public async Task <IActionResult> Create(AddUserViewModel view) { if (ModelState.IsValid) { var user = await AddUser(view); if (user == null) { ModelState.AddModelError(string.Empty, "Email esta actualmente en uso."); return(View(view)); } var collector = new Collector { PropertyCollectors = new List <PropertyCollector>(), User = user, }; _dataContext.Collectors.Add(collector); await _dataContext.SaveChangesAsync(); var myToken = await _userHelper.GenerateEmailConfirmationTokenAsync(user); var tokenLink = Url.Action("ConfirmEmail", "Account", new { userid = user.Id, token = myToken }, protocol: HttpContext.Request.Scheme); _mailHelper.SendMail(view.Username, "Email confirmation", $"<table style = 'max-width: 600px; padding: 10px; margin:0 auto; border-collapse: collapse;'>" + $" <tr>" + $" <td style = 'background-color: #34495e; text-align: center; padding: 0'>" + $" <a href = 'https://www.facebook.com/NuskeCIV/' >" + $" <img width = '20%' style = 'display:block; margin: 1.5% 3%' src= 'https://veterinarianuske.com/wp-content/uploads/2016/10/line_separator.png'>" + $" </a>" + $" </td>" + $" </tr>" + $" <tr>" + $" <td style = 'padding: 0'>" + $" <img style = 'padding: 0; display: block' src = 'https://mycollectionweb.azurewebsites.net/images/Logo_WS.jpg' width = '100%'>" + $" </td>" + $"</tr>" + $"<tr>" + $" <td style = 'background-color: #ecf0f1'>" + $" <div style = 'color: #34495e; margin: 4% 10% 2%; text-align: justify;font-family: sans-serif'>" + $" <h1 style = 'color: #e67e22; margin: 0 0 7px' > Hola </h1>" + $" <p style = 'margin: 2px; font-size: 15px'>" + $" La mejor empresa para el desarrollo de sistemas y aplicaciones Web de Sonora enfocado a brindar servicios garantizados <br>" + $" aplicando las técnicas más actuales y equipo de vanguardia para proceder a realizar un trabajo preciso y efisciente..<br>" + $" Entre los servicios tenemos:</p>" + $" <ul style = 'font-size: 15px; margin: 10px 0'>" + $" <li> Desarrollo Web.</li>" + $" <li> Desarrollo Aplicaciones Android.</li>" + $" <li> Desarrollo Aplicaciones IOS.</li>" + $" <li> Marketing Web</li>" + $" </ul>" + $" <div style = 'width: 100%;margin:20px 0; display: inline-block;text-align: center'>" + $" <img style = 'padding: 0; width: 200px; margin: 5px' src = 'https://veterinarianuske.com/wp-content/uploads/2018/07/tarjetas.png'>" + $" </div>" + $" <div style = 'width: 100%; text-align: center'>" + $" <h2 style = 'color: #e67e22; margin: 0 0 7px' >Confirmación Email</h2>" + $" Para habilitar este usuario presione el enlace:" + $" <a style ='text-decoration: none; border-radius: 5px; padding: 11px 23px; color: white; background-color: #3498db' href = \"{tokenLink}\">Confirmar</a>" + $" <p style = 'color: #b3b3b3; font-size: 12px; text-align: center;margin: 30px 0 0' > WebStudio MX 2020 </p>" + $" </div>" + $" </td >" + $"</tr>" + $"</table>"); _flashMessage.Confirmation("Registro creado con éxito."); return(RedirectToAction(nameof(Index))); } return(View(view)); }
public async Task <IActionResult> Edit(int id, NovedadesEditViewModel model) { if (id != model.Id) { return(NotFound()); } if (ModelState.IsValid) { //var novedad = _dataContext.novedades.Find(model.Id); var novedad = await _novedadesRepository.GetNovedadByIdAsync(model.Id); novedad.Solucion = model.Solucion; novedad.userSolucion = await _userHelper.GetUserAsync(this.User.Identity.Name); novedad.FechaSolucion = DateTime.Now; novedad.EstadoSolucion = model.EstadoId; try { _dataContext.Update(novedad); await _dataContext.SaveChangesAsync(); var lognovedad = new LogNovedad { novedad = novedad, Estado = model.EstadoId, Usuario = novedad.userSolucion, Fecha = DateTime.Now, Observaciones = model.Solucion, }; _dataContext.logNovedades.Add(lognovedad); await _dataContext.SaveChangesAsync(); await _logRepository.SaveLogs("Editar", "Edita Novedades id: " + novedad.Id.ToString() + "-" + novedad.EstadoSolucion, "Novedades", User.Identity.Name); ////// var datos = await _userHelper.GetUserByCedulaAsync(novedad.Cedula); var emails = novedad.userSolucion.Email + ',' + datos.Email; //TODO: cambiar direccion de correo _mailHelper.SendMail(emails, "Plataforma Clientes -- Actualización Novedad", $"<html xmlns='http://www.w3.org/1999/xhtml'>" + $"<head>" + $"<title>" + $"</title>" + $"</head>" + $"<body>" + //$"<h1>Plataforma Clientes Actualización Novedad</h1>" + $"<hr width=100% align='center' size=30 color='#002D73' style='margin:0px;padding:0px'>" + $"<hr width=100% align='center' size=5 color='#F2AE0B' style='margin:0px;padding:0px'>" + $"<br><br>" + $"<p>Estimado Cliente" + $"<p>Renting Pichincha comunica que se ha actualizado en la plataforma de clientes una Novedad perteneciente al vehículo:" + $"<table border='0' cellpadding='0' cellspacing='0' height='100%' width='100%' style='border-collapse:collapse; max-width:600px!important; width:100%; margin: auto'>" + $"<tr><td style='font-weight:bold'>Placa</td><td>{novedad.Placa}</td></tr>" + $"<tr><td style='font-weight:bold'>Motivo</td><td>{novedad.Motivo}</td></tr>" + $"<tr><td style='font-weight:bold'>SubMotivo</td><td>{novedad.SubMotivo}</td></tr>" + $"<tr><td style='font-weight:bold'>Vía Ingreso</td><td>{novedad.ViaIngreso}</td></tr>" + $"<tr><td style='font-weight:bold'>Estado</td><td>{model.EstadoId}</td></tr>" + $"<tr><td style='font-weight:bold'>Solución</td><td>{model.Solucion}</td></tr>" + $"<tr><td style='font-weight:bold'>Actualizado por</td><td>{novedad.userSolucion.FullName}</td></tr>" + $"<tr><td style='font-weight:bold'>Fecha</td><td>{novedad.FechaSolucion}</td></tr></table>" + $"<br><br>" + $"<p>Para poder revisar la información de su plataforma ingrese a su cuenta con su usuario y contraseña." + $"<div align='center'><a href='https://clientes.rentingpichincha.com'><img src='https://clientes.rentingpichincha.com/images/email1.png' align='center'></a></div>" + $"<br><br>" + $"<p>Es un placer estar en contacto.<br>" + $"<p>Saludos cordiales<br>" + $"<br><br>" + $"<p>Consorcio Pichincha S.A CONDELPI<br>" + $"<p>Av.González Suárez N32-346 y Coruña<br>" + $"<p><img src='https://clientes.rentingpichincha.com/images/call.png' width=30px>Call Center: 1-800 RENTING(736846)<br>" + $"<p><img src='https://clientes.rentingpichincha.com/images/email.png' width=25px>E-Mail: [email protected]<br>" + $"<p><img src='https://clientes.rentingpichincha.com/images/whatsapp.jpg' width=25px>WhatsApp: 0997652137" + $"<p>Quito-Ecuador" + $"<br><br>" + $"<img src='https://clientes.rentingpichincha.com/images/email2.png' width=200px>" + $"<hr width=100% align='center' size=30 color='#002D73' style='margin:0px;padding:0px'>" + $"<hr width=100% align='center' size=5 color='#F2AE0B' style='margin:0px;padding:0px'></body></html>" ); } catch (DbUpdateConcurrencyException) { if (!AnalisisExists(model.Id)) { return(NotFound()); } else { throw; } } //return RedirectToAction(nameof(Index)); return(RedirectToAction(nameof(Retorno), new { id = novedad.Cedula })); } return(View(_dataContext)); }
public async Task <IActionResult> PostUser([FromBody] UserRequest request) { if (!ModelState.IsValid) { return(BadRequest(new Response <object> { IsSuccess = false, Message = "Bad request" })); } User user = await _userHelper.GetUserByEmailAsync(request.Email); if (user != null) { return(BadRequest(new Response <object> { IsSuccess = false, Message = "This email is already registered." })); } user = new User { Address = request.Address, RFC = request.RFC, Email = request.Email, FirstName = request.FirstName, LastName = request.LastName, PhoneNumber = request.Phone, UserName = request.Email }; IdentityResult result = await _userHelper.AddUserAsync(user, request.Password); if (result != IdentityResult.Success) { return(BadRequest(result.Errors.FirstOrDefault().Description)); } User userNew = await _userHelper.GetUserByEmailAsync(request.Email); await _userHelper.AddUserToRoleAsync(userNew, "Customer"); _dataContext.Owners.Add(new Owner { User = userNew }); await _dataContext.SaveChangesAsync(); string myToken = await _userHelper.GenerateEmailConfirmationTokenAsync(user); string tokenLink = Url.Action("ConfirmEmail", "Account", new { userid = user.Id, token = myToken }, protocol: HttpContext.Request.Scheme); _mailHelper.SendMail(request.Email, "Correo de COnfirmación", $"<h1>Correo de Confirmación</h1>" + $"Permitir al usuario, " + $"por favor, dar clic en éste link:</br></br><a href = \"{tokenLink}\">Confirmar correo</a>"); return(Ok(new Response <object> { IsSuccess = true, Message = "La confrimación ha sidoe enviada a su correo. Por favor confirme su cuenta he ingrese a la Aplicación." })); }
public async Task <IActionResult> Create(RegisterNewEmployeeViewModel model) { var user = await _userHelper.GetUserByEmailAsync(model.Username); if (user == null) { var city = await _countryRepository.GetCityAsync(model.CityId); user = new User { FirstName = model.FirstName, LastName = model.LastName, Email = model.Username, UserName = model.Username, Address = model.Address, PhoneNumber = model.PhoneNumber, TaxNumber = model.TaxNumber, SocialSecurityNumber = model.SocialSecurityNumber, CityId = model.CityId, City = city, isActive = true, }; try { var result = await _userHelper.AddUserAsync(user, "123456"); } catch (Exception) { model.Departments = GetDepartments(); model.Countries = _countryRepository.GetComboCountries(); model.Cities = _countryRepository.GetComboCities(model.CityId); this.ModelState.AddModelError(string.Empty, "The user couldn't be created. Please, confirm data"); return(this.View(model)); } try { // Atribuir o role de Employee ao user await _userHelper.AddUserToRoleAsync(user, "Employee"); } catch (Exception) { model.Departments = GetDepartments(); model.Countries = _countryRepository.GetComboCountries(); model.Cities = _countryRepository.GetComboCities(model.CityId); this.ModelState.AddModelError(string.Empty, "Error adding the employee to the role! Please contact the technical support!"); return(this.View(model)); } try { var myToken = await _userHelper.GenerateEmailConfirmationTokenAsync(user); await _userHelper.ConfirmEmailAsync(user, myToken); // Confirmar automaticamente } catch (Exception) { model.Departments = GetDepartments(); model.Countries = _countryRepository.GetComboCountries(); model.Cities = _countryRepository.GetComboCities(model.CityId); this.ModelState.AddModelError(string.Empty, "Error on the email confirmation! Please, contact the technical suppoprt! "); return(this.View(model)); } try { // Adicionar o user ao departamento (tabela de detalhes de departamento) // Obter o departamento var department = await _context.Departments.FindAsync(model.DepartmentId); _context.DepartmentDetails.Add(new DepartmentDetail { User = user, StartDate = DateTime.Today, Department = department }); await _context.SaveChangesAsync(); } catch (Exception) { model.Departments = GetDepartments(); model.Countries = _countryRepository.GetComboCountries(); model.Cities = _countryRepository.GetComboCities(model.CityId); this.ModelState.AddModelError(string.Empty, "Error! The department details wasn't updated. Please contact support! "); return(this.View(model)); } try { // Criar um link que vai levar lá dentro uma acção. Quando o utilizador carregar neste link, // vai no controlador Account executar a action "ChangePassword" // Este ConfirmEmail vai receber um objecto novo que terá um userid e um token. var myTokenReset = await _userHelper.GeneratePasswordResetTokenAsync(user); var link = this.Url.Action( "ResetPassword", "Employees", new { token = myTokenReset }, protocol: HttpContext.Request.Scheme); _mailHelper.SendMail(user.Email, "Airline Password Reset", $"<h1>Airline Password Reset</h1>" + $"Welcome onboard! Please, reset your password, click in this link:</br></br>" + $"<a href = \"{link}\">Reset Password</a>"); ViewBag.Message = "The employee was created with sucess! Was sent an email to the employee for the password reset!"; return(View()); } catch (Exception) { model.Departments = GetDepartments(); model.Countries = _countryRepository.GetComboCountries(); model.Cities = _countryRepository.GetComboCities(model.CityId); this.ModelState.AddModelError(string.Empty, "Error on seeding the email to the employee! Please contact support!"); return(RedirectToAction(nameof(Index))); } } this.ModelState.AddModelError(string.Empty, "The user already exists"); return(View(model)); }
public async Task <IActionResult> PostUser([FromBody] UserRequest request) { if (!ModelState.IsValid) { return(BadRequest(new Response { IsSuccess = false, Message = "Bad request", Result = ModelState })); } User user = await _userHelper.GetUserAsync(request.Email); if (user != null) { return(BadRequest(new Response { IsSuccess = false, Message = "Error003" })); } //TODO: Translate ErrorXXX literals City city = await _context.Cities.FindAsync(request.CityId); if (city == null) { return(BadRequest(new Response { IsSuccess = false, Message = "Error004" })); } Guid imageId = Guid.Empty; if (request.ImageArray != null) { imageId = await _blobHelper.UploadBlobAsync(request.ImageArray, "users"); } user = new User { Address = request.Address, Document = request.Document, Email = request.Email, FirstName = request.FirstName, LastName = request.LastName, PhoneNumber = request.Phone, UserName = request.Email, ImageId = imageId, UserType = UserType.User, City = city }; IdentityResult result = await _userHelper.AddUserAsync(user, request.Password); if (result != IdentityResult.Success) { return(BadRequest(result.Errors.FirstOrDefault().Description)); } User userNew = await _userHelper.GetUserAsync(request.Email); await _userHelper.AddUserToRoleAsync(userNew, user.UserType.ToString()); string myToken = await _userHelper.GenerateEmailConfirmationTokenAsync(user); string tokenLink = Url.Action("ConfirmEmail", "Account", new { userid = user.Id, token = myToken }, protocol: HttpContext.Request.Scheme); _mailHelper.SendMail(request.Email, "Email Confirmation", $"<h1>Email Confirmation</h1>" + $"To confirm your email please click on the link<p><a href = \"{tokenLink}\">Confirm Email</a></p>"); return(Ok(new Response { IsSuccess = true })); }
public async Task <IActionResult> Register(AddUserViewModel model) { if (ModelState.IsValid) { var role = "Owner"; if (model.RoleId == 1) { role = "Lessee"; } var user = await _userHelper.AddUser(model, role); if (user == null) { ModelState.AddModelError(string.Empty, "This email is already used."); return(View(model)); } if (model.RoleId == 1) { var lessee = new Lessee { Contracts = new List <Contract>(), User = user }; _dataContext.Lessees.Add(lessee); } else { var owner = new Owner { Contracts = new List <Contract>(), Properties = new List <Property>(), User = user }; _dataContext.Owners.Add(owner); } await _dataContext.SaveChangesAsync(); var myToken = await _userHelper.GenerateEmailConfirmationTokenAsync(user); var tokenLink = Url.Action("ConfirmEmail", "Account", new { userid = user.Id, token = myToken }, protocol: HttpContext.Request.Scheme); _mailHelper.SendMail(model.Username, "Email confirmation", $"<table style = 'max-width: 600px; padding: 10px; margin:0 auto; border-collapse: collapse;'>" + $" <tr>" + $" <td style = 'background-color: #34495e; text-align: center; padding: 0'>" + $" <a href = '' >" + $" <img width = '20%' style = 'display:block; margin: 1.5% 3%' src= ''>" + $" </a>" + $" </td>" + $" </tr>" + $" <tr>" + $" <td style = 'padding: 0'>" + $" <img style = 'padding: 0; display: block' src = '' width = '100%'>" + $" </td>" + $"</tr>" + $"<tr>" + $" <td style = 'background-color: #ecf0f1'>" + $" <div style = 'color: #34495e; margin: 4% 10% 2%; text-align: justify;font-family: sans-serif'>" + $" <h1 style = 'color: #e67e22; margin: 0 0 7px' > Hola </h1>" + $" <p style = 'margin: 2px; font-size: 15px'>" + $" The best specialized leasing agency, focused on providing property leasing services.<br>" + $" We provide all the necessary advice to ensure the best options for owners and renters.<br>" + $" Among the services we have:</p>" + $" <ul style = 'font-size: 15px; margin: 10px 0'>" + $" <li> property management.</li>" + $" <li> contract administration.</li>" + $" <li> property photographs.</li>" + $" <li> secure application.</li>" + $" </ul>" + $" <div style = 'width: 100%;margin:20px 0; display: inline-block;text-align: center'>" + $" <img style = 'padding: 0; width: 200px; margin: 5px' src = ''>" + $" </div>" + $" <div style = 'width: 100%; text-align: center'>" + $" <h2 style = 'color: #e67e22; margin: 0 0 7px' >Email Confirmation </h2>" + $" To allow the user,plase click in this link:</ br ></ br > " + $" <a style ='text-decoration: none; border-radius: 5px; padding: 11px 23px; color: white; background-color: #3498db' href = \"{tokenLink}\">Confirm Email</a>" + $" <p style = 'color: #b3b3b3; font-size: 12px; text-align: center;margin: 30px 0 0' > Nuskë Clinica Integral Veterinaria 2019 </p>" + $" </div>" + $" </td >" + $"</tr>" + $"</table>"); ViewBag.Message = "The instructions to allow your user has been sent to email."; return(View(model)); } model.Roles = _combosHelper.GetComboRoles(); return(View(model)); }
public async Task <IActionResult> PostUserGroup([FromBody] AddUserGroupRequest request) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } UserEntity proposalUser = await _userHelper.GetUserAsync(request.UserId); if (proposalUser == null) { return(BadRequest("Error, Usuario no existe")); } UserEntity requiredUser = await _userHelper.GetUserAsync(request.Email); if (requiredUser == null) { return(BadRequest("Error, Usuario no existe")); } UserGroupEntity userGroup = await _context.UserGroups .Include(ug => ug.Users) .ThenInclude(u => u.User) .FirstOrDefaultAsync(ug => ug.User.Id == request.UserId.ToString()); if (userGroup != null) { UserGroupDetailEntity user = userGroup.Users.FirstOrDefault(u => u.User.Email == request.Email); if (user != null) { return(BadRequest("El ususario ya esta registrado al grupo")); } } UserGroupRequestEntity userGroupRequest = new UserGroupRequestEntity { ProposalUser = proposalUser, RequiredUser = requiredUser, Status = UserGroupStatus.Pending, Token = Guid.NewGuid() }; try { _context.UserGroupRequests.Add(userGroupRequest); await _context.SaveChangesAsync(); } catch (Exception ex) { return(BadRequest(ex.Message)); } string linkConfirm = Url.Action("ConfirmUserGroup", "Account", new { requestId = userGroupRequest.Id, token = userGroupRequest.Token }, protocol: HttpContext.Request.Scheme); string linkReject = Url.Action("RejectUserGroup", "Account", new { requestId = userGroupRequest.Id, token = userGroupRequest.Token }, protocol: HttpContext.Request.Scheme); Response response = _mailHelper.SendMail(request.Email, "Asunto: Solicitar unirse al grupo", $"<h1> Asunto: Solicitar unirse al grupo </h1>" + $"El Usuario: {proposalUser.FullName} ({proposalUser.Email}), Solicita que te unas al grupo" + $"</hr></br></br> Deseo confirmar <a href = \"{linkConfirm}\">Confirma aqui </a>" + $"</hr></br></br> Si deseas rechazar <a href = \"{linkReject}\"> Rechaza aqui </a>"); if (!response.IsSuccess) { return(BadRequest(response.Message)); } return(Ok("Solicitud para unirse al grupo ha sido enviada al correo electrónico.")); }
public void EnviarEmail(EmergenciaViewModel view, string?path) { var listEnvioMensajes = (from d in _dataContext.TipoDesastres join f in _dataContext.Funciones on d.Id equals f.TipoDesastresId join en in _dataContext.Entidades on f.EntidadesId equals en.Id join e in _dataContext.Encargados on en.Id equals e.Usuarios.Entidades.Id where d.Id == view.DesastresId select new { e.Usuarios.Email, e.Usuarios.PhoneNumber, en.email, en.telefono, d.NombreDesastre }).ToList(); foreach (var item in listEnvioMensajes) { HttpClient client = new HttpClient { BaseAddress = new Uri("http://www.altiria.net"), Timeout = TimeSpan.FromSeconds(60) }; var postData = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("cmd", _configuration["Sms:cmd"]), new KeyValuePair <string, string>("domainId", _configuration["Sms:domainId"]), new KeyValuePair <string, string>("login", _configuration["Sms:login"]), new KeyValuePair <string, string>("passwd", _configuration["Sms:passwd"]), new KeyValuePair <string, string>("dest", "57" + item.telefono), new KeyValuePair <string, string>("dest", "57" + item.PhoneNumber), new KeyValuePair <string, string>("msg", "Se reporto " + item.NombreDesastre + " En la dirección: " + view.direccion + " Reportado por : " + view.NombreApellido + " Teléfono:" + view.telefono + " Fecha y Hora:" + view.FechaLocal) }; HttpContent content = new FormUrlEncodedContent(postData); string err = ""; string resp = ""; try { HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "/api/http") { Content = content }; content.Headers.ContentType.CharSet = "UTF-8"; request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); HttpResponseMessage response = client.SendAsync(request).Result; var responseString = response.Content.ReadAsStringAsync(); resp = responseString.Result; } catch (Exception e) { err = e.Message; } finally { if (err != "") { Console.WriteLine(err); } else { Console.WriteLine(resp); } } if (path != null) { _mailHelper.SendMail(item.Email, "Desastre Reportado", "Se reporto " + item.NombreDesastre + "<br> En la dirección: " + view.direccion + "<br>Reportado: " + view.NombreApellido + "<br> Teléfono:" + view.telefono + "<br> Fecha y Hora:" + view.FechaLocal + "<br> <img src='https://atenciondesastres.azurewebsites.net" + path.Substring(1) + "' alt='Image' style='width: 200px; height: 200px; max - width: 100 %; height: auto; ' />"); _mailHelper.SendMail(item.email, "Desastre Reportado", "Se reporto " + item.NombreDesastre + "<br> En la dirección: " + view.direccion + "<br>Reportado: " + view.NombreApellido + "<br> Teléfono:" + view.telefono + "<br> Fecha y Hora:" + view.FechaLocal + "<br> <img src='https://atenciondesastres.azurewebsites.net" + path.Substring(1) + "' alt='Image' style='width: 200px; height: 200px; max - width: 100 %; height: auto; ' />"); } else { _mailHelper.SendMail(item.Email, "Desastre Reportado", "Se reporto " + item.NombreDesastre + "<br> En la dirección: " + view.direccion + "<br>Reportado: " + view.NombreApellido + "<br> Teléfono:" + view.telefono + "<br> Fecha y Hora:" + view.FechaLocal + "<br> Mo inserto imagen del incidente"); _mailHelper.SendMail(item.email, "Desastre Reportado", "Se reporto " + item.NombreDesastre + "<br> En la dirección: " + view.direccion + "<br>Reportado: " + view.NombreApellido + "<br> Teléfono:" + view.telefono + "<br> Fecha y Hora:" + view.FechaLocal + "<br> Mo inserto imagen del incidente"); } } }
public async Task <IActionResult> PostUser([FromBody] UserRequest request) { if (!ModelState.IsValid) { return(BadRequest(new Response { IsSuccess = false, Message = "Bad request", Result = ModelState })); } UserEntity user = await _userHelper.GetUserAsync(request.Email); if (user != null) { return(BadRequest(new Response { IsSuccess = false, Message = "Este Usuario ya existe" })); } string picturePath = string.Empty; if (request.PictureArray != null && request.PictureArray.Length > 0) { picturePath = _imageHelper.UploadImage(request.PictureArray, "Users"); } user = new UserEntity { Address = request.Address, Document = request.Document, Email = request.Email, FirstName = request.FirstName, LastName = request.LastName, PhoneNumber = request.Phone, UserName = request.Email, PicturePath = picturePath, UserType = UserType.User, }; IdentityResult result = await _userHelper.AddUserAsync(user, request.Password); if (result != IdentityResult.Success) { return(BadRequest(result.Errors.FirstOrDefault().Description)); } UserEntity userNew = await _userHelper.GetUserAsync(request.Email); await _userHelper.AddUserToRoleAsync(userNew, UserType.User.ToString()); _dataContext.AppUsers.Add(new AppUserEntity { User = userNew }); await _dataContext.SaveChangesAsync(); string myToken = await _userHelper.GenerateEmailConfirmationTokenAsync(user); string tokenLink = Url.Action("ConfirmEmail", "Account", new { userid = user.Id, token = myToken }, protocol: HttpContext.Request.Scheme); _mailHelper.SendMail(request.Email, "Confirmación de Email", $"<h1>Confirmación de Email</h1>" + $"Para habilitar el usuario, " + $"haga clic en este link: </br></br><a href = \"{tokenLink}\">Confirmar Email</a>"); return(Ok(new Response { IsSuccess = true, Message = "Un mail de confirmación fue enviado. Ingrese a su cuenta para confirmar su mail e ingrese a la App." })); }
public async Task <IActionResult> TicketNew(NewTicketModel model) { // É aqui que vou inserir os bilhetes na base de dados User user = await _userHelper.GetUserByEmailAsync(model.UserEmail); // ===================== Bilhete de Ida ===========================// Ticket ticket = new Ticket(); Flight flight = _flightRepository.GetFlight(model.FlightId); ticket.Seat = Convert.ToInt32(model.Seat); ticket.User = user; ticket.Flight = flight; ticket.Class = model.ClassName; if (model.FlightIdReturn != 0) { // ===================== Bilhete de Regresso ===========================// Ticket ticketReturn = new Ticket(); Flight flightReturn = _flightRepository.GetFlight(model.FlightIdReturn); ticket.Seat = Convert.ToInt32(model.SeatReturn); ticketReturn.User = user; ticketReturn.Flight = flightReturn; ticketReturn.Class = model.ClassNameReturn; try { await _ticketRepository.CreateAsync(ticket); // Grava Bilhete de Ida await _ticketRepository.CreateAsync(ticketReturn); // Grava Bilhete de Regresso _mailHelper.SendMail(user.Email, "Ticket", $"<h1>Ticket Confirmation</h1>" + $"Your ticket information, " + $"Flight: {ticket.Flight.Id}, " + $"Class: {ticket.Class}, " + $"Date: {ticket.Seat}, " + $"Thanks for flying with us!"); _mailHelper.SendMail(user.Email, "Return Ticket", $"<h1>Ticket Confirmation</h1>" + $"Your ticket information, " + $"Flight: {ticketReturn.Flight.Id}, " + $"Class: {ticketReturn.Class}, " + $"Date: {ticketReturn.Seat}, " + $"Thanks for flying with us!"); ViewBag.Message = "Your tickets information was sent to your email!"; return(View()); } catch (Exception ex) { ModelState.AddModelError(string.Empty, ex.InnerException.Message); return(View(model)); } } else { try { await _ticketRepository.CreateAsync(ticket);// Ao usar o create grava logo _mailHelper.SendMail(user.Email, "Ticket", $"<h1>Ticket Confirmation</h1>" + $"Your ticket information, " + $"Flight: {ticket.Flight.Id}, " + $"Class: {ticket.Class}, " + $"Date: {ticket.Seat}, " + $"Thanks for flying with us!"); ViewBag.Message = "Your ticket information was sent to your email!"; return(View()); } catch (Exception ex) { ModelState.AddModelError(string.Empty, ex.InnerException.Message); return(View(model)); } } }
public async Task <IActionResult> PostUser([FromBody] UserRequest request) { if (!ModelState.IsValid) { return(BadRequest(new Response { IsSuccess = false, Message = "Bad request", Result = ModelState })); } UserEntity user = await _userHelper.GetUserAsync(request.Email); if (user != null) { return(BadRequest(new Response { IsSuccess = false, Message = "User exist" })); } string picturePath = string.Empty; if (request.PictureUserArray != null && request.PictureUserArray.Length > 0) { picturePath = await _blobHelper.UploadBlobAsync(request.PictureUserArray, "users"); } user = new UserEntity { Document = request.Document, Email = request.Email, FirstName = request.FirstName, LastName = request.LastName, UserName = request.Email, PicturePathUser = picturePath, UserType = request.UserTypeId == 1 ? UserType.Owner : UserType.User }; IdentityResult result = await _userHelper.AddUserAsync(user, request.Password); if (result != IdentityResult.Success) { return(BadRequest(result.Errors.FirstOrDefault().Description)); } UserEntity userNew = await _userHelper.GetUserAsync(request.Email); await _userHelper.AddUserToRoleAsync(userNew, user.UserType.ToString()); string myToken = await _userHelper.GenerateEmailConfirmationTokenAsync(user); string tokenLink = Url.Action("ConfirmEmail", "Account", new { userid = user.Id, token = myToken }, protocol: HttpContext.Request.Scheme); _mailHelper.SendMail(request.Email, "Email Confimation", $"<h1>Email</h1>" + $"Welcome to Just In Case Travels</br></br><a href = \"{tokenLink}\"> Please clic Here for Confirm Email</a>"); return(Ok(new Response { IsSuccess = true, Message = "Send message for confirm Email" })); }
public async Task <IActionResult> Register(RegisterModel model) { if (ModelState.IsValid) { // var user = await userManager.FindByEmailAsync(model.Email); var user = await _userHelper.GetUserByEmailAsync(model.Email); if (user == null) { user = new ApplicationUser { Name = model.FirstName, Lastname = model.LastName, Email = model.Email, UserName = model.Email, NickName = model.NickName, PhoneNumber = model.Phone }; //var result = await userManager.CreateAsync(user, model.Password); var result = await _userHelper.AddUserAsync(user, model.Password); if (result != IdentityResult.Success) { ModelState.AddModelError(string.Empty, "The user couldn't be created."); return(View(model)); } //var loginModel = new LoginModel //{ // Password = model.Password, // RememberMe = false, // Email = model.Email //}; //var result2 = await _signInManager.PasswordSignInAsync( // model.Email, // model.Password, // true, // false); //var result2 = await _userHelper.LoginAsync(loginModel); //if (result2.Succeeded) //{ // return RedirectToAction("Index", "Home"); //} var myToken = await _userHelper.GenerateEmailConfirmationTokenAsync(user); var tokenLink = Url.Action("ConfirmEmail", "Account", new { userid = user.Id, token = myToken }, protocol: HttpContext.Request.Scheme); try { _mailHelper.SendMail(model.Email, "Tetas Email confirmation", $"<h1>Tetas Email confirmation</h1>" + $"for the activation of this account " + $"please click on the followed link:</br></br><a href = \"{tokenLink}\">Confirm Email</a>"); } finally { } // ModelState.AddModelError(string.Empty, "The instructions to activate your account was send it to your Email"); return(RedirectToAction("Index", "Home", new { message = "The instructions to activate your account was send it to your Email" })); // return View(model); } ModelState.AddModelError(string.Empty, "The username is already registered."); } return(View(model)); }
public async Task <IActionResult> PostUser([FromBody] UserRequest request) { if (!ModelState.IsValid) { return(BadRequest(new Response <object> { IsSuccess = false, Message = "Bad Request" })); } var user = await _userHelper.GetUserByEmailAsync(request.Email); if (user != null) { return(BadRequest(new Response <object> { IsSuccess = false, Message = "This email is already registered." })); } user = new User { Address = request.Address, Document = request.Document, Email = request.Email, FirstName = request.FirstName, LastName = request.LastName, PhoneNumber = request.Phone, UserName = request.Email }; var result = await _userHelper.AddUserAsync(user, request.Password); if (result != IdentityResult.Success) { return(BadRequest(result.Errors.FirstOrDefault().Description)); } var userNew = await _userHelper.GetUserByEmailAsync(request.Email); await _userHelper.AddUserToRoleAsync(userNew, request.Role); if (request.Role == "Organizer") { _dataContext.Organizers.Add(new Organizer { User = userNew }); await _dataContext.SaveChangesAsync(); var myToken = await _userHelper.GenerateEmailConfirmationTokenAsync(user); var tokenLink = Url.Action("ConfirmEmail", "Account", new { userid = user.Id, token = myToken, }, protocol: HttpContext.Request.Scheme); _mailHelper.SendMail(request.Email, "Pegassus Email confirmation", $"<h1>Email Confirmation</h1>" + $"Hi {request.FirstName}" + $"Your register as Event Organizer was successfully" + $"Please click on this link:<br><br><a href = \"{tokenLink}\">Confirm Email</a>"); return(Ok(new Response <object> { IsSuccess = true, Message = "A confirmation email was sent. Please confirm your account and login into the App." })); } else { var eventVar = _dataContext.Events.FirstOrDefault(e => e.Id == request.EventId); _dataContext.Inviteds.Add(new Invited { User = userNew, Event = eventVar }); await _dataContext.SaveChangesAsync(); var myToken = await _userHelper.GenerateEmailConfirmationTokenAsync(user); var tokenLink = Url.Action("ConfirmEmail", "Account", new { userid = user.Id, token = myToken, }, protocol: HttpContext.Request.Scheme); _mailHelper.SendMail(request.Email, "Pegassus Email confirmation", $"<h1>Email Confirmation</h1>" + $"Hi {request.FirstName} <br>" + $"You got an invitation for a <b>{eventVar.Name}</b> Event from Pegassus Events.<br>" + $" Remeber your password it's your document.<br>" + $"Please confirm your asistence on this link:<br><br><a href = \"{tokenLink}\">Confirm Email</a>"); return(Ok(new Response <object> { IsSuccess = true, Message = "A confirmation email was sent to the Invited." })); } }
public async Task <IActionResult> Register(AddUserViewModel model) { if (ModelState.IsValid) { var role = "Technical"; if (model.RoleId == 1) { role = "Company"; } var user = await _userHelper.AddUser(model, role); if (user == null) { ModelState.AddModelError(string.Empty, "Este Email ya está en uso."); return(View(model)); } if (model.RoleId == 1) { var company = new Company { //Contracts = new List<Contract>(), User = user }; _dataContext.Companies.Add(company); } else { var technical = new Technical { //VisitDetails = new List<VisitDetail>(), Visits = new List <Visit>(), User = user }; _dataContext.Technicals.Add(technical); } await _dataContext.SaveChangesAsync(); //var loginViewModel = new LoginViewModel //{ // Password = model.Password, // RememberMe = false, // Username = model.Username //}; //var result2 = await _userHelper.LoginAsync(loginViewModel); //if (result2.Succeeded) //{ // return RedirectToAction("Index", "Home"); //} var myToken = await _userHelper.GenerateEmailConfirmationTokenAsync(user); var tokenLink = Url.Action("ConfirmEmail", "Account", new { userid = user.Id, token = myToken }, protocol: HttpContext.Request.Scheme); _mailHelper.SendMail(model.Username, "MyApp - Email confirmation", $"<h1>MyApp - Email Confirmation</h1>" + $"Para permitir el Usuario, " + $"por favor haga clic en este link:</br></br><a href = \"{tokenLink}\">Confirm Email</a>"); ViewBag.Message = "Las instrucciones para habilitar su usuario han sido enviadas por mail."; return(View(model)); } model.Roles = _combosHelper.GetComboRoles(); return(View(model)); }
public async Task <IActionResult> Register(AddUserViewModel model) { if (ModelState.IsValid) { if (model.UserTypeId == "0") { ModelState.AddModelError(string.Empty, "You must select an account type"); model.UserTypes = _combosHelper.GetComboUserTypes(); return(View(model)); } var userType = model.UserTypeId; var user = await AddUserAsync(model, userType); if (user == null) { ModelState.AddModelError(string.Empty, "This email is already used."); model.UserTypes = _combosHelper.GetComboUserTypes(); return(View(model)); } if (model.UserTypeId.ToString() == "Organizer") { var organizer = new Organizer { Events = new List <Event>(), User = user, }; _dataContext.Organizers.Add(organizer); await _dataContext.SaveChangesAsync(); } else { var owner = new Owner { Rooms = new List <Room>(), User = user, }; _dataContext.Owners.Add(owner); await _dataContext.SaveChangesAsync(); } var myToken = await _userHelper.GenerateEmailConfirmationTokenAsync(user); var tokenLink = Url.Action("ConfirmEmail", "Account", new { userid = user.Id, token = myToken }, protocol: HttpContext.Request.Scheme); _mailHelper.SendMail(model.Username, "Email confirmation", $"<table style = 'max-width: 600px; padding: 10px; margin:0 auto; border-collapse: collapse;'>" + $" <tr>" + $" <td style = 'background-color: #34495e; text-align: center; padding: 0'>" + $" <a href = '' >" + $" <img width = '20%' style = 'display:block; margin: 1.5% 3%' src= ''>" + $" </a>" + $" </td>" + $" </tr>" + $" <tr>" + $" <td style = 'padding: 0'>" + $" <img style = 'padding: 0; display: block' src = '' width = '100%'>" + $" </td>" + $"</tr>" + $"<tr>" + $" <td style = 'background-color: #ecf0f1'>" + $" <div style = 'color: #34495e; margin: 4% 10% 2%; text-align: justify;font-family: sans-serif'>" + $" <h1 style = 'color: #e67e22; margin: 0 0 7px' > Hola </h1>" + $" <p style = 'margin: 2px; font-size: 15px'>" + $" Un servicio pensado en brindar los mejores espacios de reuniones y fiestas<br>" + $" Siempre con el objetivo de brindar una experiencia inolvidable<br>" + $" Entre los servicios mas especializados tenemos:</p>" + $" <ul style = 'font-size: 15px; margin: 10px 0'>" + $" <li> Bodas.</li>" + $" <li> Cumpleaños.</li>" + $" <li> Baby Shower.</li>" + $" <li> Grados.</li>" + $" <li> Despedidas de Soltero.</li>" + $" </ul>" + $" <div style = 'width: 100%;margin:20px 0; display: inline-block;text-align: center'>" + $" <img style = 'padding: 0; width: 200px; margin: 5px' src = ''>" + $" </div>" + $" <div style = 'width: 100%; text-align: center'>" + $" <h2 style = 'color: #e67e22; margin: 0 0 7px' >Email Confirmation </h2>" + $" To allow the user,plase click in this link: <br/> <br/> " + $" <a style ='text-decoration: none; border-radius: 5px; padding: 11px 23px; color: white; background-color: #3498db' href = \"{tokenLink}\">Confirm Email</a>" + $" <p style = 'color: #b3b3b3; font-size: 12px; text-align: center;margin: 30px 0 0' > Eventos Room L21 2020. </p>" + $" </div>" + $" </td >" + $"</tr>" + $"</table>"); ViewBag.Message = "The instructions to allow your user has been sent to email."; model.UserTypes = _combosHelper.GetComboUserTypes(); return(View(model)); } ModelState.AddModelError(string.Empty, "Error"); model.UserTypes = _combosHelper.GetComboUserTypes(); return(View(model)); }
public async Task <IActionResult> Create(AddUserViewModel model) { if (ModelState.IsValid) { var user = await CreateUserAsync(model); if (user != null) { var owner = new Owner { Contracts = new List <Contract>(), Properties = new List <Property>(), User = user, }; _dataContext.Owners.Add(owner); await _dataContext.SaveChangesAsync(); var myToken = await _userHelper.GenerateEmailConfirmationTokenAsync(user); var tokenLink = Url.Action("ConfirmEmail", "Account", new { userid = user.Id, token = myToken }, protocol: HttpContext.Request.Scheme); _mailHelper.SendMail(model.Username, "Email confirmation", $"<table style = 'max-width: 600px; padding: 10px; margin:0 auto; border-collapse: collapse;'>" + $" <tr>" + $" <td style = 'background-color: #34495e; text-align: center; padding: 0'>" + $" <a href = 'https://www.facebook.com/NuskeCIV/' >" + $" <img width = '20%' style = 'display:block; margin: 1.5% 3%' src= 'https://veterinarianuske.com/wp-content/uploads/2016/10/line_separator.png'>" + $" </a>" + $" </td>" + $" </tr>" + $" <tr>" + $" <td style = 'padding: 0'>" + $" <img style = 'padding: 0; display: block' src = 'http://www2.acop.cl/wp-content/uploads/property-leasing-553x300.png' width = '100%'>" + $" </td>" + $"</tr>" + $"<tr>" + $" <td style = 'background-color: #ecf0f1'>" + $" <div style = 'color: #34495e; margin: 4% 10% 2%; text-align: justify;font-family: sans-serif'>" + $" <h1 style = 'color: #e67e22; margin: 0 0 7px' > Hola </h1>" + $" <p style = 'margin: 2px; font-size: 15px'>" + $" El mejor consorcio de arrendamiento Especializado de la Ciudad de Pasto enfocado a brindar servicios Arrendamiento y Venta de inmuebles<br>" + $" nace con la misión de satisfacer las necesidades de vivienda de los habitantes del Área metropolitana. Por más de 30 años hemos concentrado nuestros esfuerzos en garantizar a nuestros clientes un servicio integral ...<br>" + $" Entre los servicios tenemos:</p>" + $" <ul style = 'font-size: 15px; margin: 10px 0'>" + $" <li> Arriendo inmueble Nuevo o usado.</li>" + $" <li> Venta inmueble Nuevo o usado.</li>" + $" <li> Oferta vacacional.</li>" + $" <li> Gestion personal</li>" + $" <li> Gestion empresarial.</li>" + $" </ul>" + $" <div style = 'width: 100%;margin:20px 0; display: inline-block;text-align: center'>" + $" <img style = 'padding: 0; width: 200px; margin: 5px' src = 'https://veterinarianuske.com/wp-content/uploads/2018/07/tarjetas.png'>" + $" </div>" + $" <div style = 'width: 100%; text-align: center'>" + $" <h2 style = 'color: #e67e22; margin: 0 0 7px' >Email Confirmation </h2>" + $" To allow the user,plase click in this link:</br ></br> " + $" <a style ='text-decoration: none; border-radius: 5px; padding: 11px 23px; color: white; background-color: #3498db' href = \"{tokenLink}\">Confirm Email</a>" + $" <p style = 'color: #b3b3b3; font-size: 12px; text-align: center;margin: 30px 0 0' > LeasingWeb 2019 </p>" + $" </div>" + $" </td >" + $"</tr>" + $"</table>"); return(RedirectToAction("index")); } ModelState.AddModelError(string.Empty, "User with this email already exists"); } return(View(model)); }
public async Task <IActionResult> Create(AddUserViewModel model) { if (ModelState.IsValid) { var user = await CreateUserAsync(model); if (user != null) { var owner = new Owner { Contracts = new List <Contract>(), Properties = new List <Property>(), User = user }; _dataContext.Owners.Add(owner); await _dataContext.SaveChangesAsync(); var myToken = await _userHelper.GenerateEmailConfirmationTokenAsync(user); var tokenLink = Url.Action("ConfirmEmail", "Account", new { userid = user.Id, token = myToken }, protocol: HttpContext.Request.Scheme); _mailHelper.SendMail(model.Username, "Email confirmation", $"<table style = 'max-width: 600px; padding: 10px; margin:0 auto; border-collapse: collapse;'>" + $" <tr>" + $" <td style = 'background-color: #34495e; text-align: center; padding: 0'>" + $" <a href = 'https://www.facebook.com/NuskeCIV/' >" + $" <img width = '20%' style = 'display:block; margin: 1.5% 3%' src= 'https://veterinarianuske.com/wp-content/uploads/2016/10/line_separator.png'>" + $" </a>" + $" </td>" + $" </tr>" + $" <tr>" + $" <td style = 'padding: 0'>" + $" <img style = 'padding: 0; display: block' src = 'https://veterinarianuske.com/wp-content/uploads/2018/07/logo-nnske-blanck.jpg' width = '100%'>" + $" </td>" + $"</tr>" + $"<tr>" + $" <td style = 'background-color: #ecf0f1'>" + $" <div style = 'color: #34495e; margin: 4% 10% 2%; text-align: justify;font-family: sans-serif'>" + $" <h1 style = 'color: #e67e22; margin: 0 0 7px' > Hola </h1>" + $" <p style = 'margin: 2px; font-size: 15px'>" + $" El mejor Hospital Veterinario Especializado de la Ciudad de Morelia enfocado a brindar servicios médicos y quirúrgicos<br>" + $" aplicando las técnicas más actuales y equipo de vanguardia para diagnósticos precisos y tratamientos oportunos..<br>" + $" Entre los servicios tenemos:</p>" + $" <ul style = 'font-size: 15px; margin: 10px 0'>" + $" <li> Urgencias.</li>" + $" <li> Medicina Interna.</li>" + $" <li> Imagenologia.</li>" + $" <li> Pruebas de laboratorio y gabinete.</li>" + $" <li> Estetica canina.</li>" + $" </ul>" + $" <div style = 'width: 100%;margin:20px 0; display: inline-block;text-align: center'>" + $" <img style = 'padding: 0; width: 200px; margin: 5px' src = 'https://veterinarianuske.com/wp-content/uploads/2018/07/tarjetas.png'>" + $" </div>" + $" <div style = 'width: 100%; text-align: center'>" + $" <h2 style = 'color: #e67e22; margin: 0 0 7px' >Email Confirmation </h2>" + $" To allow the user,plase click in this link:</ br ></ br > " + $" <a style ='text-decoration: none; border-radius: 5px; padding: 11px 23px; color: white; background-color: #3498db' href = \"{tokenLink}\">Confirm Email</a>" + $" <p style = 'color: #b3b3b3; font-size: 12px; text-align: center;margin: 30px 0 0' > Nuskë Clinica Integral Veterinaria 2019 </p>" + $" </div>" + $" </td >" + $"</tr>" + $"</table>"); return(RedirectToAction("Index")); } ModelState.AddModelError(string.Empty, "User with this eamil already exists."); } return(View(model)); }
public async Task <IActionResult> Register(RegisterNewUserViewModel model) { if (ModelState.IsValid) { var user = await _userHelper.GetUserByEmailAsync(model.Username); if (user == null) { //var city = await _countryRepository.GetCityAsync(model.CityId); user = new User { FirstName = model.FirstName, LastName = model.LastName, Email = model.Username, UserName = model.Username, TIN = model.TIN, PhoneNumber = model.PhoneNumber, //CityId = model.CityId, //City = city }; var result = await _userHelper.AddUserAsync(user, model.Password); if (result != IdentityResult.Success) { this.ModelState.AddModelError(string.Empty, "The user couldn't be created."); return(this.View(model)); } User userInDB = await _userHelper.GetUserByEmailAsync(user.UserName); await _userHelper.AddUserToRoleAsync(userInDB, "Customer"); Customer customer = new Customer { //Appointments = new List<Appointmet>(), Pets = new List <Pet>(), FullName = user.FullName, User = userInDB }; await _customerRepository.CreateAsync(customer); var myToken = await _userHelper.GenerateEmailConfirmationTokenAsync(user); var tokenLink = this.Url.Action("ConfirmEmail", "Account", new { userid = user.Id, token = myToken }, protocol: HttpContext.Request.Scheme); _mailHelper.SendMail(model.Username, "YourVet - Email confirmation", $"<h1>Customer Email Confirmation</h1>" + $"<br/>" + $"Welcome to YouVet!!" + $"To allow the user, " + $"please click in this link:</br></br><a href = \"{tokenLink}\">Confirm Email</a>"); this.ViewBag.Message = "The instructions to allow your user has been sent to email."; return(this.View(model)); } this.ModelState.AddModelError(string.Empty, "The user already exists."); } return(View(model)); }
public async Task <IActionResult> PostUser([FromBody] UserRequest request) { if (!ModelState.IsValid) { return(BadRequest(new Response { IsSuccess = false, Message = "Bad request", Result = ModelState })); } CultureInfo cultureInfo = new CultureInfo(request.CultureInfo); Resource.Culture = cultureInfo; UserEntity user = await _userHelper.GetUserAsync(request.Email); if (user != null) { return(BadRequest(new Response { IsSuccess = false, Message = Resource.UserAlreadyExists })); } string picturePath = string.Empty; if (request.PictureArray != null && request.PictureArray.Length > 0) { picturePath = _imageHelper.UploadImage(request.PictureArray, "Users"); } user = new UserEntity { Address = request.Address, Document = request.Document, Email = request.Email, FirstName = request.FirstName, LastName = request.LastName, PhoneNumber = request.Phone, UserName = request.Email, PicturePath = picturePath, UserType = request.UserTypeId == 1 ? UserType.User : UserType.Driver }; IdentityResult result = await _userHelper.AddUserAsync(user, request.Password); if (result != IdentityResult.Success) { return(BadRequest(result.Errors.FirstOrDefault().Description)); } UserEntity userNew = await _userHelper.GetUserAsync(request.Email); await _userHelper.AddUserToRoleAsync(userNew, user.UserType.ToString()); string myToken = await _userHelper.GenerateEmailConfirmationTokenAsync(user); string tokenLink = Url.Action("ConfirmEmail", "Account", new { userid = user.Id, token = myToken }, protocol: HttpContext.Request.Scheme); _mailHelper.SendMail(request.Email, Resource.EmailConfirmationSubject, $"<h1>{Resource.EmailConfirmationSubject}</h1>" + $"{Resource.EmailConfirmationBody}</br></br><a href = \"{tokenLink}\">{Resource.ConfirmEmail}</a>"); return(Ok(new Response { IsSuccess = true, Message = Resource.EmailConfirmationSent })); }
public async Task <IActionResult> AddUser([FromBody] UserRequest request) { if (!ModelState.IsValid) { return(BadRequest(new Response { IsSuccess = false, Message = "Bad request", Result = ModelState })); } UserEntity user = await _userHelper.GetUserAsync(request.Email); if (user != null) { return(BadRequest(new Response { IsSuccess = false, Message = "User already exists" })); } string picturePath = string.Empty; if (request.PictureArray != null && request.PictureArray.Length > 0) { picturePath = _imageHelper.UploadImage(request.PictureArray, "Users"); } user = new UserEntity { Email = request.Email, Document = request.Document, FirstName = request.FirstName, LastName = request.LastName, PhoneNumber = request.Phone, UserName = request.Email, PicturePath = picturePath, UserType = request.UserTypeId == 1 ? UserType.Employee : UserType.Manager }; IdentityResult result = await _userHelper.AddUserAsync(user, request.Password); if (result != IdentityResult.Success) { return(BadRequest(result.Errors.FirstOrDefault().Description)); } UserEntity userNew = await _userHelper.GetUserAsync(request.Email); await _userHelper.AddUserToRoleAsync(userNew, user.UserType.ToString()); string myToken = await _userHelper.GenerateEmailConfirmationTokenAsync(user); string tokenLink = Url.Action("ConfirmEmail", "Account", new { userid = user.Id, token = myToken }, protocol: HttpContext.Request.Scheme); _mailHelper.SendMail(request.Email, "Email Confirmation", $"<h1>Email Confirmation</h1>" + $"</br>To allow the user, please click on this link:</br><a href = \"{tokenLink}\">Confirm Email</a>"); return(Ok(new Response { IsSuccess = true, Message = "A confirmation email was sent. Please confirm your account and log into the App." })); }