Exemple #1
0
        public ActionResult Login(UserLoginViewModel loginRequest)
        {
            _logger.Debug($"Login request: '{loginRequest}'");
            if (!ModelState.IsValid)
            {
                _logger.Info("Login request is invalid");
                return(PartialView(PartialViewLoginMessage, new ResultViewModel("Please, verify input data", isSuccess: false)));
            }

            LoginResult loginResult = _authService.Login(new UserToLogin(loginRequest));

            _logger.Debug(loginResult.ToString());

            if (loginResult.IsFailure)
            {
                return(PartialView(PartialViewLoginMessage, new ResultViewModel(loginResult.ErrorCode.ToString(), isSuccess: false)));
            }

            if (loginResult.Type == LoginType.Regular)
            {
                _formsAuthentication.SetAuthCookie(loginResult.Username, createPersistentCookie: false);
                return(JavaScript($"window.location = '{GetContentUrl(AirFlowConstants.HomeContent)}'"));
            }

            return(PartialView(PartialViewLoginMessage, new ResultViewModel("Confirmation message was sent to your email", isSuccess: true)));
        }
Exemple #2
0
        public ActionResult Login(LogOnFormModel form, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                User user = userRepository.Get(u => u.Email == form.UserName && u.Activated == true);
                if (user != null)
                {
                    if (ValidatePassword(user, form.Password))
                    {
                        formAuthentication.SetAuthCookie(this.HttpContext,
                                                         UserAuthenticationTicketBuilder.CreateAuthenticationTicket(
                                                             user));

                        if (Url.IsLocalUrl(returnUrl))
                        {
                            return(Redirect(returnUrl));
                        }
                        else
                        {
                            return(RedirectToAction("Index", "Home"));
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "The user name or password provided is incorrect.");
                    }
                }
            }

            // If we got this far, something failed
            return(Json(new { errors = GetErrorsFromModelState() }));
        }
Exemple #3
0
        public JsonResult save(PhanQuyenModel.SaveModel form)
        {
            Account298  nhanVien = _account298Repository.GetById(form.idNhanVien);
            IList <int> ids      = !string.IsNullOrEmpty(nhanVien.Roles)
                                       ? nhanVien.Roles.Split(',').Select(o => Convert.ToInt32(o)).ToList()
                                       : new List <int>();

            if (form.Checked)
            {
                if (!ids.Any(o => o == form.IdQuyen))
                {
                    ids.Add(form.IdQuyen);
                }
            }
            else
            {
                ids.Remove(form.IdQuyen);
            }
            nhanVien.Roles = string.Join(",", ids);
            _account298Repository.Update(nhanVien);
            _unitOfWork.Commit();

            formAuthentication.SetAuthCookie(this.HttpContext,
                                             UserAuthenticationTicketBuilder.CreateAuthenticationTicket(
                                                 nhanVien));

            return(Json(new { ok = true, JsonRequestBehavior.AllowGet }));
        }
Exemple #4
0
        public ActionResult Login(UserVM user)
        {
            if (!ModelState.IsValid)
            {
                return(View(user));
            }

            ServiceResultModel <UserVM> serviceResult = _accountService.LoginUser(user);

            if (!serviceResult.IsSuccess)
            {
                if (serviceResult.Code == ServiceResultCode.NotFound)
                {
                    ModelState.AddModelError("", serviceResult.Message);
                    return(View(user));
                }

                if (serviceResult.Code == ServiceResultCode.EMailIsNotConfirmed)
                {
                    return(RedirectToAction("Confirm", "Account",
                                            new { email = serviceResult.Data.EMail, displayName = serviceResult.Data.DisplayName }));
                }

                return(View(user));
            }

            _formsAuthentication.SetAuthCookie(this.HttpContext, UserAuthTicketBuilder.CreateAuthTicket(serviceResult.Data));

            return(RedirectToAction("Index", "Dashboard"));
        }
        public object SignIn(string username, string password, bool rememberMe, string returnUrl)
        {
            if (string.IsNullOrEmpty(username))
            {
                ModelState.AddModelError("username", "You must specify a username.");
            }

            if (string.IsNullOrEmpty(password))
            {
                ModelState.AddModelError("password", "You must specify a password.");
            }

            if (ViewData.ModelState.IsValid)
            {
                User user = userService.GetUser(username, password);

                if (user != null)
                {
                    formsAuth.SetAuthCookie(user.Name, rememberMe);

                    if (!string.IsNullOrEmpty(returnUrl) && returnUrl.StartsWith("/"))
                    {
                        return(Redirect(returnUrl));
                    }

                    return(Redirect(Url.AppPath(Url.Home())));
                }

                ModelState.AddModelError("_FORM", "The username or password provided is incorrect.");
            }

            return(SignIn());
        }
