Ejemplo n.º 1
0
        private async Task <string> GenerateEncodedToken(ClaimsIdentity identity, ApplicationType application)
        {
            _jwtOptions.IssuedAt = DateTime.Now;

            var claims = identity.Claims.Union(
                new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, identity.Name),
                new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()),
                new Claim(
                    JwtRegisteredClaimNames.Iat,
                    _jwtOptions.IssuedAt.LocalToUtcTime().ToSecondsTimestamp().ToString(),
                    ClaimValueTypes.Integer64),
                new Claim(ClaimTypes.System, application.ToString()),
            });

            // Create the JWT security token and encode it.
            var jwt = new JwtSecurityToken(
                _jwtOptions.Issuer,
                _jwtOptions.Audience,
                claims,
                _jwtOptions.IssuedAt,
                GetExpirationDate(application),
                _jwtOptions.SigningCredentials);

            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            return(encodedJwt);
        }
        public void sendStopAction(ApplicationType appType)
        {
            // If this app type didn't start the action so it doesn't have the right to stop it
            if (!callersState.ContainsKey(appType) || callersState[appType] == 0)
            {
                return;
            }

            LOGGER.Info("Received stop action request from " + appType.ToString());
            // Change state
            callersState[appType]--;

            // Set restart delay to an initial value
            this.restartDelayInMs = 0;

            foreach (KeyValuePair <ApplicationType, Int32> app in callersState)
            {
                if (app.Value > 0)
                {
                    // someone else sent the start command too
                    return;
                }
            }

            this.stop();
        }
Ejemplo n.º 3
0
        public void TestOauthStolenAppId(ApplicationType appType)
        {
            InitApiHelpers(appType);
            var defaultAppInfo = GetDefaultApplication(appType);

            using (var appInfo = AuthenticationInfoProvider.Current.Manager.GetApplication(
                       new ApplicationSpecBuilder().ParameterEquals("type", appType.ToString()).ParameterContains("categories", "app_stolen")))
            {
                // Oauth
                APITestFramework.Resources.PublicAPI.Authentication auth = oAuthAPI.GetCodeSuccess(appInfo.Key, "code_direct");
                Assume.That(auth, Is.Not.Null, "Failed to parse the server's response");
                if (appType == ApplicationType.SecondParty)
                {
                    Assume.That(auth.Error, Is.EqualTo(Enums.PublicAPIAuthCode.Success.ToString()), auth.Message);

                    // Access Token
                    auth = tokenAPI.AccessTokenSuccess(appInfo.Key, "oauth_code", defaultAppInfo.Secret, auth.Code);
                    Assert.That(auth, Is.Not.Null, "Failed to parse the server's response");
                    Assert.That(auth.Error, Is.EqualTo(Enums.PublicAPIAuthCode.SecretInvalid.ToString()), auth.Message);
                }
                else
                {
                    Assert.That(auth.Error, Is.EqualTo(Enums.PublicAPIAuthCode.ResponseTypeInvalid.ToString()), "Wrong error message for oauth call for 3rd party app.");
                }
            }
        }
Ejemplo n.º 4
0
        public void CreateSettingsDataInterfaceFile(ApplicationType applicationType, string fileName)
        {
            var databaseConnectionString = _configurationProvider.DatabaseConnectionString
                                           .Replace("Database=blaise", $"Database={applicationType.ToString().ToLower()}");

            _dataInterfaceService.CreateSettingsDataInterface(databaseConnectionString, applicationType, fileName);
        }
