Exemple #1
0
        public async Task HandleAsync(UpdateSiteDetails message, IRequestInfo requestInfo)
        {
            var site = await _siteRepository.GetAsync(message.SiteId);

            if (site is null)
            {
                _logger.LogInformation($"Site with id: {message.SiteId} could not be found");
                _publisher.PublishEvent(
                    new SiteUpdateRejected(Codes.InvalidId, "The site cannot be retrieved to update."), requestInfo);
                return;
            }

            try
            {
                site.Update(message.Name, message.PostCode, message.AddressLine1, message.AddressLine2);
            }
            catch (VmsException e)
            {
                _logger.LogInformation($"Update failed with code: {e.Code} for reason: {e.Message}");
                _publisher.PublishEvent(new SiteUpdateRejected(e.Code, e.Message), requestInfo);
                return;
            }

            await _siteRepository.Update(site);

            _publisher.PublishEvent(new SiteUpdated(), requestInfo);
        }
        public async Task <IAuthToken> SignIn(string email, string password, string role)
        {
            var identity = await _identityRepository.GetByEmailAndRole(email, role);

            if (identity is null)
            {
                _logger.LogWarning($"No user found with email: {email} role: {role}");
                throw new VmsException(Codes.InvalidCredentials, "The credentials provided where incorrect.");
            }


            if (!_passwordManager.IsPasswordCorrect(password, identity.Hash, identity.Salt))
            {
                _logger.LogWarning($"Incorrect password for: {email}");
                throw new VmsException(Codes.InvalidCredentials, "The credentials provided where incorrect.");
            }


            var jwt          = _jwtManager.CreateToken(identity.Id, identity.Email, identity.Role);
            var refreshToken = await _tokenService.CreateRefreshToken(identity.Email);

            _logger.LogInformation($"User issued token email: {email}");

            return(AuthToken.Create(jwt, refreshToken));
        }
Exemple #3
0
        public async Task HandleAsync(CreateBusiness message, IRequestInfo requestInfo)
        {
            IBusinessDocument businessDocument;

            try
            {
                var code = await CheckCode(_numberGenerator.GenerateNumber(6));

                businessDocument = _businessesFactory.CreateBusiness(message.Name, message.TradingName, message.WebAddress,
                                                                     message.HeadContactFirstName, message.HeadContactSecondName,
                                                                     message.HeadContactContactNumber, message.HeadContactEmail, message.HeadOfficePostCode, message.HeadOfficeAddressLine1, message.HeadOfficeAddressLine2, code);


                await _repository.Add(businessDocument);
            }
            catch (VmsException e)
            {
                _logger.LogInformation("Create business rejected: " + e.Code);
                _publisher.PublishEvent(new CreateBusinessRejected(e.Code, e.Message), requestInfo);
                return;
            }

            _logger.LogInformation("Create business succeeded.");
            _publisher.PublishEvent(new BusinessCreated(businessDocument.Id, businessDocument.Code), requestInfo);
        }
Exemple #4
0
        public async Task Handle <T>(object sender, BasicDeliverEventArgs args, Func <T, IRequestInfo, Task> callback) where T : IServiceBusMessage
        {
            _logger.LogInformation($"Message received with key: {args.RoutingKey}", "RabbitMq");
            string json        = _utf8Wrapper.GetString(args.Body);
            var    split       = json.Split('\t');
            var    requestInfo = _jsonConvertWrapper.Deserialize <RequestInfo>(split[0]);

            var command = _jsonConvertWrapper.Deserialize <T>(split[1]);
            await callback.Invoke(command, requestInfo);
        }
