예제 #1
0
        public virtual void OnAuthorization(AuthorizationContext filterContext)
        {
            SigninUser luser = UserHelper.GetSigninUser;

            if (luser == null)
            {
                filterContext.Result = new RedirectResult("/Sign/In?url=" + filterContext.HttpContext.Request.RawUrl);
                return;
            }
            _roleId         = luser.RoleId.ToArray();
            _namespace      = filterContext.ActionDescriptor.ControllerDescriptor.ControllerType.Namespace;
            _actionName     = filterContext.ActionDescriptor.ActionName;
            _controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerType.Name;

            if (AuthorizeCore(filterContext.HttpContext))
            {
                // ** IMPORTANT **
                // Since we're performing authorization at the action level, the authorization code runs
                // after the output caching module. In the worst case this could allow an authorized user
                // to cause the page to be cached, then an unauthorized user would later be served the
                // cached page. We work around this by telling proxies not to cache the sensitive page,
                // then we hook our custom authorization code into the caching mechanism so that we have
                // the final say on whether a page should be served from the cache.

                HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
                cachePolicy.SetProxyMaxAge(new TimeSpan(0));
                cachePolicy.AddValidationCallback(CacheValidateHandler, null /* data */);
            }
            else
            {
                filterContext.Result = new RedirectResult("/Sign/In?m=您没有该功能的访问权限!");
                return;
            }
        }
 public static void UpdateUser(SigninUser user)
 {
     using (var DB = new ASPProjectDB())
     {
         var updated = DB.Users.First(u => u.UserName == user.Username);
         updated.FirstName = user.FirstName;
         updated.LastName  = user.LastName;
         updated.Password  = user.Password;
         updated.BirthDate = user.BirthDate;
         DB.SaveChanges();
     }
 }
 public static void AddUser(SigninUser user)
 {
     AddUser(new User
     {
         BirthDate = user.BirthDate,
         Email     = user.Email,
         FirstName = user.FirstName,
         LastName  = user.LastName,
         Password  = user.Password,
         UserName  = user.Username,
     });
 }
        public Task <SigninUserPayload> SigninUser(
            SigninUser signinUser)
        {
            User validUser = GetUserByEmail(signinUser.Email).Result;

            if (validUser != null && signinUser.Password == validUser.Password)
            {
                return(Task.FromResult(new SigninUserPayload {
                    Id = validUser.Id,
                    Token = "kaotik"
                }));
            }
            return(Task.FromResult <SigninUserPayload>(null));
        }
        public ActionResult SigninOrEdit(SigninUser user)
        {
            bool isSignin = Request.Cookies["user"] == null;

            if (isSignin && DataAccessor.Exists(user.Username, ExistenceCheckOption.ByUsername))
            {
                ModelState.AddModelError("username", "This username is taken. choose an other one.");
            }

            if (isSignin && DataAccessor.Exists(user.Email, ExistenceCheckOption.ByEmail))
            {
                ModelState.AddModelError("email", "This email is already signed in.");
            }

            if (ModelState.IsValid)
            {
                if (isSignin)
                {
                    DataCollector.AddUser(user);
                }
                else
                {
                    DataCollector.UpdateUser(user);
                }

                var u = DataAccessor.GetUser(user.Username, user.Password);

                Response.Cookies["user"]["username"]  = u.Username;
                Response.Cookies["user"]["userId"]    = u.Id.Value.ToString();
                Response.Cookies["user"]["firstName"] = u.FirstName;
                Response.Cookies["user"]["lastname"]  = u.LastNmae;
                Response.Cookies["user"].Expires      = DateTime.Now.AddDays(1);

                var ids = DataAccessor.GetProductsIds(u.Id.Value).Select(p => p.ToString());
                var Ids = new StringBuilder();
                foreach (var item in ids)
                {
                    Ids.Append(item + ",");
                }
                Response.Cookies["cart"]["productsIds"] = Ids.ToString();

                Response.Cookies["cart"].Expires = DateTime.Now.AddDays(-1);

                return(RedirectToRoute(new { Controller = "Home" }));
            }
            ViewBag.IsSignin = isSignin;
            return(View(user));
        }
