public AccountController(ApplicationSignInManager applicationSignInManager, AccountUserManager accountUserManager,
                          IAuthenticationManager authenticationManager)
 {
     this.authenticationManager    = authenticationManager;
     this.accountUserManager       = accountUserManager;
     this.applicationSignInManager = applicationSignInManager;
 }
Beispiel #2
0
        public DataAccessResponseType SendEmailToUser(string userId, string fromName, string fromEmail, string emailSubject, string emailMessage, bool isImportant, string requesterId, RequesterType requesterType, string sharedClientKey)
        {
            // Ensure the clients are certified.
            if (sharedClientKey != Sahara.Core.Platform.Requests.RequestManager.SharedClientKey)
            {
                return(null);
            }

            #region Validate Request

            var requesterName  = string.Empty;
            var requesterEmail = string.Empty;

            var requestResponseType = RequestManager.ValidateRequest(requesterId,
                                                                     requesterType, out requesterName, out requesterEmail,
                                                                     Sahara.Core.Settings.Platform.Users.Authorization.Roles.Admin,
                                                                     null); //<-- Only PlatformUsers can send notifications

            if (!requestResponseType.isApproved)
            {
                //Request is not approved, send results:
                return(new DataAccessResponseType {
                    isSuccess = false, ErrorMessage = requestResponseType.requestMessage
                });
            }

            #endregion

            return(AccountUserManager.SendEmailToUser(userId, fromName, fromEmail, emailSubject, emailMessage, isImportant));
        }
Beispiel #3
0
        public static ConstraintResponseType CheckUserConstraint(string accountId)
        {
            var response = new ConstraintResponseType {
                isConstrained = false
            };

            // Get the Account & the associated Plan:
            var account = AccountManager.GetAccount(accountId);
            var plan    = PaymentPlanManager.GetPaymentPlan(account.PaymentPlanName);

            int maxUsers = plan.MaxUsers;

            int userCount       = account.Users.Count;
            int invitationCount = AccountUserManager.GetInvitations(accountId, account.StoragePartition).Count;

            int totalAssociatedUsers = (userCount + invitationCount) - 1; //<--Offset by 1 to hide: platformadmin@[Config_PlatformEmail]  LEGACY: //<-- We remove 1 user from the validation as the account creator does not count in the constraint

            if (maxUsers <= totalAssociatedUsers)
            {
                response.isConstrained     = true;
                response.constraintMessage = "You have reached your limit of " + maxUsers + " users.";
            }


            return(response);
        }
        internal static void ClearAssociatedAccountAndUserListCaches(string accountId)
        {
            //Update user list cache for this account for next call (we do this first so it is available to Account:
            AccountUserManager.GetUsers(accountId, false);

            //We refresh this last so the above user list is already cached.
            Internal.AccountCaching.UpdateAccountDetailCache(accountId);
        }
        /// <summary>
        /// Used by AccountManager to clear all user caches on an account after an Account update
        /// </summary>
        /// <param name="accountId"></param>
        internal static void ClearAllUserCaches(string accountId)
        {
            var users = AccountUserManager.GetUsers(accountId);

            foreach (var user in users)
            {
                DeleteAllUserCacheReferences(AccountUserManager.GetUser(user.Id));
            }
        }
        //------------ Delete Account And Users ------

        internal static DataAccessResponseType DeleteAllAccountUsers(Account account)
        {
            var response = new DataAccessResponseType();

            foreach (AccountUser user in account.Users)
            {
                //We ignore verifications, all users will be purged:
                AccountUser outUser = null;
                AccountUserManager.DeleteUser(user.Id, false, out outUser);
            }

            return(response);
        }
Beispiel #7
0
        /// <summary>
        /// Used to get updated claims information on the username.
        /// Can be used when an action is denyed by attempting to check if updated claim will allow the action.
        /// You may also choose a frequency to check for updated claims on the client side.
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public ClaimsIdentity GetClaimsIdentity(string userName, string sharedClientKey)
        {
            // Ensure the clients are certified.
            if (sharedClientKey != Sahara.Core.Platform.Requests.RequestManager.SharedClientKey)
            {
                return(null);
            }

            var accountUserIdentity = AccountUserManager.GetUserIdentity(userName);

            System.Security.Claims.ClaimsIdentity identity = AccountUserManager.GetUserClaimsIdentity(
                accountUserIdentity,
                DefaultAuthenticationTypes.ApplicationCookie); //<-- Uses a cookie for the local web application

            return(identity);
        }
        private static void SeedUsers(DataContext context)
        {
            var store       = new CustomUserStore(context);
            var userManager = new AccountUserManager(store);

            var user1 = new UserAccount {
                UserName = "******", Email = "*****@*****.**"
            };
            var user2 = new UserAccount {
                UserName = "******", Email = "*****@*****.**"
            };

            var profile1 = new Profile {
                Name         = "Jar Jar Binks",
                Age          = 30, Location = "Naboo",
                SearchingFor = "Female",
                Gender       = "Male",
                UserPhoto    = null,
                Description  = "Something about me..",
                Visible      = Visible.Yes,
                UserAccount  = user1
            };

            var profile2 = new Profile
            {
                Name         = "Leia Organa",
                Age          = 45,
                Location     = "Alderaan",
                SearchingFor = "Male",
                Gender       = "Female",
                UserPhoto    = null,
                Description  = "Something about me..",
                Visible      = Visible.Yes,
                UserAccount  = user2
            };

            userManager.CreateAsync(user1, "User1!").Wait();
            userManager.CreateAsync(user2, "User2!").Wait();

            context.Profiles.Add(profile1);
            context.Profiles.Add(profile2);
        }
Beispiel #9
0
        public AuthenticationResponse Authenticate(string accountName, string email, string password, string ipAddress, string origin, string sharedClientKey)
        {
            // Ensure the clients are certified.
            if (sharedClientKey != Sahara.Core.Platform.Requests.RequestManager.SharedClientKey)
            {
                return(null);
            }

            var authResponse = new AuthenticationResponse();

            #region Refactoring Notes

            /*
             * In scenarios where users are only one to an account we make the account name the "UserName"
             * We can then look up the email address associated with the account (or vice versa depending on if it's an email or username login scenario)
             * This lookup data can be cached in Redis
             *
             */

            #endregion

            var result = AccountSecurityManager.AuthenticateUser(accountName, email, password);

            authResponse.isSuccess    = result.isSuccess;
            authResponse.ErrorMessage = result.ErrorMessage;

            if (result.isSuccess)
            {
                //Get the IdentityUser from the ResponseObject:
                var accountUserIdentity = (AccountUserIdentity)result.ResponseObject;


                //Convert to non Identity version & add to response object:
                authResponse.AccountUser = AccountUserManager.TransformAccountUserIdentityToAccountUser(accountUserIdentity);

                //Get Claims based identity for the user
                System.Security.Claims.ClaimsIdentity identity = AccountUserManager.GetUserClaimsIdentity(
                    accountUserIdentity,
                    DefaultAuthenticationTypes.ApplicationCookie); //<-- Uses a cookie for the local web application

                // You can add to claims thusly:
                //identity.AddClaim(new Claim(ClaimTypes.Name, "Name"));

                authResponse.ClaimsIdentity = identity;

                #region Log Account Activity (AuthenticationPassed)

                try
                {
                    var account = AccountManager.GetAccount(authResponse.AccountUser.AccountID.ToString());

                    AccountLogManager.LogActivity(
                        account.AccountID.ToString(),
                        account.StoragePartition,
                        CategoryType.Authentication,
                        ActivityType.Authentication_Passed,
                        "Successfull log in.",
                        authResponse.AccountUser.FirstName + " successfully logged in.",
                        authResponse.AccountUser.Id,
                        authResponse.AccountUser.FirstName,
                        authResponse.AccountUser.Email,
                        ipAddress,
                        origin);
                }
                catch { }

                #endregion
            }
            else
            {
                #region Log Account Activity (AuthenticationFailed)

                try
                {
                    //var accountId = AccountManager.GetAccountID(accountName);
                    var account = AccountManager.GetAccount(accountName);

                    AccountLogManager.LogActivity(
                        account.AccountID.ToString(),
                        account.StoragePartition,
                        CategoryType.Authentication,
                        ActivityType.Authentication_Failed,
                        "An attempt to log into account '" + accountName + "' with email '" + email + "' has failed.",
                        result.ErrorMessage,
                        "Unknown",
                        "Unknown",
                        email,
                        ipAddress,
                        origin);
                }
                catch { }

                #endregion
            }


            return(authResponse);
        }
