private void ShowLogin()
 {
     if (userLoginControl == null)
     {
         userLoginControl = new UserLoginControl();
     }
     CenterView       = userLoginControl;
     userLoginControl = null;
 }
Beispiel #2
0
 public void AssignSettings(HSTSettings settings)
 {
     _userAccess                    = settings.getUserAccessSettings();
     _userLoginControl              = new UserLoginControl(settings);
     _userLoginControl.Size         = new Size(307, 105);
     _userAccess.UserChanged       += new EventHandler(UserChanged);
     settings.OnSettingsChanged    += new EventHandler(SettingsChanged);
     _userAccess.UpdateCurrentUser += UpdateCurrentUser;
     UserAccessControl.UserLogin   += UserAccessControl_UserLogin;
 }
Beispiel #3
0
        public void UserLoginControl_Login_rest()
        {
            UserConfig.SetUri("http://localhost:49653");
            UserLoginControl control = new UserLoginControl();

            Assert.IsTrue(control.Login("zhs", "zhs"));
            var lst = control.LoginUsers;

            Assert.IsTrue(lst.Count > 0);
        }
Beispiel #4
0
        public void UserLoginControl_Login_db()
        {
            UserConfig.SetUri("");
            UserLoginControl control = new UserLoginControl();

            Assert.IsTrue(control.Login("zhs", "zhs"));
            var lst = control.LoginUsers;

            Assert.IsTrue(lst.Count > 0);
        }
        /// <summary>
        /// OnSignInFailedBySmsAsync
        /// </summary>
        /// <param name="mobile"></param>
        /// <param name="lastUser"></param>
        /// <returns></returns>
        /// <exception cref="KVStoreException"></exception>
        /// <exception cref="DatabaseException"></exception>
        /// <exception cref="CacheException"></exception>
        public async Task OnSignInFailedBySmsAsync(string mobile, string lastUser)
        {
            User?user = await _userRepo.GetByMobileAsync(mobile).ConfigureAwait(false);

            if (user == null)
            {
                return;
            }

            UserLoginControl userLoginControl = await GetOrCreateUserLoginControlAsync(lastUser, user.Id).ConfigureAwait(false);

            await OnSignInFailedAsync(userLoginControl, lastUser).ConfigureAwait(false);
        }
        /// <summary>
        /// GetOrCreateUserLoginControlAsync
        /// </summary>
        /// <param name="lastUser"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        /// <exception cref="KVStoreException"></exception>
        private async Task <UserLoginControl> GetOrCreateUserLoginControlAsync(string lastUser, long userId)
        {
            UserLoginControl?userLoginControl = await _userLoginControlRepo.GetAsync(userId).ConfigureAwait(false);

            if (userLoginControl == null)
            {
                userLoginControl = new UserLoginControl {
                    UserId = userId
                };
                await _userLoginControlRepo.AddAsync(userLoginControl, lastUser).ConfigureAwait(false);
            }

            return(userLoginControl);
        }
        /// <summary>
        /// PreSignInCheck
        /// </summary>
        /// <param name="user"></param>
        /// <param name="userLoginControl"></param>
        /// <param name="lastUser"></param>
        /// <exception cref="IdentityException"></exception>
        /// <exception cref="KVStoreException"></exception>
        private async Task PreSignInCheckAsync(User user, UserLoginControl userLoginControl, string lastUser)
        {
            ThrowIf.Null(user, nameof(user));

            SignInOptions signInOptions = _options.SignInOptions;

            //2, 手机验证
            if (signInOptions.RequireMobileConfirmed && !user.MobileConfirmed)
            {
                throw Exceptions.AuthorizationMobileNotConfirmed(userId: user.Id);
            }

            //3, 邮件验证
            if (signInOptions.RequireEmailConfirmed && !user.EmailConfirmed)
            {
                throw Exceptions.AuthorizationEmailNotConfirmed(userId: user.Id);
            }

            //4, Lockout 检查
            if (signInOptions.RequiredLockoutCheck && userLoginControl.LockoutEnabled && userLoginControl.LockoutEndDate > TimeUtil.UtcNow)
            {
                throw Exceptions.AuthorizationLockedOut(lockoutEndDate: userLoginControl.LockoutEndDate, userId: user.Id);
            }

            //5, 一段时间内,最大失败数检测
            if (signInOptions.RequiredMaxFailedCountCheck && userLoginControl.LoginFailedLastTime.HasValue)
            {
                if (TimeUtil.UtcNow - userLoginControl.LoginFailedLastTime < TimeSpan.FromDays(signInOptions.AccessFailedRecoveryDays))
                {
                    if (userLoginControl.LoginFailedCount > signInOptions.MaxFailedCount)
                    {
                        throw Exceptions.AuthorizationOverMaxFailedCount(userId: user.Id);
                    }
                }
            }

            //重置LoginControl
            if (userLoginControl.LockoutEnabled || userLoginControl.LoginFailedCount != 0)
            {
                userLoginControl.LockoutEnabled   = false;
                userLoginControl.LoginFailedCount = 0;

                await _userLoginControlRepo.UpdateAsync(userLoginControl, lastUser).ConfigureAwait(false);
            }

            if (signInOptions.RequireTwoFactorCheck && user.TwoFactorEnabled)
            {
                //TODO: 后续加上twofactor验证. 即登录后,再验证手机或者邮箱
            }
        }
        public void AssignSettings(ApplicationSettings settings, frmMain frmMain)
        {
            MainForm    = frmMain;
            _userAccess = settings.getUserAccessSettings();

            _userAccess.UserChanged       += new EventHandler(UserChanged);
            settings.OnSettingsChanged    += new EventHandler(SettingsChanged);
            _userAccess.UpdateCurrentUser += UpdateCurrentUser;

            _userAccess.getCurrentUser().Name     = "Monitor";
            _userAccess.getCurrentUser().Password = "******";
            _userAccess.getCurrentUser().Level    = 0;
            _userLoginControl      = new UserLoginControl(settings);
            _userLoginControl.Size = new Size(307, 105);
        }
        /// <summary>
        /// OnSignInFailed
        /// </summary>
        /// <param name="userLoginControl"></param>
        /// <param name="lastUser"></param>
        /// <exception cref="KVStoreException"></exception>
        private async Task OnSignInFailedAsync(UserLoginControl userLoginControl, string lastUser)
        {
            if (_options.SignInOptions.RequiredLockoutCheck)
            {
                if (userLoginControl.LoginFailedCount > _options.SignInOptions.LockoutAfterAccessFailedCount)
                {
                    userLoginControl.LockoutEnabled = true;
                    userLoginControl.LockoutEndDate = TimeUtil.UtcNow + _options.SignInOptions.LockoutTimeSpan;

                    _logger.LogWarning("有用户重复登陆失败,账户已锁定.{UserId}, {LastUser}", userLoginControl.UserId, lastUser);
                }
            }

            if (_options.SignInOptions.RequiredMaxFailedCountCheck)
            {
                userLoginControl.LoginFailedCount++;
            }

            await _userLoginControlRepo.UpdateAsync(userLoginControl, lastUser).ConfigureAwait(false);
        }
        /// <summary>
        /// SignInAsync
        /// </summary>
        /// <param name="context"></param>
        /// <param name="lastUser"></param>
        /// <returns></returns>
        /// <exception cref="IdentityException"></exception>
        /// <exception cref="DatabaseException"></exception>
        /// <exception cref="KVStoreException"></exception>
        /// <exception cref="CacheException"></exception>
        public async Task <UserAccessResult> SignInAsync(SignInContext context, string lastUser)
        {
            ThrowIf.NotValid(context, nameof(context));

            switch (context.SignInType)
            {
            case SignInType.ByMobileAndPassword:
                ThrowIf.NullOrEmpty(context.Mobile, "SignInContext.Mobile");
                ThrowIf.NullOrEmpty(context.Password, "SignInContext.Password");
                break;

            case SignInType.BySms:
                ThrowIf.NullOrEmpty(context.Mobile, "SignInContext.Mobile");
                break;

            case SignInType.ByLoginNameAndPassword:
                ThrowIf.NullOrEmpty(context.LoginName, "SignInContext.LoginName");
                ThrowIf.NullOrEmpty(context.Password, "SignInContext.Password");
                break;

            default:
                break;
            }

            TransactionContext transactionContext = await _transaction.BeginTransactionAsync <SignInToken>().ConfigureAwait(false);

            try
            {
                //查询用户
                User?user = context.SignInType switch
                {
                    SignInType.ByLoginNameAndPassword => await _userRepo.GetByLoginNameAsync(context.LoginName !, transactionContext).ConfigureAwait(false),
                    SignInType.BySms => await _userRepo.GetByMobileAsync(context.Mobile !, transactionContext).ConfigureAwait(false),
                    SignInType.ByMobileAndPassword => await _userRepo.GetByMobileAsync(context.Mobile !, transactionContext).ConfigureAwait(false),
                    _ => null
                };

                //不存在,则新建用户

                if (user == null && context.SignInType == SignInType.BySms)
                {
                    user = await _identityService.CreateUserAsync(context.Mobile !, null, context.LoginName, context.Password, true, false, lastUser, transactionContext).ConfigureAwait(false);
                }

                if (user == null)
                {
                    throw Exceptions.AuthorizationNotFound(signInContext: context);
                }

                UserLoginControl userLoginControl = await GetOrCreateUserLoginControlAsync(lastUser, user.Id).ConfigureAwait(false);

                //密码检查
                if (context.SignInType == SignInType.ByMobileAndPassword || context.SignInType == SignInType.ByLoginNameAndPassword)
                {
                    if (!PassowrdCheck(user, context.Password !))
                    {
                        await OnSignInFailedAsync(userLoginControl, lastUser).ConfigureAwait(false);

                        throw Exceptions.AuthorizationPasswordWrong(signInContext: context);
                    }
                }

                //其他检查
                await PreSignInCheckAsync(user, userLoginControl, lastUser).ConfigureAwait(false);

                //注销其他客户端
                await DeleteSignInTokensAsync(user.Id, context.DeviceInfos.Idiom, context.LogOffType, context.DeviceInfos.Name, transactionContext).ConfigureAwait(false);

                //创建Token

                SignInToken signInToken = new SignInToken
                                          (
                    userId: user.Id,
                    refreshToken: SecurityUtil.CreateUniqueToken(),
                    expireAt: TimeUtil.UtcNow + (context.RememberMe ? _options.SignInOptions.RefreshTokenLongExpireTimeSpan : _options.SignInOptions.RefreshTokenShortExpireTimeSpan),
                    deviceId: context.DeviceId,
                    deviceVersion: context.DeviceVersion,
                    deviceIp: context.DeviceIp,

                    deviceName: context.DeviceInfos.Name,
                    deviceModel: context.DeviceInfos.Model,
                    deviceOSVersion: context.DeviceInfos.OSVersion,
                    devicePlatform: context.DeviceInfos.Platform,
                    deviceIdiom: context.DeviceInfos.Idiom,
                    deviceType: context.DeviceInfos.Type
                                          );

                await _signInTokenRepo.AddAsync(signInToken, lastUser, transactionContext).ConfigureAwait(false);

                //构造 Jwt
                string jwt = await ConstructJwtAsync(user, signInToken, context.SignToWhere, transactionContext).ConfigureAwait(false);

                UserAccessResult result = new UserAccessResult
                                          (
                    accessToken: jwt,
                    refreshToken: signInToken.RefreshToken,
                    currentUser: user
                                          );

                await _transaction.CommitAsync(transactionContext).ConfigureAwait(false);

                return(result);
            }
            catch
            {
                await _transaction.RollbackAsync(transactionContext).ConfigureAwait(false);

                throw;
            }
        }
Beispiel #11
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="ctrl"></param>
 public UserLogin(UserLoginControl ctrl)
 {
     InitializeComponent();
     Control = ctrl;
 }