示例#1
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, ""));
        }
示例#2
0
        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));
        }
示例#3
0
        public async Task <IEnumerable <LatestAccessRecordDto> > HandleAsync(GetLatestSiteAccessRecords query)
        {
            IEnumerable <IUserStatusDocument> states = await _statusRepository.GetForSiteAsync(query.SiteId);

            var records = new List <LatestAccessRecordDto>();


            foreach (var state in states)
            {
                var user = await _userRepository.GetAsync(state.UserId);

                if (user is null)
                {
                    _logger.LogWarning($"User not found to match with current state id is: {state.UserId}");
                }

                records.Add(new LatestAccessRecordDto
                {
                    Action        = state.CurrentState == AccessAction.In ? "in" : "out",
                    Id            = state.Id,
                    TimeStamp     = state.Updated,
                    UserId        = state.UserId,
                    FullName      = user?.FirstName + " " + user?.SecondName,
                    Email         = user?.Email,
                    ContactNumber = user?.PhoneNumber,
                    Initials      = $"{user?.FirstName[0]}{user?.SecondName[0]}",
                    Code          = user?.Code.ToString()
                });
            }

            return(records);
        }
示例#4
0
        public async Task HandleAsync(UpdateEntryOrder message, IRequestInfo requestInfo)
        {
            var entries = await _repository.GetEntriesAsync(message.BusinessId);

            var specifications = entries.OrderBy(s => s.Order).ToList();

            var updating = specifications.FirstOrDefault(d => d.Id == message.EntryId);

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

            var replacing = specifications.FirstOrDefault(s => s.Order == message.Order);
            int oldOrder  = updating.Order;

            _specificationAggregate.UpdateOrder(updating, message.Order);
            _specificationAggregate.UpdateOrder(replacing, oldOrder);

            await _repository.UpdateAsync(updating);

            await _repository.UpdateAsync(replacing);

            _publisher.PublishEvent(new EntryOrderUpdated(), requestInfo);
        }
示例#5
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}.");
        }
示例#6
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.");
        }
示例#7
0
        public async Task CompleteUser(Guid code, string email, string password, string passwordConfirm)
        {
            var pending = await _pendingIdentityRepository.GetAsync(code, email);

            if (pending is null)
            {
                _logger.LogWarning($"Pending user not found with code: {code} and email: {email}");
                throw new VmsException(Codes.InvalidCredentials, "The account registration has not been made.");
            }


            //TODO: make sure this check is done on creation of account pending.
            //var existing = await _identityRepository.GetByEmailAndRole(email, Roles.);
            //if (existing != null)
            //    throw new VmsException(Codes.EmailInUse, "Their has already been an account created with this email.");

            if (password != passwordConfirm)
            {
                throw new VmsException(Codes.InvalidCredentials, "The credentials are invalid.");
            }

            var pword      = _passwordManager.EncryptPassword(password);
            var numberCode = await GetCode(pending.BusinessId);

            var identity = new Domain.Identity(email, pword.Hash, pword.Salt, pending.Role, pending.BusinessId, numberCode);

            await _identityRepository.AddAsync(identity);

            await _pendingIdentityRepository.RemoveAsync(pending);

            _publisher.PublishEvent(new UserAccountCreated(identity.Id, identity.Email, identity.Code), RequestInfo.Empty);
        }
示例#8
0
        public async Task RemoveAsync(string token, string email)
        {
            var refreshToken = await _repository.GetAsync(t => t.Email == email && t.Token == token);

            if (refreshToken is null)
            {
                _logger.LogWarning($"Token did not exist on removal from user: {email} ");
                throw new VmsException(Codes.NoRefreshToken, "The refresh token was not found to be revoked.");
            }

            await _repository.RemoveAsync(refreshToken.Id);
        }
示例#9
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);
        }
示例#10
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);
        }
示例#11
0
        public async Task HandleUsingRoutingKey <T>(object sender, BasicDeliverEventArgs args, Func <T, IRequestInfo, Task> callback)
        {
            _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    splitKey = args.RoutingKey.Split('.').ToList();
            var    ass      = Assembly.GetEntryAssembly();
            string name     = splitKey.Last();
            var    type     = ass.GetTypes().FirstOrDefault(t => t.Name == name);

            if (type == null)
            {
                _logger.LogWarning("Type could not be resolved from routing key: " + args.RoutingKey);
                throw new InvalidOperationException();
            }

            var command = _jsonConvertWrapper.DeserializeMessage(split[1], type);
            await callback.Invoke((T)command, requestInfo);
        }
示例#12
0
        private async Task <IActionResult> CheckHealth <T>(string healthEndpoint, T command) where T : ICommand
        {
            try
            {
                _client.Timeout = TimeSpan.FromSeconds(1);
                var res = await _client.GetAsync(healthEndpoint);

                if (res.StatusCode == HttpStatusCode.OK)
                {
                    return(PublishCommand(command));
                }
            }
            catch (Exception)
            {
                return(StatusCode(StatusCodes.Status503ServiceUnavailable));
            }

            _logger.LogWarning($"Call to check endpoint: {healthEndpoint} did not get 200 response");

            return(StatusCode(StatusCodes.Status503ServiceUnavailable));
        }
示例#13
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}");
        }
示例#14
0
        private async Task Failed(string reason)
        {
            await Clients.Client(Context.ConnectionId).SendAsync("connectionFailed", reason);

            _logger.LogWarning("Connection refused for reason: " + reason);
        }