Exemplo n.º 1
0
 /// <summary>
 /// Adds the registry service for the given service name.
 /// </summary>
 /// <param name="serviceCollection">The service collection.</param>
 /// <param name="serviceName">The service name.</param>
 /// <returns>Returns the service collection to chain further upon.</returns>
 public static IServiceCollection AddRegistryService(this IServiceCollection serviceCollection, string serviceName)
 {
     serviceCollection.AddHttpClient <IRegistryService, RegistryService>((provider, client) =>
     {
         IAccessTokenService accessTokenService = provider.GetService <IAccessTokenService>();
         RegistryServiceConfiguration registryServiceConfiguration = provider.GetService <IOptions <RegistryServiceConfiguration> >().Value;
         List <Claim> claims = new List <Claim>
         {
             new Claim(ClaimTypes.Name, serviceName),
             new Claim(ClaimTypes.Role, "Service")
         };
         client.DefaultRequestHeaders.Add("Authorization", $"Bearer {accessTokenService.GenerateAccessToken(claims)}");
         client.BaseAddress = new Uri($"http://{registryServiceConfiguration.Host}:{registryServiceConfiguration.Port}");
     });
     return(serviceCollection);
 }
Exemplo n.º 2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="HttpNetworkConnector"/> class.,
        /// </summary>
        /// <param name="messageSerializer">The message serializer.</param>
        /// <param name="messageProcessor">The message processor.</param>
        /// <param name="baseUrl">The base url for the network connector to send requests to.</param>
        /// <param name="accessTokenService">The access token service.</param>
        /// <param name="logger">The logger.</param>
        public HttpNetworkConnector(
            IMessageSerializer messageSerializer,
            IMessageProcessor messageProcessor,
            Uri baseUrl,
            IAccessTokenService accessTokenService,
            ILogger <HttpNetworkConnector> logger)
        {
            _messageSerializer = messageSerializer ?? throw new ArgumentNullException(nameof(messageSerializer));
            _messageProcessor  = messageProcessor ?? throw new ArgumentNullException(nameof(messageProcessor));
            _logger            = logger;
            _httpClient        = new HttpClient {
                BaseAddress = baseUrl
            };
            List <Claim> claims = new List <Claim>
            {
                new Claim(ClaimTypes.Name, "MessageQueue"),
                new Claim(ClaimTypes.Role, "MessageQueue")
            };

            _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {accessTokenService.GenerateAccessToken(claims)}");
            EndPoint = new DnsEndPoint(baseUrl.Host, baseUrl.Port);
        }
Exemplo n.º 3
0
        /// <inheritdoc cref="IUserService.AuthenticateAsync(AuthenticateRequest)"/>
        public async Task <AuthenticateResponse> AuthenticateAsync(AuthenticateRequest authenticateRequest)
        {
            if (string.IsNullOrWhiteSpace(authenticateRequest.Username) || string.IsNullOrWhiteSpace(authenticateRequest.Password))
            {
                return(new AuthenticateResponse(authenticateRequest.Id, Guid.Empty, message: "Credentials are null or empty."));
            }

            if (!await _credentialTypeRepository.ExistsAsync(ct => CredentialTypeCodePredicate(ct, authenticateRequest.CredentialTypeCode)))
            {
                return(new AuthenticateResponse(authenticateRequest.Id, Guid.Empty, message: "CredentialType not found."));
            }

            CredentialType credentialType = await _credentialTypeRepository.FindSingleOrDefaultAsync(ct => CredentialTypeCodePredicate(ct, authenticateRequest.CredentialTypeCode));

            if (!await _credentialRepository.ExistsAsync(cred => CredentialPredicate(credentialType, cred, authenticateRequest.Username)))
            {
                return(new AuthenticateResponse(authenticateRequest.Id, Guid.Empty, message: "Credentials not found."));
            }

            Credential credential = await _credentialRepository.FindSingleOrDefaultAsync(cred => CredentialPredicate(credentialType, cred, authenticateRequest.Username));

            if (!_hasher.VerifyHash(credential.Secret, credential.Extra, authenticateRequest.Password))
            {
                return(new AuthenticateResponse(authenticateRequest.Id, Guid.Empty, message: "Secret not valid."));
            }

            List <Claim> claims = new List <Claim>
            {
                new Claim(ClaimTypes.Name, authenticateRequest.Username),
                new Claim("Authorized", "Logged in")
            };
            User user = await _userRepository.FindSingleOrDefaultAsync(usr => string.Equals(usr.Username, authenticateRequest.Username, StringComparison.OrdinalIgnoreCase));

            string accessToken = _accessTokenService.GenerateAccessToken(claims, DateTime.Now.AddHours(2));

            return(new AuthenticateResponse(authenticateRequest.Id, user.Id, accessToken, success: true));
        }
