public async Task <IActionResult> Login(ViewModelLogin model) { try { if (ModelState.IsValid) { Usuario user = await _controladoraUsuarios.Login(model.Usuario, model.Password); if (user != null) { _session.SetString("Token", Seguridad.BuildToken(user)); _session.SetString("UserTipo", user.Tipo); _session.SetString("UserName", user.Nombre); _session.SetString("UserId", user.Id.ToString()); _session.SetString("Session", "si"); return(RedirectToAction("Index", "Home")); } return(View()); } ModelState.AddModelError(string.Empty, "Error al iniciar sesión"); return(View()); } catch (MensajeException ex) { ModelState.AddModelError(string.Empty, ex.Message); return(View()); } }
public async Task <IActionResult> Login(ViewModelLogin model) { var userFromDatabase = await _repo.Login(model.UserName.ToLower(), model.Password); if (userFromDatabase == null) { return(Unauthorized()); } var claims = new[] { new Claim(ClaimTypes.NameIdentifier, userFromDatabase.Id), new Claim(ClaimTypes.Name, userFromDatabase.UserName) }; var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes( _config.GetSection("AppSettings:Token").Value )); var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.Sha512); var tokenDescriptor = new SecurityTokenDescriptor() { SigningCredentials = signingCredentials, Subject = new ClaimsIdentity(claims), Expires = DateTime.Now.AddDays(1) }; var tokenManager = new JwtSecurityTokenHandler(); var token = tokenManager.CreateJwtSecurityToken(tokenDescriptor); return(Ok(new { token = tokenManager.WriteToken(token) })); }
public MainPage() { InitializeComponent(); // ventaja de usar un framework BindingContext = new ViewModelLogin(); }
public async Task <ActionResult> Login([FromBody] ViewModelLogin viewModel) { AuthUser authObject = null; var errors = new List <string>(); if (ModelState.IsValid) { authObject = await _managerSecurity.ValidateUser(viewModel); if (!authObject.IsAuthenticated) { errors.Add("Username or password incorrect!"); } } else { errors.AddRange(_GetModelStateErrors()); } if (errors.Count == 0) { return(StatusCode(StatusCodes.Status200OK, authObject)); } else { return(StatusCode(StatusCodes.Status400BadRequest, new { values = errors })); } }
public ActionResult Login(string ReturnUrl) { var viewModelLogin = new ViewModelLogin { UrlRetorno = ReturnUrl }; return(View(viewModelLogin)); }
internal async Task <AuthUser> ValidateUser(ViewModelLogin viewModel) { var authObject = new AuthUser(); var user = await _userManager.FindByNameAsync(viewModel.Username); if (user != null) { authObject = _BuildUserAuth(user); } return(authObject); }
public ActionResult Index(ViewModelLogin vmLogin) { bool testAjax = Request.IsAjaxRequest(); if (!ModelState.IsValid) { return(View(vmLogin)); } else { return(View()); } }
public async Task <IActionResult> GerarToken([FromBody] ViewModelLogin login) { if (ModelState.IsValid) { using (var context = new Context()) { var usuario = await context.Usuarios.FirstOrDefaultAsync(x => x.Email.Trim().ToLower() == login.Email.Trim().ToLower() && x.Senha == login.Senha); if (usuario != null) { var roles = new string[0]; var expireDate = DateTime.UtcNow.AddHours(1); var exp = new DateTimeOffset(expireDate); var payload = new Dictionary <string, object>() { { "unique_name", usuario.UsuarioId }, { "roles", roles }, //{ "company-roles",roles } , { "exp", exp.ToUnixTimeSeconds() }, { "iss", "flexxo.iss" }, { "aud", "flexxo.aud" } }; var headers = new Dictionary <string, object>(); try { var token = JWT.Encode(payload, Convert.FromBase64String(_configuration["TokenSecretKey"]), JwsAlgorithm.HS256, headers); return(Ok(new { token, usuario })); } catch (Exception e) { throw new Exception("Erro ao gerar token JWT", e); } } ModelState.AddModelError("", "Usuário ou senha inválidos"); } } return(BadRequest(ModelState)); }
public ActionResult Login(ViewModelLogin info) { var user = db.Users.Where(m => m.Login == info.Login).FirstOrDefault(); if (user != null && !user.IsValidated) { RemoveUser(user); return(RedirectToAction("Index", new { error = false })); } if (user != null && user.Password == info.Password) { return(View(user)); } return(RedirectToAction("Index", new { error = true })); }
public ActionResult Login(ViewModelLogin login, bool captchaValid) { if (!ModelState.IsValid) { return(View(login)); } Icasie.Repositories.User user = new Repositories.User(); using (IcasieEntities entity = new IcasieEntities()) { user = entity.Users.SingleOrDefault(c => c.Email == login.Email); } if (user != null && Helper.Helper.CreatePasswordHash(login.Password, user.Salt) == user.Password) { int timeout = Constant.CookieExpiration.Normal; var ticket = new FormsAuthenticationTicket(1, user.Email, DateTime.Now, DateTime.Now.AddMinutes(timeout), true, user.Role); var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket)); if (ticket.IsPersistent) { cookie.Expires = ticket.Expiration; } Response.Cookies.Add(cookie); } else { TempData["Message"] = "User & Password combination cannot be found"; return(View(login)); } switch (user.Role) { case Constant.Role.Author: return(RedirectToAction("Index", "Submission")); case Constant.Role.Participant: return(RedirectToAction("Index", "Participant")); default: return(RedirectToAction("Index", "Conference")); } }
public async Task <ActionResult> Login(ViewModelLogin model) { if (ModelState.IsValid) { var loginResult = await _signInManager.PasswordSignInAsync(model.Login, model.Password, false, false); if (loginResult.Succeeded) { if (Url.IsLocalUrl(model.ReturnUrl)) { return(Redirect(model.ReturnUrl)); } return(RedirectToAction("Index", "Home")); } ModelState.AddModelError("", "Неверные данные"); } return(View(model)); }
public void start() { BinaryServerFormatterSinkProvider serverProv = new BinaryServerFormatterSinkProvider(); serverProv.TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full; BinaryClientFormatterSinkProvider clientProv = new BinaryClientFormatterSinkProvider(); IDictionary props = new Hashtable(); props["port"] = 0; TcpChannel channel = new TcpChannel(props, clientProv, serverProv); ChannelServices.RegisterChannel(channel, false); IServer server = (IServer)Activator.GetObject(typeof(IServer), "tcp://192.168.19.1:12345/Curse"); var service = new ServiceClient(server); DataContext = new ViewModelLogin(service); }
public ViewLogin(Boolean paramIsPersonalizado, String paramNameProject) { InitializeComponent(); Panel.Margin = _app.DefaultTemplateMargin; Panel.HeightRequest = _app.ScreenHeight; Panel.WidthRequest = _app.ScreenWidth; Grid.HeightRequest = Panel.HeightRequest; Grid.WidthRequest = Panel.WidthRequest; MontaLoad(); _viewModelLogin = new ViewModelLogin(paramIsPersonalizado, paramNameProject); _viewModelLogin._view = this as IViewLogin; this.BindingContext = _viewModelLogin; }
public ActionResult Login(ViewModelLogin viewModel) { if (!ModelState.IsValid) { return(View(viewModel)); } var usuario = _usuarioBusiness.List().FirstOrDefault(u => u.Login == viewModel.Login); if (usuario == null) { ModelState.AddModelError("Login", "Login Incorreto"); return(View(viewModel)); } if (usuario.Login != viewModel.Login) { ModelState.AddModelError("Login", "Login Incorreto"); return(View(viewModel)); } if (usuario.Senha != viewModel.Senha) { ModelState.AddModelError("Senha", "Senha incorreta"); return(View(viewModel)); } var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, usuario.Nome), new Claim("Login", usuario.Login) }, "ApplicationCookie"); Request.GetOwinContext().Authentication.SignIn(identity); if (!String.IsNullOrWhiteSpace(viewModel.UrlRetorno) || Url.IsLocalUrl(viewModel.UrlRetorno)) { return(Redirect(viewModel.UrlRetorno)); } else { return(RedirectToAction("Index", "Home")); } }
public Usuario FazerLogin(ViewModelLogin vm_login) { Usuario usuario = new Usuario(); try { UsuarioBusiness usuario_business = new UsuarioBusiness(); usuario = usuario_business.GetUsuario(vm_login.LoginSenha, vm_login.LoginUsuario); } catch (Exception ex) { if (this.connection.State == System.Data.ConnectionState.Open) { this.connection.Close(); } } return(usuario); }
public ActionResult Login(ViewModelLogin newAccount) { var username = newAccount.Username; ViewBag.success = true; try { if (am.LoginCertification(newAccount.Username, newAccount.Password)) { cookiemanagement.CoockieCrationOfAustetication(username); return(RedirectToAction("Index", "Home")); } else { ViewBag.success = false; return(View()); } } catch (ArgumentException e) { return(View()); } }
public async Task <ActionResult <ViewModelResponse> > Login([FromBody] ViewModelLogin model) { try { var ldap = await ServiceLDAP.LoginAsync(model.UserName, model.Password); if (ldap) { var us = await _userManager.FindByNameAsync(model.UserName); if (us != null) { if (us.Verified) { var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, false, false); if (result.Succeeded) { var appUser = _userManager.Users.SingleOrDefault(u => u.UserName == model.UserName); var token = GenerateJwtToken(model.UserName, appUser); var httpClient = new WebClient(); byte[] bytes; try { bytes = await httpClient.DownloadDataTaskAsync(appUser.Picture); } catch (TaskCanceledException) { System.Console.WriteLine("Task Canceled!"); bytes = null; } catch (Exception e) { bytes = null; } ViewModelUser user = new ViewModelUser() { Id = new Guid(appUser.Id), Name = appUser.Name, LastName = appUser.LastName, UserName = appUser.UserName, Email = appUser.Email, Country = appUser.Country, ImageBytes = bytes, Picture = appUser.Picture }; return(Json(new ViewModelResponse() { Error = false, Response = "Ha iniciado sesión satisfactoriamente", User = user, Token = token })); } else { return(Json(new ViewModelResponse() { Error = true, Response = "Valide sus credenciales." })); } } return(Json(new ViewModelResponse() { Error = true, Response = "Debe verificar primero su cuenta, revise su correo." })); } return(Json(new ViewModelResponse() { Error = true, Response = "Valide sus credenciales. Usuario no encontrado" })); } else { return(Json(new ViewModelResponse() { Error = true, Response = "Valide sus credenciales. Usuario no encontrado" })); } } catch (Exception e) { string error = String.Format("Ocurrion un error. Intente nuevamente. {0}", e.Message); return(StatusCode(StatusCodes.Status500InternalServerError, new ViewModelResponse { Error = true, Response = error })); } }
public MainPage() { this.InitializeComponent(); loginViewModel = (ViewModelLogin)this.DataContext; }
public JsonResult <Usuario> Login(ViewModelLogin vm_login) { LoginBusiness login = new LoginBusiness(); return(Json(login.FazerLogin(vm_login))); }
public ViewModelInformation Login(ViewModelLogin viewModelLogin) { ViewModelInformation viewModelInformation = new ViewModelInformation(); viewModelInformation = new ViewModelInformation(); string js_code = viewModelLogin.Code.ToString(); string serviceAddress = "https://api.weixin.qq.com/sns/jscode2session?appid=wxece27e98fc59b527&secret=3efec00e6fe037602aeae3a317608942&js_code=" + js_code + "&grant_type=authorization_code"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress); request.Method = "GET"; request.ContentType = "text/html;charset=UTF-8"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); string key = "\"openid\":\""; int startIndex = retString.IndexOf(key); int endIndex = retString.IndexOf("\"}", startIndex); string openid = retString.Substring(startIndex + key.Length, endIndex - startIndex - key.Length); var user = unitOfWork.LoginRepository.Get().Where(s => s.OpenId.Equals(openid)).FirstOrDefault(); if (user != null) { var UserRole = (from u in unitOfWork.LoginRepository.Get() join ur in unitOfWork.LoginRoleRepository.Get() on u.ID equals ur.UserID join r in unitOfWork.SysRoleRepository.Get() on ur.PrimaryRoleID equals r.ID where u.OpenId.Equals(openid) select new { PrimaryRoleID = ur.PrimaryRoleID, RoleName = r.RoleName, ConfirmRoleID = ur.ConfirmRoleID }) .FirstOrDefault(); if (UserRole.ConfirmRoleID == 0) { viewModelInformation.Message = "角色待确认"; return(viewModelInformation); } else { if (UserRole.RoleName == "学生") { var student = unitOfWork.StudentRepository.Get().Where(s => s.OpenId.Equals(openid)).FirstOrDefault(); viewModelInformation.ID = student.ID; viewModelInformation.Message = "学生"; return(viewModelInformation); } else if (UserRole.RoleName == "教师") { var teacher = unitOfWork.TeacherRepository.Get().Where(s => s.OpenId.Equals(openid)).FirstOrDefault(); viewModelInformation.ID = teacher.ID; viewModelInformation.Message = "教师"; return(viewModelInformation); } else { viewModelInformation.Message = "admin"; return(viewModelInformation); } } } else { viewModelInformation.Message = "还没注册"; return(viewModelInformation); } }
public ViewLogin() { InitializeComponent(); BindingContext = new ViewModelLogin(); ((ViewModelLogin)BindingContext).Navigation = this.Navigation; }
public ListScoresCommand(ViewModelLogin viewmodel) { _viewModel = viewmodel; }
public ViewLogin() { BindingContext = new ViewModelLogin(); InitializeComponent(); }
public PlayCommand(ViewModelLogin viewmodel) { _viewModel = viewmodel; }