Exemple #5
0
        public async Task <IAuthToken> SignIn(string email, string password)
        {
            var identity = await _identityRepository.GetByEmail(email);

            if (identity is null || identity.Role == Roles.SystemAdmin)
            {
                _logger.LogWarning($"No user found with email: {email}.");
                throw new VmsException(Codes.InvalidCredentials, "The credentials provided where incorrect.");
            }

            if (!_passwordManager.IsPasswordCorrect(password, identity.Hash, identity.Salt))
            {
                _logger.LogWarning($"Incorrect password for: {email}");
                throw new VmsException(Codes.InvalidCredentials, "The credentials provided where incorrect.");
            }

            if (identity.BusinessId == Guid.Empty)
            {
                throw new VmsException("No business ID found on sign in.", "");
            }

            var jwt          = _jwtManager.CreateToken(identity.Id, identity.Email, identity.Role, identity.BusinessId);
            var refreshToken = await _tokenService.CreateRefreshToken(identity.Email);

            _logger.LogInformation($"User issued token email: {email}");

            return(AuthToken.Create(jwt, refreshToken));
        }
Exemple #6
0
        public async Task HandleAsync(CreateAccessRecord message, IRequestInfo requestInfo)
        {
            IUserDocument userDocument = await _userRepository.GetByCodeAsync(message.Code);

            if (userDocument is null)
            {
                _publisher.PublishEvent(new AccessRecordRejected(Codes.InvalidId, "The code used is invalid."), requestInfo);
                _logger.LogError($"User with code: {message.Code} could not be found.");
                return;
            }


            if (!await _servicesRepository.IsSiteIdValid(message.SiteId))
            {
                _publisher.PublishEvent(new AccessRecordRejected(Codes.InvalidId, "The site could not be found."), requestInfo);
                _logger.LogError($"Site with id: {message.SiteId} could not be found.");
                return;
            }

            await _userStatusService.Update(userDocument.Id, message.Action, message.SiteId);

            var record = _factory.Create(userDocument.Id, message.SiteId, message.Action, userDocument.BusinessId);
            await _accessRecordRepository.AddAsync(record);

            _publisher.PublishEvent(new AccessRecordCreated(), requestInfo);

            string action = message.Action == AccessAction.In ? "in" : "out";

            _logger.LogInformation($"{userDocument.FirstName + " " + userDocument.SecondName} signed {action} on : {record.TimeStamp}.", LoggingCategories.Access);
        }
Exemple #7
0
        public async Task <IAuthToken> SignIn(string email, string password, int businessCode)
        {
            var identity = await _identityRepository.GetByEmail(email);

            if (identity is null || identity.Role == Roles.SystemAdmin)
            {
                _logger.LogWarning($"No user found with email: {email} attempting to log into greeting system.");
                throw new VmsException(Codes.InvalidCredentials, "The credentials provided where incorrect.");
            }

            if (!await _businessRepository.IsCodeValidAsync(businessCode))
            {
                _logger.LogInformation($"No business found with code {businessCode}.");
                throw new VmsException(Codes.InvalidCredentials, "The credentials provided where incorrect.");
            }

            if (!_passwordManager.IsPasswordCorrect(password, identity.Hash, identity.Salt))
            {
                _logger.LogWarning($"Incorrect password for: {email}");
                throw new VmsException(Codes.InvalidCredentials, "The credentials provided where incorrect.");
            }

            var jwt = _jwtManager.CreateToken(Guid.NewGuid(), identity.Email, Roles.Greeting, identity.BusinessId);

            //var refresh = await _tokenService.CreateRefreshToken(id)
            //TODO: Add a mechanism to store more that just email here unique id needs to be stored instead.

            return(AuthToken.Create(jwt, ""));
        }
        public async Task <BusinessDto> HandleAsync(GetBusiness query)
        {
            var domain = await _repository.GetBusinessAsync(query.Id);

            if (domain is null)
            {
                _logger.LogInformation("No business found for the id: " + query.Id);
                return(null);
            }

            return(new BusinessDto()
            {
                Id = domain.Id,
                Name = domain.Name,
                TradingName = domain.TradingName,
                WebAddress = domain.WebAddress?.ToString(),
                Code = domain.Code.ToString(),
                Contact = new HeadContactDto()
                {
                    ContactNumber = domain.GetContact()?.ContactNumber, Email = domain.GetContact()?.Email,
                    FirstName = domain.GetContact()?.FirstName, SecondName = domain.GetContact()?.SecondName
                },
                Office = new HeadOfficeDto()
                {
                    AddressLine1 = domain.GetOffice()?.AddressLine1, AddressLine2 = domain.GetOffice()?.AddressLine2,
                    PostCode = domain.GetOffice()?.PostCode
                }
            });
        }