Ejemplo n.º 5
0
    public override string ToString()
    {
        var  sb      = new StringBuilder("LoginSession(");
        bool __first = true;

        if (TokenKey != null && __isset.tokenKey)
        {
            if (!__first)
            {
                sb.Append(", ");
            }
            __first = false;
            sb.Append("TokenKey: ");
            TokenKey.ToString(sb);
        }
        if (__isset.expirationTime)
        {
            if (!__first)
            {
                sb.Append(", ");
            }
            __first = false;
            sb.Append("ExpirationTime: ");
            ExpirationTime.ToString(sb);
        }
        if (__isset.applicationType)
        {
            if (!__first)
            {
                sb.Append(", ");
            }
            __first = false;
            sb.Append("ApplicationType: ");
            ApplicationType.ToString(sb);
        }
        if (SystemName != null && __isset.systemName)
        {
            if (!__first)
            {
                sb.Append(", ");
            }
            __first = false;
            sb.Append("SystemName: ");
            SystemName.ToString(sb);
        }
        if (AccessLocation != null && __isset.accessLocation)
        {
            if (!__first)
            {
                sb.Append(", ");
            }
            __first = false;
            sb.Append("AccessLocation: ");
            AccessLocation.ToString(sb);
        }
        sb.Append(")");
        return(sb.ToString());
    }
Ejemplo n.º 6
0
        public void TestInjection(string param, object errorCode, ApplicationType appType)
        {
            InitApiHelpers(appType);

            using (var appInfo = AuthenticationInfoProvider.Current.Manager.GetApplication(
                       new ApplicationSpecBuilder().ParameterEquals("type", appType.ToString()).ParameterContains("categories", "full_scope")))
            {
                Dictionary <string, object> oauthParams = new Dictionary <string, object>()
                {
                };

                switch (param)
                {
                case "AppId":
                    oauthParams.Add("app_id", "' or 1=1");
                    oauthParams.Add("response_type", "code_direct");
                    break;

                case "redirect_url":
                    oauthParams.Add("app_id", appInfo.Key);
                    oauthParams.Add("redirect_url", "' or 1=1");
                    oauthParams.Add("scope", "client_r");
                    oauthParams.Add("response_type", "code");
                    //oauthParams.Add("state", "0");
                    break;

                case "scope":
                    oauthParams.Add("app_id", appInfo.Key);
                    oauthParams.Add("scope", "' or 1=1");
                    oauthParams.Add("response_type", "code_direct");
                    break;

                case "state":
                    oauthParams.Add("app_id", appInfo.Key);
                    oauthParams.Add("state", "' or 1=1");
                    oauthParams.Add("response_type", "code_direct");
                    break;

                case "response_type":
                    oauthParams.Add("app_id", appInfo.Key);
                    oauthParams.Add("response_type", "' or 1=1");
                    break;
                }

                Handler handler = oAuthAPI.Read(oauthParams);
                Assert.That(handler.HttpCode, Is.EqualTo(System.Net.HttpStatusCode.OK), "The http code is invalid");

                APITestFramework.Resources.PublicAPI.Authentication result = XmlHelper.ParseXMLString <APITestFramework.Resources.PublicAPI.Authentication>(handler.RawContent);
                Assert.That(result, Is.Not.Null, "Failed to parse the server's response");
                Assert.That(int.Parse(result.Error), Is.EqualTo(errorCode), result.Message);
            }
        }