Exemple #6
0
 public ActionResult Login(DangNhapModel form, string returnUrl)
 {
     if (ModelState.IsValid)
     {
         Account298 user = _account298Repository.Get(o => o.Username.Equals(form.Username));
         if (user != null)
         {
             if (ValidatePassword(user, form.Password))
             {
                 //dang nhap thanh cong
                 //  SetCookieLogin(this.Request.RequestContext, form.Username);
                 formAuthentication.SetAuthCookie(this.HttpContext, UserAuthenticationTicketBuilder.CreateAuthenticationTicket(user));
                 return(RedirectToAction("ViewDanhMuc", "DanhMucSanPham"));
             }
             else
             {
                 ViewData["Message"] = "Mật Khẩu Sai";
                 return(View("Index", form));
             }
         }
         else
         {
             ViewData["Message"] = "Tên đăng nhập không tồn tại";
             return(View("Index", form));
         }
     }
     else
     {
         return(View("Index", form));
     }
 }
Exemple #7
0
        //
        // GET: /Account/Login
        //[AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            _logger.Info("登录页面:访问IP:" + CerCommon.GetIp());

            if (CurrentUser != null && !(CurrentUser is EmptyUserContract))
            {
                _formsAuthentication.SetAuthCookie(CurrentUser.UserName, false);
                _contextService.SetCookie("role", CurrentUser.RoleId.ToString());
                _contextService.NickName  = CurrentUser.NickName;
                _contextService.DepId     = CurrentUser.DepId.ToString();
                _contextService.UserPhoto = ConfigurationManager.AppSettings["USER_AVATAR"] + CurrentUser.UserInfoPhoto;
                _logger.Info(CurrentUser.Id + "登录成功" + "文档管理系统");

                return(Redirect("/home/index"));
            }
            var model = new LoginModel();
            //读取保存的Cookie信息
            HttpCookie cookies = Request.Cookies["USER_COOKIE"];

            if (cookies != null && !string.IsNullOrEmpty(cookies.Value))
            {
                //如果Cookie不为空,则将Cookie里面的用户名和密码读取出来赋值给前台的文本框。
                model.UserName = Md5Util.Decrypt(cookies["UserName"]);
                model.Password = Md5Util.Decrypt(cookies["UserPassword"]);

                //这里依然把记住密码的选项给选中。
                model.RememberMe  = true;
                ViewBag.ReturnUrl = returnUrl;
                if (model.AutoLogin)
                {
                    return(Login(model, returnUrl));
                }

                return(View(model));
            }

            //if (!string.IsNullOrEmpty(returnUrl) && returnUrl.EndsWith("/account/logoff"))
            //{
            //    returnUrl = returnUrl.Replace("/account/logoff", "/home/index");
            //}
            ViewBag.ReturnUrl = returnUrl;
            return(View(model));
        }
 public ActionResult Edit(User updatedUser)
 {
     if (updatedUser.UserId == CurrentUserId)
     {
         if (ModelState.IsValid)
         {
             updatedUser.HasRegistered = true;
             UserServices.UpdateUser(updatedUser);
             formsAuthentication.SetAuthCookie(HttpContext,
                                               UserAuthenticationTicketBuilder.CreateAuthenticationTicket(
                                                   updatedUser));
             return(RedirectToRoute("Dashboard"));
         }
         User model = updatedUser;
         AddCountryListToViewBag();
         return(View(model));
     }
     throw new SecurityException("Not authorized");
 }
        public void SignIn(AdminUser adminUser, HttpSessionStateBase session)
        {
            if (adminUser == null)
            {
                throw new ArgumentNullException("Invalid authentication");
            }

            formsAuthentication.SetAuthCookie(adminUser.Name, false);
            session.Add("adminUser", adminUser);
        }