Beispiel #10
0
 public ApplicationSignInManager(AccountUserManager userAccountManager, IAuthenticationManager authenticationManager)
     : base(userAccountManager, authenticationManager)
 {
 }
Beispiel #11
0
        public static DataAccessResponseType AuthenticateUser(string accountName, string email, string password)
        {
            var response = new DataAccessResponseType();


            #region Refactoring Notes

            /*
             * In scenarios where users are only one to an account we make the account name the "UserName"
             * We can then look up the email address associated with the account (or vice versa depending on if it's an email or username login scenario)
             * This lookup data can be cached in Redis
             *
             */

            #endregion


            //Verifiy all prameters
            if (string.IsNullOrEmpty(accountName))
            {
                response.ErrorMessages.Add("Please include an account name.");
            }
            if (string.IsNullOrEmpty(email))
            {
                response.ErrorMessages.Add("Please include an email.");
            }
            if (string.IsNullOrEmpty(password))
            {
                response.ErrorMessages.Add("Please include a password.");
            }

            if (string.IsNullOrEmpty(accountName) || string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password))
            {
                response.isSuccess    = false;
                response.ErrorMessage = "Not all parameters contain a value!";
                return(response);
            }



            try
            {
                //Get the account associated with the attempted login
                //var account = AccountManager.GetAccountByNameKey(Sahara.Core.Common.AccountNames.ConvertToAccountNameKey(login.AccountName), false);
                var account = AccountManager.GetAccount(accountName, false, AccountManager.AccountIdentificationType.AccountName);


                if (account == null)
                {
                    response.isSuccess    = false;
                    response.ErrorMessage = "This account does not exist.";
                    response.ErrorMessages.Add("This account does not exist.");
                    return(response);
                }

                //Deny access if account is marked for closure/deprovisioning
                if (String.IsNullOrEmpty(account.PaymentPlanName))
                {
                    response.isSuccess    = false;
                    response.ErrorMessage = "This account is closed.";
                    response.ErrorMessages.Add("This account is closed.");
                    return(response);
                }

                //Derive UserName from Email + AccountID
                string globalUniqueUserName = Sahara.Core.Common.Methods.AccountUserNames.GenerateGlobalUniqueUserName(email, account.AccountID.ToString());

                //Get user with 'Login' info (username + password)
                response = AccountUserManager.GetUserWithLogin(globalUniqueUserName, password);

                if (response.isSuccess)
                {
                    var user = (AccountUserIdentity)response.ResponseObject; //<-- ResponseObject can be converted to AccountUser by consuming application

                    //Add the Account object to the user:
                    //user.Account = account;

                    if (!account.Provisioned)
                    {
                        response.isSuccess    = false;
                        response.ErrorMessage = "Account is not yet provisioned.";
                        response.ErrorMessages.Add("Account is not yet provisioned. Please try again after you get notice that provisioning is complete.");
                    }
                    if (!account.Active && account.Activated)
                    {
                        response.isSuccess    = false;
                        response.ErrorMessage = "This account is no longer active.";
                        response.ErrorMessages.Add("This account is no longer active.");
                    }


                    //Validate that the user is active
                    if (!user.Active)
                    {
                        response.isSuccess    = false;
                        response.ErrorMessage = "This user is not currently active.";
                        response.ErrorMessages.Add("This user is not currently active.");
                    }


                    return(response);
                }
                else
                {
                    return(response);
                }
            }
            catch (Exception e)
            {
                //Log exception and email platform admins
                PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                    e,
                    "attempting to authenticate: " + email + " on: " + accountName,
                    System.Reflection.MethodBase.GetCurrentMethod(),
                    null,
                    accountName
                    );



                var exceptionResponse = new DataAccessResponseType();

                exceptionResponse.isSuccess    = false;
                exceptionResponse.ErrorMessage = e.Message;

                return(exceptionResponse);
            }
        }
        public static DataAccessResponseType ProvisionAccount(Account account)
        {
            var response = new DataAccessResponseType();

            #region Pre Provisioning Verification

            bool _documentPartitioning = true;        //<-- If false will skip provisioning DocumentDB resources for accounts
            bool _searchPartitioning   = true;        //<-- If false will skip provisioning Search resources for accounts
            bool _storagePartitioning  = true;        //<-- If false will skip provisioning Search resources for accounts
            bool _sqlPartitioning      = true;        //<-- If false will skip provisioning a SQL Location and SchemeName for accounts

            StoragePartition storagePartition = null; //<-- Chosen partition for this account
            SearchPartition  searchPartition  = null; //<-- Chosen partition for this account

            //Make sure account isn't already provisioned
            if (account.Provisioned)
            {
                response.isSuccess    = false;
                response.ErrorMessage = "Account is already provisioned!";

                return(response);
            }
            if (account.StripeSubscriptionID == null || account.StripeCustomerID == null)
            {
                response.isSuccess    = false;
                response.ErrorMessage = "This account has not been assigned a payment plan or a Stripe CustomerID";

                return(response);
            }

            //If Account object is passed in without users get all/initial user(s):
            if (account.Users == null)
            {
                account.Users = AccountUserManager.GetUsers(account.AccountID.ToString());
            }

            #region Ensure that there is a storage partition available and select next available spot

            if (_storagePartitioning)
            {
                var storagePartitions = StoragePartitioningManager.GetStoragePartitions();


                //Sort with lowest tenant count at the top:
                storagePartitions = storagePartitions.OrderBy(o => o.TenantCount).ToList();

                if (storagePartitions.Count > 0)
                {
                    if (storagePartitions[0].TenantCount >= Settings.Platform.Partitioning.MaximumTenantsPerStorageAccount)
                    {
                        response.isSuccess    = false;
                        response.ErrorMessage = "There are no storage partitions available for this account! Please create one before attempting to provision.";

                        //Reset account to inactive so you can restart partitioning sequence after partition hopper has additional partitions added
                        AccountManager.UpdateAccountActiveState(account.AccountID.ToString(), false);

                        return(response);
                    }
                    else
                    {
                        //Assign storage partition:
                        storagePartition = storagePartitions[0];
                    }
                }
                else
                {
                    response.isSuccess    = false;
                    response.ErrorMessage = "There are no storage partitions available on this platform! Cannot provision any accounts!";

                    //Reset account to inactive so you can restart partitioning sequence after partition hopper has additional partitions added
                    AccountManager.UpdateAccountActiveState(account.AccountID.ToString(), false);

                    return(response);
                }
            }



            #endregion

            #region Ensure that there is a search partition available and select next available spot

            if (_searchPartitioning)
            {
                //Get search plan type for this plan tier
                string searchPlan = account.PaymentPlan.SearchPlan;

                //Get list of search partitions available with this plan type
                var searchPartitions = SearchPartitioningManager.GetSearchPartitions(searchPlan);

                int maxTenantsAllowed = Int32.Parse((searchPlan.Substring(searchPlan.LastIndexOf("-") + 1)));

                /* MAx Tenatnts are now pulled from the SarchPlan name
                 *
                 * int maxTenantsAllowed = 0;
                 *
                 * if(searchPlan == "Basic")
                 * {
                 *  maxTenantsAllowed = Settings.Platform.Partitioning.MaximumTenantsPerBasicSearchServiceShared;
                 * }
                 * else if (searchPlan == "Basic-Dedicated")
                 * {
                 *  maxTenantsAllowed = Settings.Platform.Partitioning.MaximumTenantsPerBasicSearchServiceDedicated;
                 * }
                 * else if(searchPlan == "S1")
                 * {
                 *  maxTenantsAllowed = Settings.Platform.Partitioning.MaximumTenantsPerS1SearchServiceShared;
                 * }
                 * else if (searchPlan == "S1-Dedicated")
                 * {
                 *  maxTenantsAllowed = Settings.Platform.Partitioning.MaximumTenantsPerS1SearchServiceDedicated;
                 * }
                 * else if (searchPlan == "S2")
                 * {
                 *  maxTenantsAllowed = Settings.Platform.Partitioning.MaximumTenantsPerS2SearchServiceShared;
                 * }
                 * else if (searchPlan == "S2-Dedicated")
                 * {
                 *  maxTenantsAllowed = Settings.Platform.Partitioning.MaximumTenantsPerS2SearchServiceDedicated;
                 * }
                 * else if(searchPlan == "Free")
                 * {
                 *  maxTenantsAllowed = Settings.Platform.Partitioning.MaximumTenantsPerFreeSearchService;
                 * }
                 */

                //Sort with lowest tenant count at the top:
                searchPartitions = searchPartitions.OrderBy(o => o.TenantCount).ToList();

                if (searchPartitions.Count > 0)
                {
                    if (searchPartitions[0].TenantCount >= maxTenantsAllowed)
                    {
                        response.isSuccess    = false;
                        response.ErrorMessage = "There are no '" + searchPlan + "' search partitions available for this account! Please create one before attempting to provision.";

                        //Reset account to inactive so you can restart partitioning sequence after partition hopper has additional partitions added
                        AccountManager.UpdateAccountActiveState(account.AccountID.ToString(), false);

                        return(response);
                    }
                    else
                    {
                        //Assign storage partition:
                        searchPartition = searchPartitions[0];
                    }
                }
                else
                {
                    response.isSuccess    = false;
                    response.ErrorMessage = "There are no '" + searchPlan + "' search partitions available on this platform! Cannot provision any accounts!";

                    //Reset account to inactive so you can restart partitioning sequence after partition hopper has additional partitions added
                    AccountManager.UpdateAccountActiveState(account.AccountID.ToString(), false);

                    return(response);
                }
            }



            #endregion

            #endregion

            #region Account Partitioning

            #region Document Database Partitioning (REMOVED)

            if (_documentPartitioning)
            {
                //Connect to the document client & get the database selfLink
                //var client = Sahara.Core.Settings.Azure.DocumentDbClients.AccountDocumentClient;

                //Sahara.Core.Settings.Azure.DocumentDbClients.AccountDocumentClient.OpenAsync().ConfigureAwait(false);
                //Sahara.Core.Settings.Azure.DocumentDbClients.AccountDocumentClient.OpenAsync();

                //var dataBaseSelfLink = Sahara.Core.Settings.Azure.DocumentDB.AccountPartitionDatabaseSelfLink;

                //STEP 1: Get or create the next available document partition for the 'Free' tier
                var partitioningResult = DocumentPartitioningManager.CreateDocumentCollectionAccountPartition(account.AccountNameKey, Sahara.Core.Settings.Azure.DocumentDbClients.AccountDocumentClient, Sahara.Core.Settings.Azure.DocumentDB.AccountPartitionDatabaseId);

                if (partitioningResult.isSuccess == true)
                {
                    DocumentCollection nextAvailablePartitionCollection = (DocumentCollection)partitioningResult.ResponseObject;

                    #region STEP 4: Add Account Settings Document for this account on the collection

                    var       accountSettingsDocumentCreated = false;
                    Exception accountSettingsException       = null;

                    try
                    {
                        var accountSettingsDocument = new AccountSettingsDocumentModel {
                            Id = "AccountSettings"
                        };

                        accountSettingsDocument.ContactSettings             = new ContactSettingsModel();
                        accountSettingsDocument.ContactSettings.ContactInfo = new ContactInfoModel();
                        accountSettingsDocument.SalesSettings = new SalesSettingsModel();

                        //Default LeadLabels
                        accountSettingsDocument.SalesSettings.LeadLabels = new List <string>();
                        accountSettingsDocument.SalesSettings.LeadLabels.Add("New");
                        accountSettingsDocument.SalesSettings.LeadLabels.Add("Archive");
                        accountSettingsDocument.SalesSettings.LeadLabels.Add("Deleted");

                        accountSettingsDocument.Theme = "Light";                                   //<-- Default Theme
                        accountSettingsDocument.SalesSettings.ButtonCopy      = "I'm interested!"; //<-- Default Theme
                        accountSettingsDocument.SalesSettings.DescriptionCopy = "Fill out our contact form and a member of our team will contact you directly.";



                        Sahara.Core.Settings.Azure.DocumentDbClients.AccountDocumentClient.CreateDocumentAsync(nextAvailablePartitionCollection.SelfLink, accountSettingsDocument).ConfigureAwait(false);

                        accountSettingsDocumentCreated = true;
                    }
                    #region Manage Exception & Create Manual Instructions

                    catch (DocumentClientException de)
                    {
                        accountSettingsException = de.GetBaseException();
                    }
                    catch (Exception e)
                    {
                        accountSettingsException = e;
                    }

                    if (!accountSettingsDocumentCreated)
                    {
                        #region Log Exception

                        if (accountSettingsException != null)
                        {
                            PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                                accountSettingsException,
                                "creating an account settings document into a partition during account provisioning",
                                System.Reflection.MethodBase.GetCurrentMethod(),
                                account.AccountID.ToString(),
                                account.AccountName
                                );
                        }


                        #endregion

                        #region Manual Instructions

                        //Not successfull, All tasks within 'GetNextAvailableDocumentPartition' must be run manually
                        PlatformLogManager.LogActivity(
                            CategoryType.ManualTask,
                            ActivityType.ManualTask_DocumentDB,
                            "AccountSettingsDocumentModel file creation failed during account provisioning",
                            "Please create the 'AccountSettingsDocumentModel' document for '" + account.AccountName + "' within the '" + nextAvailablePartitionCollection.Id + "' collection manually.",
                            account.AccountID.ToString(),
                            account.AccountName,
                            null,
                            null,
                            null,
                            null,
                            System.Reflection.MethodBase.GetCurrentMethod().ToString()
                            );

                        #endregion
                    }

                    #endregion

                    #endregion
                }
                else
                {
                    #region Manual Instructions

                    //Not successfull, All tasks within 'GetNextAvailableDocumentPartition' must be run manually
                    PlatformLogManager.LogActivity(
                        CategoryType.ManualTask,
                        ActivityType.ManualTask_Other,
                        "Document partitioning failed during account provisioning",
                        "Please run all tasks under 'DocumentPartitioningManager.GetNextAvailableDocumentPartition('Free', client, dataBaseSelfLink)' as Well as 'if (partitioningResult.isSuccess == true)' manually. This may include creating a new DocumentPartition, updating account DocumentPartitionId and creating an AccountPropertiesDocument for this account into the new partition.",
                        account.AccountID.ToString(),
                        account.AccountName,
                        null,
                        null,
                        null,
                        null,
                        System.Reflection.MethodBase.GetCurrentMethod().ToString()
                        );

                    #endregion
                }

                #region Depricated DocumentDB Code

                /*
                 * try
                 * {
                 *  DocumentClient client = Sahara.Core.Settings.Azure.DocumentDB.DocumentClients.AccountDocumentClient;
                 *  client.OpenAsync(); //<-- By default, the first request will have a higher latency because it has to fetch the address routing table. In order to avoid this startup latency on the first request, you should call OpenAsync() once during initialization as follows.
                 *
                 *
                 *  //Generate Account Database
                 *  Database accountDatabase = client.CreateDatabaseAsync(new Database { Id = account.AccountID.ToString() }).Result;
                 *
                 *
                 *  //Generate "AccountProperties" Collection on the database
                 *  DocumentCollection accountPropertiesCollection = client.CreateDocumentCollectionAsync(accountDatabase.SelfLink, new DocumentCollection { Id = "AccountProperties" }).Result;
                 *
                 *
                 *  //Generate "SelfLinkReferences" Document within AccountProperties" collection
                 *  Document selfLinkReferencesDocument = client.CreateDocumentAsync(accountPropertiesCollection.SelfLink, new SelfLinkReferencesDocumentModel { Id = "SelfLinkReferences" }).Result;
                 *
                 *
                 *  //Store all the SelfLinks
                 *  var documentUpdateResults = Sql.Statements.UpdateStatements.UpdateDocumentDatabaseLinks(account.AccountID.ToString(), accountDatabase.SelfLink, accountPropertiesCollection.SelfLink, selfLinkReferencesDocument.SelfLink);
                 *  if (documentUpdateResults)
                 *  {
                 *
                 *  }
                 *  else
                 *  {
                 *
                 *      var errorMessage = "DocumentDB Selflink insertion into the '" + account.AccountName + "' account has failed";
                 *      var errorDetails = "AccountID: '" + account.AccountID + "' Error: 'DocumentDB resources have been provisioned, but an error occured when updating database columns for the account'";
                 *
                 *      //Log Errors
                 *      PlatformLogManager.LogActivity(
                 *              CategoryType.Error,
                 *              ActivityType.Error_Other,
                 *              errorMessage,
                 *              errorDetails,
                 *              account.AccountID.ToString(),
                 *              account.AccountName
                 *          );
                 *
                 *      return new DataAccessResponseType { isSuccess = false, ErrorMessage = errorMessage };
                 *  }
                 * }
                 * catch (Exception e)
                 * {
                 #region Handle Exception
                 *
                 *  //Log exception and email platform admins
                 *  PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                 *      e,
                 *      "attempting to partition DocumentDB resources for the '" + account.AccountName + "' account during provisioning.",
                 *      System.Reflection.MethodBase.GetCurrentMethod(),
                 *      account.AccountID.ToString(),
                 *      account.AccountName
                 *  );
                 *
                 #endregion
                 * }
                 */

                #endregion
            }

            #endregion

            #region Storage Partitioning

            if (_storagePartitioning)
            {
                /* No longer need to set anything up (Back to document db)
                 *
                 * //Create setings JSON doc in storage (DocumentDB is now OFF)
                 * var accountSettingsDocument = new AccountSettingsDocumentModel { Id = "AccountSettings" };
                 *
                 * accountSettingsDocument.ContactSettings = new ContactSettingsModel();
                 * accountSettingsDocument.ContactSettings.ContactInfo = new ContactInfoModel();
                 * accountSettingsDocument.SalesSettings = new SalesSettingsModel();
                 *
                 * //Default LeadLabels
                 * accountSettingsDocument.SalesSettings.LeadLabels = new List<string>();
                 * accountSettingsDocument.SalesSettings.LeadLabels.Add("New");
                 * accountSettingsDocument.SalesSettings.LeadLabels.Add("Archive");
                 * accountSettingsDocument.SalesSettings.LeadLabels.Add("Deleted");
                 *
                 * accountSettingsDocument.Theme = "Light"; //<-- Default Theme
                 * accountSettingsDocument.SalesSettings.ButtonCopy = "I'm interested!"; //<-- Default Theme
                 * accountSettingsDocument.SalesSettings.DescriptionCopy = "Fill out our contact form and a member of our team will contact you directly.";
                 *
                 * //Save to designated storage account
                 * CloudStorageAccount storageAccount;
                 * StorageCredentials storageCredentials = new StorageCredentials(storagePartition.Name, storagePartition.Key);
                 * storageAccount = new CloudStorageAccount(storageCredentials, false);
                 * CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
                 *
                 * //Create and set retry policy
                 * IRetryPolicy exponentialRetryPolicy = new ExponentialRetry(TimeSpan.FromMilliseconds(400), 6);
                 * blobClient.DefaultRequestOptions.RetryPolicy = exponentialRetryPolicy;
                 *
                 * //Creat/Connect to the Blob Container for this account
                 * blobClient.GetContainerReference(account.AccountNameKey).CreateIfNotExists(BlobContainerPublicAccessType.Blob); //<-- Create and make public
                 *
                 *
                 * CloudBlobContainer blobContainer = blobClient.GetContainerReference(account.AccountNameKey);
                 *
                 * //Get reference to the text blob or create if not exists.
                 * CloudBlockBlob blockBlob = blobContainer.GetBlockBlobReference("settings/" + "accountSettings.json");
                 *
                 * blockBlob.UploadText(JsonConvert.SerializeObject(accountSettingsDocument));
                 *
                 * //Save to storage
                 * //Convert final BMP to byteArray
                 * //Byte[] finalByteArray;
                 *
                 * //finalByteArray = outStream.ToArray();
                 *
                 * //blockBlob.UploadFromByteArray(finalByteArray, 0, finalByteArray.Length);
                 *
                 */
            }

            #endregion

            #region SQL Partitioning

            if (_sqlPartitioning)
            {
                try
                {
                    // 1. Get and assign the next available database partition for this account to be provisioned into:
                    var getAndAssignPartitionResponse = SqlPartitioningManager.GetAndAssignNextAvailableAccountSqlPartition(account.AccountID.ToString());

                    if (getAndAssignPartitionResponse.isSuccess)
                    {
                        string DatabasePartitionName = getAndAssignPartitionResponse.SuccessMessage;

                        // 2. Run creation scripts to provision accounts schema to the selected partition:
                        var generateAccountSchemaResponse = AccountProvisioning.GenerateAccountSchema(account.AccountID.ToString(), DatabasePartitionName);

                        if (generateAccountSchemaResponse.isSuccess)
                        {
                            generateAccountSchemaResponse.SuccessMessage = DatabasePartitionName; //<-- Return the name of the database partition name
                        }
                        else
                        {
                            return(generateAccountSchemaResponse);
                        }
                    }
                    else
                    {
                        return(getAndAssignPartitionResponse);
                    }
                }
                catch (Exception e)
                {
                    #region Handle Exception

                    //Log exception and email platform admins
                    PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                        e,
                        "attempting to partition SQL for the '" + account.AccountName + "' account during provisioning.",
                        System.Reflection.MethodBase.GetCurrentMethod(),
                        account.AccountID.ToString(),
                        account.AccountName
                        );

                    #endregion
                }
            }



            #endregion

            #region Search Partitioning

            if (_searchPartitioning)
            {
                //Create an Product Search Index for this account on the selected search partition ---------------------
                var searchIndexCreated = ProductSearchManager.CreateProductSearchIndex(account.AccountNameKey, searchPartition.Name, searchPartition.Key);
            }

            #endregion

            #endregion

            #region Post Partitioning Tasks

            // 1. Mark the Account as Provisioned, Active and assign a ProvisioningDate:
            var result = Sql.Statements.UpdateStatements.UpdateProvisiongStatus(account.AccountID.ToString(), true, true, storagePartition.Name, searchPartition.Name);


            if (result)
            {
                // 1. Create a platform user account SO we can log into the account for management purposes:
                AccountUserManager.CreateAccountUser(account.AccountID.ToString(), "platformadmin@[Config_PlatformEmail]", "Platform", "Admin", "[Config_PlatformPassword_AzureKeyVault]", Settings.Accounts.Users.Authorization.Roles.PlatformAdmin, true, null, true);

                // 2. Invalidated/Update the cache for this account
                AccountManager.UpdateAccountDetailCache(account.AccountNameKey);

                // 3. Email the creator with sucessful provisioning message and login info:

                /*
                 * EmailManager.Send(
                 *      account.Users[0].Email, //<-- Will only have the initial user
                 *      Settings.Endpoints.Emails.FromProvisioning,
                 *      Settings.Copy.EmailMessages.ProvisioningComplete.FromName,
                 *      Settings.Copy.EmailMessages.ProvisioningComplete.Subject,
                 *      String.Format(Settings.Copy.EmailMessages.ProvisioningComplete.Body, account.AccountNameKey),
                 *      true
                 *  );*/

                // 4. Send an alert to the platform admin(s):
                EmailManager.Send(
                    Settings.Endpoints.Emails.PlatformEmailAddresses,
                    Settings.Endpoints.Emails.FromProvisioning,
                    "Provisioning " + Settings.Application.Name,
                    "Account Provisioned",
                    "<b>'" + account.AccountName + "'</b> has just been provisioned.",
                    true
                    );

                // 5. Log Successfull Provisioning Activity
                PlatformLogManager.LogActivity(CategoryType.Account,
                                               ActivityType.Account_Provisioned,
                                               "Provisioning of '" + account.AccountName + "' has completed",
                                               "AccountID: '" + account.AccountID + "'",
                                               account.AccountID.ToString(), account.AccountName);

                //Register subdomains
                try
                {
                    var cloudFlareResult = CloudFlareManager.RegisterSubdomains(account.AccountNameKey);

                    if (cloudFlareResult.isSuccess == false)
                    {
                        //Log exception and email platform admins
                        PlatformExceptionsHelper.LogErrorAndAlertAdmins(
                            cloudFlareResult.ErrorMessage,
                            "attempting to add cloudflare subdomains for the '" + account.AccountName + "' account during provisioning.",
                            System.Reflection.MethodBase.GetCurrentMethod(),
                            account.AccountID.ToString(),
                            account.AccountName
                            );
                    }
                }
                catch (Exception e)
                {
                    //Log exception and email platform admins
                    PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                        e,
                        "attempting to register cloudflare subdomains for the '" + account.AccountName + "' account during provisioning.",
                        System.Reflection.MethodBase.GetCurrentMethod(),
                        account.AccountID.ToString(),
                        account.AccountName
                        );
                }

                return(new DataAccessResponseType {
                    isSuccess = true
                });
            }
            else
            {
                var errorMessage = "Account has been fully provisioned, but an error occured when setting the Account table to Active and assigning a provisioning date";

                PlatformLogManager.LogActivity(CategoryType.Error,
                                               ActivityType.Error_Other,
                                               "Provisioning of '" + account.AccountName + "' has failed",
                                               errorMessage,
                                               account.AccountID.ToString(), account.AccountName);

                return(new DataAccessResponseType {
                    isSuccess = false, ErrorMessage = errorMessage
                });
            }



            #endregion
        }