Ejemplo n.º 7
0
        public void TestOauthWithoutScopeRegister(string scope, string type, object errorCode, ApplicationType appType)
        {
            InitApiHelpers(appType);

            using (var appInfoRead = AuthenticationInfoProvider.Current.Manager.GetApplication(
                       new ApplicationSpecBuilder().ParameterEquals("type", appType.ToString()).ParameterContains("categories", "read_scope")))
            {
                using (var appInfoWrite = AuthenticationInfoProvider.Current.Manager.GetApplication(
                           new ApplicationSpecBuilder().ParameterEquals("type", appType.ToString()).ParameterContains("categories", "write_scope")))
                {
                    Dictionary <string, object> oauthParams = new Dictionary <string, object>()
                    {
                    };
                    oauthParams.Add("response_type", "code_direct");
                    oauthParams.Add("scope", scope);

                    string appId = string.Empty;
                    switch (type)
                    {
                    case "read":
                        appId = appInfoWrite.Key;
                        break;

                    case "write":
                        appId = appInfoRead.Key;
                        break;
                    }
                    oauthParams.Add("app_id", appId);

                    Handler handler = oAuthAPI.Read(oauthParams);
                    Assert.That(handler.HttpCode, Is.EqualTo(System.Net.HttpStatusCode.OK), "The http code is invalid");

                    APITestFramework.Resources.PublicAPI.Authentication result = XmlHelper.ParseXMLString <APITestFramework.Resources.PublicAPI.Authentication>(handler.RawContent);
                    Assert.That(result, Is.Not.Null, "Failed to parse the server's response");
                    Assert.That(int.Parse(result.Error), Is.EqualTo(errorCode), result.Message);
                }
            }
        }
        // called from other parts of ProActive Agent
        // this method dispatches action depending on type
        // and calls internal methods

        public void sendStartAction(ApplicationType appType)
        {
            LOGGER.Info("Received start action request from " + appType.ToString());

            if (callersState.ContainsKey(appType))
            {
                callersState[appType]++;
            }
            else
            {
                callersState.Add(appType, 1);
            }

            // Invoke start
            this.start();
        }
Ejemplo n.º 9
0
        public override string ToString()
        {
            string result = string.Empty;

            result +=
                Environment.NewLine + "Вид заявление:" + Environment.NewLine + //TODO change
                this.ApplicationType.GetDisplay(ApplicationType.ToString());   //
            result += Environment.NewLine + this.SUNAUServiceName.ToString() + ":.";

            result += Environment.NewLine + "Администрация - доставчик на услугата:." + Environment.NewLine
                      + this.ElectronicServiceProviderBasicData.ToString();
            result += Environment.NewLine + "Данни за заявител:." + Environment.NewLine
                      + this.ElectronicServiceApplicant.ToString();
            result += Environment.NewLine + "Данни за контакт с заявителя:." + Environment.NewLine
                      + this.ElectronicServiceApplicantContactData.ToString();


            return(result);
        }
Ejemplo n.º 10
0
        Given_An_ApplicationType_When_I_Call_CreateSettingsDataInterfaceFile_Then_The_DatabaseName_Is_Updated_In_The_Connection_String(
            ApplicationType applicationType)
        {
            //arrange
            const string fileName = "LMS2101_BK1";
            const string existingConnectionString = "User Id=username;Server=ipaddress;Database=blaise;Password=password";

            var expectedConnectionString
                = $"User Id=username;Server=ipaddress;Database={applicationType.ToString().ToLower()};Password=password";

            _configurationMock.Setup(c => c.DatabaseConnectionString)
            .Returns(existingConnectionString);

            //act
            _sut.CreateSettingsDataInterfaceFile(applicationType, fileName);

            //assert
            _dataInterfaceMock.Verify(v => v.CreateSettingsDataInterface(
                                          expectedConnectionString, applicationType, fileName), Times.Once);
        }
Ejemplo n.º 11
0
        public void TestCodeDirectRequirements(bool isSubscribedApp, ApplicationType appType)
        {
            InitApiHelpers(appType);

            using (var appInfo = AuthenticationInfoProvider.Current.Manager.GetApplication(
                       new ApplicationSpecBuilder().
                       ParameterEquals("type", appType.ToString()).
                       ParameterEquals("authorised", isSubscribedApp.ToLowerString()).
                       ParameterEquals("clean", (!isSubscribedApp).ToLowerString())))
            {
                var oauthResponse = XmlHelper.ParseXMLString <APITestFramework.Resources.PublicAPI.Authentication>(oAuthAPI.GetCode(appInfo.Key, "code_direct").RawContent);

                if (appType == ApplicationType.SecondParty && isSubscribedApp)
                {
                    Assert.That(oauthResponse?.Error, Is.Null.Or.EqualTo(((int)AuthResponseCode.Success).ToString()), "Code_Direct request failed, while expected success.");
                }
                else
                {
                    Assert.That(oauthResponse?.Error, Is.EqualTo(((int)AuthResponseCode.InvalidResponseType).ToString()), "Code_Direct request error code is wrong.");
                }
            }
        }
