public string CreateToken(int userId, string role)
        {
            var jwtKey = appSettings.Secrets?.JwtKey;

            if (string.IsNullOrWhiteSpace(jwtKey))
            {
                throw new ConfigurationException(nameof(jwtKey));
            }

            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = ASCII.GetBytes(jwtKey);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[]
                {
                    new Claim(ClaimTypes.Name, userId.ToString()),
                    new Claim(ClaimTypes.Role, role)
                }),
                Expires            = UtcNow.AddHours(appSettings.JwtExpirationTimeHours),
                SigningCredentials = new SigningCredentials(
                    new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token       = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

            return(tokenString);
        }
Пример #2
0
        /// <summary>
        /// Caches the data based upon a key
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="item">The item.</param>
        /// <returns></returns>
        public Task SetAsync(string key, T item)
        {
            var expiration = UtcNow.Add(this.duration);

            cache.Set(key, item, expiration);
            return(Task.FromResult(0));
        }
Пример #3
0
        public async Task CanIncludeMostRecentJuncture_Success()
        {
            var           productId       = Guid.NewGuid();
            const decimal mostRecentPrice = 10.00m;

            var product = new Product {
                Id               = productId,
                Name             = "MacBook Pro",
                Code             = "XYZ",
                Created          = UtcNow,
                LastModified     = UtcNow,
                ProductJunctures = new List <ProductJuncture> {
                    new ProductJuncture {
                        Price = 11.95m, Juncture = UtcNow.AddDays(-1)
                    },
                    new ProductJuncture {
                        Price = mostRecentPrice, Juncture = UtcNow
                    },
                    new ProductJuncture {
                        Price = 10.95m, Juncture = UtcNow.AddDays(-4)
                    },
                }
            };

            InitializeData(new Product[] { product });

            var response = await Service.GetByIdAsync(productId);

            Assert.Equal(product.Name, response.Name);
            Assert.Equal(product.Code, response.Code);
            Assert.Equal(product.Created, response.Created);
            Assert.Equal(product.LastModified, response.LastModified);

            Assert.Equal(mostRecentPrice, response.Price);
        }
            internal DownloadMetadata2CatalogAsyncTest()
            {
                UtcNow      = DateTime.UtcNow;
                LastCreated = UtcNow.AddHours(-3);
                LastEdited  = UtcNow.AddHours(-2);
                LastDeleted = UtcNow.AddHours(-1);

                Packages = new SortedList <DateTime, IList <FeedPackageDetails> >();

                PackageCatalogItemCreator = new Mock <IPackageCatalogItemCreator>(MockBehavior.Strict);
                Storage          = new Mock <IStorage>(MockBehavior.Strict);
                TelemetryService = new Mock <ITelemetryService>(MockBehavior.Strict);
                Logger           = new Mock <ILogger>();

                CatalogBaseUri  = new Uri("https://nuget.test/v3-catalog0/");
                CatalogIndexUri = new Uri(CatalogBaseUri, "index.json");

                Storage.Setup(x => x.ResolveUri(
                                  It.Is <string>(relativeUri => relativeUri == "index.json")))
                .Returns(CatalogIndexUri);

                FeedPackageDetails = new FeedPackageDetails(
                    new Uri("https://nuget.test/packages/a"),
                    UtcNow.AddMinutes(-45),
                    UtcNow.AddMinutes(-30),
                    UtcNow.AddMinutes(-15),
                    packageId: "a",
                    packageVersion: "1.0.0");
            }
Пример #5
0
        /// <inheritdoc />
        public Uri GetUrl(string fileName, string folderName, DateTime expiration)
        {
            if (IsNullOrWhiteSpace(fileName))
            {
                throw new ArgumentNullException(nameof(fileName));
            }

            if (IsNullOrWhiteSpace(folderName))
            {
                throw new ArgumentNullException(nameof(folderName));
            }

            if (expiration == default)
            {
                throw new ArgumentException("Invalid expiration", nameof(expiration));
            }

            var policy = new SharedAccessBlobPolicy
            {
                SharedAccessStartTime  = UtcNow.AddMinutes(-5),
                SharedAccessExpiryTime = expiration,
                Permissions            = Read
            };
            var blob = _cloudBlobClient
                       .GetContainerReference(folderName)
                       .GetBlockBlobReference(fileName);
            var sharedAccessSignature = blob.GetSharedAccessSignature(policy);

            return(new Uri(sharedAccessSignature));
        }
