public ActionResult Login(UserLoginModel model, string returnUrl) { if (!ModelState.IsValid) { return View(model); } if (ur.ValidLogin(model.username, UserRepository.GetSHA512(model.password, model.username))) { ModelState.AddModelError("", "Login correcto."); //Para testeo HttpCookie cookieUser = new HttpCookie("user", model.username); HttpCookie cookieToken = new HttpCookie("token", model.username + ":" + UserRepository.GetSHA512(model.username + UserRepository.GetSHA512(model.password, model.username), model.username)); cookieUser.Expires = DateTimeOffset.Now.AddYears(1).Date; cookieToken.Expires = DateTimeOffset.Now.AddYears(1).Date; this.HttpContext.Response.SetCookie(cookieUser); this.HttpContext.Response.SetCookie(cookieToken); if (String.IsNullOrEmpty(returnUrl)) return View(model); else return Redirect(returnUrl); } else { ModelState.AddModelError("", "Intento de inicio de sesión no válido."); return View(model); } }
public HttpResponseMessage LoginUser(UserLoginModel model) { var responseMsg = this.ExceptionHandler( () => { UserDataPersister.ValidateUsername(model.Username); UserDataPersister.ValidateAuthCode(model.AuthCode); var usernameToLower = model.Username.ToLower(); var users = this.userRepository.All(); var user = users.FirstOrDefault( usr => usr.Username == usernameToLower && usr.AuthCode == model.AuthCode); if (user == null) { throw new InvalidOperationException("Invalid Username or Password"); } this.userRepository.Update(user, user.Id, true); var loggedModel = new UserLoggedModel { DisplayName = user.DisplayName, SessionKey = user.SessionKey }; var response = this.Request.CreateResponse(HttpStatusCode.Created, loggedModel); response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = user.Id })); return response; }); return responseMsg; }
public LoginPage(IUserRepository userRepository = null, INotifyPage notifyPage = null, IValuesRepository valuesRepository = null) { _userRepository = userRepository ?? DependencyService.Get<IUserRepository>(); _notifyPage = notifyPage ?? new NotifyPage(this); _valuesRepository = valuesRepository ?? DependencyService.Get<IValuesRepository>(); _userLoginModel = _userRepository.GetUserLoginModel(); BindingContext = _userLoginModel; InitializeComponent(); }
public UserLoginModel VerifyAccessToken(string accesToken) { try { UserLoginModel user_login = new UserLoginModel(); DataTable dt = new DataTable(); JWTPayload payload = JWT.Decode <JWTPayload>(accesToken, this.secretKey); if (payload == null) { return(null); } if (payload.exp < DateTime.UtcNow) { return(null); } string sql = " select PkAdminweb.admin_ID, " + " PkAdminweb.name, " + " PkAdminweb.admin_level_id, " + " PkAdminweb.Terncode, " + " PkAdminweb.Ternsubcode," + " PkDepartments.DeptName, " + " PkAdminweb.adminname , " + " PkAdminweb.Custom " + " from PkAdminweb " + " left join PkAdminweb_level on PkAdminweb.admin_level_id = PkAdminweb_level.admin_level_id " + " left join PkDepartments on PkAdminweb.Ternsubcode = PkDepartments.DeptID and PkAdminweb.Terncode = PkDepartments.CompanyID " + " where (PkAdminweb.adminname = '" + payload.username + "' )"; dt = dabase.QueryDataTable(sql); user_login = (from c in dt.AsEnumerable() select new UserLoginModel { AdminId = Convert.ToInt32(c["admin_ID"]), name = c["name"].ToString(), AdminLevel = Convert.ToInt32(c["admin_level_id"]), Aminname = c["adminname"].ToString(), CommanyName = c["DeptName"].ToString(), CompanyID = c["Terncode"].ToString(), DeptID = c["Ternsubcode"].ToString(), Custom = c["Custom"].ToString() }).SingleOrDefault(); return(user_login); } catch (Exception ex) { return(null); } }
public async Task <object> Login(UserLoginModel userLoginModel) { var res = await _unitOfWork.SignInManager .PasswordSignInAsync(userLoginModel.Email, userLoginModel.Password, userLoginModel.RememberMe, false); if (res.Succeeded) { var user = await _unitOfWork.UserManager.Users.SingleOrDefaultAsync(u => u.Email == userLoginModel.Email); return(GenerateJwtToken(userLoginModel.Email, user.AdaptToDTO())); } throw new Exception("Login failed"); }
/// <summary> /// 记录日志 /// </summary> public async Task SaveLog(string userId, int clientId, string loginIp, UserLoginModel loginModel) { var logEntity = new OperatorLogEntity { UserId = userId, Content = loginModel.ToString(), Ip = loginIp, CreateDate = DateTime.Now, ClientId = clientId }; await _operatorLogRepository.InsertAsync(logEntity); await _unitOfWork.SaveChangesAsync(); }
public static string Login(UserLoginModel user) { return("lol"); //if(!String.IsNullOrWhiteSpace(user.Username) && !String.IsNullOrWhiteSpace(user.Password)) //{ // User loginUser = new Models.User(user.Username, user.Password); // if (Models.User.IsRegistered(loginUser)) // { // Session.Add("user", user.Username); // Response.Redirect("/Pages/OrderStatus.aspx"); // } //} //return "Invalid Username/Password"; }
/// <summary> /// Authorizing existing user /// </summary> /// <param name="loginModel">Model for authorization</param> /// <param name="profile">Existing user profile</param> /// <returns></returns> public UserModel Authenticate(UserLoginModel loginModel, UserProfile profile) { UserModel user = null; var userNameMatches = string.Equals(loginModel.Username, profile.Login, StringComparison.InvariantCultureIgnoreCase); var passwordMatches = _passwordHasher.VerifyHashedPassword(profile, profile.Password, loginModel.Password) == PasswordVerificationResult.Success; if (userNameMatches && passwordMatches) { user = new UserModel(profile); } return(user); }
public async Task <IActionResult> Index(UserLoginModel model) { var claims = new List <Claim>() { new Claim(ClaimTypes.Name, model.UserName) }; var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), new AuthenticationProperties() { IsPersistent = true }); return(RedirectToAction("Show")); }
public async Task <IActionResult> Login(UserLoginModel userModel) { var user = await _userManager.FindByEmailAsync(userModel.Email); if (user != null && await _userManager.CheckPasswordAsync(user, userModel.Password)) { var signingCredentials = GetSigningCredentials(); var claims = GetClaims(user); var tokenOptions = GenerateTokenOptions(signingCredentials, await claims); var token = new JwtSecurityTokenHandler().WriteToken(tokenOptions); return(Ok(token)); } return(Unauthorized("Invalid Authentication")); }
public ActionResult AppLogin(UserLoginModel model) //public ActionResult AppLogin(string username,string password) { if (model.UserName == null || model.Password == null) { return(Json(new { Code = 301, Msg = "post未获取到参数" })); } var user = SysUserDAL.GetByOne(q => q.UserName == model.UserName && q.Password == model.Password); if (user != null) { user.Token = TokenProccessor.MakeToken(); LoginUserModel loginUser = new LoginUserModel { Token = user.Token, Id = user.Id, UserName = user.UserName, RealName = user.RealName, Email = user.Email, OpenId = user.OpenId, QQ = user.QQ, MobilePhone = user.MobilePhone, UserType = user.UserType, RoleIds = new List <int> { 1, 2, 3, 4 }, RoleName = "系统管理员", FirstDepId = "1001", FirstDepName = "管理中心", DepName = "财政部", Name = "李四" }; ResultData <LoginUserModel> rst = new ResultData <LoginUserModel> { Code = 200, Msg = "success", Result = loginUser }; //更新登录用户Token SysUserDAL.Update(user); LoginUser = loginUser; return(Json(rst)); } else { return(Json(new { Code = 401, Msg = "用户不存在或密码错误" })); } }
public ServiceResponse Login(UserLoginModel model) { this.Response = new ServiceResponse(); this.Context.ReadOnly = false; var user = Db.UserQueryByEmail(model.Email).Include(u => u.Business).FirstOrDefault(); if (user == null) { this.Response.Messages.AddError("Email", ResourceModelUser.MU004); return(this.Response); } // Check password var pwdHash = Crypto.Hash(model.Password, user.Salt); if (string.Compare(pwdHash, user.Password) != 0) { this.Response.Messages.AddError("Email", ResourceModelUser.MU004); return(this.Response); } if (!user.Approved) { this.Response.Messages.AddError("Email", ResourceModelUser.MU006); return(this.Response); } if (!user.Enabled) { this.Response.Messages.AddError("Email", ResourceModelUser.MU005); return(this.Response); } if (!user.Business.Enabled) { this.Response.Messages.AddError("Email", ResourceModelUser.MU022); return(this.Response); } user.LastLoginOn = DateTime.UtcNow; Db.SaveChanges(); this.Response.Model = model; return(this.Response); }
public ActionResult Login(UserLoginModel userLoginModel, string ReturnUrl) { string message = ""; using (DatabaseEntities de = new DatabaseEntities()) { var user = de.Users.Where(a => a.EmailID == userLoginModel.EmailID).FirstOrDefault(); if (user != null) { if (user.IsEmailVerified == true) { if (string.Compare(Crypto.Hash(userLoginModel.Password), user.Password) == 0) { int timeout = userLoginModel.RememberMe ? 525600 : 20; // 525600 mins = 1 year var ticket = new FormsAuthenticationTicket(userLoginModel.EmailID, userLoginModel.RememberMe, timeout); string encrypted = FormsAuthentication.Encrypt(ticket); var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted); cookie.Expires = DateTime.Now.AddMinutes(timeout); cookie.HttpOnly = true; Response.Cookies.Add(cookie); if (Url.IsLocalUrl(ReturnUrl)) { return(Redirect(ReturnUrl)); } else { return(RedirectToAction("DisplayAllVideos", "Video")); } } else { message = "Invalid credentials provided!"; } } else if (user.IsEmailVerified == false) { message = "You must verify your account before you can log in with it!"; } } else { message = "Invalid credentials provided!"; } } ViewBag.Message = message; return(View()); }
/// <summary> /// Handles the logic for getting the user token from /// the supplied credentials. /// </summary> /// <param name="controllerContext"></param> /// <returns></returns> public UserToken GetUserToken(ControllerBase controllerContext) { // create LoginModel from the request UserLoginModel data = new UserLoginModel(); // if request data is from the from, populate LoginModel from the form if (controllerContext.Request.HasFormContentType) { data.username = controllerContext.Request.Form["username"]; data.password = controllerContext.Request.Form["password"]; } else { // get the LoginModel passed in the request body if (controllerContext.Request.ContentType == "application/json") { StringWriter s = new StringWriter(); using (var sr = new StreamReader(controllerContext.Request.Body)) { s.Write(sr.ReadToEnd()); } data = JsonConvert.DeserializeObject <UserLoginModel>(s.ToString()); } } if (data == null) { throw new ArgumentNullException(nameof(data), "The login data may not be null."); } //TODO: Run username and password against regex validation rules if (string.IsNullOrWhiteSpace(data.username)) { throw new ArgumentException("Neither the Username or Password may be null or whitespace."); } if (string.IsNullOrWhiteSpace(data.password)) { throw new ArgumentException("Neither the Username or Password may be null or whitespace."); } var user = CheckUsernamePassword(data.username, data.password); // username and password matches if (user != null) { return(MakeUserToken(controllerContext, user)); } return(null); }
public JsonResult LoginUser(UserLoginModel.UserLoginRequestModel model) { var result = new UserLoginModel.UserLoginResponseModel(); if (WebSecurity.Login(model.userName, model.password, persistCookie: model.rememberMe)) { FormsAuthentication.SetAuthCookie(model.userName, model.rememberMe); result.validLogin = true; if (!string.IsNullOrEmpty(model.returnUrl)) result.validLoginUrl = model.returnUrl; else result.validLoginUrl = @"/"; return Json(result); } return Json(result); }
public async Task <IActionResult> SignInAsync([FromBody] UserLoginModel loginModel) { var userInfoModel = await _accountService.SignInAsync(loginModel); if (userInfoModel.Errors.Any()) { return(Ok(userInfoModel)); } var result = _jwtHelper.Generate(userInfoModel, _configOptions); GenerateCookie(result); return(Ok(userInfoModel)); }
public IActionResult Login([FromBody] UserLoginModel userLogin) { User user = UserRepository.Get().GetUser(userLogin.UserName); if (user == null) { NotFound($"Could not find username {userLogin.UserName}"); } if (!Util.PasswordsMatch(user, userLogin.Password)) { throw new AuthenticationException("Passwords don't match"); } return(Ok(Util.GenerateJWT(user, _tokenOptions))); }
public UserModel Login(UserLoginRequestModel req) { UserModel currentUser = new UserModel(); { UserLoginModel userInfo = Get(req.Email); bool validPassword = BCrypt.Net.BCrypt.Verify(req.Password, userInfo.Password); if (validPassword) { currentUser = userInfo; } } return(currentUser); }
//인증 public ClaimsPrincipal GetClaimsPrincipal(UserLoginModel model) { var userData = ReadUser(model.Id); var claims = new Claim[] { new Claim("id", userData.Id), new Claim("pw", userData.Pw) }; var ci = new ClaimsIdentity(claims, model.Pw); return(new ClaimsPrincipal(ci)); }
public ActionResult Map() { if (!Logged()) { return(RedirectToAction("Index", "Login")); } szmalDBEvents db = new szmalDBEvents(); UserLoginModel userLoginModel = new UserLoginModel(); var bigmodel = new BigModel() { EventToShowModel = db.zgloszenies.Select(s => s), UserLoginModel = null }; return(View("~/Views/Home/Map.cshtml", bigmodel)); }
public TokenInfo Registrer([FromBody] UserLoginModel user) { Argument.Require(user != null, Localizer["ERROR_ARGUMENT_NULL", nameof(user)]); UserBase newUser = new UserBase() { Login = user.Login, Email = user.Email, PasswordHash = user.Password }; newUser = UserService.CreateUser(newUser); TokenInfo token = this._GenerateToken(newUser); return(token); }
async Task CheckSignInIfValidAsync(UserLoginModel model) { ValidationResult result = validator.Validate(model); if (result.IsValid) { await SignInIfCredentialsOK(model); } else { errorCollector.AddErrors(result.Errors); errorCollector.Save(); NavigateTo(NavigationLocation.Current); } }
public ActionResult ResetForgetPassword(UserLoginModel user) { bool result = Services.UserService.ChangePassword(user); if (result == true) { //TempData["Success"] = "Your password has been successfully changed. Please login now."; return(RedirectToAction("Login", "MyAccount")); } else { ViewBag.Message = "Sorry, Unable to change your password."; return(View()); } }
public HttpResponseMessage LoginUser(UserLoginModel user) { var responseMsg = this.PerformOperation(() => { string nickname = string.Empty; var sessionKey = UserDataPersister.LoginUser(user.Username, user.AuthCode, out nickname); return(new UserLoggedModel() { Nickname = nickname, SessionKey = sessionKey }); }); return(responseMsg); }
public override bool Registration(string name, byte[] password) { UserLoginModel model = CreateUserLoginModel(name, password); if (model != null) { using (var unit = DIManager.UnitOfWork) { CreateUser(model, unit); userAthorization(model.Name); return(true); } } return(false); }
public void Validate_WhenUserNameAndPasswordArePresent_ReturnsValidResult() { //Given UserLoginValidator validator = new UserLoginValidator(); UserLoginModel model = new UserLoginModel() { Username = "******", Password = "******" }; //When ValidationResult result = validator.Validate(model); //Then Assert.True(result.IsValid); }
public ActionResult EditStudent(StudentModel model) { HttpCookie loggedStudent = Request.Cookies["LoggedUser"]; UserServices services = new UserServices(); StudentModel student = services.GetStudent(loggedStudent.Values.Get("Login")); services.ChangePassword(student.Login, student.Name, student.Surname, model.Password); UserLoginModel logged = new UserLoginModel(); logged.Login = student.Login; logged.Name = student.Name; logged.Surname = student.Surname; return(RedirectToAction("Index", logged)); }
public bool Login(UserLoginModel userLogin) { var user = this.Mapper.Map <UserLoginModel, User>(userLogin); var findUser = this.UOW.UserRepository.GetByEmail(user.Email); bool success = false; if (findUser != null && findUser.IsDeleted == false) { UOW.SignInManager.SignOutAsync(); var result = UOW.SignInManager.PasswordSignInAsync(findUser, user.PasswordHash, true, false).Result; success = result.Succeeded; } return(success); }
public async System.Threading.Tasks.Task <string> LoginAsync(UserLoginModel user) { var uri = new Uri(string.Format(usersUrl, "authenticate")); var json = JsonConvert.SerializeObject(user); var content = new StringContent(json, Encoding.UTF8, "application/json"); var response = await client.PostAsync(uri, content); var t = await response.Content.ReadAsStringAsync(); LoggedUser = JsonConvert.DeserializeObject <LoggedUser>(t); return(LoggedUser.Email); }
public HttpResponseMessage Login([FromBody] UserLoginModel user) { var responseJson = new TokenResponse { StatusCode = (int)HttpStatusCode.Unauthorized, StatusText = HttpStatusCode.Unauthorized.ToString() }; if (CheckParameters(user.UserName, user.Password)) { responseJson = DoGenerateToken(user.UserName); } return(ResponAuthToken(responseJson)); }
public ActionResult Register(string identify, string jobNumber) { UserLoginModel model = new UserLoginModel { IdNumber = identify, LoginType = LoginType.Novice, JobNumber = jobNumber }; var result = securityBusinesscs.UserVerify(model); Session["UserInfo"] = new FakeUserInfo(result.UserId); return(RedirectToAction("IndexPic", "Home", null)); }
public void LoginTest() { using (TransactionScope transaction = new TransactionScope()) { UserLoginModel model = new UserLoginModel(); HomeController controller = new HomeController(); model.Password = "******"; model.Username = "******"; ActionResult result = controller.Login(model, null); Assert.IsNotNull(result); } }
public IResult LoginUser([FromBody] UserLoginModel loginModel) { var userResult = _userService.LoginUser(loginModel.UserEmail, loginModel.UserPassword); if (userResult.Status == Status.Success) { var token = new ObjectResult(GenerateToken(userResult.Body)); userResult.Body = token.Value; } else { userResult.Body = Unauthorized(); } return(userResult); }
/// <summary> /// 验证用户名密码 /// </summary> /// <param name="model"></param> /// <returns></returns> public async Task <bool> ValidateCredentials(UserLoginModel model) { using (var uw = this.CreateUnitOfWork()) { var user = await uw.GetAsync <UserLogin>(t => t.UserName == model.UserName && t.UserPwd == model.UserPwd); if (user == null) { return(false); } return(true); } }
public ActionResult Login(UserLoginModel model, string returnurl) { ViewBag.returnUrl = returnurl; if (!ModelState.IsValid) { return View(model); } if (ur.ValidLogin(model.Username, UserRepository.GetSHA512(model.Password, model.Username))) { var user = ur.FindByUsername(model.Username); if (user.Confirmed) { ModelState.AddModelError("", "Login correcto."); //Para testeo if (String.IsNullOrEmpty(returnurl)) return View(model); else { // Aquí generamos el token y el usuario para que otros subsistemas lo usen. var uriBuilder = new UriBuilder(returnurl); var query = HttpUtility.ParseQueryString(uriBuilder.Query); query["token"] = ur.GetToken(model.Username, UserRepository.GetSHA512(model.Password, model.Username)); uriBuilder.Query = query.ToString(); returnurl = uriBuilder.ToString(); returnurl = returnurl.Replace("%3a", ":"); return Redirect(returnurl); } } else { sendConfirmationEmail(user); return View(model); } } else { ModelState.AddModelError("", "Intento de inicio de sesión no válido."); return View(model); } }
public JsonResult RegisterUser(UserLoginModel.UserRegistrationModel model) { // Attempt to register the user try { WebSecurity.CreateUserAndAccount( model.userName, model.password, new { FirstName = model.firstName, LastName = model.lastName }, false ); } catch (MembershipCreateUserException e) { //ModelState.AddModelError("", ErrorCodeToString(e.StatusCode)); return Json(new { success = false, error = e.StatusCode }); } return Json(new { success = true }); }
public LoginEventArgs(UserLoginModel userLoginModel) { UserLoginModel = userLoginModel; }
public UserLoginModel GetCredentials() { UserLoginModel creds = new UserLoginModel(UserNameBox.Text, PasswordTextBox.Text); return creds; }
public ActionResult Login(UserLoginModel user, string returnUrl) { if (ModelState.IsValid) { if (Membership.ValidateUser(user.Email, user.Password)) { FormsAuthentication.SetAuthCookie(user.Email, user.Remember); if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } else { return RedirectToAction("Index", "Home"); } } else { ModelState.AddModelError(string.Empty, "Wrong email or password"); } } return View(user); }
public UserLoginModel GetUserLoginModel() { return _userLoginModel ?? (_userLoginModel = CreateLoginModel()); }