public ActionResult Index(AdminLoginModel adminLoginModel) { if (!ModelState.IsValid) { return(View(adminLoginModel)); } AdminLoginDto admin = new AdminLoginDto() { UserName = adminLoginModel.UserName, Password = adminLoginModel.Password }; admin = AdminAuthenticationRepository.GetAdminDetails(admin); if (admin.AdminId > 0) { FormsAuthentication.SetAuthCookie(adminLoginModel.UserName, false); var authTicket = new FormsAuthenticationTicket(1, admin.UserName, DateTime.Now, DateTime.Now.AddMinutes(20), false, admin.UserRole); string encryptedTicket = FormsAuthentication.Encrypt(authTicket); var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); HttpContext.Response.Cookies.Add(authCookie); TempData["AdminDetails"] = admin; TempData.Keep(); Session["AdminId"] = admin.AdminId; return(RedirectToAction("DashBoard", "Admin")); } else { ViewBag.LoginError = "Invalid Login Attempt"; return(View()); } }
public ActionResult AdminLogin(AdminLoginModel model) { if (ModelState.IsValid) //kiểm tra form rỗng { var dao = new AdminDao(); var result = dao.AdminLogin(model.TenDN, Encryptor.MD5Hash(model.MatKhau)); if (result == 1) { var admin = dao.GetByNameADMIN(model.TenDN); var adminSession = new AdminLogin(); adminSession.TenDN = admin.TenDN; adminSession.MaADMIN = admin.MaADMIN; Session.Add(CommonConstants.SESSION_ADMIN, adminSession); return(Redirect("/thong-tin-admin")); } else if (result == 0) { ModelState.AddModelError("", "Tên đăng nhập không đúng. Vui lòng kiểm tra lại!"); } else { ModelState.AddModelError("", "Mật khẩu không chính xác. Vui lòng nhập lại!"); } } return(View("AdminLoginView")); }
public new void ProcessRequest(HttpContext context) { ClearCookies(); string loginName = GetFormValue("loginName", ""); string loginPassword = EncryptHelper.MD5(GetFormValue("password", "")); int loginType = GetFormValue("loginType", 0); string json = string.Empty; AdminLoginModel data = UserLogic.Instance.Login(loginName, loginPassword); if (data != null) { //判断账户是否已启用 if (data.UserStatus == 1) { WriteCookies(data); //if (data.ID > 0) // ManagerLogic.UpdateLastLoginTime(data.ID); json = JsonHelper.JsonSerializer(new ResultModel(ApiStatusCode.OK)); } else { json = JsonHelper.JsonSerializer(new ResultModel(ApiStatusCode.账户已禁用)); } } else { json = JsonHelper.JsonSerializer(new ResultModel(ApiStatusCode.账户密码不正确)); } context.Response.ContentType = "application/json"; context.Response.Write(json); }
public async Task <ActionResult> Login(AdminLoginModel model, string ReturnUrl) { if (ModelState.IsValid) { AppUser user = await userManager.FindAsync(model.ID, model.Password); if (user == null) { //ModelState.AddModelError("Password", "아이디 또는 비밀번호가 잘못되었습니다."); TempData["message"] = "아이디 또는 비밀번호가 잘못되었습니다."; } else { authManager = System.Web.HttpContext.Current.GetOwinContext().Authentication; ClaimsIdentity ident = await userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); authManager.SignOut(); authManager.SignIn(new AuthenticationProperties { IsPersistent = true }, ident); ViewBag.AdminId = model.ID; return(RedirectToAction("Index")); } } ViewBag.returnUrl = ReturnUrl; return(View(model)); }
public async Task <IActionResult> AdminLogin([FromBody] AdminLoginModel adminLoginModel) { try { if (adminLoginModel.Password == null || adminLoginModel.Email == null) { throw new Exception(AdminExceptions.ExceptionType.NULL_EXCEPTION.ToString()); } //Throws Custom Exception When Fields are Empty Strings. if (adminLoginModel.Password == "" || adminLoginModel.Email == "") { throw new Exception(AdminExceptions.ExceptionType.EMPTY_EXCEPTION.ToString()); } RAdminLoginModel data = await this.adminBL.AdminLogin(adminLoginModel); if (data != null) { data.Token = this.CreateToken(data, "authenticate role"); return(this.Ok(new { status = "True", message = "Login Successfully", data })); } else { return(this.NotFound(new { status = "False", message = "Login UnSuccessfully" })); } } catch (Exception exception) { bool Success = false; return(BadRequest(new { Success, Message = exception.Message })); } }
public ActionResult Create(AdminLoginModel a) { try { // TODO: Add insert logic here if (ModelState.IsValid) { if (al.AdminLogin(a) == true) { Session["AEmail"] = a.AEmail.ToString(); ViewBag.Message = "Login successfull"; return(RedirectToAction("Welcome", "AdminLogin")); } else { return(View()); } } return(View()); } catch (Exception e) { throw e; } }
public async void TestAdminLoginValidModelStateButNotAnExistingUser() { MockStoreContexts mocks = new MockStoreContexts(); mocks.UserManager.Setup(x => x.CreateAsync(It.IsAny <ApplicationUser>(), It.IsAny <string>())) .ReturnsAsync(IdentityResult.Success); mocks.UserManager.Setup(x => x.FindByEmailAsync(It.IsAny <string>())) .ReturnsAsync(mocks.User); mocks.UserManager.Setup(x => x.IsInRoleAsync(It.IsAny <ApplicationUser>(), It.IsAny <string>())) .ReturnsAsync(true); mocks.UserManager.Setup(x => x.AddToRoleAsync(It.IsAny <ApplicationUser>(), It.IsAny <string>())) .ReturnsAsync(IdentityResult.Success); mocks.SignInManager.Setup(x => x.PasswordSignInAsync( It.IsAny <string>(), It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <bool>())) .ReturnsAsync(Microsoft.AspNetCore.Identity.SignInResult.Failed); await mocks.UserManager.Object.CreateAsync(mocks.User, "Abcdefg1!"); await mocks.UserManager.Object.AddToRoleAsync(mocks.User, ApplicationRoles.Admin); AdminLoginModel alm = new AdminLoginModel(mocks.UserManager.Object, mocks.SignInManager.Object, mocks.Configuration.Object) { Email = "*****@*****.**", Password = "******" }; MockValidation.CheckValidation(alm); var result = alm.OnPost().Result; Assert.IsType <PageResult>(result); }
public async Task <IActionResult> CheckLogin([FromBody] AdminLoginModel AdminLogin) { //查看token是否存在 如果存在就从缓存里取值 //ReturnJson returnjson = (new TokenValidate()).CheckToken(token, _cache); //if (returnjson.CheckParamsSuccess == "ok") { // returnjson.ErrorMsg = "登录成功,已有token"; // returnjson.Data = token; // return Json(returnjson); //} LoginService _loginservice = new LoginService(); var items = await _loginservice.CheckAdmin(AdminLogin, _context); if (items == null) { //Response.StatusCode = (int)HttpStatusCode.Created; return(Json(new ReturnJson { ErrorCode = 10002, ErrorMsg = "用户名或密码错误", Data = "", Success = false })); } //获取token string key_token = _loginservice.UpdateCache(items, _cache); return(Json(new ReturnJson { ErrorCode = 80000, ErrorMsg = "登录成功", Data = key_token, Success = true })); }
{/// <summary> /// 检查登录 /// </summary> /// <param name="appCode"></param> /// <returns></returns> public static bool CheckLogin(ref ApiStatusCode appCode) { AdminLoginModel data = GetCurrentUser(); if (data != null) { data = UserLogic.Instance.Login(data.LoginName, data.LoginPassword); if (data != null) { if (data.UserStatus == 1) { WriteCookies(data); appCode = ApiStatusCode.OK; return(true); } else { appCode = ApiStatusCode.账户已禁用; } } else { appCode = ApiStatusCode.账户密码不正确; } } else { appCode = ApiStatusCode.没有登录; } return(false); }
public Administrator AdministratorLogin(AdminLoginModel a) { var admin = (from i in administrators where i.Password == a.Password && i.UserName == a.UserName select i).SingleOrDefault(); Administrator administrator = admin; return(administrator); }
public Task <Tuple <List <AdminLoginModel>, TranStatus> > AdminLogin(AdminLoginModel model) { using (adminRepository = new AdminRepository()) { return(adminRepository.AdminLogin(model)); } }
/// <summary> /// 退出登录 /// </summary> /// <returns></returns> public async Task <ActionResult> LoginOut() { HttpCookie cookie = HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName]; if (cookie == null || string.IsNullOrEmpty(cookie.Value)) { return(RedirectToAction("Index")); } FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value); AdminLoginModel model = JsonConvert.DeserializeObject <AdminLoginModel>(ticket.UserData); if (model != null) { //写注销日志 string loginLog = $"退出账号:{model.UserName},登录IP:{CommonTools.GetIpAddress()}"; _repositoryFactory.ISysLog.Add(new Entity.SysLog() { CreateTime = DateTime.Now, Type = (int)EnumHepler.LogType.LoginOut, Remark = loginLog }); await _repositoryFactory.SaveChanges(); cookie.Expires = DateTime.Now.AddDays(-1); Response.Cookies.Set(cookie); } return(RedirectToAction("Index")); }
public async Task <ActionResult> Login(AdminLoginModel model, string returnUrl) { Admin newAdmin = new Admin { Name = "admin", UserName = "******" }; UserManager.Create(newAdmin, "123456"); if (ModelState.IsValid) { var user = await UserManager.FindAsync(model.Login, model.Password); if (user != null) { await SignInAsync(user, model.RememberMe); return(RedirectToLocal(returnUrl)); } else { ModelState.AddModelError("", "Invalid username or password."); } } // If we got this far, something failed, redisplay form return(View(model)); }
public string Login(AdminLoginModel adminLogin) { if (adminLogin == null) { return("Invalid Login info"); } Admin loggedAdmin = _uow .GetRepository <Admin>() .GetAll() .SingleOrDefault(a => a.AdminUsername == adminLogin.AdminUsername); if (loggedAdmin != null) { if (loggedAdmin.Password != adminLogin.Password) { return(null); } } string jwtToken = tokenManager.CreateAdminAccessToken(new AdminModel { AdminId = loggedAdmin.AdminId, AdminUsername = loggedAdmin.AdminUsername }); return(jwtToken); }
/// <summary> /// 更新信息 /// </summary> /// <param name="model">The model.</param> /// <returns>true if XXXX, false otherwise.</returns> /// <exception cref="System.NotImplementedException"></exception> public static bool Update(AdminLoginModel model) { using (var dal = FactoryDispatcher.ManagerFactory()) { return(dal.Update(model)); } }
/// <summary> /// Inserts the specified model. /// </summary> /// <param name="model">The model.</param> /// <returns>System.Int32.</returns> /// <exception cref="System.NotImplementedException"></exception> public static int Insert(AdminLoginModel model) { using (var dal = FactoryDispatcher.ManagerFactory()) { return(dal.Insert(model)); } }
public JsonResult Login(AdminLoginModel model) { if (!ModelState.IsValid) { return(Json(new AjaxResult { Status = "error", ErrorMsg = MVCHelper.GetValidMsg(ModelState) })); } if ((string)TempData["VerifyCode"] != model.VerifyCode) { return(Json(new AjaxResult { Status = "error", ErrorMsg = "验证码错误" })); } bool result = AdminUserService.CheckLogin(model.PhoneNum, model.Password); if (result) { Session["LoginUserId"] = AdminUserService.GetByPhoneNum(model.PhoneNum).Id; return(Json(new AjaxResult { Status = "ok" })); } else { return(Json(new AjaxResult { Status = "error", ErrorMsg = "用户名或者密码错误" })); } }
public IActionResult Login(AdminLoginModel adminLogin) { if (adminLogin == null) { return(BadRequest("Bad Input")); } string result = null; try { result = _auth.Login(adminLogin); } catch (Exception e) { Console.WriteLine(e.Message + e.StackTrace + e.Source); } if (result == null) { return(NotFound("Incorrect username or password")); } return(Ok("Login Successfully.\n\n\n " + result)); }
public ActionResult Login(AdminLoginModel model) { if (!ModelState.IsValid) { return(this.Fail(ModelState.Values.First(e => e.Errors.Count > 0).Errors[0].ErrorMessage)); } MiddleTier.MemberManager.SysLogin(model.UserName, model.Password); return(this.Success()); }
public ActionResult AdminLogin(AdminLoginModel model, bool remember_me) { if (ModelState.IsValid) { ViewBag.ErrorMessage = ""; int flag = 0; var admin = api.GetAllAdminList(); foreach (var user in admin) { string str = api.decrypt(user.Password); if (api.decrypt(user.Password) == model.Password && user.EmailId == model.EmailId) { if (user.Status == true) { flag = 1; Session["EmailId"] = user.EmailId; Session["Password"] = (user.Password); Session["AdminId"] = user.Id; Session["AdminName"] = user.Name; break; } else { Response.Write(@"<script language='javascript'>alert('You Are Not an Active Admin.');</script>"); return(View()); } } } if (remember_me == true) { HttpCookie cookie = new HttpCookie("AdminLogin"); cookie.Values["EmailId"] = Session["EmailId"].ToString(); cookie.Values["Password"] = Session["Password"].ToString(); cookie.Values["AdminId"] = Session["AdminId"].ToString(); cookie.Values["AdminId"] = Session["AdminName"].ToString(); cookie.Expires = DateTime.Now.AddDays(1); Response.Cookies.Add(cookie); } if (flag == 1) { return(RedirectToAction("Index", "Login")); } else { Response.Write(@"<script language='javascript'>alert('User Name or Password is Incorrect.');</script>"); return(View()); } } else { return(View()); } }
public static AdminLoginModel SuperAdmin() { var passwordSalat = passwordSalatAdmin; var obj = new AdminLoginModel(); obj.UserName = SecurityModel.Username; return(obj); }
//查询 public async Task <Admin> CheckAdmin(AdminLoginModel AdminLogin, basisContext _context) { var entity = new Admin { UserName = AdminLogin.UserName, Password = AdminLogin.Password }; var items = await _context.Admins.Where(a => a.UserName == entity.UserName && a.Password == entity.Password).SingleOrDefaultAsync(); //await _context.AdminScopes.Where(a => a.Identifier == items.AdminScopeIdentifier).SingleOrDefaultAsync(); return(items); }
public IActionResult AdminLogin() { var model = new AdminLoginModel() { PageTitle = "登录", WebTitle = WebSettings.Value.WebTitle }; return(View(model)); }
public void AdminLoginEmailGetterAndSetter() { MockStoreContexts mocks = new MockStoreContexts(); AdminLoginModel alm = new AdminLoginModel(mocks.UserManager.Object, mocks.SignInManager.Object, mocks.Configuration.Object); Assert.Null(alm.Email); alm.Email = "*****@*****.**"; Assert.Equal("*****@*****.**", alm.Email); }
/// <summary> /// Admin login method /// </summary> /// <param name="adminLoginModel"></param> /// <returns></returns> public async Task <RAdminLoginModel> AdminLogin(AdminLoginModel adminLoginModel) { try { var user = await _userManger.FindByEmailAsync(adminLoginModel.Email); if (user == null) { throw new Exception(AdminExceptions.ExceptionType.INVALID_EMAIL_IDENTITY.ToString()); } var result = await _userManger.CheckPasswordAsync(user, adminLoginModel.Password); if (!result) { throw new Exception(AdminExceptions.ExceptionType.INVALID_PASSWORD_IDENTITY.ToString()); } adminLoginModel.Password = Encrypt(adminLoginModel.Password).ToString(); DatabaseConnection databaseConnection = new DatabaseConnection(this.configuration); SqlConnection sqlConnection = databaseConnection.GetConnection(); SqlCommand sqlCommand = databaseConnection.GetCommand("spAdminLogin", sqlConnection); sqlCommand.Parameters.AddWithValue("@EmailId", adminLoginModel.Email); sqlCommand.Parameters.AddWithValue("@Password", adminLoginModel.Password); sqlConnection.Open(); SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(); var userData = new RAdminLoginModel(); while (sqlDataReader.Read()) { int status = sqlDataReader.GetInt32(0); if (status == 0) { return(null); } userData.Id = (int)sqlDataReader["ID"]; userData.Name = sqlDataReader["Name"].ToString(); userData.EmailId = sqlDataReader["EmailId"].ToString(); userData.Role = sqlDataReader["Role"].ToString(); userData.RoleId = Convert.ToInt32(sqlDataReader["RoleId"]); userData.Gender = sqlDataReader["Gender"].ToString(); userData.CreatedDate = sqlDataReader["ModificateDate"].ToString(); } if (userData != null) { return(userData); } return(null); } catch (Exception e) { throw new Exception(e.Message); } }
public void AdminLoginPasswordGetterAndSetter() { MockStoreContexts mocks = new MockStoreContexts(); AdminLoginModel alm = new AdminLoginModel(mocks.UserManager.Object, mocks.SignInManager.Object, mocks.Configuration.Object); Assert.Null(alm.Password); alm.Password = "******"; Assert.Equal("Abcdefg1!", alm.Password); }
/// <summary> /// Function For Register User. /// </summary> /// <param name="user"></param> /// <returns></returns> public async Task <RAdminLoginModel> AdminLogin(AdminLoginModel adminLoginModel) { try { return(await this.adminRL.AdminLogin(adminLoginModel)); } catch (Exception exception) { throw exception; } }
private void createSessionSuperAdmin(AdminLoginModel obj) { var host = Request.Url.Host; // Create user login var userLogin = new AdminLoginModel { UserName = obj.UserName, }; Session[string.Format("{0}_{1}", SessionConfig.SuperAdminSession, host)] = userLogin; }
/// <summary> /// 编辑用户信息 /// </summary> /// <param name="model">The model.</param> /// <returns>true if XXXX, false otherwise.</returns> public static bool EditUser(AdminLoginModel model) { if (model.ID > 0) { return(Update(model)); } else { return(Insert(model) > 0); } }
public async Task <ApiResponse <AdministratorDTO> > LoginAsync(AdminLoginModel model) { ApiResponse <AdministratorDTO> result = new ApiResponse <AdministratorDTO>(); try { var user = await unitOfWork.UserManager.FindByEmailAsync(model.Email); if (user != null) { bool res = await unitOfWork.UserManager.CheckPasswordAsync(user, model.Password); if (res) { var admin = unitOfWork.AdministratorsManager.GetAdminByUserId(user.Id); if (admin != null) { result.Data = admin; result.Succeeded = true; return(result); } else { result.Succeeded = false; result.Errors.Add("Cannot find an administrator with the specified id !"); result.ErrorType = ErrorType.LogicalError; return(result); } } else { result.Succeeded = false; result.Errors.Add("Invalid login attempt."); result.ErrorType = ErrorType.LogicalError; return(result); } } else { result.Succeeded = false; result.Errors.Add("Invalid login attempt."); result.ErrorType = ErrorType.LogicalError; return(result); } } catch (Exception ex) { result.Succeeded = false; result.Errors.Add(ex.Message); result.ErrorType = ErrorType.SystemError; return(result); } }