Пример #6
0
 protected virtual bool IsVerificationKeyStale(UserAccount account)
 {
     if (account.VerificationKeySent == null)
     {
         return(true);
     }
     return(account.VerificationKeySent < UtcNow.Subtract(_settings.Auth.VerificationKeyLifetime));
 }
Пример #7
0
            public void Sleep(int milliSeconds)
            {
                if (milliSeconds <= 0)
                {
                    throw new InvalidOperationException();
                }

                _internalUtcNow = UtcNow.AddMilliseconds(milliSeconds);
            }
        internal static void Log(string message, bool basic)
        {
            Logged.Add($"{UtcNow.ToShortTimeString()}: {message}\n");

            if (!basic && Settings.LogLevel != LogLevel.Verbose)
            {
                return;
            }

            WriteLine($"{UtcNow.ToShortTimeString()}: {message}\n");
        }
Пример #9
0
        public void get_delivery_time_should_return_now_plus_delay()
        {
            // arrange
            var when    = UtcNow.AddHours(1d);
            var options = new SendOptions().DelayDeliveryBy(FromHours(1d));

            // act
            var deliveryTime = options.GetDeliveryTime();

            // assert
            deliveryTime.Should().BeOnOrAfter(when);
        }
Пример #10
0
        public void get_delivery_time_should_return_when()
        {
            // arrange
            var tomorrow = UtcNow.AddDays(1d);
            var options  = new SendOptions().DoNotDeliverBefore(tomorrow);

            // act
            var deliveryTime = options.GetDeliveryTime();

            // assert
            deliveryTime.Should().Be(tomorrow);
        }
Пример #11
0
        public void get_delivery_delay_should_return_when_minus_now()
        {
            // arrange
            var tomorrow = UtcNow.AddDays(1d);
            var options  = new SendOptions().DoNotDeliverBefore(tomorrow);

            // act
            var delay = options.GetDeliveryDelay();

            // assert
            delay.Should().BeLessOrEqualTo(FromDays(1d));
        }
Пример #12
0
 private CheckResult GetCheckResult(int minutesDelta, CheckResultType type)
 {
     return(new CheckResult
     {
         Check = new Check
         {
             Name = CheckName
         },
         CheckBatch = new CheckBatch(),
         Type = type,
         Time = TimeUtilities.DateTimeOffsetToLong(UtcNow.AddMinutes(minutesDelta))
     });
 }
Пример #13
0
        protected virtual bool VerifyTwoFactorAuthToken(UserAccount account, string token)
        {
            if (account == null)
            {
                throw new ArgumentNullException(nameof(account));
            }

            _logger.LogInformation(GetLogMessage($"called for accountID: {account.UserId}"));

            if (account.AccountTwoFactorAuthMode != TwoFactorAuthMode.Mobile)
            {
                _logger.LogError(GetLogMessage("AccountTwoFactorAuthMode is not mobile"));
                return(false);
            }

            if (string.IsNullOrWhiteSpace(token))
            {
                _logger.LogError(GetLogMessage("failed -- no token"));
                return(false);
            }

            token = _crypto.Hash(token);

            var expiration  = UtcNow.AddDays(Settings.TwoFactorAuthTokenDurationDays);
            var removequery =
                from t in account.TwoFactorAuthTokenCollection
                where
                t.Issued < account.PasswordChanged ||
                t.Issued < account.MobilePhoneNumberChanged ||
                t.Issued < expiration
                select t;
            var itemsToRemove = removequery.ToArray();

            _logger.LogInformation(GetLogMessage($"number of stale tokens being removed: {itemsToRemove.Length}"));

            foreach (var item in itemsToRemove)
            {
                account.RemoveTwoFactorAuthToken(item);
            }

            var matchquery =
                from t in account.TwoFactorAuthTokenCollection.ToArray()
                where _crypto.VerifyHash(token, t.Token)
                select t;

            var result = matchquery.Any();

            _logger.LogInformation(GetLogMessage($"result was token verified: {result}"));

            return(result);
        }
        protected override void OnSessionChange(SessionChangeDescription changeDescription)
        {
            try
            {
                Restart();
            }
            catch (Exception ex) when(!AutoLog)
            {
                string directory = AppDomain.CurrentDomain.BaseDirectory;
                string filePath  = Path.Combine(directory, UtcNow.ToString("OnSessionChange failure at yyyy-MM-dd HH_mm_ss"));

                File.AppendAllText(filePath, ex.ToString());
            }
        }
        protected override void OnPause()
        {
            try
            {
                _NancyHost.Stop();
            }
            catch (Exception ex) when(!AutoLog)
            {
                string directory = AppDomain.CurrentDomain.BaseDirectory;
                string filePath  = Path.Combine(directory, UtcNow.ToString("OnPause failure at yyyy-MM-dd HH_mm_ss"));

                File.AppendAllText(filePath, ex.ToString());
            }
        }
