Пример #1
0
        public BusinessLayerResult <Admin> LoginAdmin(AdminLoginViewModel data)
        {
            Admin a = Find(x => x.mail == data.email && x.password != data.password);

            if (a != null)
            {
                a.notifications.Add(new Notification {
                    notification = "IP: " + GetIp() + " - HATALI GİRİŞ YAPILMIŞTIR", link = "#", IsRead = false
                });
            }
            Admin admin = Find(x => x.mail == data.email && x.password == data.password);
            BusinessLayerResult <Admin> res = new BusinessLayerResult <Admin>();

            res.Result = admin;
            if (admin != null)
            {
                if (!admin.IsActive)
                {
                    res.AddError(ErrorMessageCode.UserIsNotActive, "Hesap aktifleştirilmemiştir.");
                    res.AddError(ErrorMessageCode.CheckYourEmail, "Lütfen E-Posta adresinizi kontrol ediniz.");
                }
            }
            else
            {
                res.AddError(ErrorMessageCode.EMailorPassWrong, "Kullanıcı adı ya da parola uyuşmuyor.");
            }
            return(res);
        }
        public async Task <IActionResult> Login(AdminLoginViewModel loginVM)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            AppUser admin = await _userManager.FindByNameAsync(loginVM.UserName);

            if (admin == null)
            {
                ModelState.AddModelError("", "Username or Password is incorrect!");
                return(View());
            }

            if (await _userManager.CheckPasswordAsync(admin, loginVM.Password))
            {
                ModelState.AddModelError("", "Username or Password is incorrect!");
                return(View());
            }


            ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[]
            {
                new Claim(ClaimTypes.Name, admin.UserName),
                new Claim(ClaimTypes.Role, "Admin")
            }, "Admin_Auth");
            ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
            await HttpContext.SignInAsync("Admin_Auth", claimsPrincipal);

            return(RedirectToAction("index", "dashboard"));
        }
Пример #3
0
        public IActionResult Login()

        {
            AdminLoginViewModel adminLoginViewModel = new AdminLoginViewModel();

            return(View((object)adminLoginViewModel));
        }
        public async Task <bool> AuthenticateAdminAccountAsync(AdminLoginViewModel adminModel)
        {
            var admin = await _userManager.FindByEmailAsync(adminModel.Email);

            if (admin != null)
            {
                if (await _userManager.CheckPasswordAsync(admin, adminModel.Password))
                {
                    List <ApplicationRole> model = new List <ApplicationRole>();
                    model = _roleManager.Roles.Where(x => x.NormalizedName.Equals("ADMIN")).Select(r => new ApplicationRole
                    {
                        Id          = r.Id,
                        CreatedDate = r.CreatedDate,
                        Description = r.Description
                    }).ToList();
                    List <ApplicationUser> admins = _userManager.Users.Where(x => x.Roles.Select(y => y.RoleId).Contains(model.FirstOrDefault().Id)).ToList();
                    if (admins.Contains(admin))
                    {
                        return(true);
                    }
                }
            }
            // Credentials are invalid, or account doesn't exist
            return(false);
        }
Пример #5
0
 public ActionResult Login(AdminLoginViewModel adminLoginViewModel)
 {
     if (ModelState.IsValid)
     {
         AdminFunc adminFunc = new AdminFunc();
         var       _response = adminFunc.Verify(adminLoginViewModel.Accounts, adminLoginViewModel.Password);
         if (_response.Code == 1)
         {
             var _user = adminFunc.Find(adminLoginViewModel.Accounts);
             Session.Add("AdminID", _user.AdministratorID);
             Session.Add("Accounts", _user.Accounts);
             adminFunc.UpdateAdminLoginInfo(_user.AdministratorID, DateTime.Now, "127.0.0.1");
             return(RedirectToAction("Index", "Admin"));
         }
         else if (_response.Code == 3)
         {
             ModelState.AddModelError("Accounts Or Password", _response.Message);
         }
         else
         {
             ModelState.AddModelError("", _response.Message);
         }
     }
     return(View(adminLoginViewModel));
 }