Beispiel #13
0
        public static string SharedClientKey = "[Config_SharedClientKey]"; //<-- Used to verify calls for WCF service methods NOT tied to a user login.

        public static RequestResponseType ValidateRequest(string requesterId, RequesterType requsterType, out string requesterName, out string requesterEmail, string lowestRoleRequirementPlatform = null, string lowestRoleRequirementAccount = null, bool requiresAccountOwner = false, bool ignoreAccountActiveState = false)
        {
            var response = new RequestResponseType();

            requesterName  = string.Empty;
            requesterEmail = string.Empty;

            #region validate request

            if (string.IsNullOrEmpty(requesterId))
            {
                return(new RequestResponseType {
                    isApproved = false, requestMessage = "A valid RequesterID must be used with this action"
                });
            }

            /*
             * if (requsterType == null)
             * {
             *  return new RequestResponseType { isApproved = false, requestMessage = "A RequesterType must be used with this action" };
             * }*/

            #endregion



            switch (requsterType)
            {
            //Request is exempt from further validation
            case RequesterType.Exempt:
            {
                response.isApproved     = true;
                response.requestMessage = "This request is exempt from validation.";

                #region get the requester info for the out object for logging purposes in WCF services

                try
                {
                    var requestUser = AccountUserManager.GetUser(requesterId);

                    if (requestUser != null)
                    {
                        requesterName  = requestUser.FirstName;
                        requesterEmail = requestUser.Email;
                    }
                    else
                    {
                        var plaformUser = PlatformUserManager.GetUser(requesterId);
                        requesterName  = plaformUser.FirstName;
                        requesterEmail = plaformUser.Email;
                    }
                }
                catch
                {
                    var requestUser = PlatformUserManager.GetUser(requesterId);
                    requesterName  = requestUser.FirstName;
                    requesterEmail = requestUser.Email;
                }

                #endregion

                break;
            }

            //validate request for a PlatformUser:
            case RequesterType.PlatformUser:
            {
                if (lowestRoleRequirementPlatform != null)
                {
                    //userRole = PlatformUserManager.GetUserRole(requesterId);

                    var platformUser = PlatformUserManager.GetUser(requesterId);

                    requesterName  = platformUser.FirstName;
                    requesterEmail = platformUser.Email;

                    //userRole = AccountUserManager.GetUserRole(requesterId);

                    //Check requester Active state:
                    if (!platformUser.Active)
                    {
                        response.isApproved     = false;
                        response.requestMessage = "You must be an active platform user to make this request.";

                        //immediatley return the failed result
                        return(response);
                    }


                    //Check requester role:
                    response.isApproved = Internal.RoleChecker.IsRoleAllowed(requsterType, platformUser.Role, lowestRoleRequirementPlatform);

                    if (response.isApproved)
                    {
                        response.requestMessage = "This request is valid.";
                    }
                    else
                    {
                        response.requestMessage = "This request is not valid for this platform user role.";
                    }
                }
                else
                {
                    response.isApproved     = false;
                    response.requestMessage = "This request is not valid for platform users";
                }

                break;
            }


            //Validate request(s) for an AccountUser:
            case RequesterType.AccountUser:
            {
                var accountUser = AccountUserManager.GetUser(requesterId);

                requesterName  = accountUser.FirstName;
                requesterEmail = accountUser.Email;

                var account = AccountManager.GetAccount(accountUser.AccountID.ToString(), true, AccountManager.AccountIdentificationType.AccountID);

                //Ensure that the account is Active (and Active state is not ignored):
                if (!ignoreAccountActiveState && !account.Active)
                {
                    response.isApproved     = false;
                    response.requestMessage = "This account is not currently active.";
                    //Immediately return the failed result
                    return(response);
                }

                if (!account.Provisioned)
                {
                    response.isApproved     = false;
                    response.requestMessage = "This account is not yet provisioned.";
                    //Immediately return the failed result
                    return(response);
                }

                /*
                 * //Ensure that the account is Active (and Active state is not ignored):
                 * if (!ignoreAccountActiveState && !AccountManager.IsAccountActive(accountUser.AccountID.ToString()))
                 * {
                 *  response.isApproved = false;
                 *  response.requestMessage = "This account is not currently active.";
                 *  //Immediately return the failed result
                 *  return response;
                 * }
                 *
                 */

                if (requiresAccountOwner)
                {
                    //Check if the user is an account owner
                    if (accountUser.AccountOwner)
                    {
                        response.isApproved     = true;
                        response.requestMessage = "This request is valid.";
                    }
                    else
                    {
                        response.isApproved     = false;
                        response.requestMessage = "Only account owners can make this request or update.";

                        //Immediately return the failed result
                        return(response);
                    }
                }
                else if (lowestRoleRequirementAccount != null)
                {
                    //Check requester Active state:
                    if (!accountUser.Active)
                    {
                        response.isApproved     = false;
                        response.requestMessage = "You must be an active account user to make this request.";

                        //Immediately return the failed result
                        return(response);
                    }

                    //Check requester role:
                    response.isApproved = Internal.RoleChecker.IsRoleAllowed(requsterType, accountUser.Role, lowestRoleRequirementAccount);

                    if (response.isApproved)
                    {
                        response.requestMessage = "This request is valid.";
                    }
                    else
                    {
                        response.requestMessage = "This request is not valid for this account user role.";

                        //immediatly return the failed result
                        return(response);
                    }
                }
                else
                {
                    response.isApproved     = false;
                    response.requestMessage = "This request is not valid for account users";

                    //immediatly return the failed result
                    return(response);
                }

                break;
            }


            default:
            {
                response.isApproved     = false;
                response.requestMessage = "Cannot validate this request with the parameters given.";
                break;
            }
            }


            return(response);
        }
        public static DataAccessResponseType RegisterNewAccount(RegisterNewAccountModel model)
        {
            //trim the name of whitespaces (start & end):
            model.AccountName = model.AccountName.Trim();

            #region Refactoring notes

            /*
             *
             *  With some refactoring you can start them directly with a chosen payment plan by passing a planid parameter to the Registration site (and ultimatly into this method) along with C.C. info
             *
             *  This method will then check for a MonthlyRate > 0 and attempt to process the C.C.
             *  note: You would only add a Credit Card capture form to the Registration site if a plan with a MonthlyRate above 0 is selected -->
             *
             *
             *
             *  -- Adding a new "AllowRegistration" bool to the PaymentPlan object will allow for validation of selected plans coming in from users on this method for scenarios where users can choose a plan while signing up to avoid passing in ID's for plans such as "Unlimited" which must be approved by a Platform Admin
             *
             */

            #endregion

            var response = new DataAccessResponseType {
                isSuccess = true
            };

            try
            {
                #region Validate Account Info
                //Validate Registration Data:

                #region Refactoring notes

                /*
                 *
                 *
                 *  -- Adding a new "AllowRegistration" bool to the PaymentPlan object will allow for validation of selected plans coming in from users on AccountRegistrationManager for scenarios where users can choose a plan while signing up to avoid passing in ID's for plans such as "Unlimited" which must be approved by a Platform Admin
                 *
                 *              > response.ErrorMessages.Add("Not a valid payment plan for public registration");
                 *
                 */

                #endregion


                #region Validate Password(s) Match
                if (model.Password != model.ConfirmPassword)
                {
                    response.isSuccess = false;

                    response.ErrorMessages.Add("Password and password confirmation do not match");
                }
                #endregion

                #region Validate Account Name:

                ValidationResponseType accountNameValidationResponse = ValidationManager.IsValidAccountName(model.AccountName);
                if (!accountNameValidationResponse.isValid)
                {
                    response.isSuccess = false;

                    response.ErrorMessages.Add(accountNameValidationResponse.validationMessage);

                    //return response;
                }

                #endregion

                #region Validate User Name

                ValidationResponseType firstNameValidationResponse = ValidationManager.IsValidFirstName(model.FirstName);
                if (!firstNameValidationResponse.isValid)
                {
                    response.isSuccess = false;

                    response.ErrorMessages.Add(firstNameValidationResponse.validationMessage);

                    //return response;
                }

                ValidationResponseType lastNameValidationResponse = ValidationManager.IsValidLastName(model.LastName);
                if (!lastNameValidationResponse.isValid)
                {
                    response.isSuccess = false;

                    response.ErrorMessages.Add(lastNameValidationResponse.validationMessage);

                    //return response;
                }

                #endregion


                #region Validate Email Unique (Optional)

                /*
                 * var userValidation = AccountUserManager.GetUserIdentity(model.Email);
                 * if (userValidation != null)
                 * {
                 *  response.isSuccess = false;
                 *  response.ErrorMessages.Add("Another account is associated with that email address, please provide another");
                 * }
                 */

                #endregion


                //If validation(s) fails, return the response:
                if (response.isSuccess == false)
                {
                    //Log Platform Activity
                    string errors = string.Empty;

                    foreach (string error in response.ErrorMessages)
                    {
                        errors += error + "|";
                    }

                    PlatformLogManager.LogActivity(CategoryType.Registration,
                                                   ActivityType.Registration_Failed,
                                                   String.Format("Registration failed for: '{0}' by: {1} from: {2}", model.AccountName, model.Email, model.Origin),
                                                   String.Format("Errors:{0}", errors
                                                                 ));

                    //Return the response
                    response.ErrorMessage = "Could not register this account";
                    return(response);
                }

                #endregion


                // Generate AccountID ====================================
                Guid accountId = Guid.NewGuid();

                #region Register Initial AccountUser (AKA: AccountOwner)


                #region Validate & Create Account Owner User

                // Further validations and account owner creation:

                var registerUserResponse = AccountUserManager.RegisterAccountOwner(
                    model.FirstName,
                    model.LastName,
                    accountId.ToString(),
                    model.AccountName,
                    model.Email,
                    model.Password
                    );

                #endregion

                if (!registerUserResponse.isSuccess)
                {
                    //Log Platform Activity
                    string errors = string.Empty;

                    foreach (string error in registerUserResponse.ErrorMessages)
                    {
                        errors += error + "|";
                    }

                    PlatformLogManager.LogActivity(CategoryType.Registration,
                                                   ActivityType.Registration_Failed,
                                                   String.Format("Registration failed for: '{0}' by: {1} from: {2}", model.AccountName, model.Email, model.Origin),
                                                   String.Format("Errors:{0}", errors
                                                                 ));

                    //Return the response
                    response.isSuccess    = false;
                    response.ErrorMessage = registerUserResponse.ErrorMessage;

                    response.ErrorMessages = registerUserResponse.ErrorMessages;

                    return(response);
                }

                //Get user back from result
                var user = (AccountUserIdentity)registerUserResponse.ResponseObject;

                #endregion

                #region Create Account

                try
                {
                    // Create Accounts =============================================================

                    InsertStatements insertStatements = new InsertStatements();
                    var insertResult = insertStatements.InsertNewAccount(model, accountId);

                    if (insertResult.isSuccess)
                    {
                        // (Optional) for certain scenrios
                        //Add user to account, make them the owner, and assign them as SuperAdmin role:
                        //AccountManager.AddUserToAccount(user.Id, AccountID.ToString(), true); // <-- Only for certain scenarios

                        response.isSuccess      = true;
                        response.SuccessMessage = Sahara.Core.Settings.Copy.PlatformMessages.AccountRegistration.SuccessMessage;

                        var origin = "";
                        if (model.Origin != null)
                        {
                            origin = "<br/><br/><b>Origin:</b> " + model.Origin;
                        }

                        var name  = "<br/><br/><b>Name:</b> " + model.FirstName + " " + model.LastName;
                        var email = "<br/><br/><b>Email:</b> " + model.Email;

                        var phone = "";
                        if (model.PhoneNumber != null)
                        {
                            phone = "<br/><br/><b>Phone:</b> " + model.PhoneNumber;
                        }

                        try
                        {
                            //Send an alert to the platform admin(s):
                            EmailManager.Send(
                                Settings.Endpoints.Emails.PlatformEmailAddresses,
                                Settings.Endpoints.Emails.FromRegistration,
                                "Registration",
                                "New Registrant",
                                "A new account named <b>'" + model.AccountName + "'</b> has just been registered." + name + email + phone + origin,
                                true
                                );
                        }
                        catch
                        {
                        }

                        //Log The Activity ------------ :
                        //PlatformLogManager.LogActivity(CategoryType.Registration,
                        //ActivityType.Registration_Succeeded,
                        //String.Format("Registration completed for: '{0}' by: {1} from: {2}", model.AccountName, model.Email, model.Origin),
                        //String.Format("Name:'{0}', Email:'{1}', Origin:{2}", model.AccountName, model.Email, model.Origin));

                        PlatformLogManager.LogActivity(CategoryType.Account,
                                                       ActivityType.Account_Registered,
                                                       String.Format("Registration completed for: '{0}' by: {1} from: {2}", model.AccountName, model.Email, model.Origin),
                                                       String.Format("Name:'{0}', Email:'{1}', Origin:{2}", model.AccountName, model.Email, model.Origin),
                                                       accountId.ToString(),
                                                       model.AccountName,
                                                       null,
                                                       null,
                                                       null,
                                                       null,
                                                       model.Origin);


                        return(response);
                    }
                    else
                    {
                        #region Error Handling
                        string error = insertResult.ErrorMessage;

                        AccountUser outUser = null;

                        //rollback user creation:
                        AccountUserManager.DeleteUser(user.Id, false, out outUser);

                        //Log The Activity ------------ :
                        PlatformLogManager.LogActivity(CategoryType.Registration,
                                                       ActivityType.Registration_Failed,
                                                       String.Format("Registration failed for: '{0}' by: {1} from: {2}", model.AccountName, model.Email, model.Origin),
                                                       String.Format("Error:{0}", error));

                        //PlatformLogManager.LogActivity(ErrorLogActivity.PlatformError,
                        //String.Format("Registration failed for: '{0}' by: {1} from: {2}", model.AccountName, model.Email, model.Origin),
                        //String.Format("Error:{0}", error));


                        response.isSuccess    = false;
                        response.ErrorMessage = error;

                        response.ErrorMessages.Add(error);

                        return(response);

                        #endregion
                    }
                }
                catch (Exception e)
                {
                    #region Error Handling
                    string error = String.Empty;

                    AccountUser outUser = null;

                    //rollback user creation:
                    AccountUserManager.DeleteUser(user.Id, false, out outUser);

                    try
                    {
                        error = e.Message;
                    }
                    catch
                    {
                        error = "An error occured";
                    }

                    //rollback user:
                    //To Do: AccountUserManager.DeleteUser(model.Email);

                    string errorDetails = String.Format("Registration failed for: '{0}' by: {1} from: {2}", model.AccountName, model.Email, model.Origin);

                    //Log The Error(s) ------------ :
                    PlatformLogManager.LogActivity(CategoryType.Registration,
                                                   ActivityType.Registration_Error,
                                                   errorDetails,
                                                   String.Format("Error:{0}", error));



                    PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                        e,
                        "registering a new account for " + model.AccountName + " / " + model.Email + " / " + model.FirstName + " " + model.LastName + " from: " + model.Origin,
                        System.Reflection.MethodBase.GetCurrentMethod());


                    response.isSuccess    = false;
                    response.ErrorMessage = error;

                    response.ErrorMessages.Add(error);

                    return(response);

                    #endregion
                }



                #endregion
            }
            catch (Exception e)
            {
                //Log The Error(s) ------------ :
                PlatformLogManager.LogActivity(CategoryType.Registration,
                                               ActivityType.Registration_Error,
                                               String.Format("Registration failed for: '{0}' by: {1} from: {2}", model.AccountName, model.Email, model.Origin),
                                               String.Format("Error:{0}", e.Message));



                PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                    e,
                    "registering a new account for " + model.AccountName + " / " + model.Email + " / " + model.FirstName + " " + model.LastName + " from: " + model.Origin,
                    System.Reflection.MethodBase.GetCurrentMethod());



                response.isSuccess    = false;
                response.ErrorMessage = "An error occured when creating the account";

                response.ErrorMessages.Add(e.Message);

                try
                {
                    response.ErrorMessages.Add(e.InnerException.InnerException.Message);
                }
                catch
                {
                }

                return(response);
            }
        }
 public ManageController(AccountUserManager userManager)
 {
     UserManager = userManager;
 }
        public static DataAccessResponseType DeprovisionAccount(Account account)
        {
            DataAccessResponseType response = new DataAccessResponseType();

            if (account.AccountID == Guid.Empty)
            {
                response.isSuccess    = false;
                response.ErrorMessage = "No account to deprovision";
                return(response);
            }

            try
            {
                // 0. Get Account Users:
                account.Users = AccountUserManager.GetUsers(account.AccountID.ToString());



                #region LOG ACTIVITY (Deprovisioning Started)


                if (account.Provisioned)
                {
                    PlatformLogManager.LogActivity(
                        CategoryType.Account,
                        ActivityType.Account_Deprovisioning_Started,
                        "Deprovisioning of '" + account.AccountName + "' has started",
                        "AccountID: '" + account.AccountID +
                        "' SqlPartition: '" + account.SqlPartition +
                        "' DocumentPartition: '" + account.DocumentPartition +
                        "' StripeCustomerID: '" + account.StripeCustomerID +
                        "'"
                        );
                }
                else if (!account.Provisioned)
                {
                    //Account has not been provisioned, only delete the account and user objects, This will be a simple purge and not a full deprovisioning
                    PlatformLogManager.LogActivity(CategoryType.Account, ActivityType.Account_Purge_Started, "Purging of unprovisioned account '" + account.AccountName + "' has started", "AccountID: '" + account.AccountID + "' Account Owner: '" + account.Users[0].UserName + "'");
                }

                #endregion


                // Owners of accounts that have been provisioned will get an email, create a list of owner emails before all users are delted
                var accountOwnerEmails = AccountManager.GetAccountOwnerEmails(account.AccountID.ToString());

                string accountOwners = string.Empty;

                foreach (string ownerEmail in accountOwnerEmails)
                {
                    accountOwners += ownerEmail + " ";
                }


                #region STEPS 1-3 DELETE ACCOUNT USERS AND ACCOUNT

                // 1. Delete All Account Users
                AccountDeprovisioning.DeleteAllAccountUsers(account);

                // 2. Delete Account
                AccountDeprovisioning.DeleteAccount(account);

                // 3. Delete Customer in Stripe if the account has a StripeCustomerID
                if (account.StripeCustomerID != null)
                {
                    try
                    {
                        var stripeManager = new StripeManager();
                        stripeManager.DeleteCustomer(account.StripeCustomerID);
                    }
                    catch
                    {
                    }
                }

                #endregion

                if (!account.Provisioned)
                {
                    #region Log closure if account is not provisioned
                    //Account has never been provisioned, since we already deleted the account and all associated users, we are done. Log activity completion and return result:
                    PlatformLogManager.LogActivity(
                        CategoryType.Account,
                        ActivityType.Account_Purged,
                        "Purging of unprovisioned account '" + account.AccountName + "' has completed",
                        "Account Owners: '" + accountOwners + "'",
                        account.AccountID.ToString(),
                        account.AccountName,
                        null,
                        null,
                        null,
                        null,
                        null,
                        JsonConvert.SerializeObject(account)
                        );


                    //Log the closed account
                    PlatformLogManager.LogActivity(
                        CategoryType.Account,
                        ActivityType.Account_Closed,
                        "Unprovisioned",
                        account.AccountNameKey,
                        account.AccountID.ToString(),
                        account.AccountName,
                        null,
                        null,
                        null,
                        null,
                        null,
                        JsonConvert.SerializeObject(account));

                    response.isSuccess      = true;
                    response.SuccessMessage = "Purging of account '" + account.AccountID + "' Complete!";


                    #endregion
                }
                else
                {
                    // 4. Clear SQL Data Schema &
                    AccountDeprovisioning.DestroySqlSchemaAndTables(account);

                    // 5. Clear Table Storage Data
                    AccountDeprovisioning.DestroyTableStorageData(account);

                    // 6. Clear Blob Storage Data
                    AccountDeprovisioning.DestroyBlobStorageData(account);

                    // 7. Clear Document Data (Retired)
                    AccountDeprovisioning.DestroyDocumentCollection(account);

                    // 8. Clear Search Indexes
                    AccountDeprovisioning.DestroySearchIndexes(account);

                    // 9. Decriment both STORAGE & SEARCH Partitions
                    Sql.Statements.UpdateStatements.UpdatePartitionsTenantCounts(account.StoragePartition, account.SearchPartition);

                    // 10. Log Activity
                    #region Logging


                    PlatformLogManager.LogActivity(
                        CategoryType.GarbageCollection,
                        ActivityType.GarbageCollection_ClosedAccounts,
                        "All resources for account '" + account.AccountName + "' have been destroyed",
                        "Purged resources now available to new accounts",
                        account.AccountID.ToString(),
                        account.AccountName,
                        null,
                        null,
                        null,
                        null,
                        null,
                        JsonConvert.SerializeObject(account)
                        );


                    PlatformLogManager.LogActivity(
                        CategoryType.Account,
                        ActivityType.Account_Deprovisioned,
                        "Deprovisioning of '" + account.AccountName + "' has completed",
                        "SqlPartition: '" + account.SqlPartition + "'",
                        account.AccountID.ToString(),
                        account.AccountName,
                        null,
                        null,
                        null,
                        null,
                        null,
                        JsonConvert.SerializeObject(account)
                        );

                    //Log the closed account
                    PlatformLogManager.LogActivity(
                        CategoryType.Account,
                        ActivityType.Account_Closed,
                        "Deprovisioned",
                        account.AccountNameKey + " | " + account.PaymentPlanName,
                        account.AccountID.ToString(),
                        account.AccountName,
                        null,
                        null,
                        null,
                        null,
                        null,
                        JsonConvert.SerializeObject(account));

                    #endregion

                    // 11. Email all account users regarding closure:
                    EmailManager.Send(
                        accountOwnerEmails,
                        Settings.Endpoints.Emails.FromAlerts,
                        Settings.Copy.EmailMessages.DeprovisioningComplete.FromName,
                        Settings.Copy.EmailMessages.DeprovisioningComplete.Subject,
                        String.Format(Settings.Copy.EmailMessages.DeprovisioningComplete.Body, account.AccountName),
                        true);

                    // 12. Destroy ALL caches associated with an account
                    AccountManager.DestroyAccountCaches(account.AccountID.ToString(), account.AccountNameKey, account.StripeCustomerID);

                    // 13. Destroy subdomains
                    try
                    {
                        var cloudFlareResult = CloudFlareManager.RemoveSubdomains(account.AccountNameKey);

                        if (cloudFlareResult.isSuccess == false)
                        {
                            //Log exception and email platform admins
                            PlatformExceptionsHelper.LogErrorAndAlertAdmins(
                                cloudFlareResult.ErrorMessage,
                                "attempting to remove cloudflare subdomains for the '" + account.AccountName + "' account during deprovisioning.",
                                System.Reflection.MethodBase.GetCurrentMethod(),
                                account.AccountID.ToString(),
                                account.AccountName
                                );
                        }
                    }
                    catch (Exception e)
                    {
                        //Log exception and email platform admins
                        PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                            e,
                            "attempting to remove cloudflare subdomains for the '" + account.AccountName + "' account during deprovisioning.",
                            System.Reflection.MethodBase.GetCurrentMethod(),
                            account.AccountID.ToString(),
                            account.AccountName
                            );
                    }

                    response.isSuccess      = true;
                    response.SuccessMessage = "Deprovisioning of account '" + account.AccountID + "' Complete!";
                }

                //TODO: Log purged account into ClosedAccounts Table
            }
            catch (Exception e)
            {
                #region LOG ERROR (Deprovisioning Errors)

                //Log exception and email platform admins
                PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                    e,
                    "attempting to deprovision or purge account: " + account.AccountName,
                    System.Reflection.MethodBase.GetCurrentMethod(),
                    account.AccountID.ToString(),
                    account.AccountName
                    );

                #endregion

                response.isSuccess    = false;
                response.ErrorMessage = e.Message;
            }

            // Archive the closed account
            //ClosedAccountsStorageManager.ArchiveClosedAccount(account);


            return(response);
        }