Пример #16
0
        protected override async Task Context()
        {
            _streamId = Guid.NewGuid().ToString();

            _now   = UtcNow.AddYears(1);
            _first = _streamId.BuildAttempt(now: _now.AddSeconds(1));
            await Persistence.Commit(_first);

            _second = await Persistence.CommitNext(_first);

            _third = await Persistence.CommitNext(_second);

            await Persistence.CommitNext(_third);
        }
Пример #17
0
        protected virtual bool IsMobileCodeOlderThan(UserAccount account, int duration)
        {
            if (account == null)
            {
                throw new ArgumentNullException(nameof(account));
            }

            if (account.MobileCodeSent == null || string.IsNullOrWhiteSpace(account.MobileCode))
            {
                return(true);
            }

            return(account.MobileCodeSent < UtcNow.AddMinutes(-duration));
        }
Пример #18
0
        protected internal virtual bool HasTooManyRecentPasswordFailures(int failedLoginCount, TimeSpan lockoutDuration)
        {
            if (failedLoginCount <= 0)
            {
                throw new ArgumentException("failedLoginCount");
            }

            if (failedLoginCount <= FailedLoginCount)
            {
                return(LastFailedLogin >= UtcNow.Subtract(lockoutDuration));
            }

            return(false);
        }
Пример #19
0
        public bool ValidateTimeLimits(ElectricityReading electricityReading, PanelType panelType)
        {
            switch (panelType)
            {
            case PanelType.Regular when DateTime.UtcNow.Subtract(electricityReading.ReadingDateTime).Hours >= 1:
            case PanelType.Limited when DateTime.UtcNow.Subtract(electricityReading.ReadingDateTime).Days >= 1 &&
                electricityReading.KiloWatt < 5:
            case PanelType.Ultimate
                when DateTime.UtcNow.Subtract(electricityReading.ReadingDateTime).Minutes >= 1 &&
                electricityReading.KiloWatt >= 5:
                return(true);

            default:
                return(false);
            }
        }
        protected override void OnStart(string[] args)
        {
            try
            {
                AutoLog = bool.Parse(ConfigurationManager.AppSettings["AutoLog"] ?? "true");

                _NancyHost = CreateHost();
                _NancyHost.Start();
            }
            catch (Exception ex) when(!AutoLog)
            {
                string directory = AppDomain.CurrentDomain.BaseDirectory;
                string filePath  = Path.Combine(directory, UtcNow.ToString("OnStart failure at yyyy-MM-dd HH_mm_ss"));

                File.AppendAllText(filePath, ex.ToString());
            }
        }
Пример #21
0
        private DateTime ToAbsolute(CacheExpires expires)
        {
            // this is less sophisticated than the web caching implementation, but
            // it only needs to satisfy expectations of unit tests. they should always
            // use utc for abs

            if (expires == null)
            {
                return(CacheExpires.NoAbsoluteExpiration);
            }

            if (expires.Sliding != CacheExpires.NoSlidingExpiration)
            {
                return(UtcNow.Add(expires.Sliding));
            }

            return(expires.Absolute);
        }
