Exemplo n.º 1
0
        /// <summary>
        /// Проверяет токен и возвращает признак его валидности.
        /// </summary>
        /// <param name="accessToken">Валидируемый токен.</param>
        /// <param name="utcTimeProvider">Провайдер UTC времени.</param>
        /// <returns>Признак валидности токена.</returns>
        public void Validate(AccessToken accessToken, IUtcTimeProvider utcTimeProvider)
        {
            if (accessToken == null)
            {
                throw new ArgumentNullException(nameof(accessToken));
            }
            if (utcTimeProvider == null)
            {
                throw new ArgumentNullException(nameof(utcTimeProvider));
            }

            if (State != SessionState.Active)
            {
                throw new InactiveSessionException();
            }

            var utcNow = utcTimeProvider.UtcNow;

            if (utcNow > accessToken.Expiration)
            {
                throw new InvalidTokenException("Token expired.");
            }

            if (!BCrypt.Net.BCrypt.Verify(Id, accessToken.Token))
            {
                throw new InvalidTokenException("Incorrect token hash.");
            }
        }
Exemplo n.º 2
0
        public InMemoryEventStore(string microserviceName, IUtcTimeProvider time, ITextSerializer serializer, IGuidProvider guid, ILogger log)
        {
            Ensure.NotNull(microserviceName, nameof(microserviceName));
            Ensure.NotNull(time, nameof(time));
            Ensure.NotNull(serializer, nameof(serializer));
            Ensure.NotNull(guid, nameof(guid));
            Ensure.NotNull(log, nameof(log));

            this.streamType = microserviceName;
            this.time       = time;
            this.serializer = serializer;
            this.guid       = guid;
            this.log        = log;
            this.cache      = new MemoryCache(microserviceName);

            /// TODO: could be replaced with a compiled lambda to make it more performant.
            var fromMementoConstructor = typeof(T).GetConstructor(new[] { typeof(Guid), typeof(ISnapshot) });

            Ensure.CastIsValid(fromMementoConstructor, "Type T must have a constructor with the following signature: .ctor(Guid, IMemento)");
            this.originatorAggregateFactory = (id, memento) => (T)fromMementoConstructor.Invoke(new object[] { id, memento });

            var fromStreamConstructor = typeof(T).GetConstructor(new[] { typeof(Guid), typeof(IEnumerable <IEvent>) });

            Ensure.CastIsValid(fromStreamConstructor, "Type T must have a constructor with the following signature: .ctor(Guid, IEnumerable<IEvent>)");
            this.aggregateFactory = (id, streamOfEvents) => (T)fromStreamConstructor.Invoke(new object[] { id, streamOfEvents });

            if (this.Events.Any(e => e.StreamType == this.streamType))
            {
                this.eventCollectionVersion = this.Events.Where(e => e.StreamType == this.streamType).Max(e => e.EventCollectionVersion);
            }
        }
