public async Task UsesCallbackToRetrieveTwoFactorCode()
            {
                var firstResponse = new TwoFactorRequiredException(TwoFactorType.AuthenticatorApp);
                var twoFactorChallengeResult = new TwoFactorChallengeResult("two-factor-code");
                var secondResponse = new ApplicationAuthorization("OAUTHSECRET");

                var client = Substitute.For<IObservableAuthorizationsClient>();
                client.GetOrCreateApplicationAuthentication(Args.String, Args.String, Args.NewAuthorization)
                    .Returns(Observable.Throw<ApplicationAuthorization>(firstResponse));
                client.GetOrCreateApplicationAuthentication(
                    Args.String,
                    Args.String,
                    Args.NewAuthorization,
                    "two-factor-code")
                    .Returns(Observable.Return(secondResponse));

                var result = await client.GetOrCreateApplicationAuthentication(
                    "clientId",
                    "secret",
                    new NewAuthorization { Note = "Was it this one?" },
                    _ => Observable.Return(twoFactorChallengeResult));

                Assert.Equal("OAUTHSECRET", result.Token);
                client.Received().GetOrCreateApplicationAuthentication(
                    "clientId", "secret", Arg.Is<NewAuthorization>(a => a.Note == "Was it this one?"));
                client.Received().GetOrCreateApplicationAuthentication(
                    "clientId", "secret", Arg.Is<NewAuthorization>(a => a.Note == "Was it this one?"),
                    "two-factor-code");
            }
            public async Task RetriesWhenResendRequested()
            {
                var firstResponse = new TwoFactorRequiredException(TwoFactorType.AuthenticatorApp);
                var challengeResults = new Queue<TwoFactorChallengeResult>(new[]
                {
                    TwoFactorChallengeResult.RequestResendCode,
                    new TwoFactorChallengeResult("two-factor-code")
                });
                var secondResponse = new ApplicationAuthorization("OAUTHSECRET");

                var client = Substitute.For<IObservableAuthorizationsClient>();
                client.GetOrCreateApplicationAuthentication(Args.String, Args.String, Args.NewAuthorization)
                    .Returns(Observable.Throw<ApplicationAuthorization>(firstResponse));
                client.GetOrCreateApplicationAuthentication(
                    Args.String,
                    Args.String,
                    Args.NewAuthorization,
                    "two-factor-code")
                    .Returns(Observable.Return(secondResponse));

                var result = await client.GetOrCreateApplicationAuthentication(
                    "clientId",
                    "secret",
                    new NewAuthorization { Note = "Was it this one?" },
                    _ => Observable.Return(challengeResults.Dequeue()));

                client.Received(2).GetOrCreateApplicationAuthentication("clientId",
                    "secret",
                    Arg.Any<NewAuthorization>());
                client.Received().GetOrCreateApplicationAuthentication("clientId",
                    "secret",
                    Arg.Any<NewAuthorization>(), "two-factor-code");
                Assert.Equal("OAUTHSECRET", result.Token);
            }
Example #3
0
            public async Task RetriesWhenResendRequested()
            {
                var firstResponse    = new TwoFactorRequiredException(TwoFactorType.AuthenticatorApp);
                var challengeResults = new Queue <TwoFactorChallengeResult>(new[]
                {
                    TwoFactorChallengeResult.RequestResendCode,
                    new TwoFactorChallengeResult("two-factor-code")
                });
                var secondResponse = new ApplicationAuthorization(0, null, null, null, null, null, null, null, DateTimeOffset.Now, DateTimeOffset.Now, null, "OAUTHSECRET");

                var client = Substitute.For <IObservableAuthorizationsClient>();

                client.GetOrCreateApplicationAuthentication(Args.String, Args.String, Args.NewAuthorization)
                .Returns(Observable.Throw <ApplicationAuthorization>(firstResponse));
                client.GetOrCreateApplicationAuthentication(
                    Args.String,
                    Args.String,
                    Args.NewAuthorization,
                    "two-factor-code")
                .Returns(Observable.Return(secondResponse));

                var result = await client.GetOrCreateApplicationAuthentication(
                    "clientId",
                    "secret",
                    new NewAuthorization { Note = "Was it this one?" },
                    _ => Observable.Return(challengeResults.Dequeue()));

                client.Received(2).GetOrCreateApplicationAuthentication("clientId",
                                                                        "secret",
                                                                        Arg.Any <NewAuthorization>());
                client.Received().GetOrCreateApplicationAuthentication("clientId",
                                                                       "secret",
                                                                       Arg.Any <NewAuthorization>(), "two-factor-code");
                Assert.Equal("OAUTHSECRET", result.Token);
            }