Пример #22
0
        protected override async Task Context()
        {
            _now = UtcNow.AddYears(1);

            var commitToBucketA = Guid.NewGuid().ToString().BuildAttempt(_now.AddSeconds(1), _bucketAId);

            await Persistence.Commit(commitToBucketA);

            await Persistence.Commit(commitToBucketA = commitToBucketA.BuildNextAttempt());

            await Persistence.Commit(commitToBucketA = commitToBucketA.BuildNextAttempt());

            await Persistence.Commit(commitToBucketA.BuildNextAttempt());

            _commitToBucketB = Guid.NewGuid().ToString().BuildAttempt(_now.AddSeconds(1), _bucketBId);

            await Persistence.Commit(_commitToBucketB);
        }
Пример #23
0
        public void can_mock_delegate()
        {
            //given
            var builder = new ContainerBuilder();

            builder.DiscoverDelegates <Timer>();

            UtcNow mockUtcNow = () => new DateTime(1991, 2, 7);

            builder.RegisterDelegate(() => mockUtcNow).SingleInstance();

            var container = builder.Build();

            //when
            var utcNow = container.Resolve <UtcNow>();

            //then
            utcNow().Should().Be(new DateTime(1991, 2, 7));
        }
        protected override void OnCustomCommand(int command)
        {
            try
            {
                if (command != (int)Command.Restart)
                {
                    return;
                }

                //useful for config changes
                Restart();
            }
            catch (Exception ex) when(!AutoLog)
            {
                string directory = AppDomain.CurrentDomain.BaseDirectory;
                string filePath  = Path.Combine(directory, UtcNow.ToString("OnCustomCommand failure at yyyy-MM-dd HH_mm_ss"));

                File.AppendAllText(filePath, ex.ToString());
            }
        }
Пример #25
0
 ExceptionDispatchInfo GetCachedError()
 {
     try
     {
         var cache = exceptionCache;
         if (cache.Exception != null)
         {
             if (exceptionCache.CacheExpiryDateTime > DateTime.UtcNow)
             {
                 return(cache.Exception);
             }
         }
         throw new Exception("Test");
     }
     catch (Exception ex)
     {
         ExceptionDispatchInfo edi = ExceptionDispatchInfo.Capture(ex);
         exceptionCache = (edi, DateTime.UtcNow.AddSeconds(ExpirySeconds));
         return(edi);
     }
 }
Пример #26
0
        void IXmlSerializable.WriteXml(XmlWriter writer)
        {
            writer.WriteAttributeString("Date", Date.ToString(CultureInfo.InvariantCulture));
            writer.WriteAttributeString("UtcNow", UtcNow.ToString(CultureInfo.InvariantCulture));
            writer.WriteAttributeString("TimeZone", TimeZone.ToString());
            writer.WriteAttributeString("Culture", CurrentCulture);
            writer.WriteAttributeString("UICulture", CurrentUICulture);

            writer.WriteStartElement("OSVersion");
            ((IXmlSerializable)OSVersion).WriteXml(writer);
            writer.WriteEndElement();

            writer.WriteStartElement("Frameworks");
            foreach (var o in FrameworksVersions)
            {
                writer.WriteElementString("Framework", o.ToString());
            }

            writer.WriteEndElement();

            writer.WriteStartElement("Pathes");

            if (Paths.IsNotEmpty())
            {
                foreach (var pair in Paths)
                {
                    writer.WriteStartElement("Path");
                    writer.WriteAttributeString("Name", pair.Name);
                    writer.WriteAttributeString("Value", pair.Value.ToString());
                    writer.WriteEndElement();
                }
            }
            writer.WriteEndElement();

            writer.WriteStartElement("DomainInfo");
            ((IXmlSerializable)DomainInfo).WriteXml(writer);
            writer.WriteEndElement();
        }
Пример #27
0
 public void AddToUtcTime(TimeSpan timeSpan)
 {
     UtcNow = UtcNow.Add(timeSpan);
 }
