Esempio n. 1
0
        public async Task <InvokeResult <Solution> > LoadFullSolutionAsync(string id, EntityHeader org, EntityHeader user)
        {
            var result = new InvokeResult <Solution>();

            var solution = await _deploymentRepo.GetSolutionAsync(id);

            foreach (var config in solution.DeviceConfigurations)
            {
                var loadResult = await _deviceConfigManager.LoadFullDeviceConfigurationAsync(config.Id, org, user);

                if (result.Successful)
                {
                    config.Value = loadResult.Result;
                }
                else
                {
                    result.Concat(loadResult);
                }
            }

            if (solution.Planner.IsEmpty())
            {
                result.Errors.Add(DeploymentErrorCodes.NoPlannerSpecified.ToErrorMessage());
            }
            else
            {
                var loadResult = await _pipelineModuleManager.LoadFullPlannerConfigurationAsync(solution.Planner.Id);

                if (loadResult.Successful)
                {
                    solution.Planner.Value = loadResult.Result;
                }
                else
                {
                    result.Concat(loadResult);
                }
            }

            foreach (var listenerConfig in solution.Listeners)
            {
                var loadResult = await _pipelineModuleManager.LoadFullListenerConfigurationAsync(listenerConfig.Id);

                if (loadResult.Successful)
                {
                    listenerConfig.Value = loadResult.Result;
                }
                else
                {
                    result.Concat(loadResult);
                }
            }

            return(InvokeResult <Solution> .Create(solution));
        }
Esempio n. 2
0
        private async Task <InvokeResult> RenewRefreshToken()
        {
            var authRequest = new AuthRequest();

            authRequest.AppId         = _appConfig.AppId;
            authRequest.ClientType    = "mobileapp";
            authRequest.DeviceId      = _deviceInfo.DeviceUniqueId;
            authRequest.AppInstanceId = _authManager.AppInstanceId;
            authRequest.GrantType     = "refreshtoken";
            authRequest.UserName      = _authManager.User.Email;
            authRequest.Email         = _authManager.User.Email;
            authRequest.RefreshToken  = _authManager.RefreshToken;

            var response = await _authClient.LoginAsync(authRequest);

            if (response.Successful)
            {
                _authManager.AccessToken = response.Result.AccessToken;
                _authManager.AccessTokenExpirationUTC  = response.Result.AccessTokenExpiresUTC;
                _authManager.RefreshToken              = response.Result.RefreshToken;
                _authManager.AppInstanceId             = response.Result.AppInstanceId;
                _authManager.RefreshTokenExpirationUTC = response.Result.RefreshTokenExpiresUTC;
                _logger.AddCustomEvent(LogLevel.Message, "RawRestClient_RenewRefreshTokenAsync", "Access Token Renewed with Refresh Token");
                await _authManager.PersistAsync();

                return(InvokeResult.Success);
            }
            else
            {
                _logger.AddCustomEvent(LogLevel.Error, "RawRestClient_RenewRefreshTokenAsync", "Could Not Renew Access Token", response.ErrorsToKVPArray());
                var result = new InvokeResult();
                result.Concat(response);
                throw new Exceptions.CouldNotRenewTokenException();
            }
        }