Exemplo n.º 4
0
        /// <inheritdoc cref="IUserService.AuthenticateAsync(AuthenticateRequest)"/>
        public async Task <AuthenticateResponse> AuthenticateAsync(AuthenticateRequest authenticateRequest)
        {
            if (string.IsNullOrWhiteSpace(authenticateRequest.Username) || string.IsNullOrWhiteSpace(authenticateRequest.Password))
            {
                return(new AuthenticateResponse(authenticateRequest.Id, Guid.Empty, message: "Credentials are null or empty."));
            }

            if (!await _credentialTypeRepository.ExistsAsync(ct => ct.Code == authenticateRequest.CredentialTypeCode))
            {
                return(new AuthenticateResponse(authenticateRequest.Id, Guid.Empty, message: "CredentialType not found."));
            }

            CredentialType credentialType = await _credentialTypeRepository.FindSingleOrDefaultAsync(ct => ct.Code == authenticateRequest.CredentialTypeCode);

            if (!await _credentialRepository.ExistsAsync(cred => cred.CredentialTypeId == credentialType.Id && cred.Identifier == authenticateRequest.Username))
            {
                return(new AuthenticateResponse(authenticateRequest.Id, Guid.Empty, message: "Credentials not found."));
            }

            Credential credential = await _credentialRepository.FindSingleOrDefaultAsync(cred => cred.CredentialTypeId == credentialType.Id && cred.Identifier == authenticateRequest.Username);

            if (!_hasher.VerifyHash(credential.Secret, credential.Extra, authenticateRequest.Password))
            {
                return(new AuthenticateResponse(authenticateRequest.Id, Guid.Empty, message: "Secret not valid."));
            }

            List <Claim> claims = new List <Claim>
            {
                new Claim(ClaimTypes.Name, authenticateRequest.Username),
                new Claim(ClaimTypes.Role, "User")
            };
            User user = await EntityRepository.FindSingleOrDefaultAsync(usr => usr.Username == authenticateRequest.Username);

            string accessToken = _accessTokenService.GenerateAccessToken(claims);

            return(new AuthenticateResponse(authenticateRequest.Id, user.Id, accessToken, "Login successful!", true));
        }
Exemplo n.º 5
0
        /// <summary>
        /// Updates the location of the car and takes care of the status as well as returns appropriate requests
        /// </summary>
        /// <param name="lon"></param>
        /// <param name="lat"></param>
        /// <param name="accessToken"></param>
        /// <param name="absent"></param>
        /// <param name="free"></param>
        /// <param name="onAddress"></param>
        /// <returns></returns>
        public JsonResult Pull(double lon, double lat, string accessToken, bool absent = false, bool free = false,
                               bool onAddress = false)
        {
            if (HttpContext.Request.RequestType == "POST")
            {
                var newAccessToken = _accessTokenService.GenerateAccessToken(accessToken);

                if (newAccessToken == null)
                {
                    return(Json(new { status = "INVALID ACCESSTOKEN" }));
                }

                var userId = _accessTokenService.GetUserId(newAccessToken);

                var driver = _driverService.GetDriverByUserId(userId);
                var car    = _carService.GetCarByDriver(driver);
                _carService.UpdateCarInfo(car, new Models.Models.Location {
                    Latitude = lat, Longitude = lon
                }, absent, free);

                if (onAddress)
                {
                    if (_carService.CarOnAddress(car))
                    {
                        return
                            (Json(
                                 new
                        {
                            status = "OK",
                            onAddress = true,
                            carStatus = car.CarStatus,
                            accessToken = newAccessToken
                        }));
                    }
                }

                if (_carService.CarOnAddressCheck(car))
                {
                    return
                        (Json(
                             new
                    {
                        status = "OK",
                        onAddress = true,
                        carStatus = car.CarStatus,
                        accessToken = newAccessToken
                    }));
                }

                var requestObj = _requestService.AppropriateRequest(car);
                if (requestObj != null)
                {
                    return
                        (Json(
                             new
                    {
                        status = "OK",
                        accessToken = newAccessToken,
                        carStatus = car.CarStatus,
                        request = requestObj
                    }));
                }

                return(Json(new { status = "OK", carStatus = car.CarStatus, accessToken = newAccessToken }));
            }
            return(Json(new { }));
        }