Exemplo n.º 3
0
        public OptimizedEventStore(string streamType, ITextSerializer serializer, string connectionString, IUtcTimeProvider time, IGuidProvider guid, ILogger log)
        {
            Ensure.NotNullNeitherEmtpyNorWhiteSpace(streamType, nameof(streamType));
            Ensure.NotNull(serializer, nameof(serializer));
            Ensure.NotNullNeitherEmtpyNorWhiteSpace(connectionString, nameof(connectionString));
            Ensure.NotNull(time, nameof(time));
            Ensure.NotNull(guid, nameof(guid));
            Ensure.NotNull(log, nameof(log));

            this.streamType       = streamType;
            this.serializer       = serializer;
            this.connectionString = connectionString;
            this.time             = time;
            this.guid             = guid;
            this.log   = log;
            this.cache = new MemoryCache(streamType);

            this.sql = new SqlClientLite(this.connectionString, timeoutInSeconds: 120);

            /// TODO: could be replaced with a compiled lambda to make it more performant.
            var fromMementoConstructor = typeof(T).GetConstructor(new[] { typeof(Guid), typeof(ISnapshot) });

            Ensure.CastIsValid(fromMementoConstructor, "Type T must have a constructor with the following signature: .ctor(Guid, IMemento)");
            this.originatorAggregateFactory = (id, memento) => (T)fromMementoConstructor.Invoke(new object[] { id, memento });

            var fromStreamConstructor = typeof(T).GetConstructor(new[] { typeof(Guid), typeof(IEnumerable <IEvent>) });

            Ensure.CastIsValid(fromStreamConstructor, "Type T must have a constructor with the following signature: .ctor(Guid, IEnumerable<IEvent>)");
            this.aggregateFactory = (id, streamOfEvents) => (T)fromStreamConstructor.Invoke(new object[] { id, streamOfEvents });

            this.eventCollectionVersion = this.GetLatestEventCollectionVersionFromDb();
        }
        public AdoDotNetEventStore(string streamType, ITextSerializer serializer, string connectionString, IUtcTimeProvider time, IGuidProvider guid, ILogger log, bool persistIncomingPayloads, bool persistSnapshots, Func <string, ITextSerializer, string, bool> consumerFilter)
            : base(streamType)
        {
            Ensure.NotNull(serializer, nameof(serializer));
            Ensure.NotNullNeitherEmtpyNorWhiteSpace(connectionString, nameof(connectionString));
            Ensure.NotNull(time, nameof(time));
            Ensure.NotNull(guid, nameof(guid));
            Ensure.NotNull(log, nameof(log));

            this.serializer       = serializer;
            this.connectionString = connectionString;
            this.time             = time;
            this.guid             = guid;
            this.log            = log;
            this.consumerFilter = consumerFilter != null ? consumerFilter : EventStoreFuncs.DefaultFilter;
            this.cache          = new MemoryCache(streamType);

            this.sql = new SqlClientLite(this.connectionString, timeoutInSeconds: 120);

            /// TODO: could be replaced with a compiled lambda to make it more performant.
            var fromMementoConstructor = typeof(T).GetConstructor(new[] { typeof(Guid), typeof(ISnapshot) });

            Ensure.CastIsValid(fromMementoConstructor, "Type T must have a constructor with the following signature: .ctor(Guid, IMemento)");
            this.originatorAggregateFactory = (id, memento) => (T)fromMementoConstructor.Invoke(new object[] { id, memento });

            var fromStreamConstructor = typeof(T).GetConstructor(new[] { typeof(Guid), typeof(IEnumerable <IEvent>) });

            Ensure.CastIsValid(fromStreamConstructor, "Type T must have a constructor with the following signature: .ctor(Guid, IEnumerable<IEvent>)");
            this.aggregateFactory = (id, streamOfEvents) => (T)fromStreamConstructor.Invoke(new object[] { id, streamOfEvents });

            this.eventCollectionVersion        = this.GetLatestEventCollectionVersionFromDb();
            this.CurrentEventCollectionVersion = this.eventCollectionVersion;

            if (persistIncomingPayloads)
            {
                this.addToInboxFactory = this.AddToInboxWithPayload;
            }
            else
            {
                this.addToInboxFactory = this.AddToInboxWithoutPayload;
            }

            // adding app subscription if missing
            var appSubCount = this.sql.ExecuteReaderFirstOrDefault(this.tryFindAppSubscription, r => r.GetInt32(0),
                                                                   new SqlParameter("@SubscriberStreamType", this.streamType),
                                                                   new SqlParameter("@StreamType", this.streamType + Constants.AppEventStreamNameSufix));

            if (appSubCount == 0)
            {
                var now = DateTime.Now;
                this.sql.ExecuteNonQuery(this.createAppSubscription,
                                         new SqlParameter("@SubscriberStreamType", this.streamType),
                                         new SqlParameter("@StreamType", this.streamType + Constants.AppEventStreamNameSufix),
                                         new SqlParameter("@CreationLocalTime", now),
                                         new SqlParameter("@UpdateLocalTime", now));
            }

            this.persistSnapshots = persistSnapshots;
        }
Exemplo n.º 5
0
        public SubscriptionRepository(Func <bool, IEventStoreDbContext> contextFactory, string streamType, ITextSerializer serializer, IUtcTimeProvider time)
        {
            Ensure.NotNull(contextFactory, "contextFactory");
            Ensure.NotNull(serializer, "serializer");
            Ensure.NotNull(time, "time");
            Ensure.NotNullNeitherEmtpyNorWhiteSpace(streamType, nameof(streamType));

            this.contextFactory = contextFactory;
            this.serializer     = serializer;
            this.time           = time;
            this.streamType     = streamType;
        }