Example #4
0
            public async Task UsesCallbackToRetrieveTwoFactorCode()
            {
                var firstResponse            = new TwoFactorRequiredException(TwoFactorType.AuthenticatorApp);
                var twoFactorChallengeResult = new TwoFactorChallengeResult("two-factor-code");
                var secondResponse           = new ApplicationAuthorization(0, null, null, null, null, null, null, null, DateTimeOffset.Now, DateTimeOffset.Now, null, "OAUTHSECRET");

                var client = Substitute.For <IObservableAuthorizationsClient>();

                client.GetOrCreateApplicationAuthentication(Args.String, Args.String, Args.NewAuthorization)
                .Returns(Observable.Throw <ApplicationAuthorization>(firstResponse));
                client.GetOrCreateApplicationAuthentication(
                    Args.String,
                    Args.String,
                    Args.NewAuthorization,
                    "two-factor-code")
                .Returns(Observable.Return(secondResponse));

                var result = await client.GetOrCreateApplicationAuthentication(
                    "clientId",
                    "secret",
                    new NewAuthorization { Note = "Was it this one?" },
                    _ => Observable.Return(twoFactorChallengeResult));

                Assert.Equal("OAUTHSECRET", result.Token);
                client.Received().GetOrCreateApplicationAuthentication(
                    "clientId", "secret", Arg.Is <NewAuthorization>(a => a.Note == "Was it this one?"));
                client.Received().GetOrCreateApplicationAuthentication(
                    "clientId", "secret", Arg.Is <NewAuthorization>(a => a.Note == "Was it this one?"),
                    "two-factor-code");
            }
Example #5
0
        /// <inheritdoc/>
        public async Task <User> Login(
            HostAddress hostAddress,
            IGitHubClient client,
            string userName,
            string password)
        {
            Guard.ArgumentNotNull(hostAddress, nameof(hostAddress));
            Guard.ArgumentNotNull(client, nameof(client));
            Guard.ArgumentNotEmptyString(userName, nameof(userName));
            Guard.ArgumentNotEmptyString(password, nameof(password));

            // Start by saving the username and password, these will be used by the `IGitHubClient`
            // until an authorization token has been created and acquired:
            await keychain.Save(userName, password, hostAddress).ConfigureAwait(false);

            var newAuth = new NewAuthorization
            {
                Scopes      = scopes,
                Note        = authorizationNote,
                Fingerprint = fingerprint,
            };

            ApplicationAuthorization auth = null;

            do
            {
                try
                {
                    auth = await CreateAndDeleteExistingApplicationAuthorization(client, newAuth, null)
                           .ConfigureAwait(false);

                    EnsureNonNullAuthorization(auth);
                }
                catch (TwoFactorAuthorizationException e)
                {
                    auth = await HandleTwoFactorAuthorization(hostAddress, client, newAuth, e)
                           .ConfigureAwait(false);
                }
                catch (Exception e)
                {
                    // Some enterpise instances don't support OAUTH, so fall back to using the
                    // supplied password - on intances that don't support OAUTH the user should
                    // be using a personal access token as the password.
                    if (EnterpriseWorkaround(hostAddress, e))
                    {
                        auth = new ApplicationAuthorization(password);
                    }
                    else
                    {
                        await keychain.Delete(hostAddress).ConfigureAwait(false);

                        throw;
                    }
                }
            } while (auth == null);

            await keychain.Save(userName, auth.Token, hostAddress).ConfigureAwait(false);

            return(await ReadUserWithRetry(client));
        }
        public async Task UpdateAsync(ApplicationAuthorization update, CancellationToken cancellationToken)
        {
            var resource = update;
            var entity   =
                await _context.ApplicationAuthorizations.FirstOrDefaultAsync(r => r.Id == update.Id, cancellationToken);

            if (entity != null)
            {
                entity.Id           = resource.Id;
                entity.Application  = resource.Application;
                entity.Scopes       = resource.Scopes;
                entity.Status       = resource.Status;
                entity.Subject      = resource.Subject;
                entity.CreationDate = resource.CreationDate;
                entity.Type         = resource.Type;
            }

            try
            {
                await _context.SaveChangesAsync(cancellationToken);
            }
            catch (DbUpdateException e)
            {
                Log.Logger.Error(e.Message);
                throw;
            }
        }
        ApplicationAuthorization EnsureNonNullAuthorization(ApplicationAuthorization auth)
        {
            // If a mock IGitHubClient is not set up correctly, it can return null from
            // IGutHubClient.Authorization.Create - this will cause an infinite loop in Login()
            // so prevent that.
            if (auth == null)
            {
                throw new InvalidOperationException("IGutHubClient.Authorization.Create returned null.");
            }

            return(auth);
        }