Пример #6
0
        public ActionResult AdminLogin(AdminLoginViewModel adminLogin)
        {
            if (ModelState.IsValid)
            {
                string MyHash = FormsAuthentication.HashPasswordForStoringInConfigFile(adminLogin.UserPassword, "MD5");
                var    user   = db.Users.FirstOrDefault(u => u.UserEmail == adminLogin.UserEmail && u.UserPassword == MyHash);

                if (user != null)
                {
                    FormsAuthentication.SetAuthCookie(adminLogin.UserEmail, true);
                    if (user.IsActive)
                    {
                        if (user.Role.RoleName == "Admin")
                        {
                            return(Redirect("/Admin/Dashboard/Index"));
                        }
                        else
                        {
                            ModelState.AddModelError("UserEmail", "There is no user with the entered details");
                        }
                    }
                    else
                    {
                        return(RedirectToAction("RegisterWithEmail"));
                    }
                }
                else
                {
                    ModelState.AddModelError("UserEmail", "There is no user with the entered details");
                }
            }

            return(PartialView());
        }
        public async Task <IActionResult> AdminLogin(AdminLoginViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            // Log Info
            _logger.LogInformation("Admin logging in...");
            if (ModelState.IsValid)
            {
                var activeUser = await _context.Users.FirstOrDefaultAsync(m => m.UserName == model.AdminEmail);

                if (activeUser == null)
                {
                    ViewData["ErrorMsg"] = "Email is incorrect or user doesn't exist!";
                    return(View(model));
                }

                var result = await _signInManager.CheckPasswordSignInAsync(activeUser, model.Password, false);

                if (result.Succeeded)
                {
                    await _signInManager.PasswordSignInAsync(activeUser, model.Password, false, false);

                    HttpContext.Session.SetString(SessionUserName, activeUser.UserName);
                    HttpContext.Session.SetString(SessionUserEmail, activeUser.Email);

                    return(RedirectToAction($"AdminHome", $"Admin", new { id = activeUser.Id }));
                }

                ModelState.AddModelError(string.Empty, "Invalid Username or Password...");
                return(View(model));
            }

            _logger.LogInformation("Invalid State Condition!");
            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Пример #8
0
        public async Task <ActionResult> AdminLogin(AdminLoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false);

            switch (result)
            {
            case SignInStatus.Success:
                return(RedirectToLocal(returnUrl));

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }));

            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid login attempt.");
                return(View(model));
            }
        }
Пример #9
0
 public ActionResult Login(AdminLoginViewModel login)
 {
     if (ModelState.IsValid)
     {
         if (TempData["VerificationCode"] == null || TempData["VerificationCode"].ToString() != login.VerificationCode.ToUpper())
         {
             ModelState.AddModelError("VerificationCode", "1验证码不正确");
             return(View(login));
         }
         var _admin = adminbll.Find(login.LoginName);
         if (_admin == null)
         {
             ModelState.AddModelError("LoginName", "用户名不存在");
         }
         else if (_admin.LoginPwd == Utils.MD5(login.LoginPwd))
         {
             var _identity = adminbll.CreateIdentity(_admin, DefaultAuthenticationTypes.ApplicationCookie);
             AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
             AuthenticationManager.SignIn(new AuthenticationProperties()
             {
                 IsPersistent = false
             }, _identity);
             return(RedirectToAction("Index", "Main"));
         }
         else
         {
             ModelState.AddModelError("LoginPwd", "密码错误");
         }
     }
     return(View());
 }
Пример #10
0
        public async Task <OpreationResult <Administrator> > LoginAsync(AdminLoginViewModel model)
        {
            var dbAdmin = await db.Set <Administrator>().Where(a => a.LoginName == model.LoginName).AsNoTracking().FirstOrDefaultAsync();

            if (dbAdmin == null)
            {
                return(OpreationResult <Administrator> .Init(OpreationResuleType.QueryNull, null, "用户不存在"));
            }
            if (dbAdmin.Password != SHA.SHA512(model.Password).ToLower())
            {
                return(OpreationResult <Administrator> .Init(OpreationResuleType.ValidtorError, null, "您的密码不正确"));
            }
            var updateModel = new AdministratorDto()
            {
                Id            = dbAdmin.Id,
                LastLoginIp   = model.LastLoginIp,
                LastLoginTime = DateTime.Now,
                Password      = dbAdmin.Password,
                LoginName     = dbAdmin.LoginName
            };

            await CreateOrUpdate(updateModel);

            dbAdmin.Password = null;
            return(OpreationResult <Administrator> .Init(OpreationResuleType.Success, dbAdmin));
        }
Пример #11
0
        public async Task <IActionResult> Login(AdminLoginViewModel adminLogin)
        {
            if (!this.ModelState.IsValid)
            {
                return(View(adminLogin));
            }

            var administrator = await this.administratorService.GetAdminAsync(adminLogin.Username, adminLogin.Password);

            if (administrator == null)
            {
                //throw exception stamp data

                return(View(adminLogin));
            }

            var scheme = CookieAuthenticationDefaults.AuthenticationScheme;

            var identity = new ClaimsIdentity(this.cookieService.PrepareAdminClaims(administrator), scheme);



            await this.HttpContext.SignInAsync(scheme, new ClaimsPrincipal(identity), this.cookieService.GetCookieOptions());

            //private admin dashboard
            return(RedirectToAction("Dashboard", "Authorize"));
        }