Esempio n. 3
0
        public async Task <InvokeResult <AuthResponse> > CreateUserAsync(RegisterUser newUser)
        {
            if (String.IsNullOrEmpty(newUser.Email))
            {
                _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "UserServicesController_CreateNewAsync", UserAdminErrorCodes.RegMissingEmail.Message);
                return(InvokeResult <AuthResponse> .FromErrors(UserAdminErrorCodes.RegMissingEmail.ToErrorMessage()));
            }

            var user = await _appUserRepo.FindByEmailAsync(newUser.Email);

            if (user != null)
            {
                _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "UserServicesController_CreateNewAsync", UserAdminErrorCodes.RegErrorUserExists.Message);
                return(InvokeResult <AuthResponse> .FromErrors(UserAdminErrorCodes.RegErrorUserExists.ToErrorMessage()));
            }

            /* Need to check all these, if any fail, we want to aboart, we need to refactor this into the UserAdmin module :( */
            if (String.IsNullOrEmpty(newUser.AppId))
            {
                _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "UserServicesController_CreateNewAsync", UserAdminErrorCodes.AuthMissingAppId.Message);
                return(InvokeResult <AuthResponse> .FromErrors(UserAdminErrorCodes.AuthMissingAppId.ToErrorMessage()));
            }

            if (String.IsNullOrEmpty(newUser.ClientType))
            {
                _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "UserServicesController_CreateNewAsync", UserAdminErrorCodes.AuthMissingClientType.Message);
                return(InvokeResult <AuthResponse> .FromErrors(UserAdminErrorCodes.AuthMissingClientType.ToErrorMessage()));
            }

            if (String.IsNullOrEmpty(newUser.DeviceId))
            {
                _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "UserServicesController_CreateNewAsync", UserAdminErrorCodes.AuthMissingDeviceId.Message);
                return(InvokeResult <AuthResponse> .FromErrors(UserAdminErrorCodes.AuthMissingDeviceId.ToErrorMessage()));
            }

            if (String.IsNullOrEmpty(newUser.FirstName))
            {
                _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "UserServicesController_CreateNewAsync", UserAdminErrorCodes.RegMissingFirstLastName.Message);
                return(InvokeResult <AuthResponse> .FromErrors(UserAdminErrorCodes.RegMissingFirstLastName.ToErrorMessage()));
            }

            if (String.IsNullOrEmpty(newUser.LastName))
            {
                _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "UserServicesController_CreateNewAsync", UserAdminErrorCodes.RegMissingLastName.Message);
                return(InvokeResult <AuthResponse> .FromErrors(UserAdminErrorCodes.RegMissingLastName.ToErrorMessage()));
            }


            if (String.IsNullOrEmpty(newUser.Password))
            {
                _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "UserServicesController_CreateNewAsync", UserAdminErrorCodes.RegMissingPassword.Message);
                return(InvokeResult <AuthResponse> .FromErrors(UserAdminErrorCodes.RegMissingPassword.ToErrorMessage()));
            }

            var emailRegEx = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");

            if (!emailRegEx.Match(newUser.Email).Success)
            {
                _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "UserServicesController_CreateNewAsync", UserAdminErrorCodes.RegInvalidEmailAddress.Message);
                return(InvokeResult <AuthResponse> .FromErrors(UserAdminErrorCodes.RegInvalidEmailAddress.ToErrorMessage()));
            }

            var appUser = new AppUser(newUser.Email, $"{newUser.FirstName} {newUser.LastName}")
            {
                FirstName = newUser.FirstName,
                LastName  = newUser.LastName,
            };

            /* In the testing environment we just go ahead and not make the user confirm by email or phone number so we can start using
             * right away, eventually we will probably build this into testing but need some way of getting the confirmation tokens */

            if (_appConfig.Environment == Environments.Testing)
            {
                appUser.PhoneNumberConfirmed = true;
                appUser.EmailConfirmed       = true;
            }

            var identityResult = await _userManager.CreateAsync(appUser, newUser.Password);

            if (identityResult.Successful)
            {
                await LogEntityActionAsync(appUser.Id, typeof(AppUser).Name, "New User Registered", null, appUser.ToEntityHeader());

                await _signInManager.SignInAsync(appUser);

                if (newUser.ClientType != "WEBAPP")
                {
                    var authRequest = new AuthRequest()
                    {
                        AppId         = newUser.AppId,
                        DeviceId      = newUser.DeviceId,
                        AppInstanceId = newUser.AppInstanceId,
                        ClientType    = newUser.ClientType,
                        GrantType     = "password",
                        Email         = newUser.Email,
                        UserName      = newUser.Email,
                        Password      = newUser.Password,
                    };

                    var tokenResponse = await _authTokenManager.AccessTokenGrantAsync(authRequest);

                    if (tokenResponse.Successful)
                    {
                        await _userVerificationmanager.SendConfirmationEmailAsync(null, appUser.ToEntityHeader());

                        return(InvokeResult <AuthResponse> .Create(tokenResponse.Result));
                    }
                    else
                    {
                        var failedValidationResult = new InvokeResult <AuthResponse>();
                        failedValidationResult.Concat(tokenResponse);
                        return(failedValidationResult);
                    }
                }
                else
                {
                    await _userVerificationmanager.SendConfirmationEmailAsync(null, appUser.ToEntityHeader());

                    /* If we are logging in as web app, none of this applies */
                    return(InvokeResult <AuthResponse> .Create(new AuthResponse()
                    {
                        AccessToken = "N/A",
                        AccessTokenExpiresUTC = "N/A",
                        RefreshToken = "N/A",
                        AppInstanceId = "N/A",
                        RefreshTokenExpiresUTC = "N/A",
                        IsLockedOut = false,
                        User = appUser.ToEntityHeader(),
                        Roles = new List <EntityHeader>()
                    }));
                }
            }
            else
            {
                return(InvokeResult <AuthResponse> .FromInvokeResult(identityResult));
            }
        }
        public async Task <InvokeResult> PopulateDeviceConfigToDeviceAsync(Device device, EntityHeader instanceEH, EntityHeader org, EntityHeader user)
        {
            Console.WriteLine("Hhhhh...eeerrre");

            var result = new InvokeResult();

            if (EntityHeader.IsNullOrEmpty(instanceEH))
            {
                result.AddSystemError($"Device does not have a valid device configuration Device Id={device.Id}");
                return(result);
            }

            Console.WriteLine("H1");

            var deviceConfig = await GetDeviceConfigurationAsync(device.DeviceConfiguration.Id, org, user);

            if (deviceConfig == null)
            {
                result.AddSystemError($"Could Not Load Device Configuration with Device Configuration {device.DeviceConfiguration.Text}, Id={device.DeviceConfiguration.Id}.");
                return(result);
            }

            var instance = await _deploymentInstanceManager.GetInstanceAsync(instanceEH.Id, org, user);

            Console.WriteLine("H2");

            if (instance != null && instance.Status.Value == DeploymentInstanceStates.Running)
            {
                if (instance.InputCommandSSL)
                {
                    device.DeviceURI = $"https://{instance.DnsHostName}:{instance.InputCommandPort}/devices/{device.Id}";
                }
                else
                {
                    device.DeviceURI = $"http://{instance.DnsHostName}:{instance.InputCommandPort}/devices/{device.Id}";
                }

                var endpoints = new List <InputCommandEndPoint>();
                foreach (var route in deviceConfig.Routes)
                {
                    Console.WriteLine("H3");

                    foreach (var module in route.PipelineModules)
                    {
                        Console.WriteLine("H4");

                        if (module.ModuleType.Value == Pipeline.Admin.Models.PipelineModuleType.Workflow)
                        {
                            Console.WriteLine("H4.1");
                            var wfLoadResult = await _deviceAdminManager.LoadFullDeviceWorkflowAsync(module.Module.Id, org, user);

                            Console.WriteLine("H4.2");
                            if (wfLoadResult.Successful)
                            {
                                Console.WriteLine("H4.3");
                                if (wfLoadResult.Result.Attributes != null)
                                {
                                    foreach (var attribute in wfLoadResult.Result.Attributes)
                                    {
                                        if (device.AttributeMetaData == null)
                                        {
                                            device.AttributeMetaData = new List <DeviceAdmin.Models.Attribute>();
                                        }
                                        if (!device.AttributeMetaData.Where(attr => attr.Key == attribute.Key).Any())
                                        {
                                            device.AttributeMetaData.Add(attribute);
                                        }
                                    }
                                }

                                Console.WriteLine("H4.4");

                                if (wfLoadResult.Result.StateMachines != null)
                                {
                                    if (device.StateMachineMetaData == null)
                                    {
                                        device.StateMachineMetaData = new List <StateMachine>();
                                    }
                                    foreach (var stateMachine in wfLoadResult.Result.StateMachines)
                                    {
                                        if (!device.StateMachineMetaData.Where(attr => attr.Key == stateMachine.Key).Any())
                                        {
                                            device.StateMachineMetaData.Add(stateMachine);
                                        }
                                    }
                                }

                                Console.WriteLine("H4.5");

                                if (wfLoadResult.Result.InputCommands != null)
                                {
                                    foreach (var inputCommand in wfLoadResult.Result.InputCommands)
                                    {
                                        var protocol = instance.InputCommandSSL ? "https://" : "http://";
                                        var endPoint = new InputCommandEndPoint
                                        {
                                            EndPoint     = $"{protocol}{instance.DnsHostName}:{instance.InputCommandPort}/{deviceConfig.Key}/{route.Key}/{wfLoadResult.Result.Key}/{inputCommand.Key}/{device.DeviceId}",
                                            InputCommand = inputCommand
                                        };

                                        if (!endpoints.Where(end => end.EndPoint == endPoint.EndPoint).Any())
                                        {
                                            endpoints.Add(endPoint);
                                        }
                                    }
                                }

                                Console.WriteLine("H43");
                            }
                            else
                            {
                                result.Concat(result);
                            }
                        }
                    }
                }
                device.InputCommandEndPoints = endpoints;
            }
            else
            {
                Console.WriteLine("H21");
                device.InputCommandEndPoints = new List <InputCommandEndPoint>();
                device.AttributeMetaData     = new List <DeviceAdmin.Models.Attribute>();
                device.StateMachineMetaData  = new List <StateMachine>();
            }

            Console.WriteLine("H5");

            if (deviceConfig.Properties != null)
            {
                device.PropertiesMetaData = new List <DeviceAdmin.Models.CustomField>();
                foreach (var prop in deviceConfig.Properties.OrderBy(prop => prop.Order))
                {
                    device.PropertiesMetaData.Add(prop);
                    if (prop.FieldType.Value == DeviceAdmin.Models.ParameterTypes.State)
                    {
                        prop.StateSet.Value = await _deviceAdminManager.GetStateSetAsync(prop.StateSet.Id, org, user);
                    }
                    else if (prop.FieldType.Value == DeviceAdmin.Models.ParameterTypes.ValueWithUnit)
                    {
                        prop.UnitSet.Value = await _deviceAdminManager.GetAttributeUnitSetAsync(prop.UnitSet.Id, org, user);
                    }
                }
            }

            Console.WriteLine("H6");

            return(result);
        }
        public async Task <InvokeResult> PopulateRoutes(Route route, EntityHeader org, EntityHeader user)
        {
            var fullLoadResult = new InvokeResult();

            var msgLoadResult = await _deviceMessageDefinitionManager.LoadFullDeviceMessageDefinitionAsync(route.MessageDefinition.Id, org, user);

            if (msgLoadResult.Successful)
            {
                route.MessageDefinition.Value = msgLoadResult.Result;
            }
            else
            {
                fullLoadResult.Concat(fullLoadResult);
            }

            foreach (var module in route.PipelineModules)
            {
                switch (module.ModuleType.Value)
                {
                case Pipeline.Admin.Models.PipelineModuleType.InputTranslator:
                {
                    var result = await _pipelineModuleManager.LoadFullInputTranslatorConfigurationAsync(module.Module.Id);

                    if (result.Successful)
                    {
                        module.Module.Value = result.Result;
                    }
                    else
                    {
                        fullLoadResult.Concat(result);
                    }
                }
                break;

                case Pipeline.Admin.Models.PipelineModuleType.DataStream:
                {
                    var result = await _dataStreamManager.LoadFullDataStreamConfigurationAsync(module.Module.Id);

                    if (result.Successful)
                    {
                        module.Module.Value = result.Result;
                    }
                    else
                    {
                        fullLoadResult.Concat(result);
                    }
                }
                break;

                case Pipeline.Admin.Models.PipelineModuleType.Sentinel:
                {
                    var result = await _pipelineModuleManager.LoadFullSentinelConfigurationAsync(module.Module.Id);

                    if (result.Successful)
                    {
                        module.Module.Value = result.Result;
                    }
                    else
                    {
                        fullLoadResult.Concat(result);
                    }
                }
                break;

                case Pipeline.Admin.Models.PipelineModuleType.Workflow:
                {
                    var result = await _deviceAdminManager.LoadFullDeviceWorkflowAsync(module.Module.Id, org, user);

                    if (result.Successful)
                    {
                        module.Module.Value = result.Result;
                        var destModuleConfig = route.PipelineModules.Where(mod => mod.Id == module.PrimaryOutput.Id).FirstOrDefault();

                        if (destModuleConfig.ModuleType.Value == Pipeline.Admin.Models.PipelineModuleType.OutputTranslator)
                        {
                            if (module.PrimaryOutput != null && module.PrimaryOutput.Mappings != null)
                            {
                                for (var idx = 0; idx < module.PrimaryOutput.Mappings.Count; ++idx)
                                {
                                    var mapping = module.PrimaryOutput.Mappings[idx];
                                    if (mapping.Value != null)
                                    {
                                        var mappingValue = JsonConvert.DeserializeObject <OutputCommandMapping>(mapping.Value.ToString());
                                        if (mappingValue != null && !EntityHeader.IsNullOrEmpty(mappingValue.OutgoingDeviceMessage))
                                        {
                                            var outgoingMsgLoadResult = await _deviceMessageDefinitionManager.LoadFullDeviceMessageDefinitionAsync(mappingValue.OutgoingDeviceMessage.Id, org, user);

                                            mappingValue.OutgoingDeviceMessage.Value = outgoingMsgLoadResult.Result;
                                            module.PrimaryOutput.Mappings[idx]       = new KeyValuePair <string, object>(mapping.Key, mappingValue);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        fullLoadResult.Concat(result);
                    }
                }
                break;

                case Pipeline.Admin.Models.PipelineModuleType.OutputTranslator:
                {
                    var result = await _pipelineModuleManager.LoadFullOutputTranslatorConfigurationAsync(module.Module.Id);

                    if (result.Successful)
                    {
                        module.Module.Value = result.Result;
                    }
                    else
                    {
                        fullLoadResult.Concat(result);
                    }
                }
                break;

                case Pipeline.Admin.Models.PipelineModuleType.Transmitter:
                {
                    var result = await _pipelineModuleManager.LoadFullTransmitterConfigurationAsync(module.Module.Id);

                    if (result.Successful)
                    {
                        module.Module.Value = result.Result;
                    }
                    else
                    {
                        fullLoadResult.Concat(result);
                    }
                }
                break;

                case Pipeline.Admin.Models.PipelineModuleType.Custom:
                {
                    var result = await _pipelineModuleManager.LoadFullCustomPipelineModuleConfigurationAsync(module.Module.Id);

                    if (result.Successful)
                    {
                        module.Module.Value = result.Result;
                    }
                    else
                    {
                        fullLoadResult.Concat(result);
                    }
                }
                break;
                }
            }

            return(fullLoadResult);
        }
        public async Task <InvokeResult> ValidateConnectionAsync(DataStream stream)
        {
            var result = new InvokeResult();

            var builder = new System.Data.SqlClient.SqlConnectionStringBuilder();

            builder.Add("Data Source", stream.DbURL);
            builder.Add("Initial Catalog", stream.DbName);
            builder.Add("User Id", stream.DbUserName);
            builder.Add("Password", stream.DbPassword);
            _connectionString = builder.ConnectionString;

            /* be careful when updating the SQL below, the rdr uses field indexes,
             * if this wasn't so small and self contained, I probably wouldn't be so lazy,
             * buf for one field...well...moving on.*/
            var sql = $@"
select
	b.name as ColumnName,
	type_name(b.xusertype) ColumnType,
	b.IsNullable,
	columnproperty(a.id, b.name, 'isIdentity') IsIdentity,
	sm.text AS DefaultValue
from sysobjects a 
   inner join syscolumns b on a.id = b.id
   LEFT JOIN sys.syscomments sm ON sm.id = b.cdefault
    WHERE a.xtype = 'U' and a.name = @tableName";

            var fields = new List <SQLFieldMetaData>();

            using (var cn = new System.Data.SqlClient.SqlConnection(_connectionString))
                using (var cmd = new System.Data.SqlClient.SqlCommand(sql, cn))
                {
                    cmd.Parameters.AddWithValue("@tableName", stream.DbTableName);
                    try
                    {
                        await cn.OpenAsync();

                        using (var rdr = await cmd.ExecuteReaderAsync())
                        {
                            while (await rdr.ReadAsync())
                            {
                                fields.Add(new SQLFieldMetaData()
                                {
                                    ColumnName   = rdr["ColumnName"].ToString(),
                                    IsRequired   = !Convert.ToBoolean(rdr["IsNullable"]),
                                    DataType     = rdr["ColumnType"].ToString(),
                                    IsIdentity   = Convert.ToBoolean(rdr["IsIdentity"]),
                                    DefaultValue = Convert.ToString(rdr["DefaultValue"])
                                });
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        result.AddUserError($"Could not access SQL Server: {ex.Message}");
                        return(result);
                    }
                }

            if (fields.Count == 0)
            {
                result.AddUserError($"Table [{stream.DbTableName}] name not found on SQL Server database [{stream.DbName}] on server [{stream.DbURL}.");
            }
            else
            {
                result.Concat(stream.ValidateSQLSeverMetaData(fields));
            }

            return(result);
        }