Example #8
0
 internal BaseActionReturnModel AddApplicationAuthorization(ApplicationAuthorization AdminAuth)
 {
     try
     {
         // do thing
         ctx.ApplicationAuthorizations.Add(AdminAuth);
         return(BaseActionReturnModel.CreateSuccededResult("OK", false, null, false));
     }
     catch (Exception exc)
     {
         return(BaseActionReturnModel.CreateException(exc, false));
     }
 }
        public async Task CreateAsync(ApplicationAuthorization resource, CancellationToken cancellationToken)
        {
            var newResource = resource;

            newResource.CreationDate = DateTime.UtcNow;

            try
            {
                await _context.ApplicationAuthorizations.AddAsync(newResource, cancellationToken);

                await _context.SaveChangesAsync(cancellationToken);
            }
            catch (DbUpdateException e)
            {
                Log.Logger.Error(e.Message);
                throw;
            }
        }
Example #10
0
        /// <inheritdoc/>
        public async Task <User> Login(
            HostAddress hostAddress,
            IGitHubClient client,
            string userName,
            string password)
        {
            Guard.ArgumentNotNull(hostAddress, nameof(hostAddress));
            Guard.ArgumentNotNull(client, nameof(client));
            Guard.ArgumentNotEmptyString(userName, nameof(userName));
            Guard.ArgumentNotEmptyString(password, nameof(password));

            // Start by saving the username and password, these will be used by the `IGitHubClient`
            // until an authorization token has been created and acquired:
            await keychain.Save(userName, password, hostAddress).ConfigureAwait(false);

            var newAuth = new NewAuthorization
            {
                Scopes      = scopes,
                Note        = authorizationNote,
                Fingerprint = fingerprint,
            };

            ApplicationAuthorization auth = null;

            do
            {
                try
                {
                    auth = await CreateAndDeleteExistingApplicationAuthorization(client, newAuth, null)
                           .ConfigureAwait(false);

                    EnsureNonNullAuthorization(auth);
                }
                catch (TwoFactorAuthorizationException e)
                {
                    auth = await HandleTwoFactorAuthorization(hostAddress, client, newAuth, e)
                           .ConfigureAwait(false);
                }
                catch (Exception e)
                {
                    // Some enterpise instances don't support OAUTH, so fall back to using the
                    // supplied password - on intances that don't support OAUTH the user should
                    // be using a personal access token as the password.
                    if (EnterpriseWorkaround(hostAddress, e))
                    {
                        auth = new ApplicationAuthorization(password);
                    }
                    else
                    {
                        await keychain.Delete(hostAddress).ConfigureAwait(false);

                        throw;
                    }
                }
            } while (auth == null);

            await keychain.Save(userName, auth.Token, hostAddress).ConfigureAwait(false);

            var retry = 0;

            while (true)
            {
                try
                {
                    return(await client.User.Current().ConfigureAwait(false));
                }
                catch (AuthorizationException)
                {
                    if (retry++ == 3)
                    {
                        throw;
                    }
                }

                // It seems that attempting to use a token immediately sometimes fails, retry a few
                // times with a delay of of 1s to allow the token to propagate.
                await Task.Delay(1000);
            }
        }