Пример #12
0
        public ActionResult Login(AdminLoginViewModel model)
        {
            if (User.Identity.IsAuthenticated && User.IsInRole("admin"))
            {
                return(RedirectToRoute(new { area = "manage", controller = "Admin", action = "Index" }));
            }
            else
            {
                if (!ModelState.IsValid)
                {
                    return(View(new AdminLoginViewModel()));
                }

                using (ProjectDBEntities Context = new ProjectDBEntities())
                {
                    model.Password = Hashing.CreateHash(model.Password);

                    var admin = Context.Administrators.Where(x => x.AdminUserName == model.Username && x.AdminPassword == model.Password).FirstOrDefault <Administrator>();

                    if (admin != null)
                    {
                        FormsAuthentication.SetAuthCookie(admin.AdminUserName, true);
                        return(RedirectToRoute(new { area = "manage", controller = "Admin", action = "Index" }));
                    }
                }

                ViewBag.Message = "Incorrect username/password combination..";
                return(View(new AdminLoginViewModel()));
            }
        }
Пример #13
0
        // [ValidateAntiForgeryToken]
        public async Task <ActionResult> AdminLogin(AdminLoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindAsync(model.UserName, model.Password);

                if (user != null)
                {
                    if (UserManager.IsInRole(user.Id, "Admin"))
                    {
                        await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout : false);

                        if (String.IsNullOrEmpty(returnUrl))
                        {
                            return(RedirectToAction("Index", "Home", new { area = "Admin" }));
                        }
                        else
                        {
                            return(RedirectToLocal(returnUrl));
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "Invalid username or password.");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Invalid username or password.");
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Пример #14
0
        public IActionResult Login([Bind("Username, Password")] AdminLoginViewModel adminViewModel)
        {
            if (ModelState.IsValid)
            {
                if (adminViewModel != null)
                {
                    Administrator admin = FindAdminByUsername(adminViewModel.Username);
                    if (admin == null)
                    {
                        ModelState.AddModelError("LoginError", "Username/Password does not exist");
                        return(View());
                    }
                    if (admin.Password.Equals(AccountsController.EncryptionPassword(adminViewModel.Password)))
                    {
                        HttpContext.Session.SetString("token", adminViewModel.Username);
                        HttpContext.Session.SetString("user", "Admin");
                        HttpContext.Session.SetString("userType", "Admin");

                        return(RedirectToAction("Index", "Admin"));
                    }
                }
            }
            ModelState.AddModelError("LoginError", "Email address/Password does not exist");
            return(View());
        }
Пример #15
0
        public async Task <IActionResult> Login(AdminLoginViewModel model, string returnUrl = "/admin")
        {
            ViewData["ReturnUrl"] = returnUrl;

            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            var user = await _userService.GetUserByName(model.UserName);

            if (user != null && !_userService.IsInRole(user, RoleName.Customer).Result)
            {
                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                var result = await _userService.Login(model.UserName, model.Password, model.RememberMe, true);

                if (result == LoginStatus.Succeeded)
                {
                    return(Redirect(returnUrl));
                }
                else if (result == LoginStatus.IsLockedOut)
                {
                    var timeLockedOut = user.LockoutEnd == null ? 60 : (user.LockoutEnd.Value.LocalDateTime - DateTime.Now).Seconds;
                    ViewData["Message"] = string.Format(ValidationMessages.AccountLockedOut, timeLockedOut < 0 ? 60 : timeLockedOut);
                    return(View(model));
                }
            }

            ViewData["Message"] = ValidationMessages.LoginFailed;
            return(View(model));
        }
Пример #16
0
        public ActionResult Login(AdminLoginViewModel model)
        {
            //Checking the state of model passed as parameter.
            if (ModelState.IsValid)
            {
                //Validating the user, whether the user is valid or not.
                var isValidUser = IsValidUser(model);

                //If user is valid & present in database, we are redirecting it to Welcome page.
                if (isValidUser != null)
                {
                    FormsAuthentication.SetAuthCookie(model.AdminId, false);
                    return(RedirectToAction("Index"));
                }
                else
                {
                    //If the username and password combination is not present in DB then error message is shown.
                    ModelState.AddModelError("Failure", "Wrong Username and password combination !");
                    return(View());
                }
            }
            else
            {
                //If model state is not valid, the model with error message is returned to the View.
                return(View(model));
            }
        }
Пример #17
0
        public async Task <IActionResult> Login(AdminLoginViewModel model)
        {
            if (User.Identity.IsAuthenticated)
            {
                return(AdminDashboardActionResult);
            }
            if (ModelState.IsValid)
            {
                var user = await this.userManager.FindByEmailAsync(model.Email);

                if (await this.authenticationService.UserHasAdministrationAccessRightsAsync(user))
                {
                    var result = await this.authenticationService.SignInAsync(user, model.Password, this.HttpContext, CookieAuthenticationDefaults.AuthenticationScheme, AuthenticationProperties);

                    if (result.RequiresTwoFactor)
                    {
                        return(RedirectToAction(nameof(LoginWith2fa)));
                    }
                    if (result.IsLockedOut)
                    {
                        return(RedirectToAction(nameof(Lockout)));
                    }
                    if (result.Succeeded)
                    {
                        return(AdminDashboardActionResult);
                    }
                }

                ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                return(View(model));
            }

            return(View(model));
        }
Пример #18
0
        public ActionResult Login(AdminLoginViewModel model, string returnUrl)
        {
            var admin = accountService.AdminLogin(model.Account, model.Password);

            if (admin != null)
            {
                LocalDateTimeService timeService = new LocalDateTimeService();
                var today = timeService.GetLocalDateTime(LocalDateTimeService.CHINA_STANDARD_TIME);
                var name  = admin.Adm_Name;
                HttpContext.Session.Clear();
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
                                                                                 name,
                                                                                 today,
                                                                                 DateTime.Now.AddHours(24),
                                                                                 false,
                                                                                 "Admin"
                                                                                 );

                string enTicket = FormsAuthentication.Encrypt(ticket);
                Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, enTicket));
                return(Redirect("/Admin/Soap"));
            }

            TempData["loginFail"] = "帳號或密碼錯誤!";
            return(View());
        }