Ejemplo n.º 12
0
    public override string ToString()
    {
        var  sb      = new StringBuilder("SimpleChannelClient(");
        bool __first = true;

        if (ApplicationType != null && __isset.applicationType)
        {
            if (!__first)
            {
                sb.Append(", ");
            }
            __first = false;
            sb.Append("ApplicationType: ");
            ApplicationType.ToString(sb);
        }
        if (ApplicationVersion != null && __isset.applicationVersion)
        {
            if (!__first)
            {
                sb.Append(", ");
            }
            __first = false;
            sb.Append("ApplicationVersion: ");
            ApplicationVersion.ToString(sb);
        }
        if (Locale != null && __isset.locale)
        {
            if (!__first)
            {
                sb.Append(", ");
            }
            __first = false;
            sb.Append("Locale: ");
            Locale.ToString(sb);
        }
        sb.Append(")");
        return(sb.ToString());
    }
Ejemplo n.º 13
0
        public static int WriteEvent(string level, string group, ApplicationType applicationType, string applicationName, string loggingUserType, string logginUserId, string affectedUserType, string affectedUserId, string type, string details, string clientip, string hostip)
        {
            int?   eventid    = null;
            string resultcode = null;

            if (clientip == null)
            {
                clientip = ClientTools.IPAddress();
            }
            if (hostip == null)
            {
                hostip = ServerTools.IPv4Addresses.First().ToString();
            }

            XElement xDetails = XElement.Parse(string.Format("<details>{0}</details>", details));

            using (LumberjackLinqDataContext db = new LumberjackLinqDataContext(ConfigurationManager.ConnectionStrings["LumberjackConnectionString"].ToString())) {
                db.xspWriteDirectEvent(
                    applicationType.ToString(),
                    applicationName,
                    1,
                    loggingUserType,
                    logginUserId,
                    affectedUserType,
                    affectedUserId,
                    group,
                    level,
                    type,
                    xDetails,
                    clientip,
                    hostip,
                    ref eventid,
                    ref resultcode
                    );
            }

            return((int)eventid);
        }
Ejemplo n.º 14
0
    public override string ToString()
    {
        var  sb      = new StringBuilder("NotificationTarget(");
        bool __first = true;

        if (ApplicationType != null && __isset.applicationType)
        {
            if (!__first)
            {
                sb.Append(", ");
            }
            __first = false;
            sb.Append("ApplicationType: ");
            ApplicationType.ToString(sb);
        }
        if (ApplicationVersion != null && __isset.applicationVersion)
        {
            if (!__first)
            {
                sb.Append(", ");
            }
            __first = false;
            sb.Append("ApplicationVersion: ");
            ApplicationVersion.ToString(sb);
        }
        if (Region != null && __isset.region)
        {
            if (!__first)
            {
                sb.Append(", ");
            }
            __first = false;
            sb.Append("Region: ");
            Region.ToString(sb);
        }
        sb.Append(")");
        return(sb.ToString());
    }
Ejemplo n.º 15
0
        private void VerifyCodeDirectScope(string scope, ApplicationType appType)
        {
            using (var appInfo = AuthenticationInfoProvider.Current.Manager.GetApplication(
                       new ApplicationSpecBuilder().
                       ParameterEquals("type", appType.ToString()).
                       ParameterEquals("authorised", "true")))
            {
                var oauthResponse = XmlHelper.ParseXMLString <APITestFramework.Resources.PublicAPI.Authentication>(oAuthAPI.Read(new Dictionary <string, object>
                {
                    ["app_id"]        = appInfo.Key,
                    ["response_type"] = "code_direct",
                    ["scope"]         = scope
                }).RawContent);

                if (appType == ApplicationType.SecondParty)
                {
                    Assert.That(oauthResponse?.Error, Is.Null.Or.EqualTo(((int)AuthResponseCode.Success).ToString()), "Code_Direct request failed, while expected success.");
                }
                else
                {
                    Assert.That(oauthResponse?.Error, Is.EqualTo(((int)AuthResponseCode.InvalidResponseType).ToString()), "Code_Direct request error code is wrong.");
                }
            }
        }