Example #11
0
        public static void SeedAdminUser(SecurityDataContext db)
        {
            // 2 managers sharing the same DBContext coming from Seed methde implementation
            ApplicationUserManager       userManager   = new ApplicationUserManager(new UserStore <ApplicationUser>(db));
            SecurityConfigurationManager ConfigManager = new SecurityConfigurationManager(db);

            const string name     = AppConfig.AdminName;
            const string mail     = AppConfig.AdminEmail;
            const string password = AppConfig.AdminPassword;


            var user = userManager.FindByName(name);

            if (user != null)
            {
                userManager.Delete(user);
            }

            user = new ApplicationUser {
                UserName = name, Email = mail
            };
            user.EmailConfirmed = true;
            IdentityResult result = userManager.Create(user, password);

            result = userManager.SetLockoutEnabled(user.Id, false);

            // Seed admin Authorizations
            ApplicationAuthorization AdminAuth = new ApplicationAuthorization();

            AdminAuth.Code        = AuthorizationCode.SuperAdmin;
            AdminAuth.Description = "All access from all client type";
            AdminAuth.Name        = "SuperAdmin";
            ConfigManager.AddApplicationAuthorization(AdminAuth);


            //Seed default ClientApplications
            ClientApplication WPFApp = new ClientApplication();

            WPFApp.ApplicationDescription = "WPF client application";
            WPFApp.ApplicationCode        = "WPF";
            WPFApp.ApplicationSecret      = "WPF123";
            ConfigManager.AddClientApplication(WPFApp);
            userManager.AuthorizeApplicationtoClient(WPFApp, user, db);

            ClientApplication WebApp = new ClientApplication();

            WebApp.ApplicationDescription = "WEB client application";
            WebApp.ApplicationCode        = "WEB";
            WebApp.ApplicationSecret      = "WEB123";
            ConfigManager.AddClientApplication(WebApp);
            userManager.AuthorizeApplicationtoClient(WebApp, user, db);

            ClientApplication WStoreApp = new ClientApplication();

            WStoreApp.ApplicationDescription = "WStore client application";
            WStoreApp.ApplicationCode        = "WStore";
            WStoreApp.ApplicationSecret      = "WStore123";
            ConfigManager.AddClientApplication(WStoreApp);
            userManager.AuthorizeApplicationtoClient(WStoreApp, user, db);

            // Assign ClientAutorisation to user
            userManager.AssignAuthForClientAppToUser(AdminAuth, WPFApp, user, db);
            userManager.AssignAuthForClientAppToUser(AdminAuth, WebApp, user, db);
            userManager.AssignAuthForClientAppToUser(AdminAuth, WStoreApp, user, db);
        }