Пример #19
0
        public async Task <IActionResult> Login([FromBody] AdminLoginViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            try
            {
                var admin = await _context.Admin.Where(x => x.Email == model.Email).AsNoTracking().FirstOrDefaultAsync();

                if (admin == null)
                {
                    return(NotFound("Administrador não encontrado!"));
                }

                if (admin.Login(model.Password))
                {
                    return(Ok("Administrador autenticado com sucesso!"));
                }

                return(BadRequest("Senha inválida, favor verificar!"));
            }
            catch (Exception ex)
            {
                return(BadRequest("Erro ao realizar o login do administrador, favor tentar novamente! " + ex.Message));
            }
        }
Пример #20
0
        public ActionResult Login(LoginViewModel loginModel)
        {
            if (ModelState.IsValid)
            {
                int flag = userBLL.Login1(loginModel.UserName, loginModel.Password);
                switch (flag)
                {
                case 0:
                    ModelState.AddModelError("", "Tài khoản không tồn tại!");
                    break;

                case 1:
                    ModelState.AddModelError("", "Tài khoản Client không được phép!");
                    break;

                case 2:
                    var user      = userBLL.GetUser(loginModel.UserName);
                    var userLogin = new AdminLoginViewModel();
                    userLogin.ID       = user.ID;
                    userLogin.UserName = user.UserName;
                    Session.Add(CommonConstants.ADMIN_SESSION, userLogin);
                    return(RedirectToAction("Index", "Dashboard"));

                case 3:
                    ModelState.AddModelError("", "Tài khoản hoặc mật khẩu không đúng!");
                    break;
                }
            }
            return(View("Index"));
        }
        public ActionResult Index(AdminLoginViewModel model)
        {
            if (ModelState.IsValid)
            {
                var resultInit = SignInManager.PasswordSignIn(model.UserName, model.Password,
                                                              true, shouldLockout: false);

                if (resultInit == SignInStatus.Success)
                {
                    var signInManager = HttpContext.GetOwinContext().Get <ApplicationSignInManager>();

                    var result = signInManager.PasswordSignIn(model.UserName, model.Password, false, false);
                    switch (result)
                    {
                    case SignInStatus.Success:
                    {
                        return(RedirectToAction("Home"));
                    }

                    case SignInStatus.LockedOut:
                        return(View("Lockout"));

                    case SignInStatus.Failure:
                    default:
                        ModelState.AddModelError("", "Invalid login attempt.");
                        return(View(model));
                    }
                }
            }
            return(View(model));
        }