Exemple #9
0
        public async Task HandleAsync(SiteCreated message, IRequestInfo requestInfo)
        {
            var site = _factory.CreateSite(message.Id, message.Name);
            await _siteRepository.AddSiteAsync(site);

            _logger.LogInformation($"Site created in users service with id: {site.Id}");
        }
        public async Task HandleAsync(UpdateHeadContact message, IRequestInfo requestInfo)
        {
            var business = await _repository.GetBusinessAsync(message.BusinessId);

            if (business is null)
            {
                _publisher.PublishEvent(new UpdateBusinessRejected(Codes.InvalidId, "A business with the id: " + message.BusinessId + "could not be found"), requestInfo);
                return;
            }

            try
            {
                business.GetContact().Update(message.FirstName, message.SecondName, message.ContactNumber, message.Email);
            }
            catch (VmsException e)
            {
                _publisher.PublishEvent(new UpdateBusinessRejected(e.Code, e.Message), requestInfo);
                return;
            }

            await _repository.UpdateAsync(business);

            _publisher.PublishEvent(new BusinessContactUpdated(), requestInfo);
            _logger.LogInformation("The business contact was updated successfully.");
        }
Exemple #11
0
        public async Task HandleAsync(BusinessCreated message, IRequestInfo requestInfo)
        {
            var business = new Business().Create(message.Id);
            await _repository.AddAsync(business);

            _logger.LogInformation("Business added to Site Service with id:" + business.Id);
        }
Exemple #12
0
        public async Task <bool> ContainsUserAsync(Guid userId)
        {
            var site = await _client.GetAsync($"{_baseAddress}/rest/{userId}");

            _vmsLogger.LogInformation($"Checked user service for id: {userId} got response {site.StatusCode}");
            return(site.StatusCode == HttpStatusCode.OK);
        }
        public async Task HandleAsync(UpdateHeadOffice message, IRequestInfo requestInfo)
        {
            var business = await _repository.GetBusinessAsync(message.BusinessId);

            if (business is null)
            {
                _publisher.PublishEvent(new UpdateBusinessRejected(Codes.InvalidId, "A business with the id: " + message.BusinessId + "could not be found"), requestInfo);
                return;
            }

            try
            {
                business.GetOffice().Update(message.PostCode, message.AddressLine1, message.AddressLine2);
            }
            catch (VmsException e)
            {
                _publisher.PublishEvent(new UpdateBusinessRejected(e.Code, e.Message), requestInfo);
                return;
            }

            await _repository.UpdateAsync(business);

            _publisher.PublishEvent(new BusinessOfficeUpdated(), requestInfo);
            _logger.LogInformation("The business head office was updated successfully.");
        }
Exemple #14
0
        public async Task HandleAsync(DeprecateDataEntry message, IRequestInfo requestInfo)
        {
            var entries = await _repository.GetEntriesAsync(message.BusinessId);

            var dataSpecifications = entries.ToList();

            if (!dataSpecifications.Any())
            {
                _logger.LogWarning($"No entries found with business ID: {message.BusinessId}");
                _publisher.PublishEvent(new DataEntryDeprecationRejected(Codes.InvalidBusinessId, $"Entries with the id {message.BusinessId} could not be found."), requestInfo);
                return;
            }

            var spec = dataSpecifications.FirstOrDefault(d => d.Id == message.Id);

            if (spec is null)
            {
                _logger.LogWarning($"No entry found with ID: {message.Id}");
                _publisher.PublishEvent(new DataEntryDeprecationRejected(Codes.InvalidId, $"Entry with the id {message.Id} could not be found."), requestInfo);
                return;
            }

            if (spec.IsMandatory)
            {
                _logger.LogInformation($"{spec.Label} is  set as mandatory and cannot be deprecated.");
                _publisher.PublishEvent(new DataEntryDeprecationRejected(Codes.InvalidId, $"{spec.Label} is  set as mandatory and cannot be deprecated."), requestInfo);
                return;
            }

            _specificationAggregate.Deprecate(spec);
            await _repository.UpdateAsync(spec);

            dataSpecifications.Remove(spec);
            dataSpecifications = dataSpecifications.Where(s => s.IsMandatory == false).ToList();

            var ordered = dataSpecifications.OrderBy(d => d.Order).ToList();

            for (int i = 0; i < ordered.Count; i++)
            {
                _specificationAggregate.UpdateOrder(ordered[i], i + 1);
                await _repository.UpdateAsync(ordered[i]);
            }

            _publisher.PublishEvent(new DataEntryDeprecated(), requestInfo);
            _logger.LogInformation($"Entry deprecated with id: {message.Id} and other entries re-ordered.");
        }