Beispiel #17
0
        internal DataAccessResponseType InitializePlatform()
        {
            DataAccessResponseType response = new DataAccessResponseType();

            /*======================================
             *          CREATE DATABASES
             * ========================================*/

            //Create Platform Database:
            DatabaseModel platformDatabase = new DatabaseModel();

            platformDatabase.DatabaseTier = DatabaseTier.Basic;
            platformDatabase.DatabaseName = "Platform";
            platformDatabase.DatabaseSize = MaxSize_Basic._2GB;

            Sql.Scripts.Create.CreateDatabase(platformDatabase, Sahara.Core.Settings.Azure.Databases.DatabaseConnections.MasterSqlConnection);



            //Create Accounts Database:
            DatabaseModel accountsDatabase = new DatabaseModel();

            accountsDatabase.DatabaseTier = DatabaseTier.Basic;
            accountsDatabase.DatabaseName = "Accounts";
            accountsDatabase.DatabaseSize = MaxSize_Basic._2GB;

            Sql.Scripts.Create.CreateDatabase(accountsDatabase, Sahara.Core.Settings.Azure.Databases.DatabaseConnections.MasterSqlConnection);


            /*======================================
             *      Schema & Tables & Seed
             * ========================================*/

            //Run Schema for Accounts on Accounts DB:
            var accountDBInitialization = new Sql.Scripts.AccountsDB.Initialization.Initialization();

            accountDBInitialization.InitializeAccountsDB(Sahara.Core.Settings.Azure.Databases.DatabaseConnections.AccountsSqlConnection);

            //using (Sahara.Core.Settings.Azure.Databases.DatabaseConnections.AccountsSqlConnection)
            //{

            //}

            //Run Schema for Platform on Platform DB:
            var platformDBInitialization = new Sql.Scripts.PlatformDB.Initialization.Initialization();

            platformDBInitialization.InitializePlatformDB(Sahara.Core.Settings.Azure.Databases.DatabaseConnections.PlatformSqlConnection);



            /*======================================
             *  Create Initial Platform Roles
             * ========================================*/

            var createPlatformRolesResult = PlatformUserManager.CreateRoles(Sahara.Core.Settings.Platform.Users.Authorization.Roles.GetRoles()).Result;

            /*======================================
             *   Create Initial AccountUser Roles
             * ========================================*/

            var createAccountRolesResult = AccountUserManager.CreateRoles(Sahara.Core.Settings.Accounts.Users.Authorization.Roles.GetRoles()).Result;


            /*=====================================
             *  Initialize Available Themes
             * ========================================*/


            #region Create Default Theme(s)

            ThemesManager.CreateTheme(new ThemeModel
            {
                Name   = "Light",
                Font   = "segoe",
                Colors = new ThemeColorsModel
                {
                    Background               = "FFFFFF",
                    BackgroundGradianetTop   = "FFFFFF",
                    BackgroundGradientBottom = "DEDEDE",
                    Shadow     = "858585",
                    Highlight  = "000000",
                    Foreground = "000000",
                    Overlay    = "3D3D3D",
                    Trim       = "5E5E5E"
                }
            });


            ThemesManager.CreateTheme(new ThemeModel
            {
                Name   = "Charcoal",
                Font   = "segoe",
                Colors = new ThemeColorsModel
                {
                    Background               = "000000",
                    BackgroundGradianetTop   = "000000",
                    BackgroundGradientBottom = "4A4A4A",
                    Shadow     = "A8A8A8",
                    Highlight  = "D9D9D9",
                    Foreground = "FFFFFF",
                    Overlay    = "828282",
                    Trim       = "4D4D4D"
                }
            });

            ThemesManager.CreateTheme(new ThemeModel
            {
                Name   = "Cyan",
                Font   = "segoe",
                Colors = new ThemeColorsModel
                {
                    Background               = "9DD9ED",
                    BackgroundGradianetTop   = "9DD9ED",
                    BackgroundGradientBottom = "4F94AB",
                    Shadow     = "1D4E5E",
                    Highlight  = "CFF3FF",
                    Foreground = "1D4E5E",
                    Overlay    = "A18F28",
                    Trim       = "FF8800"
                }
            });


            #endregion


            response.isSuccess = true;

            return(response);
        }