Пример #22
0
        public async Task <IActionResult> Login(AdminLoginViewModel model)
        {
            var result = new ResponseModel {
                ResultCode = (int)ResultCode.UnknownError
            };

            if (string.IsNullOrWhiteSpace(model.UserName))
            {
                result.ResultCode = (int)AccountResultCode.UserNameNotNull;
                result.Message    = "用户名不能为空";
                return(Json(result));
            }
            if (string.IsNullOrWhiteSpace(model.Password))
            {
                result.ResultCode = (int)AccountResultCode.PasswordNotNull;
                result.Message    = "密码不能为空";
                return(Json(result));
            }
            result = await this.AccountBll.AdminLogin(new AdminLoginDto
            {
                Model   = model,
                LoginIP = this.HttpContext.GetUserIp(),
                Result  = result,
            });

            //登陆成功后写Session
            if (result.ResultCode == (int)ResultCode.Successful)
            {
            }

            return(Json(result));
        }
Пример #23
0
        public ActionResult Login(AdminLoginViewModel model)
        {
            if (User.Identity.IsAuthenticated && User.IsInRole("admin"))
                return RedirectToRoute(new { area = "manage", controller = "Admin", action = "Index" });
            else
            {
                if (!ModelState.IsValid)
                    return View(new AdminLoginViewModel());

                using (ProjectDBEntities Context = new ProjectDBEntities())
                {
                    model.Password = Hashing.CreateHash(model.Password);

                    var admin = Context.Administrators.Where(x => x.AdminUserName == model.Username && x.AdminPassword == model.Password).FirstOrDefault<Administrator>();

                    if (admin != null)
                    {
                        FormsAuthentication.SetAuthCookie(admin.AdminUserName, true);
                        return RedirectToRoute(new { area = "manage", controller = "Admin", action = "Index" });
                    }
                }

                ViewBag.Message = "Incorrect username/password combination..";
                return View(new AdminLoginViewModel());
            }
        }
Пример #24
0
 public ActionResult Login(AdminLoginViewModel user)
 {
     if (user.Email == "*****@*****.**" && user.Password == "147258369")
     {
         return(new RedirectResult(Url.Action("Main")));
     }
     user.Message = "用户名或密码不对!";
     return(View(user));
 }
Пример #25
0
        public IActionResult Login(string returnUrl = "")
        {
            AdminLoginViewModel VM = new AdminLoginViewModel
            {
                ReturnUrl = returnUrl
            };

            return(View(VM));
        }
Пример #26
0
        private AdminLoginViewModel createViewModel()
        {
            UserRepository      userRepository      = new UserRepository();
            UserService         userService         = new UserService(userRepository);
            AdminLoginViewModel adminLoginViewModel = new AdminLoginViewModel(userService);

            adminLoginViewModel.LogInError             += showErrorMessage;
            adminLoginViewModel.LoginSuccessfullAction += OpenAdminMenuWindow;
            return(adminLoginViewModel);
        }
Пример #27
0
        public IActionResult Login()
        {
            if (this.User.Identity.IsAuthenticated)
            {
                return(this.AdminDashboardActionResult);
            }

            AdminLoginViewModel model = new AdminLoginViewModel();

            return(this.View(model));
        }
Пример #28
0
 public async Task <IActionResult> Login(AdminLoginViewModel model)
 {
     if (ModelState.IsValid)
     {
         if (await _adminService.LoginAsync(model.UserName, model.Password))
         {
             return(RedirectToAction("Index", new { controller = "Home" }));
         }
         ModelState.AddModelError("", "Authetication Failed.");
     }
     return(View(model));
 }
        public ActionResult Login()
        {
            if (Request.Cookies["Login"] != null)
            {
                var adminLogin = new AdminLoginViewModel()
                {
                    Username = Request.Cookies["Login"].Values["Username"]
                };
                return(View(adminLogin));
            }

            return(View());
        }
Пример #30
0
        public async Task <IActionResult> AdminLoginAsync(AdminLoginViewModel vm)
        {
            bool loginValid = false;

            if (ModelState.IsValid)
            {
                var admin = await _context.Admin
                            .SingleOrDefaultAsync(a => a.Password.Equals(vm.Password));

                loginValid = admin != null;
            }
            return(loginValid ? RedirectToAction("Index", "Admin/KUAdmins") : RedirectToAction("AdminLoginFail"));
        }
Пример #31
0
        public async Task <IActionResult> Login(AdminLoginViewModel model)
        {
            Microsoft.AspNetCore.Identity.SignInResult result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, isPersistent : true, lockoutOnFailure : false);

            if (result.Succeeded)
            {
                return(RedirectToAction("Index"));
            }
            else
            {
                return(View());
            }
        }