public async Task <IActionResult> RegisterCliente(RegisterClienteViewModel model) { if (string.IsNullOrWhiteSpace(model.UserName)) { ModelState.AddModelError("", "Nome de usuário está vazio ou contém espaços vazios."); return(View(model)); } if (!ModelState.IsValid) { ModelState.AddModelError("", "Erro ao efetuar o cadastro! Verifique se os campos estão corretos."); return(View(model)); } try { var user = new ApplicationUser() { UserName = model.UserName, Email = model.Email, FullName = model.FullName, Ativo = true }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { var addRole = await _userManager.AddToRoleAsync(user, "Cliente"); if (!addRole.Succeeded) { ModelState.AddModelError("", "Ocorreu um problema ao processar a sua requisiçao."); await _userManager.DeleteAsync(user); return(SmartResult(model)); } // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713 // Send an email with this link //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme); //await _emailSender.SendEmailAsync(model.Email, "Confirm your account", // "Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>"); //await _signInManager.SignInAsync(user, isPersistent: false); //_logger.LogInformation(3, "User created a new account with password."); return(RedirectToAction(nameof(HomeController.Index), "Home")); } if (!result.Succeeded) { foreach (var errors in result.Errors) { ModelState.AddModelError("", errors.Description); } } //AddErrors(result); } catch (Exception ex) { Log(ex, "Account/Register :POST"); } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <IActionResult> Register(RegisterClienteViewModel clienteInfo) { if (!ModelState.IsValid) { return(View(clienteInfo)); } string username = clienteInfo.EmailCliente; IdentityUser user = await _userManager.FindByNameAsync(username); if (user != null) { ModelState.AddModelError("Email", "Já foi criada uma conta com este email."); return(View(clienteInfo)); } user = new IdentityUser(username); await _userManager.CreateAsync(user, clienteInfo.Password); await _userManager.AddToRoleAsync(user, "Cliente"); Cliente cliente = new Cliente { NomeCliente = clienteInfo.NomeCliente, NumeroTelefoneCliente = clienteInfo.NumeroTelefoneCliente, NifCliente = clienteInfo.NifCliente, EmailCliente = clienteInfo.EmailCliente }; _context.Add(cliente); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index), "Home")); }
public async Task <IActionResult> RegisterCliente(RegisterClienteViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { HistoricoTransacoeMonetarias h1 = new HistoricoTransacoeMonetarias(); ContaDeCreditos conta = new ContaDeCreditos(); conta.HistoricoTransacoeMonetarias = h1; Cliente user = new Cliente { Nome = model.Nome, Apelido = model.Apelido, UserName = model.Email, Email = model.Email, ContaDeCreditos = conta }; var result = await _userManager.CreateAsync(user, model.Password);// cria um user com a pw if (result.Succeeded) { Notificacao notificacao1 = new Notificacao() { Mensagem = "Bem vindo à plataforma", Tipo = Notificacao.TYPE_INFO, Lida = false, UtilizadorId = user.Id }; _context.Notificacao.Add(notificacao1); Notificacao notificacao2 = new Notificacao() { Mensagem = "Confirme o seu email", Tipo = Notificacao.TYPE_WARNING, Lida = false, UtilizadorId = user.Id }; _context.Notificacao.Add(notificacao2); await _userManager.AddToRoleAsync(user, Roles.ROLE_CLIENTE);//atribui a role // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713 // Send an email with this link var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); var callbackUrl = Url.Action("ConfirmEmail", "Autenticacao", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme); await _emailSender.SendEmailAsync(model.Email, "Confirm your account", $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>"); await _signInManager.SignInAsync(user, isPersistent : false);//para ele depois fazer login, regista-se e fica logo loged-in _logger.LogInformation(3, "User created a new account with password."); return(RedirectToLocal(returnUrl));// redirecionar para o homeloged in? sim xD } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <ActionResult> RegisterCliente(RegisterClienteViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { var r = UserManager.AddToRole(user.Id, "Cliente"); model.ClienteVM.Cliente.UserNameID = user.Id; model.ClienteVM.Cliente.Email = user.Email; Direccion direccion = db.Direccions.Add(model.ClienteVM.Direccion); db.SaveChanges(); model.ClienteVM.Cliente.Fecha_Ingreso = DateTime.Now; model.ClienteVM.Cliente.Estado_Cliente = db.Estado_Clientes.Where(e => e.Descripcion == "Activo").FirstOrDefault(); model.ClienteVM.Cliente.Direccion_DireccionID = direccion.DireccionID; db.Clientes.Add(model.ClienteVM.Cliente); db.SaveChanges(); await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); // Para obtener más información sobre cómo habilitar la confirmación de cuentas y el restablecimiento de contraseña, visite https://go.microsoft.com/fwlink/?LinkID=320771 // Enviar correo electrónico con este vínculo // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // await UserManager.SendEmailAsync(user.Id, "Confirmar cuenta", "Para confirmar la cuenta, haga clic <a href=\"" + callbackUrl + "\">aquí</a>"); return(RedirectToAction("Index", "Home")); } AddErrors(result); } ViewBag.Tipo_Identificacion_Tipo_IdentificacionID = new SelectList(db.Tipo_Identificacions, "TipoID", "Descripcion", model.ClienteVM.Cliente.Tipo_Identificacion_Tipo_IdentificacionID); ViewBag.Pais_PaisID = new SelectList(db.Paises, "PaisID", "Nombre_Pais", model.ClienteVM.Direccion.Pais_PaisID); // Si llegamos a este punto, es que se ha producido un error y volvemos a mostrar el formulario return(View(model)); }
public async Task <ActionResult> RegisterCliente(RegisterClienteViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.email, Email = model.email, ativo = true, dataCadastro = DateTime.Now }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { //await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); NetGoogleGeocoding geoCoder = new NetGoogleGeocoding(); string endereco = model.endereco + ", " + model.numero; string enderecoConsulta = endereco + " - " + model.cidade + " - " + model.estado; Clientes c = new Clientes(); c.clienteId = user.Id; //c.cpf = model.cpf.Replace(".", "").Replace("-", ""); // Se Habilitar o cadastro com CPF, descomente está linha c.tipo = model.tipo.ToString(); c.nome = model.nome; c.endereco = enderecoConsulta; c.email = model.email; c.sexo = model.sexo.ToString(); c.dataNascimento = model.dataNascimento; if (model.telefone != null) { c.telefone = model.telefone.Replace("(", "").Replace(")", "").Replace("-", "").Replace(" ", ""); // adicionei o Replace (Teste) - Titans } c.celular = model.celular.Replace("(", "").Replace(")", "").Replace("-", "").Replace(" ", ""); // adicionei o Replace (Teste) - Titans c.cooperativaId = model.cooperativaId; try { var response = geoCoder.GoogleGeocode(enderecoConsulta).GeoCodes[0]; if (response != null) { c.enderecoCoordenada = geoCoder.ConvertLatLonToDbGeometry(response.Longitude, response.Latitude); } else { c.enderecoCoordenada = null; } } catch (Exception) { c.enderecoCoordenada = null; } Roles r = db.Roles.Find("1"); if (r == null) { r = new Roles(); r.Id = "1"; r.Name = "Cliente"; db.Roles.Add(r); } UsuarioRole ur = new UsuarioRole(); ur.UserId = user.Id; ur.RoleId = "1"; db.UsuarioRole.Add(ur); db.Clientes.Add(c); db.SaveChanges(); LoginViewModel lvm = new LoginViewModel() { Email = model.email, Password = model.Password, RememberMe = false }; return(await Login(lvm, null)); } AddErrors(result); } #region ValidaçãoFalha var SexoList = new List <dynamic>(); SexoList.Add(new { Id = "M", Text = "Masculino" }); SexoList.Add(new { Id = "F", Text = "Feminino" }); ViewBag.sexo = new SelectList(SexoList, "Id", "Text"); var TipoList = new List <dynamic>(); TipoList.Add(new { Id = "D", Text = "Doador" }); TipoList.Add(new { Id = "V", Text = "Vendedor" }); ViewBag.tipo = new SelectList(TipoList, "Id", "Text"); var EstadoList = new List <dynamic>(); EstadoList.Add(new { Id = "SE", Text = "Sergipe" }); EstadoList.Add(new { Id = "BA", Text = "Bahia" }); ViewBag.estado = new SelectList(EstadoList, "Id", "Text"); ViewBag.cooperativas = new SelectList(db.Cooperativas, "cooperativaId", "cnpj", model.cooperativaId); ViewBag.retorno = @Url.Action("Login", "Account"); #endregion return(View(model)); }