Exemplo n.º 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);
        }