Exemplo n.º 6
0
        /// <summary>
        /// Adds services from the <see cref="Application"/> assembly into the <see cref="serviceCollection"/>.
        /// </summary>
        /// <param name="serviceCollection">The service collection.</param>
        /// <returns>Returns the service collection to chain further upon.</returns>
        public static IServiceCollection AddApplicationServices(this IServiceCollection serviceCollection)
        {
            serviceCollection.AddAutoMapper(Assembly.GetAssembly(typeof(TrainingRoomStartupExtensions)));

            serviceCollection.AddLogging(p => p.AddConsole());

            serviceCollection.AddSingleton <IFactory <TrainingRoomDbContext>, TrainingRoomDatabaseFactory>();

            // Instead of using .AddDbContext, .AddTransient is used because, the IFactory<TrainingRoomDbContext>
            // needs to be used for creating an instance of the TrainingRoomDbContext.
            serviceCollection.AddTransient <TrainingRoomDbContext>(p => p.GetService <IFactory <TrainingRoomDbContext> >().Create());

            #region Validators
            serviceCollection.AddTransient <IEntityValidator <TrainingRoom>, TrainingRoomValidator>();
            serviceCollection.AddTransient <IEntityValidator <TrainingSession>, TrainingSessionValidator>();
            serviceCollection.AddTransient <IEntityValidator <TrainingRoomSettings>, TrainingRoomSettingsValidator>();
            #endregion Validators

            #region Repositories
            serviceCollection.AddTransient <IRepository <TrainingRoom>, Repository <TrainingRoom, TrainingRoomDbContext> >();
            serviceCollection.AddTransient <ITrainingSessionRepository, TrainingSessionRepository>();
            serviceCollection.AddTransient <IRepository <TrainingRoomSettings>, Repository <TrainingRoomSettings, TrainingRoomDbContext> >();
            #endregion Repositories

            serviceCollection.AddSingleton <IMessageSerializer, JsonMessageSerializer>();

            #region Services
            serviceCollection.AddTransient <IAccessTokenService, JwtAccessTokenService>();
            serviceCollection.AddTransient <ITrainingRoomService, Application.Services.TrainingRoomService>();
            serviceCollection.AddTransient <ITrainingSessionService, Application.Services.TrainingSessionService>();
            serviceCollection.AddRegistryService("TrainingRoomService");
            serviceCollection.AddSingleton <IUserService, UserService>(provider =>
            {
                ILogger <UserService> logger         = provider.GetRequiredService <ILogger <UserService> >();
                IMessageSerializer messageSerializer = provider.GetService <IMessageSerializer>();
                HttpClient httpClient = provider.GetService <IHttpClientFactory>().CreateClient("UserService");
                IAccessTokenService accessTokenService = provider.GetService <IAccessTokenService>();
                IRegistryService registryService       = provider.GetService <IRegistryService>();
                // NOTE: May deadlock
                ServiceDto serviceDto = registryService.GetServiceAsync("UserService").GetAwaiter().GetResult();
                // NOTE: What if null? maybe wait before user service is available? several attempts?
                if (serviceDto is null)
                {
                    logger.LogError($"Failed to initialize UserService!");
                    throw new InitializationException("Failed to initialize UserService!");
                }
                List <Claim> claims = new List <Claim>
                {
                    new Claim(ClaimTypes.Name, "TrainingRoomService"),
                    new Claim(ClaimTypes.Role, "Service")
                };
                httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {accessTokenService.GenerateAccessToken(claims)}");
                httpClient.BaseAddress = new Uri($"http://{serviceDto.Host}:{serviceDto.Port}");
                return(new UserService(messageSerializer, httpClient, logger));
            });
            serviceCollection.AddSingleton <IStartupService, StartupService>();
            #endregion Services

            serviceCollection.VerifyDatabaseConnection <TrainingRoomDbContext>();

            serviceCollection.AddHealthChecks <TrainingRoomDbContext>();

            return(serviceCollection);
        }