Exemplo n.º 6
0
 public EventScheduleController(
     ICommandSender commandSender,
     ISessionProvider sessionProvider,
     IUtcTimeProvider utcTimeProvider,
     ILocalTimeProvider localTimeProvider,
     IQuerySender querySender)
 {
     _commandSender     = commandSender;
     _querySender       = querySender;
     _sessionProvider   = sessionProvider;
     _utcTimeProvider   = utcTimeProvider;
     _localTimeProvider = localTimeProvider;
 }
Exemplo n.º 7
0
        public AuthenticationController(
            IUserService userService,
            IUtcTimeProvider utcTimeProvider)
        {
            if (userService == null)
            {
                throw new ArgumentNullException(nameof(userService));
            }
            if (utcTimeProvider == null)
            {
                throw new ArgumentNullException(nameof(utcTimeProvider));
            }

            _userService     = userService;
            _utcTimeProvider = utcTimeProvider;
        }
Exemplo n.º 8
0
        public UserService(
            IConfirmationKeyGenerator confirmationKeyGenerator,
            IUtcTimeProvider utcTimeProvider,
            IUserRepository userRepository,
            IUserSessionRepository userSessionRepository,
            IConfirmationRepository confirmationRepository,
            IConfirmationProducer confirmationProducer,
            IConfigurationRoot configuration)
        {
            if (confirmationKeyGenerator == null)
            {
                throw new ArgumentNullException(nameof(confirmationKeyGenerator));
            }
            if (utcTimeProvider == null)
            {
                throw new ArgumentNullException(nameof(utcTimeProvider));
            }
            if (userRepository == null)
            {
                throw new ArgumentNullException(nameof(userRepository));
            }
            if (userSessionRepository == null)
            {
                throw new ArgumentNullException(nameof(userSessionRepository));
            }
            if (confirmationRepository == null)
            {
                throw new ArgumentNullException(nameof(confirmationRepository));
            }
            if (confirmationProducer == null)
            {
                throw new ArgumentNullException(nameof(confirmationProducer));
            }
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            _confirmationKeyGenerator = confirmationKeyGenerator;
            _utcTimeProvider          = utcTimeProvider;
            _userRepository           = userRepository;
            _userSessionRepository    = userSessionRepository;
            _confirmationRepository   = confirmationRepository;
            _confirmationProducer     = confirmationProducer;

            _confirmationUrl = GetConfirmationUrl(configuration);
        }
Exemplo n.º 9
0
        public EventStore(string streamType, ITextSerializer serializer, Func <bool, IEventStoreDbContext> contextFactory, IUtcTimeProvider time, IGuidProvider guid, ILogger log)
        {
            Ensure.NotNullNeitherEmtpyNorWhiteSpace(streamType, nameof(streamType));
            Ensure.NotNull(serializer, nameof(serializer));
            Ensure.NotNull(contextFactory, nameof(contextFactory));
            Ensure.NotNull(time, nameof(time));
            Ensure.NotNull(guid, nameof(guid));
            Ensure.NotNull(log, nameof(log));

            this.streamType     = streamType;
            this.serializer     = serializer;
            this.contextFactory = contextFactory;
            this.time           = time;
            this.guid           = guid;
            this.log            = log;
            this.cache          = new MemoryCache(streamType);

            /// TODO: could be replaced with a compiled lambda to make it more performant.
            var fromMementoConstructor = typeof(T).GetConstructor(new[] { typeof(Guid), typeof(ISnapshot) });

            Ensure.CastIsValid(fromMementoConstructor, "Type T must have a constructor with the following signature: .ctor(Guid, IMemento)");
            this.originatorAggregateFactory = (id, memento) => (T)fromMementoConstructor.Invoke(new object[] { id, memento });

            var fromStreamConstructor = typeof(T).GetConstructor(new[] { typeof(Guid), typeof(IEnumerable <IEvent>) });

            Ensure.CastIsValid(fromStreamConstructor, "Type T must have a constructor with the following signature: .ctor(Guid, IEnumerable<IEvent>)");
            this.aggregateFactory = (id, streamOfEvents) => (T)fromStreamConstructor.Invoke(new object[] { id, streamOfEvents });

            if (typeof(IDenormalizer).IsAssignableFrom(typeof(T)))
            {
                this.denormalizeIfApplicable = (aggregate, context) => ((IDenormalizer)aggregate).UpdateReadModel(context);
            }
            else
            {
                this.denormalizeIfApplicable = (aggregate, context) => { }
            };

            using (var context = this.contextFactory.Invoke(true))
            {
                if (context.Events.Any(e => e.StreamType == this.streamType))
                {
                    this.eventCollectionVersion = context.Events.Where(e => e.StreamType == this.streamType).Max(e => e.EventCollectionVersion);
                }
            }
        }
