Пример #1
0
        private async Task <bool> TryAuthenticateUser(LoginCredentialsDto credentials)
        {
            using var activity = traceActivityDecorator.StartActivity();

            var cacheKey            = CacheKeys.FailedLoginRequests;
            var cacheKeyName        = cacheKey.Name(credentials.Key);
            var usersAndPasswords   = GetUsersAndPasswords();
            var failedLoginRequests = await cache.TryGetAsync <int>(cacheKeyName);

            if (failedLoginRequests.Success && failedLoginRequests.Value >= MaxLoginTries)
            {
                logger.LogInformation($"User {credentials.Key} has {failedLoginRequests.Value} failed login attempts in the last {cacheKey.TimeToLive.TotalHours} hour(s) and cannot login");
                return(false);
            }

            if (!usersAndPasswords.ContainsKey(credentials.Key) || usersAndPasswords[credentials.Key] != credentials.Secret)
            {
                logger.LogInformation($"The given password for the user {credentials.Key} is wrong");
                await cache.SetAsync(cacheKeyName, failedLoginRequests.Value + 1, cacheKey.TimeToLive);

                return(false);
            }

            await cache.SetAsync(cacheKeyName, 0, cacheKey.TimeToLive);

            return(true);
        }
        public override async Task <HealthCheckResult> DoCheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
        {
            var adminUsername = config.Get(ConfigNames.AdminUsername);
            var cacheKey      = CacheKeys.FailedLoginRequests;
            var attempts      = await cache.TryGetAsync <int>(cacheKey.Name(adminUsername));

            var message = $"There are {attempts.Value} login attempts for the admin user in the last {cacheKey.TimeToLive} hours";

            if (attempts.Success && attempts.Value >= LoginController.MaxLoginTries)
            {
                return(HealthCheckResult.Degraded(message));
            }

            return(HealthCheckResult.Healthy(message));
        }