Ejemplo n.º 16
0
 protected override void PerformExecuteWith(IExecutionContext context)
 {
     _oldApplicationType         = _schemaItem.ApplicationType;
     _schemaItem.ApplicationType = _newApplicationType;
     Description = PKSimConstants.Command.SetApplicationSchemaItemApplicationTypeDescription(_oldApplicationType.ToString(), _newApplicationType.ToString());
 }
Ejemplo n.º 17
0
 internal static string GetGroups(int userId, ApplicationType applicationType, bool sortingMode)
 {
     return "SELECT * FROM " + TblGroupsForUsers + " WHERE UserID=" + userId + " AND AppType = '" + applicationType.ToString() + "' ORDER BY GroupName "+(sortingMode?"ASC":"DESC");
 }
Ejemplo n.º 18
0
        private static IEnumerable<int> GetMyGroupsIds(int userId, ApplicationType appType)
        {
            var res = new List<int>();
            string sql = "SELECT * FROM " + TblGroupsForUsers + " WHERE UserID=" + userId + " AND AppType = '" + appType.ToString() + "' AND Privilege = 'Creator' ORDER BY GroupName " + (SortingModeIsAsc ? "ASC" : "DESC");

            var reader = GetReader(sql);
            if (reader != null)
            {
                while (reader.Read())
                {
                    res.Add(reader.GetInt32("GroupId"));
                }

                reader.Close();
            }

            return res;
        }
Ejemplo n.º 19
0
        public static List<GroupModel> GetGroupsForUser(int userId, ApplicationType appType)
        {
            var groupList = new List<GroupModel>();

            string sql = "SELECT * FROM " + TblGroupsForUsers + " WHERE UserID = '" + userId + "' AND AppType = '" + appType.ToString() + "' ORDER BY GroupName " + (SortingModeIsAsc ? "ASC" : "DESC");
            var reader = GetReader(sql);
            if (reader != null)
            {
                while (reader.Read())
                {
                    var symbol = new GroupModel
                    {
                        GroupId = reader.GetInt32(2),
                        GroupName = reader.GetString(3),
                        TimeFrame = reader.GetString(4),
                        Start = reader.GetDateTime(5),
                        End = reader.GetDateTime(6),
                        CntType = reader.GetString(7),
                        Depth = reader.GetInt32("Depth"),
                        IsAutoModeEnabled = reader.GetBoolean("IsAutoModeEnabled")
                    };

                    GroupPrivilege privilege;
                    ApplicationType appType1;
                    Enum.TryParse(reader.GetString(8), out privilege);
                    Enum.TryParse(reader.GetString(9), out appType1);

                    symbol.Privilege = privilege;
                    symbol.AppType = appType1;

                    groupList.Add(symbol);
                }
                reader.Close();
            }
            return groupList;
        }