Exemplo n.º 10
0
        public InMemoryEventStore(string streamType, IUtcTimeProvider time, ITextSerializer serializer, IGuidProvider guid, ILogger log, bool persistIncomingPayloads, Func <string, ITextSerializer, string, bool> consumerFilter)
            : base(streamType)
        {
            Ensure.NotNull(time, nameof(time));
            Ensure.NotNull(serializer, nameof(serializer));
            Ensure.NotNull(guid, nameof(guid));
            Ensure.NotNull(log, nameof(log));

            this.time           = time;
            this.serializer     = serializer;
            this.guid           = guid;
            this.log            = log;
            this.cache          = new MemoryCache(streamType);
            this.consumerFilter = consumerFilter != null ? consumerFilter : EventStoreFuncs.DefaultFilter;

            /// TODO: could be replaced with a compiled lambda to make it more performant.
            var fromMementoConstructor = typeof(T).GetConstructor(new[] { typeof(Guid), typeof(ISnapshot) });

            Ensure.CastIsValid(fromMementoConstructor, "Type T must have a constructor with the following signature: .ctor(Guid, IMemento)");
            this.originatorAggregateFactory = (id, memento) => (T)fromMementoConstructor.Invoke(new object[] { id, memento });

            var fromStreamConstructor = typeof(T).GetConstructor(new[] { typeof(Guid), typeof(IEnumerable <IEvent>) });

            Ensure.CastIsValid(fromStreamConstructor, "Type T must have a constructor with the following signature: .ctor(Guid, IEnumerable<IEvent>)");
            this.aggregateFactory = (id, streamOfEvents) => (T)fromStreamConstructor.Invoke(new object[] { id, streamOfEvents });

            if (persistIncomingPayloads)
            {
                this.inboxEntityFactory = incomingEvent => new InboxEntity
                {
                    InboxStreamType = this.streamType,
                    EventId         = incomingEvent.EventId,
                    Payload         = this.serializer.Serialize(incomingEvent),
                    TransactionId   = incomingEvent.TransactionId
                }
            }
            ;
            else
            {
                this.inboxEntityFactory = incomingEvent => new InboxEntity {
                    InboxStreamType = this.streamType, EventId = incomingEvent.EventId, TransactionId = incomingEvent.TransactionId
                }
            };

            if (!this.events.IsEmpty)
            {
                this.eventCollectionVersion = this.events.Max(e => e.Key);
            }
            this.CurrentEventCollectionVersion = this.eventCollectionVersion;

            // Add subscription of app, if not exists
            if (!this.subscriptions.Any(s => s.SubscriberStreamType == this.streamType && s.StreamType == this.streamType + Constants.AppEventStreamNameSufix))
            {
                // We should add the new subscription
                this.subscriptions.Add(new SubscriptionEntity
                {
                    SubscriberStreamType = this.streamType,
                    StreamType           = this.streamType + Constants.AppEventStreamNameSufix,
                    Url   = "none",
                    Token = "#token",
                    ProcessorBufferVersion = 0,
                    IsPoisoned             = false,
                    WasCanceled            = true,
                    CreationLocalTime      = DateTime.Now,
                    UpdateLocalTime        = DateTime.Now
                });
            }
        }