Пример #28
0
        public async Task ResetPasswordFromSecretQuestionAndAnswerAsync(Guid accountGuid, PasswordResetQuestionAnswer[] answers)
        {
            _logger.LogInformation(GetLogMessage($"called: {accountGuid}"));

            if (answers == null || answers.Length == 0 || answers.Any(x => string.IsNullOrWhiteSpace(x.Answer)))
            {
                _logger.LogError(GetLogMessage("failed -- no answers"));
                throw new ValidationException(GetValidationMessage(UserAccountConstants.ValidationMessages.SecretAnswerRequired));
            }

            var account = await GetByGuidAsync(accountGuid, x => x.PasswordResetSecretCollection);

            if (account == null)
            {
                _logger.LogError(GetLogMessage("failed -- invalid account id"));
                throw new Exception("Invalid Account ID");
            }

            if (string.IsNullOrWhiteSpace(account.Email))
            {
                _logger.LogError(GetLogMessage("no email to use for password reset"));
                throw new ValidationException(GetValidationMessage(UserAccountConstants.ValidationMessages.PasswordResetErrorNoEmail));
            }

            if (!account.PasswordResetSecretCollection.Any())
            {
                _logger.LogError(GetLogMessage("failed -- account not configured for secret question/answer"));
                throw new ValidationException(GetValidationMessage(UserAccountConstants.ValidationMessages.AccountNotConfiguredWithSecretQuestion));
            }

            if (account.FailedPasswordResetCount >= Settings.AccountLockoutFailedLoginAttempts &&
                account.LastFailedPasswordReset >= UtcNow.Subtract(Settings.AccountLockoutDuration))
            {
                account.FailedPasswordResetCount++;

                AddEvent(new PasswordResetFailedEvent {
                    Account = account
                });

                Update(account, true);

                _logger.LogError(GetLogMessage("failed -- too many failed password reset attempts"));
                throw new ValidationException(GetValidationMessage(UserAccountConstants.ValidationMessages.InvalidQuestionOrAnswer));
            }

            var secrets = account.PasswordResetSecretCollection.ToArray();
            var failed  = false;

            foreach (var answer in answers)
            {
                var secret = secrets.SingleOrDefault(x => x.Guid == answer.QuestionId);
                if (secret != null && _crypto.VerifyHash(answer.Answer, secret.Answer))
                {
                    continue;
                }
                _logger.LogError(GetLogMessage($"failed on question id: {answer.QuestionId}"));
                failed = true;
            }

            if (failed)
            {
                account.LastFailedPasswordReset = UtcNow;
                if (account.FailedPasswordResetCount <= 0)
                {
                    account.FailedPasswordResetCount = 1;
                }
                else
                {
                    account.FailedPasswordResetCount++;
                }
                AddEvent(new PasswordResetFailedEvent {
                    Account = account
                });
            }
            else
            {
                _logger.LogTrace(GetLogMessage("success"));

                account.LastFailedPasswordReset  = null;
                account.FailedPasswordResetCount = 0;
                ResetPassword(account);
            }

            Update(account, true);

            if (failed)
            {
                throw new ValidationException(GetValidationMessage(UserAccountConstants.ValidationMessages.InvalidQuestionOrAnswer));
            }
        }
Пример #29
0
        public async Task InvalidConcurrencyCannotUpdate_Failure()
        {
            var productId = Guid.NewGuid();

            InitializeData(new Product[]
            {
                new Product {
                    Id = productId, Name = "MacBook Pro", Code = "XYZ", Created = UtcNow, LastModified = UtcNow
                }
            });

            var product = new Product {
                Id = productId, Name = "iMac", Code = "ABC", Created = UtcNow, LastModified = UtcNow.AddDays(1)
            };

            await Assert.ThrowsAsync <DbUpdateConcurrencyException>(() =>
            {
                return(Service.UpdateAsync(product));
            });
        }
Пример #30
0
 public void AdvanceSeconds(int seconds)
 {
     UtcNow = UtcNow.AddSeconds(seconds);
 }