Ejemplo n.º 20
0
        public static bool AddGroupForUser(int userId, GroupModel group, ApplicationType appType)
        {
            var startDateStr = Convert.ToDateTime(group.Start).ToString("yyyy/MM/dd HH:mm:ss", CultureInfo.InvariantCulture);
            var endDateStr = Convert.ToDateTime(group.End).ToString("yyyy/MM/dd HH:mm:ss", CultureInfo.InvariantCulture);

            var sql = "INSERT IGNORE INTO " + TblGroupsForUsers
                      + " (`UserID`, `GroupID`, `GroupName`, `TimeFrame`, `Start`, `End`, `CntType`, `Privilege`, `AppType`,`IsAutoModeEnabled`,`Depth`)"
                      + "VALUES('" + userId + "',"
                      + " '" + group.GroupId + "',"
                      + " '" + group.GroupName + "',"
                      + " '" + group.TimeFrame + "',"
                      + " '" + startDateStr + "',"
                      + " '" + endDateStr + "',"
                      + " '" + group.CntType + "',"
                      + " '" + GroupPrivilege.Creator + "',"
                      + " '" + appType.ToString() + "',"
                      + " " + (group.IsAutoModeEnabled ? "1" : "0") + ","
                      + " " + group.Depth + ""
                      + ");COMMIT;";

            return DoSql(sql);
        }
 public override string ToString()
 {
     return("[" + ApplicationType.ToString() + "]:" + this.Title);
 }
Ejemplo n.º 22
0
        public override void Execute(IExecutionContext context)
        {
            var oldApplicationType = _schemaItem.ApplicationType;

            Description = PKSimConstants.Command.SetApplicationSchemaItemApplicationTypeDescription(oldApplicationType.ToString(), _newApplicationType.ToString());
            context.UpdateBuildingBlockPropertiesInCommand(this, context.BuildingBlockContaining(_schemaItem));
            Add(new ChangeApplicationTypeCommand(_schemaItem, _newApplicationType, context));

            if (shouldResetFormulation(oldApplicationType))
            {
                Add(new SetSchemaItemFormulationKeyCommand(_schemaItem, string.Empty, context));
            }

            else if (shouldSetDefaultFormulation())
            {
                Add(new SetSchemaItemFormulationKeyCommand(_schemaItem, CoreConstants.DEFAULT_FORMULATION_KEY, context));
            }

            //update parameters according to application
            var applicationParameterRetriever = context.Resolve <ISchemaItemParameterRetriever>();

            //First delete all dynamic parameters
            foreach (var parameterToDelete in applicationParameterRetriever.AllDynamicParametersFor(_schemaItem))
            {
                Add(new RemoveParameterFromContainerCommand(parameterToDelete, _schemaItem, context)
                {
                    Visible = false
                });
            }

            //Then add all new dynamic parameters
            foreach (var parameter in applicationParameterRetriever.AllDynamicParametersFor(_newApplicationType))
            {
                Add(new AddParameterToContainerCommand(parameter, _schemaItem, context)
                {
                    Visible = false
                });
            }

            //now execute all commands
            base.Execute(context);

            //clear references
            _schemaItem = null;
        }
Ejemplo n.º 23
0
 internal static string GetGroups(int userId, ApplicationType applicationType, bool sortingMode)
 {
     return("SELECT * FROM " + TblGroupsForUsers + " WHERE UserID=" + userId + " AND AppType = '" + applicationType.ToString() + "' ORDER BY GroupName " + (sortingMode?"ASC":"DESC"));
 }
Ejemplo n.º 24
0
        internal static Dependency CreateDependency(FileInfo file, ApplicationType application, bool isLauncherExecutable = false)
        {
            var dependency = new Dependency();

            dependency.Name = file.Name;
            var destination = isLauncherExecutable ? LauncherConstants.ExecutablePathVariable : LauncherConstants.ApplicationBaseVariable;

            dependency.Destination = $"%{destination}%";
            dependency.Version     = FileVersionInfo.GetVersionInfo(file.FullName).FileVersion;
            dependency.Sha2        = FileHashHelper.GetFileHash(file.FullName, FileHashHelper.HashType.Sha256);
            dependency.Size        = file.Length;
            dependency.Origin      = UrlCombine.Combine(Program.LaunchOptions.OriginPathRoot, application.ToString(), file.Name);
            Logger.Debug($"Dependency created: {dependency}");
            return(dependency);
        }