Exemplo n.º 11
0
        public OrmEventStore(string streamType, ITextSerializer serializer, Func <bool, IEventStoreDbContext> contextFactory, IUtcTimeProvider time, IGuidProvider guid, ILogger log, bool persistIncomingPayloads, Func <string, ITextSerializer, string, bool> consumerFilter)
            : base(streamType)
        {
            Ensure.NotNull(serializer, nameof(serializer));
            Ensure.NotNull(contextFactory, nameof(contextFactory));
            Ensure.NotNull(time, nameof(time));
            Ensure.NotNull(guid, nameof(guid));
            Ensure.NotNull(log, nameof(log));

            this.serializer     = serializer;
            this.contextFactory = contextFactory;
            this.time           = time;
            this.guid           = guid;
            this.log            = log;
            this.cache          = new MemoryCache(streamType);
            this.consumerFilter = consumerFilter != null ? consumerFilter : EventStoreFuncs.DefaultFilter;

            /// TODO: could be replaced with a compiled lambda to make it more performant.
            var fromMementoConstructor = typeof(T).GetConstructor(new[] { typeof(Guid), typeof(ISnapshot) });

            Ensure.CastIsValid(fromMementoConstructor, "Type T must have a constructor with the following signature: .ctor(Guid, IMemento)");
            this.originatorAggregateFactory = (id, memento) => (T)fromMementoConstructor.Invoke(new object[] { id, memento });

            var fromStreamConstructor = typeof(T).GetConstructor(new[] { typeof(Guid), typeof(IEnumerable <IEvent>) });

            Ensure.CastIsValid(fromStreamConstructor, "Type T must have a constructor with the following signature: .ctor(Guid, IEnumerable<IEvent>)");
            this.aggregateFactory = (id, streamOfEvents) => (T)fromStreamConstructor.Invoke(new object[] { id, streamOfEvents });

            if (typeof(IDenormalizer).IsAssignableFrom(typeof(T)))
            {
                this.denormalizeIfApplicable = (aggregate, context) => ((IDenormalizer)aggregate).UpdateReadModel(context);
            }
            else
            {
                this.denormalizeIfApplicable = (aggregate, context) => { }
            };

            using (var context = this.contextFactory.Invoke(false))
            {
                // getting event collection version
                if (context.Events.Any(e => e.StreamType == this.streamType))
                {
                    this.eventCollectionVersion = context.Events.Where(e => e.StreamType == this.streamType).Max(e => e.EventCollectionVersion);
                }

                // adding subscription if missing
                if (!context.Subscriptions.Any(s => s.SubscriberStreamType == this.streamType && s.StreamType == this.streamType + Constants.AppEventStreamNameSufix))
                {
                    // We should add the new subscription
                    context.Subscriptions.Add(new SubscriptionEntity
                    {
                        SubscriberStreamType = this.streamType,
                        StreamType           = this.streamType + Constants.AppEventStreamNameSufix,
                        Url   = "none",
                        Token = "#token",
                        ProcessorBufferVersion = 0,
                        IsPoisoned             = false,
                        WasCanceled            = true,
                        CreationLocalTime      = DateTime.Now,
                        UpdateLocalTime        = DateTime.Now
                    });

                    context.SaveChanges();
                }
            }
            this.CurrentEventCollectionVersion = this.eventCollectionVersion;

            if (persistIncomingPayloads)
            {
                this.inboxEntityFactory = (IEvent incomingEvent, DateTime localNow) => new InboxEntity
                {
                    InboxStreamType        = this.streamType,
                    EventId                = incomingEvent.EventId,
                    TransactionId          = incomingEvent.TransactionId,
                    StreamType             = incomingEvent.StreamType,
                    StreamId               = incomingEvent.StreamId,
                    Version                = incomingEvent.Version,
                    EventType              = incomingEvent.GetType().Name,
                    EventCollectionVersion = incomingEvent.EventCollectionVersion,
                    CreationLocalTime      = localNow,
                    Payload                = this.serializer.Serialize(incomingEvent)
                }
            }
            ;
            else
            {
                this.inboxEntityFactory = (IEvent incomingEvent, DateTime localNow) => new InboxEntity
                {
                    InboxStreamType   = this.streamType,
                    EventId           = incomingEvent.EventId,
                    TransactionId     = incomingEvent.TransactionId,
                    CreationLocalTime = localNow
                }
            };
        }