예제 #6
0
        public string PostSignIn(SigninUser usr)
        {
            // Find user with username
            User FoundUser = _userService.Users.Single(u => u.Username == usr.Username);

            // Clear expired tokens -- doesn't actually execute until SaveChanges()
            var ExpTokens = _userService.AuthorizationTokens
                            .Where(
                t => t.UserUid == FoundUser.Uid &&
                t.ExpirationDate < DateTime.Now
                )
                            .ToList();

            foreach (AuthorizationToken token in ExpTokens)
            {
                _userService.Remove(token);
            }

            // Must have confirmed email
            if (!FoundUser.EmailConfirmed)
            {
                throw new ArgumentException();
            }

            // Check if the passwords match
            if (BCrypt.Net.BCrypt.Verify(usr.Password, FoundUser.Password))
            {
                // Correct password -- create a new token
                _userService.Add(new AuthorizationToken
                {
                    UserUid        = FoundUser.Uid,
                    CreationDate   = DateTime.Now,
                    ExpirationDate = DateTime.Now.AddDays(30)
                });
                _userService.SaveChanges();

                // TODO: return the newly minted token, not just the first
                // Return token
                return(_userService.AuthorizationTokens.FirstOrDefault(t => t.User == FoundUser).Uid);
            }
            else
            {
                // Incorrect password
                throw new ArgumentException();
            }
        }
예제 #7
0
        public virtual void OnAuthorization(AuthorizationContext filterContext)
        {
            SigninUser luser         = UserHelper.GetSigninUser;
            bool       isAjaxRequest = IsAjaxRequest(filterContext.RequestContext.HttpContext.Request);

            if (luser == null && !isAjaxRequest)
            {
                filterContext.Result = new RedirectResult("/Sign/In?url=" + filterContext.HttpContext.Request.RawUrl);
                return;
            }

            if (luser == null && isAjaxRequest)
            {
                filterContext.Result = new RedirectResult("/Error/Timeout");
                return;
            }
        }
예제 #8
0
        public async Task <IActionResult> Index(SigninUser model, string returnUrl = null)
        {
            try
            {
                var settings = await _settingsManager.GetSettingsAsync <SecuritySettings>();

#if !DEBUG
                if (settings.ValidCode && !IsValidateCode("login", model.Code))
                {
                    return(Error("验证码错误!"));
                }
#endif
                returnUrl      = returnUrl ?? Url.GetDirection(settings.LoginDirection);
                model.UserName = model.UserName.Trim();
                model.Password = model.Password.Trim();

                var result = await _userManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, async user => await EventLogger.LogAsync(user.UserId, Resources.EventType, "成功登录系统。"));

                if (result.Succeeded)
                {
                    Response.Cookies.Delete("login");
                    return(Success(new { url = returnUrl }));
                }

                if (result.RequiresTwoFactor)
                {
                    return(Success(new { reurl = Url.Page("/LoginWith2fa", new { model.RememberMe, returnUrl, area = SecuritySettings.ExtensionName }) }));
                }

                if (result.IsLockedOut)
                {
                    Logger.LogWarning($"账户[{model.UserName}]被锁定。");
                    return(Error("账户被锁定!"));
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, $"账户[{model.UserName}]登录失败:{ex.Message}");
            }
            Logger.LogWarning($"账户[{model.UserName}]登录失败。");
            return(Error("用户名或密码错误!"));
        }
예제 #9
0
 public BaseViewService(IMongoDbDataAccess mongoDbDataAccess)
 {
     this.mMongoDbDataAccess = mongoDbDataAccess;
     this.mSigninUser        = CPSSAuthenticate.GetCurrentUser();
 }