Exemple #10
0
        public bool Authenticate(string email, string password)
        {
            var user = _users.Users.WithEmail(email);

            if (user != null && _hash.ValidateMD5Hash(password, user.PasswordHash))
            {
                _forms.SetAuthCookie(email, false);
                return(true);
            }

            return(false);
        }
Exemple #11
0
        public ActionResult Edit(User user, string action = null)
        {
            if (action == "cancel")
            {
                //Reset user profile with current user info
                user.Country     = CurrentUser.Country;
                user.DisplayName = CurrentUser.DisplayName;
            }

            user.UserId        = CurrentUserId;
            user.HasRegistered = true;

            _updateUser.Execute(user);

            var ticket = _formsAuthentication.GetAuthenticationTicket(HttpContext);

            if (ticket != null)
            {
                _formsAuthentication.SetAuthCookie(HttpContext,
                                                   UserAuthenticationTicketBuilder.CreateAuthenticationTicket(
                                                       user, ticket.IssueDate, ticket.IsPersistent));
            }

            if (ModelState.IsValid || action == "cancel")
            {
                if (Request.IsAjaxRequest())
                {
                    return(new HttpStatusCodeResult((int)HttpStatusCode.OK, Messages.ProfileController_ProfileUpdated));
                }

                if (action != "cancel")
                {
                    this.SetConfirmationMessage(Messages.ProfileController_ProfileUpdated);
                }

                return(RedirectToAction("Index", "Dashboard"));
            }

            if (Request.IsAjaxRequest())
            {
                return(new HttpStatusCodeResult((int)HttpStatusCode.BadRequest, Messages.ProfileController_InvalidData));
            }

            return(SetupProfileForm(user));
        }
Exemple #12
0
        public string PartnerLogin(string authKey, string username)
        {
            if (!Regex.IsMatch(authKey, "[a-zA-Z0-9_-]+"))
            {
                throw new ArgumentException("Invalid auth key");
            }

            int  siteId      = 0;
            Guid?unitId      = Guid.Empty;
            bool canDelegate = false;

            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["AuthStore"].ConnectionString))
            {
                conn.Open();
                string     query  = string.Format("SELECT siteId,unitId,canDelegate,defaultUser FROM partners WHERE authKey='{0}'", authKey);
                SqlCommand cmd    = new SqlCommand(query, conn);
                var        reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    if (siteId != 0)
                    {
                        throw new InvalidOperationException("Multiple matching keys");
                    }
                    siteId      = reader.GetInt32(0);
                    unitId      = reader.IsDBNull(1) ? (Guid?)null : reader.GetGuid(1);
                    canDelegate = reader.GetBoolean(2);
                    // Assume we're going to be the default partner user.
                    string user = reader.GetString(3);

                    if (unitId != null && canDelegate && !string.IsNullOrWhiteSpace(username))
                    {
                        DateTime now = DateTime.Now;
                        if (!this.db.Members.Any(f => f.Username == username && f.Memberships.Any(g => g.Activated < now && (g.EndTime == null || g.EndTime > now) && g.Unit.Id == unitId && g.Status.IsActive)))
                        {
                            throw new InvalidOperationException("Not able to delegate as " + username);
                        }
                        user = username;
                    }

                    formsAuth.SetAuthCookie(username, false);
                }
            }

            return("OK");
        }
        public ActionResult SignInResponse()
        {
            var response = _relyingParty.GetResponse();

            switch (response.Status)
            {
            case AuthenticationStatus.Authenticated:
                var user = _getUserByClaimId.Execute(response.ClaimedIdentifier);
                if (user == null)
                {
                    user = _createUser.Execute(response.ClaimedIdentifier);
                }

                var isPersistent = (TempData.ContainsKey("rememberMe") && (bool)TempData["rememberMe"]);

                var ticket = UserAuthenticationTicketBuilder.CreateAuthenticationTicket(user, DateTime.Now, isPersistent);

                _formsAuthentication.SetAuthCookie(HttpContext, ticket);

                return(RedirectToAction("Index", "Dashboard"));

            case AuthenticationStatus.Canceled:

                this.SetConfirmationMessage(Messages.AuthController_CanceledAuthentication);

                return(RedirectToAction("Index"));

            case AuthenticationStatus.Failed:
                this.SetAlertMessage(response.Exception.Message);
                return(RedirectToAction("Index"));

            default:
                this.SetAlertMessage(Messages.AuthController_SignIn_UnableToAuthenticateWithProvider);
                return(RedirectToAction("Index"));
            }
        }