Example #12
0
        /// <inheritdoc/>
        public async Task <LoginResultData> Login(
            UriString host,
            IGitHubClient client,
            string username,
            string password)
        {
            Guard.ArgumentNotNull(host, nameof(host));
            Guard.ArgumentNotNull(client, nameof(client));
            Guard.ArgumentNotNullOrWhiteSpace(username, nameof(username));
            Guard.ArgumentNotNullOrWhiteSpace(password, nameof(password));

            // Start by saving the username and password, these will be used by the `IGitHubClient`
            // until an authorization token has been created and acquired:
            keychain.Connect(host);
            keychain.SetCredentials(new Credential(host, username, password));

            var newAuth = new NewAuthorization
            {
                Scopes      = scopes,
                Note        = authorizationNote,
                Fingerprint = fingerprint,
            };

            ApplicationAuthorization auth = null;

            try
            {
                logger.Info("Login Username:{0}", username);

                auth = await CreateAndDeleteExistingApplicationAuthorization(client, newAuth, null);

                EnsureNonNullAuthorization(auth);
            }
            catch (TwoFactorAuthorizationException e)
            {
                LoginResultCodes result;
                if (e is TwoFactorRequiredException)
                {
                    result = LoginResultCodes.CodeRequired;
                    logger.Debug("2FA TwoFactorAuthorizationException: {0} {1}", LoginResultCodes.CodeRequired, e.Message);
                }
                else
                {
                    result = LoginResultCodes.CodeFailed;
                    logger.Error(e, "2FA TwoFactorAuthorizationException: {0} {1}", LoginResultCodes.CodeRequired, e.Message);
                }

                return(new LoginResultData(result, e.Message, client, host, newAuth));
            }
            catch (LoginAttemptsExceededException e)
            {
                logger.Warning(e, "Login LoginAttemptsExceededException: {0}", e.Message);

                await keychain.Clear(host, false);

                return(new LoginResultData(LoginResultCodes.LockedOut, Localization.LockedOut, host));
            }
            catch (ApiValidationException e)
            {
                logger.Warning(e, "Login ApiValidationException: {0}", e.Message);

                var message = e.ApiError.FirstErrorMessageSafe();
                await keychain.Clear(host, false);

                return(new LoginResultData(LoginResultCodes.Failed, message, host));
            }
            catch (Exception e)
            {
                logger.Warning(e, "Login Exception");

                // Some enterprise instances don't support OAUTH, so fall back to using the
                // supplied password - on instances that don't support OAUTH the user should
                // be using a personal access token as the password.
                if (EnterpriseWorkaround(host, e))
                {
                    auth = new ApplicationAuthorization(password);
                }
                else
                {
                    await keychain.Clear(host, false);

                    return(new LoginResultData(LoginResultCodes.Failed, Localization.LoginFailed, host));
                }
            }

            keychain.SetToken(host, auth.Token);
            await keychain.Save(host);

            return(new LoginResultData(LoginResultCodes.Success, "Success", host));
        }
 private static void AssertValidApplicationDefinition(ApplicationDefinition model, ApplicationDefinition getResult)
 {
     Assert.AreEqual(model.Data.Name, getResult.Data.Name);
     Assert.AreEqual(model.Data.Id, getResult.Data.Id);
     Assert.AreEqual(model.Data.Type, getResult.Data.Type);
     Assert.AreEqual(model.Data.LockLevel, getResult.Data.LockLevel);
     Assert.AreEqual(model.Data.DisplayName, getResult.Data.DisplayName);
     Assert.AreEqual(model.Data.IsEnabled, getResult.Data.IsEnabled);
     Assert.AreEqual(model.Data.Authorizations, getResult.Data.Authorizations);
     if (model.Data.Authorizations != null || getResult.Data.Authorizations != null)
     {
         Assert.NotNull(model.Data.Authorizations);
         Assert.NotNull(getResult.Data.Authorizations);
         Assert.AreEqual(model.Data.Authorizations.Count, getResult.Data.Authorizations.Count);
         for (int i = 0; i < model.Data.Authorizations.Count; ++i)
         {
             ApplicationAuthorization modelAuthorizations = model.Data.Authorizations[i], getResultAuthorizations = getResult.Data.Authorizations[i];
             AssertValidAuthorizations(modelAuthorizations, getResultAuthorizations);
         }
     }
     if (model.Data.Artifacts != null || getResult.Data.Artifacts != null)
     {
         Assert.NotNull(model.Data.Artifacts);
         Assert.NotNull(getResult.Data.Artifacts);
         Assert.AreEqual(model.Data.Artifacts.Count, getResult.Data.Artifacts.Count);
         for (int i = 0; i < model.Data.Artifacts.Count; ++i)
         {
             ApplicationDefinitionArtifact modelArtifacts = model.Data.Artifacts[i], getResultArtifacts = getResult.Data.Artifacts[i];
             AssertValidArtifacts(modelArtifacts, getResultArtifacts);
         }
     }
     Assert.AreEqual(model.Data.Description, getResult.Data.Description);
     Assert.AreEqual(model.Data.PackageFileUri, getResult.Data.PackageFileUri);
     Assert.AreEqual(model.Data.MainTemplate, getResult.Data.MainTemplate);
     Assert.AreEqual(model.Data.CreateUiDefinition, getResult.Data.CreateUiDefinition);
     if (model.Data.NotificationPolicy != null || getResult.Data.NotificationPolicy != null)
     {
         Assert.NotNull(model.Data.NotificationPolicy);
         Assert.NotNull(getResult.Data.NotificationPolicy);
         if (model.Data.NotificationPolicy.NotificationEndpoints != null || getResult.Data.NotificationPolicy.NotificationEndpoints != null)
         {
             Assert.NotNull(model.Data.NotificationPolicy.NotificationEndpoints);
             Assert.NotNull(getResult.Data.NotificationPolicy.NotificationEndpoints);
             Assert.AreEqual(model.Data.NotificationPolicy.NotificationEndpoints.Count, getResult.Data.NotificationPolicy.NotificationEndpoints.Count);
             for (int i = 0; i < model.Data.NotificationPolicy.NotificationEndpoints.Count; ++i)
             {
                 Assert.AreEqual(model.Data.NotificationPolicy.NotificationEndpoints[i].Uri, getResult.Data.NotificationPolicy.NotificationEndpoints[i].Uri);
             }
         }
     }
     if (model.Data.LockingPolicy != null || getResult.Data.LockingPolicy != null)
     {
         Assert.NotNull(model.Data.LockingPolicy);
         Assert.NotNull(getResult.Data.LockingPolicy);
         if (model.Data.LockingPolicy.AllowedActions != null || getResult.Data.LockingPolicy.AllowedActions != null)
         {
             Assert.NotNull(model.Data.LockingPolicy.AllowedActions);
             Assert.NotNull(getResult.Data.LockingPolicy.AllowedActions);
             Assert.AreEqual(model.Data.LockingPolicy.AllowedActions.Count, getResult.Data.LockingPolicy.AllowedActions.Count);
             for (int i = 0; i < model.Data.LockingPolicy.AllowedActions.Count; ++i)
             {
                 Assert.AreEqual(model.Data.LockingPolicy.AllowedActions[i], getResult.Data.LockingPolicy.AllowedActions[i]);
             }
         }
     }
     if (model.Data.DeploymentPolicy != null || getResult.Data.DeploymentPolicy != null)
     {
         Assert.NotNull(model.Data.DeploymentPolicy);
         Assert.NotNull(getResult.Data.DeploymentPolicy);
         Assert.AreEqual(model.Data.DeploymentPolicy.DeploymentMode, getResult.Data.DeploymentPolicy.DeploymentMode);
     }
     if (model.Data.ManagementPolicy != null || getResult.Data.ManagementPolicy != null)
     {
         Assert.NotNull(model.Data.ManagementPolicy);
         Assert.NotNull(getResult.Data.ManagementPolicy);
         Assert.AreEqual(model.Data.ManagementPolicy.Mode, getResult.Data.ManagementPolicy.Mode);
     }
     if (model.Data.Policies != null || getResult.Data.Policies != null)
     {
         Assert.NotNull(model.Data.Policies);
         Assert.NotNull(getResult.Data.Policies);
         Assert.AreEqual(model.Data.Policies.Count, getResult.Data.Policies.Count);
         for (int i = 0; i < model.Data.Policies.Count; ++i)
         {
             ApplicationPolicy policy = model.Data.Policies[i], getPolicy = getResult.Data.Policies[i];
             AssertValidPolicy(policy, getPolicy);
         }
     }
 }
 private static void AssertValidAuthorizations(ApplicationAuthorization model, ApplicationAuthorization getResult)
 {
     Assert.AreEqual(model.PrincipalId, getResult.PrincipalId);
     Assert.AreEqual(model.RoleDefinitionId, getResult.RoleDefinitionId);
 }