Exemple #15
0
        private async Task Success(Guid id)
        {
            await Groups.AddToGroupAsync(Context.ConnectionId, $"users:{id.ToString()}");

            await Clients.Client(Context.ConnectionId).SendAsync("connectionSucceeded");

            _logger.LogInformation("User connected successfully with Id: " + id);
        }
Exemple #16
0
        public async Task HandleAsync(BusinessCreated message, IRequestInfo requestInfo)
        {
            var spec = _specificationAggregate.Create("Full Name", 1, "Please enter your name.", "Required", message.Id,
                                                      true);
            await _repository.AddAsync(spec);

            _logger.LogInformation($"Mandatory name field added for business with id: {message.Id}");
        }
Exemple #17
0
        public async Task Update(Guid userId, AccessAction action, Guid siteId)
        {
            var status = await repository.GetStatusForUserAsync(userId);

            if (status is null)
            {
                logger.LogInformation("No status found creating one now for user: "******"Updated users status {userId} to: {action}");

            status.Update(action, siteId);
            await repository.UpdateAsync(status);
        }
Exemple #18
0
        public async Task HandleAsync(object message, IRequestInfo requestInfo)
        {
            //var serviceBusMessage = message as IServiceBusMessage;
            //if (serviceBusMessage.BelongsToSaga())
            //{
            //    var context = SagaContext.Create(new SagaId(), "", new List<ISagaContextMetadata>
            //    {
            //        new SagaData(SagaData.OperationIdKey, requestInfo.OperationId.ToString()),
            //        new SagaData(SagaData.UserIdKey, requestInfo.UserId)
            //    });
            //    await _sagaCoordinator.ProcessAsync(serviceBusMessage, context);
            //    return;
            //}


            switch (message)
            {
            case IRejectedEvent rejected:
                requestInfo.Fail();
                _logger.LogInformation($"Operation [{requestInfo.OperationId}]: Rejected Event code: [{rejected.Code}] Reason: {rejected.Reason}");
                await _operationsCache.SaveAsync(requestInfo.OperationId, requestInfo.State.ToString().ToLower(), rejected.Code, rejected.Reason);

                _publisher.PublishEvent(new OperationFailed(rejected.Code, rejected.Reason), requestInfo);
                break;

            case ICommand _:
                _logger.LogInformation($"Operation [{requestInfo.OperationId}]: PENDING");
                await _operationsCache.SaveAsync(requestInfo.OperationId, RequestState.Pending.ToString());

                break;

            case IEvent _:
                requestInfo.Complete();
                _logger.LogInformation($"Operation: [{requestInfo.OperationId}] COMPLETE");
                await _operationsCache.SaveAsync(requestInfo.OperationId, requestInfo.State.ToString().ToLower());

                _publisher.PublishEvent(new OperationComplete(), requestInfo);
                break;

            default:
                break;
            }
        }
Exemple #19
0
        void Publish <T>(T message, IRequestInfo requestInfo, string exchange, string routingKey) where T : IServiceBusMessage
        {
            var messageJson = _jsonConvertWrapper.Serialize(message);
            var requestJson = _jsonConvertWrapper.Serialize(requestInfo);
            var json        = requestJson + "\t" + messageJson;
            var body        = _utf8Wrapper.GetBytes(json);
            var connection  = _serviceBusConnectionFactory.ResolveServiceBusConnection();

            connection.Channel.BasicPublish(exchange, routingKey, true, new BasicProperties(), body);
            _logger.LogInformation($"Published message with key: {routingKey}", "RabbitMq");
        }
Exemple #20
0
        public async Task HandleAsync(object message, IRequestInfo requestInfo)
        {
            switch (message)
            {
            case OperationComplete complete:
                _logger.LogInformation($"Operation [{requestInfo.OperationId}] completed and sent to user: {requestInfo.UserId}");
                await _pushService.OperationComplete(requestInfo.OperationId, requestInfo.UserId);

                break;

            case OperationFailed failed:
                _logger.LogInformation($"Operation [{requestInfo.OperationId}] failed with code {failed.Code} and sent to user: {requestInfo.UserId}");
                await _pushService.OperationFailed(requestInfo.OperationId, requestInfo.UserId, failed.Code, failed.Reason);

                break;

            case OperationPending pending:
                break;

            default:
                break;
            }
        }
Exemple #21
0
        public async Task HandleAsync(VisitorSignOut message, IRequestInfo requestInfo)
        {
            var visitor = await _visitorsRepository.GetAsync(message.VisitorId);

            if (visitor is null)
            {
                _logger.LogWarning($"No visitor found with ID : ${message.VisitorId}");
                _publisher.PublishEvent(new VisitorSignOutRejected(Codes.InvalidId, "You could not be signed out."), requestInfo);
            }

            _visitorAggregate.SignOut(visitor);
            await _visitorsRepository.UpdateAsync(visitor);

            _logger.LogInformation($"Visitor with id: {message.VisitorId} signed out successfully");
            _publisher.PublishEvent(new VisitorSignedOut(), requestInfo);
        }
Exemple #22
0
        public async Task HandleAsync(CreateUser message, IRequestInfo requestInfo)
        {
            var account = await _accountRepository.GetAsync(message.AccountId);

            if (account is null)
            {
                _logger.LogWarning($"Account not found when completing user profile account id: {message.AccountId}.");
                _publisher.PublishEvent(new CreateUserRejected(Codes.InvalidId, $"The account with the id: {message.AccountId} cannot be found"), requestInfo);
                return;
            }

            if (!await _servicesRepository.IsBusinessIdValid(message.BusinessId))
            {
                _logger.LogWarning($"The business id: {message.BusinessId} could not be fetched from the business service.");
                _publisher.PublishEvent(new CreateUserRejected(Codes.InvalidId, $"The business id: {message.BusinessId} could not be fetched from the business service."), requestInfo);
                return;
            }

            if (!await _servicesRepository.IsSiteIdValid(message.BasedSiteId))
            {
                _logger.LogWarning($"The site id: {message.BasedSiteId} could not be fetched from the site service.");
                _publisher.PublishEvent(new CreateUserRejected(Codes.InvalidId, $"The site id: {message.BasedSiteId} could not be fetched from the site service."), requestInfo);
                return;
            }


            IUserDocument userDocument = null;

            try
            {
                userDocument = _factory.CreateUser(message.FirstName, message.SecondName, account.Email, message.PhoneNumber,
                                                   message.BusinessPhoneNumber, message.BasedSiteId, message.BusinessId, message.AccountId, account.Code);
            }
            catch (VmsException e)
            {
                _publisher.PublishEvent(new CreateUserRejected(e.Code, e.Message), requestInfo);
                return;
            }

            await _userRepository.AddAsync(userDocument);

            var state = _recordFactory.Create(userDocument.Id, userDocument.BasedSiteId, AccessAction.Out);
            await _repository.AddAsync(state);

            _publisher.PublishEvent(new UserCreated(), requestInfo);
            _logger.LogInformation($"User created with id: {userDocument.Id} and name: {userDocument.FirstName + " " + userDocument.SecondName}.");
        }
        public async Task <IEnumerable <BusinessSummaryDto> > HandleAsync(BusinessesSummary query)
        {
            var businesses = await _repository.GetBusinessesAsync();

            var returns = new List <BusinessSummaryDto>();

            foreach (var business in businesses)
            {
                returns.Add(new BusinessSummaryDto()
                {
                    Id = business.Id, Name = business.Name, TradingName = business.TradingName
                });
            }

            _logger.LogInformation($"{returns.Count} summaries returned.");

            return(returns);
        }
Exemple #24
0
        public async Task HandleAsync(CreateVisitor message, IRequestInfo requestInfo)
        {
            if (!await _userServiceClient.ContainsUserAsync(message.VisitingId))
            {
                _logger.LogWarning($"No user with id: {message.VisitingId} could be found");
                PublishFailure(requestInfo);
                return;
            }

            var site = await _siteServiceClient.GetSiteAsync(message.SiteId);

            if (site is null)
            {
                _logger.LogInformation($"No site found with id: {message.SiteId}");
                PublishFailure(requestInfo);
                return;
            }

            try
            {
                await _validatorService.Validate(site.BusinessId, message.Data);
            }
            catch (VmsException e)
            {
                _messagePublisher.PublishEvent(new CreateVisitorRejected(e.Code, e.Message), requestInfo);
                return;
            }

            //TODO: create service to validate data entrys

            var visitorData = new List <VisitorData>();

            foreach (var visitorDataEntry in message.Data)
            {
                visitorData.Add(_visitorAggregate.CreateData(visitorDataEntry.FieldId, visitorDataEntry.Value));
            }

            var visitor = _visitorAggregate.Create(message.VisitingId, site.BusinessId, message.SiteId, visitorData);

            await _visitorsRepository.AddAsync(visitor);

            _messagePublisher.PublishEvent(new VisitorCreated(), requestInfo);
        }
Exemple #25
0
        public async Task HandleAsync(CreateDataEntry message, IRequestInfo requestInfo)
        {
            SpecificationDocument specificationDocument;
            var order = await _repository.GetNextOrderNumberAsync(message.BusinessId);

            try
            {
                specificationDocument =
                    _aggregate.Create(message.Label, order, message.ValidationMessage, message.ValidationCode, message.BusinessId);
            }
            catch (VmsException e)
            {
                _publisher.PublishEvent(new DataSpecificationRejected(e.Code, e.Message), requestInfo);
                _logger.LogWarning(e.Message, LoggingCategories.DomainValidation);
                return;
            }

            await _repository.AddAsync(specificationDocument);

            _publisher.PublishEvent(new DataSpecificationCreated(), requestInfo);
            _logger.LogInformation($"Data specification labeled {message.Label} created with id: {specificationDocument.Id}");
        }
        public async Task HandleAsync(UpdateBusinessDetails message, IRequestInfo requestInfo)
        {
            var business = await _repository.GetBusinessAsync(message.Id);
            if (business is null)
            {
                _publisher.PublishEvent(new UpdateBusinessRejected(Codes.InvalidId, "A business with the id: " + message.Id + "could not be found"), requestInfo);
                return;
            }

            try
            {
                business.Update(message.Name, message.TradingName, message.WebAddress);
            }
            catch (VmsException e)
            {
                _publisher.PublishEvent(new UpdateBusinessRejected(e.Code, e.Message), requestInfo);
                return;
            }

            await _repository.UpdateAsync(business);
            _publisher.PublishEvent(new BusinessDetailsUpdated(), requestInfo);
            _logger.LogInformation("The business was updated successfully.");
        }
Exemple #27
0
        public async Task HandleAsync(UserAccountCreated message, IRequestInfo requestInfo)
        {
            await _accountRepository.AddAsync(_factory.CreateAccount(message.Id, message.Email, message.Code));

            _logger.LogInformation($"Account added to users service with id: {message.Id} and email: {message.Email}");
        }
Exemple #28
0
 public Task HandleAsync(object message, IRequestInfo requestInfo)
 {
     _logger.LogInformation($"Operation [{requestInfo.OperationId}]: PENDING");
     return(_cache.SaveAsync(requestInfo.OperationId, requestInfo.State.ToString().ToLower()));
 }
        public async Task HandleAsync(BusinessCreated message, IRequestInfo requestInfo)
        {
            await _repository.AddAsync(new Business(message.Id, message.Code));

            _logger.LogInformation($"Business with id: {message.Id} stored in identity service");
        }