Exemple #14
0
        public ActionResult Register(string username, string email, string password, string securityquestion, string securityanswer)
        {
            if (string.IsNullOrEmpty(username))
            {
                ViewData.ModelState.AddModelError("username", "username is required");
            }
            else if (!AppHelper.IsValidUsername(username))
            {
                ViewData.ModelState.AddModelError("username", "username is invalid");
            }
            if (string.IsNullOrEmpty(email))
            {
                ViewData.ModelState.AddModelError("email", "email is required");
            }
            else if (!AppHelper.IsValidEmail(email))
            {
                ViewData.ModelState.AddModelError("email", "email is invalid");
            }
            if (string.IsNullOrEmpty(password))
            {
                ViewData.ModelState.AddModelError("password", "password is required");
            }
            if (string.IsNullOrEmpty(securityquestion))
            {
                ViewData.ModelState.AddModelError("securityQuestion", "security question is required");
            }
            if (string.IsNullOrEmpty(securityanswer))
            {
                ViewData.ModelState.AddModelError("securityAnswer", "security answer is required");
            }

            if (!ViewData.ModelState.IsValid)
            {
                return(View(new RegisterModel()
                {
                    email = email, password = password, username = username, securityQuestion = securityquestion, securityAnswer = securityanswer
                }));
            }
            System.Web.Security.MembershipCreateStatus status;
            var newUser = _provider.CreateUser(username, password, email, securityquestion, securityanswer, true, null, out status);

            if (newUser != null)
            {
                _formsAuth.SetAuthCookie(username, false);
                return(RedirectToAction("Index", "Home"));
            }

            if (status == System.Web.Security.MembershipCreateStatus.DuplicateUserName)
            {
                ViewData.ModelState.AddModelError("provider", "username is not unique");
            }
            if (status == System.Web.Security.MembershipCreateStatus.DuplicateEmail)
            {
                ViewData.ModelState.AddModelError("provider", "email is not unique");
            }

            return(View(new RegisterModel()
            {
                email = email, password = password, username = username, securityQuestion = securityquestion, securityAnswer = securityanswer
            }));
        }
Exemple #15
0
 public virtual void SetAuthenticationCookie(string email)
 {
     formsAuth.SetAuthCookie(email, true);
 }
        public object SignIn(string username, string password, bool rememberMe, string returnUrl)
        {
            //TODO: (erikpo) Move the following validation logic into a validator

            if (string.IsNullOrEmpty(username))
            {
                ModelState.AddModelError("username", "You must specify a username.");
            }

            if (string.IsNullOrEmpty(password))
            {
                ModelState.AddModelError("password", "You must specify a password.");
            }

            if (ViewData.ModelState.IsValid)
            {
                if (userService.SignIn(() => userService.GetUser(username, password), (u) => formsAuthentication.SetAuthCookie(u.Name, rememberMe)))
                {
                    if (!string.IsNullOrEmpty(returnUrl) && returnUrl.StartsWith("/"))
                    {
                        return(Redirect(returnUrl));
                    }

                    return(Redirect(Url.AppPath(Url.Home())));
                }

                ModelState.AddModelError("_FORM", "The username or password provided is incorrect.");
            }

            return(SignIn());
        }