Example #15
0
        internal static ApplicationDefinitionData DeserializeApplicationDefinitionData(JsonElement element)
        {
            Optional <string>            managedBy = default;
            Optional <SkuAutoGenerated>  sku       = default;
            IDictionary <string, string> tags      = default;
            Location             location          = default;
            ResourceIdentifier   id          = default;
            string               name        = default;
            ResourceType         type        = default;
            ApplicationLockLevel lockLevel   = default;
            Optional <string>    displayName = default;
            Optional <bool>      isEnabled   = default;
            Optional <IList <ApplicationAuthorization> >      authorizations = default;
            Optional <IList <ApplicationDefinitionArtifact> > artifacts      = default;
            Optional <string> description        = default;
            Optional <string> packageFileUri     = default;
            Optional <object> mainTemplate       = default;
            Optional <object> createUiDefinition = default;
            Optional <ApplicationNotificationPolicy>             notificationPolicy = default;
            Optional <ApplicationPackageLockingPolicyDefinition> lockingPolicy      = default;
            Optional <ApplicationDeploymentPolicy> deploymentPolicy = default;
            Optional <ApplicationManagementPolicy> managementPolicy = default;
            Optional <IList <ApplicationPolicy> >  policies         = default;

            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("managedBy"))
                {
                    managedBy = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("sku"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    sku = SkuAutoGenerated.DeserializeSkuAutoGenerated(property.Value);
                    continue;
                }
                if (property.NameEquals("tags"))
                {
                    Dictionary <string, string> dictionary = new Dictionary <string, string>();
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        dictionary.Add(property0.Name, property0.Value.GetString());
                    }
                    tags = dictionary;
                    continue;
                }
                if (property.NameEquals("location"))
                {
                    location = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("id"))
                {
                    id = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("type"))
                {
                    type = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("properties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        if (property0.NameEquals("lockLevel"))
                        {
                            lockLevel = property0.Value.GetString().ToApplicationLockLevel();
                            continue;
                        }
                        if (property0.NameEquals("displayName"))
                        {
                            displayName = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("isEnabled"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            isEnabled = property0.Value.GetBoolean();
                            continue;
                        }
                        if (property0.NameEquals("authorizations"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List <ApplicationAuthorization> array = new List <ApplicationAuthorization>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(ApplicationAuthorization.DeserializeApplicationAuthorization(item));
                            }
                            authorizations = array;
                            continue;
                        }
                        if (property0.NameEquals("artifacts"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List <ApplicationDefinitionArtifact> array = new List <ApplicationDefinitionArtifact>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(ApplicationDefinitionArtifact.DeserializeApplicationDefinitionArtifact(item));
                            }
                            artifacts = array;
                            continue;
                        }
                        if (property0.NameEquals("description"))
                        {
                            description = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("packageFileUri"))
                        {
                            packageFileUri = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("mainTemplate"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            mainTemplate = property0.Value.GetObject();
                            continue;
                        }
                        if (property0.NameEquals("createUiDefinition"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            createUiDefinition = property0.Value.GetObject();
                            continue;
                        }
                        if (property0.NameEquals("notificationPolicy"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            notificationPolicy = ApplicationNotificationPolicy.DeserializeApplicationNotificationPolicy(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("lockingPolicy"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            lockingPolicy = ApplicationPackageLockingPolicyDefinition.DeserializeApplicationPackageLockingPolicyDefinition(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("deploymentPolicy"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            deploymentPolicy = ApplicationDeploymentPolicy.DeserializeApplicationDeploymentPolicy(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("managementPolicy"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            managementPolicy = ApplicationManagementPolicy.DeserializeApplicationManagementPolicy(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("policies"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List <ApplicationPolicy> array = new List <ApplicationPolicy>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(ApplicationPolicy.DeserializeApplicationPolicy(item));
                            }
                            policies = array;
                            continue;
                        }
                    }
                    continue;
                }
            }
            return(new ApplicationDefinitionData(id, name, type, tags, location, managedBy.Value, sku.Value, lockLevel, displayName.Value, Optional.ToNullable(isEnabled), Optional.ToList(authorizations), Optional.ToList(artifacts), description.Value, packageFileUri.Value, mainTemplate.Value, createUiDefinition.Value, notificationPolicy.Value, lockingPolicy.Value, deploymentPolicy.Value, managementPolicy.Value, Optional.ToList(policies)));
        }
Example #16
0
        internal static ApplicationData DeserializeApplicationData(JsonElement element)
        {
            Optional <Plan> plan = default;
            string          kind = default;
            Optional <IdentityAutoGenerated> identity                           = default;
            Optional <string>            managedBy                              = default;
            Optional <SkuAutoGenerated>  sku                                    = default;
            IDictionary <string, string> tags                                   = default;
            Location                     location                               = default;
            ResourceIdentifier           id                                     = default;
            string                       name                                   = default;
            ResourceType                 type                                   = default;
            Optional <string>            managedResourceGroupId                 = default;
            Optional <string>            applicationDefinitionId                = default;
            Optional <object>            parameters                             = default;
            Optional <object>            outputs                                = default;
            Optional <ProvisioningState> provisioningState                      = default;
            Optional <ApplicationBillingDetailsDefinition> billingDetails       = default;
            Optional <ApplicationJitAccessPolicy>          jitAccessPolicy      = default;
            Optional <string> publisherTenantId                                 = default;
            Optional <IReadOnlyList <ApplicationAuthorization> > authorizations = default;
            Optional <ApplicationManagementMode>            managementMode      = default;
            Optional <ApplicationPackageContact>            customerSupport     = default;
            Optional <ApplicationPackageSupportUrls>        supportUrls         = default;
            Optional <IReadOnlyList <ApplicationArtifact> > artifacts           = default;
            Optional <ApplicationClientDetails>             createdBy           = default;
            Optional <ApplicationClientDetails>             updatedBy           = default;

            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("plan"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    plan = JsonSerializer.Deserialize <Plan>(property.Value.ToString());
                    continue;
                }
                if (property.NameEquals("kind"))
                {
                    kind = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("identity"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    identity = IdentityAutoGenerated.DeserializeIdentityAutoGenerated(property.Value);
                    continue;
                }
                if (property.NameEquals("managedBy"))
                {
                    managedBy = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("sku"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    sku = SkuAutoGenerated.DeserializeSkuAutoGenerated(property.Value);
                    continue;
                }
                if (property.NameEquals("tags"))
                {
                    Dictionary <string, string> dictionary = new Dictionary <string, string>();
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        dictionary.Add(property0.Name, property0.Value.GetString());
                    }
                    tags = dictionary;
                    continue;
                }
                if (property.NameEquals("location"))
                {
                    location = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("id"))
                {
                    id = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("type"))
                {
                    type = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("properties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        if (property0.NameEquals("managedResourceGroupId"))
                        {
                            managedResourceGroupId = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("applicationDefinitionId"))
                        {
                            applicationDefinitionId = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("parameters"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            parameters = property0.Value.GetObject();
                            continue;
                        }
                        if (property0.NameEquals("outputs"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            outputs = property0.Value.GetObject();
                            continue;
                        }
                        if (property0.NameEquals("provisioningState"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            provisioningState = new ProvisioningState(property0.Value.GetString());
                            continue;
                        }
                        if (property0.NameEquals("billingDetails"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            billingDetails = ApplicationBillingDetailsDefinition.DeserializeApplicationBillingDetailsDefinition(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("jitAccessPolicy"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            jitAccessPolicy = ApplicationJitAccessPolicy.DeserializeApplicationJitAccessPolicy(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("publisherTenantId"))
                        {
                            publisherTenantId = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("authorizations"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List <ApplicationAuthorization> array = new List <ApplicationAuthorization>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(ApplicationAuthorization.DeserializeApplicationAuthorization(item));
                            }
                            authorizations = array;
                            continue;
                        }
                        if (property0.NameEquals("managementMode"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            managementMode = new ApplicationManagementMode(property0.Value.GetString());
                            continue;
                        }
                        if (property0.NameEquals("customerSupport"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            customerSupport = ApplicationPackageContact.DeserializeApplicationPackageContact(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("supportUrls"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            supportUrls = ApplicationPackageSupportUrls.DeserializeApplicationPackageSupportUrls(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("artifacts"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List <ApplicationArtifact> array = new List <ApplicationArtifact>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(ApplicationArtifact.DeserializeApplicationArtifact(item));
                            }
                            artifacts = array;
                            continue;
                        }
                        if (property0.NameEquals("createdBy"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            createdBy = ApplicationClientDetails.DeserializeApplicationClientDetails(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("updatedBy"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            updatedBy = ApplicationClientDetails.DeserializeApplicationClientDetails(property0.Value);
                            continue;
                        }
                    }
                    continue;
                }
            }
            return(new ApplicationData(id, name, type, tags, location, managedBy.Value, sku.Value, plan, kind, identity.Value, managedResourceGroupId.Value, applicationDefinitionId.Value, parameters.Value, outputs.Value, Optional.ToNullable(provisioningState), billingDetails.Value, jitAccessPolicy.Value, publisherTenantId.Value, Optional.ToList(authorizations), Optional.ToNullable(managementMode), customerSupport.Value, supportUrls.Value, Optional.ToList(artifacts), createdBy.Value, updatedBy.Value));
        }