Esempio n. 1
0
        private UserAccessLevels CheckUserAccess()
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "CheckUserAccess invoked");
            bool isFarmAdmin = SPFarm.Local.CurrentUserIsAdministrator(true);

            UPSBrowserLogger.LogDebug(loggingCategory, $"isFarmAdmin: {isFarmAdmin}");
            if (isFarmAdmin)
            {
                return(UserAccessLevels.Admin);
            }
            else
            {
                var allowedEmails = UPSBrowserSettings.AllowedUserEmails;
                UPSBrowserLogger.LogDebug(loggingCategory, $"allowedEmails : {string.Join(",", allowedEmails)}");
                if (allowedEmails.Count > 0)
                {
                    string currentUserEmail = SPContext.Current.Web.CurrentUser.Email.ToLower();
                    UPSBrowserLogger.LogDebug(loggingCategory, $"currentUserEmail: {currentUserEmail}");
                    int matchCount = allowedEmails.Where(ae => ae.ToLower() == currentUserEmail).Count();
                    UPSBrowserLogger.LogDebug(loggingCategory, $"matchCount: {matchCount}");
                    if (matchCount > 0)
                    {
                        return(UserAccessLevels.User);
                    }
                }
                return(UserAccessLevels.None);
            }
        }
Esempio n. 2
0
        public DataTable GetFilteredUserProfiles()
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "GetFilteredUserProfiles invoked");
            string      filter   = UserFilterTextBox.Text;
            List <User> upsUsers = upsUsersDAL.getUsersBySearchString(filter);

            if (upsUsers == null)
            {
                return(null);
            }
            ;

            DataTable dt = new DataTable();

            dt.Columns.Add("UserGuid");
            dt.Columns.Add("AccountName");
            dt.Columns.Add("DisplayName");
            dt.Columns.Add("WorkEmail");
            dt.Columns.Add("JobTitle");
            dt.Columns.Add("Department");

            upsUsers.ForEach((upsUser) => {
                DataRow dr        = dt.NewRow();
                dr["UserGuid"]    = upsUser.UserGuid;
                dr["AccountName"] = upsUser.AccountName;
                dr["DisplayName"] = upsUser.DisplayName;
                dr["WorkEmail"]   = upsUser.WorkEmail;
                dr["JobTitle"]    = upsUser.JobTitle;
                dr["Department"]  = upsUser.Department;
                dt.Rows.Add(dr);
            });

            return(dt);
        }
Esempio n. 3
0
 void UserProfilesGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
 {
     UPSBrowserLogger.LogDebug(loggingCategory, "UserProfilesGridView_PageIndexChanging invoked");
     UserProfilesGridView.PageIndex = e.NewPageIndex;
     UPSBrowserLogger.LogDebug(loggingCategory, $"e.NewPageIndex: {e.NewPageIndex}");
     BindUserProfilesGridView();
 }
Esempio n. 4
0
        protected void Page_Load(object sender, EventArgs e)
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "Page_Load invoked");

            if (ViewState["needParentRefreshing"] != null)
            {
                needParentRefreshing = (bool)ViewState["needParentRefreshing"];
            }

            if (Request.QueryString["guid"] != null)
            {
                formMode = formModeEnum.EditForm;
                userGuid = Request.QueryString["guid"];
            }
            else
            {
                formMode             = formModeEnum.NewForm;
                userGuid             = null;
                identityProviderName = Request.QueryString["idp"];
                UPSBrowserLogger.LogDebug(loggingCategory, $"identityProviderName: {identityProviderName}");
            };

            UPSBrowserLogger.LogDebug(loggingCategory, $"formMode: {formMode}, userGuid: {userGuid}");
            SetupFormFields();

            CloseButton.Click  += CloseButton_Click;
            DeleteButton.Click += DeleteButton_Click;
            upsbrowser_form_savebutton.Click  += SaveButton_Click;
            upsbrowser_form_savebutton.Enabled = false;

            ErrorMessage.Text    = "";
            ErrorMessage.Visible = false;
        }
Esempio n. 5
0
        public List <User> getUsersBySearchString(string searchString)
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "WSExternalUsersSource.getUsersBySearchString invoked");
            UPSBrowserLogger.LogDebug(loggingCategory, $"searchString: {searchString}");

            if (string.IsNullOrEmpty(searchString) || searchString.Length < Constants.searchStringMingLength)
            {
                return(null);
            }
            ;

            string path            = $"searchadusers";
            string queryParameters = $"searchstring={searchString}";
            string jsonString      = callJsonWebService(path, false, queryParameters, null);

            if (string.IsNullOrEmpty(jsonString))
            {
                return(null);
            }
            ;


            List <User> usersToReturn = JsonConvert.DeserializeObject <List <User> >(jsonString);

            return(usersToReturn);
        }
Esempio n. 6
0
        private void SetupFormFields()
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "SetupFormFields invoked");

            if (formMode == formModeEnum.EditForm)
            {
                if (!IsPostBack)
                {
                    User upsUser = upsUsersDAL.getUserByGuid(userGuid);
                    if (upsUser == null)
                    {
                        string errorMessage = $"Error getting user form UPS by guid: {userGuid}";
                        UPSBrowserLogger.LogError(loggingCategory, errorMessage);
                        throw new Exception(errorMessage);
                    }
                    ;

                    FillTextboxes(upsUser);
                }
            }
            else
            {
                WorkEmailTextBox.Enabled   = true;
                WorkEmailTextBox.ReadOnly  = false;
                AccountNameLabel.Visible   = false;
                AccountNameTextBox.Visible = false;
                UserGuidLabel.Visible      = false;
                UserGuidTextBox.Visible    = false;
            };
        }
Esempio n. 7
0
        private void DeleteButton_Click(object sender, EventArgs e)
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "DeleteButton_Click invoked");

            string userGuid = UserGuidTextBox.Text;

            if (upsUsersDAL.deleteUserByGuid(userGuid))
            {
                UPSBrowserLogger.LogDebug(loggingCategory, "User deleted successfully");
                needParentRefreshing = true;

                ErrorMessage.Text    = "";
                ErrorMessage.Visible = false;

                CloseForm();
            }
            else
            {
                UPSBrowserLogger.LogError(loggingCategory, "Error deleting user");

                ErrorMessage.Text    = "Error deleting user";
                ErrorMessage.Visible = true;

                return;
            }
        }
Esempio n. 8
0
        public User updateUser(User updatedUser)
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "updateUser invoked");
            UPSBrowserLogger.LogDebug(loggingCategory, $"updatedUser.UserGuid: {updatedUser.UserGuid}");

            User userToUpdate = _users.SingleOrDefault(user => user.UserGuid == updatedUser.UserGuid);

            if (userToUpdate == null)
            {
                UPSBrowserLogger.LogError(loggingCategory, $"User profile not found");
                //UPSBrowserLogger.LogActivity(userToUpdate.Username, UPSBrowserLogger.LogActivityActionEnum.Update, UPSBrowserLogger.LogActivityResultEnum.Error);
                ActivityLogger.LogActivity(userToUpdate.AccountName, LogActivityActionEnum.Update, LogActivityResultEnum.Error);
                return(null);
            }

            //_users.Where()
            UPSBrowserLogger.LogError(loggingCategory, $"User profile found, updating properties");
            userToUpdate.WorkEmail   = updatedUser.WorkEmail;
            userToUpdate.AccountName = updatedUser.AccountName;
            userToUpdate.DisplayName = updatedUser.DisplayName;
            userToUpdate.JobTitle    = updatedUser.JobTitle;
            userToUpdate.Department  = updatedUser.Department;

            // log completed activity
            //UPSBrowserLogger.LogActivity(userToUpdate.Username, UPSBrowserLogger.LogActivityActionEnum.Update, UPSBrowserLogger.LogActivityResultEnum.Success);
            ActivityLogger.LogActivity(userToUpdate.AccountName, LogActivityActionEnum.Update, LogActivityResultEnum.Success);

            return(userToUpdate);
        }
Esempio n. 9
0
        private void ConfigureImportUsersSearchResultsGridViewColumns()
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "ConfigureImportUsersSearchResultsGridViewColumns invoked");

            HyperLinkField col1 = new HyperLinkField();

            col1.HeaderText     = "Display Name";
            col1.DataTextField  = "DisplayName";
            col1.SortExpression = "DisplayName";
            ImportUsersSearchResultsGridView.Columns.Add(col1);

            SPBoundField col2 = new SPBoundField();

            col2.HeaderText     = "Work Email";
            col2.DataField      = "WorkEmail";
            col2.SortExpression = "WorkEmail";
            ImportUsersSearchResultsGridView.Columns.Add(col2);

            SPBoundField col3 = new SPBoundField();

            col3.HeaderText     = "Job title";
            col3.DataField      = "JobTitle";
            col3.SortExpression = "JobTitle";
            ImportUsersSearchResultsGridView.Columns.Add(col3);

            SPBoundField col4 = new SPBoundField();

            col4.HeaderText     = "Department";
            col4.DataField      = "Department";
            col4.SortExpression = "Department";
            ImportUsersSearchResultsGridView.Columns.Add(col4);
        }
Esempio n. 10
0
        void ImportUsersSearchResultsGridView_Sorting(object sender, GridViewSortEventArgs e)
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "ImportUsersSearchResultsGridView_Sorting invoked");
            string lastExpression = "";

            if (ViewState["SortExpressionSearchResults"] != null)
            {
                lastExpression = ViewState["SortExpressionSearchResults"].ToString();
            }
            string lastDirection = "asc";

            if (ViewState["SortDirectionSearchResults"] != null)
            {
                lastDirection = ViewState["SortDirectionSearchResults"].ToString();
            }
            string newDirection = string.Empty;

            if (e.SortExpression == lastExpression)
            {
                e.SortDirection = (lastDirection == "asc") ? System.Web.UI.WebControls.SortDirection.Descending : System.Web.UI.WebControls.SortDirection.Ascending;
            }
            newDirection = (e.SortDirection == System.Web.UI.WebControls.SortDirection.Descending) ? "desc" : "asc";
            ViewState["SortExpressionSearchResults"] = e.SortExpression;
            ViewState["SortDirectionSearchResults"]  = newDirection;
            BindImportUsersSearchResultsGridView();
        }
Esempio n. 11
0
        public static void LogActivity(string user, LogActivityActionEnum action, LogActivityResultEnum result, string additionalInfo = "")
        {
            // Log to SharePoint tracing log
            UPSBrowserLogger.LogActivity(user, action.ToString(), result.ToString(), additionalInfo);

            EnsureActivitiesList();
            AddActivityToList(user, action, result, additionalInfo);
        }
Esempio n. 12
0
 private void SettingsTabButton_Click(object sender, EventArgs e)
 {
     UPSBrowserLogger.LogDebug(loggingCategory, "SettingsTabButton_Click invoked");
     MainViewTabButton.CssClass         = "kcell-upsbrowser-tabbutton";
     ImportUsersTabButton.CssClass      = "kcell-upsbrowser-tabbutton";
     SettingsTabButton.CssClass         = "kcell-upsbrowser-tabbutton--clicked";
     MultiViewContainer.ActiveViewIndex = 2;
 }
Esempio n. 13
0
        private string callJsonWebService(string path, bool isPostRequest, string queryParameters, string body)
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "WSExternalUsersSource.callJsonWebService invoked");
            UPSBrowserLogger.LogDebug(loggingCategory, $"path: {path}");
            UPSBrowserLogger.LogDebug(loggingCategory, $"isPostRequest: {isPostRequest}");
            UPSBrowserLogger.LogDebug(loggingCategory, $"queryParameters: {queryParameters}");
            UPSBrowserLogger.LogDebug(loggingCategory, $"body: {body}");

            if (string.IsNullOrEmpty(wsBaseUrl) || (tokenSigningCert == null))
            {
                string message = "Call Init method to set configuration parameters before calling getUsersBySearchString";
                UPSBrowserLogger.LogError(loggingCategory, message);
                return(null);
            }
            ;


            string jsonString = null;

            try
            {
                string wsUrl = $"{wsBaseUrl}/{path}";
                wsUrl = string.IsNullOrEmpty(queryParameters) ? $"{wsUrl}": $"{wsUrl}?{queryParameters}";
                WebClient webClient = getWebClient();

                // Generating jwt token using the cert selected on the "Settings" tab
                UPSBrowserLogger.LogDebug(loggingCategory, $"TokenSigningCert.subject: {tokenSigningCert.subject}; TokenSigningCert.friendlyName: {tokenSigningCert.friendlyName}");
                ITokenHelper tokenHelper = new TokenHelper();
                string       tokenString = tokenHelper.getTokenString(tokenSigningCert);
                if (string.IsNullOrEmpty(tokenString))
                {
                    string message = "TokenHelper returned null token, external web service call will not be called";
                    UPSBrowserLogger.LogError(loggingCategory, message);
                    return(null);
                }

                webClient.Headers.Add("Authorization", $"Bearer {tokenString}");
                webClient.Headers.Add("Content-Type", "application/json; charset=utf-8");
                if (isPostRequest)
                {
                    jsonString = webClient.UploadString(wsUrl, body);
                }
                else
                {
                    jsonString = webClient.DownloadString(wsUrl);
                }

                UPSBrowserLogger.LogDebug(loggingCategory, $"jsonString: {jsonString}");
            }
            catch (Exception e)
            {
                string message = $"Error getting data from external web service: {e.Message}";
                UPSBrowserLogger.LogError(loggingCategory, message);
                throw e;
            };

            return(jsonString);
        }
Esempio n. 14
0
        public static Tuple <string, string> EnsureActivitiesList()
        {
            string currentSiteUrl         = SPContext.Current.Site.Url;
            Tuple <string, string> result = null;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                try
                {
                    using (SPSite site = new SPSite(currentSiteUrl))
                        using (SPWeb rootWeb = site.OpenWeb())
                        {
                            rootWeb.AllowUnsafeUpdates = true;

                            SPList extistingList = rootWeb.Lists.TryGetList(ActivityLoggerListTitle);
                            if (extistingList != null)
                            {
                                result = Tuple.Create(extistingList.ID.ToString(), extistingList.DefaultView.ID.ToString());
                                return;
                            }

                            SPListCollection lists = rootWeb.Lists;
                            lists.Add(ActivityLoggerListInternalName, "UPSBrowser logged activities", SPListTemplateType.GenericList);
                            SPList list = rootWeb.Lists[ActivityLoggerListInternalName];

                            list.Title = ActivityLoggerListTitle;
                            list.Fields.Add("RegisteredDate", SPFieldType.DateTime, true);
                            list.Fields.Add("Initiator", SPFieldType.Text, true);
                            list.Fields.Add("User", SPFieldType.Text, true);
                            list.Fields.Add("Action", SPFieldType.Text, true);
                            list.Fields.Add("Result", SPFieldType.Text, true);
                            list.Fields.Add("AdditionalInfo", SPFieldType.Text, false);
                            list.Update();

                            SPView view = list.DefaultView;
                            view.ViewFields.Add("RegisteredDate");
                            view.ViewFields.Add("Initiator");
                            view.ViewFields.Add("User");
                            view.ViewFields.Add("Action");
                            view.ViewFields.Add("Result");
                            view.ViewFields.Add("AdditionalInfo");
                            view.Update();

                            rootWeb.AllowUnsafeUpdates = false;

                            result = Tuple.Create(list.ID.ToString(), list.DefaultView.ID.ToString());
                        };
                }
                catch (Exception e)
                {
                    UPSBrowserLogger.LogError(loggingCategory, $"Error creating list '{ActivityLoggerListTitle}' in the root web at {currentSiteUrl}. Exception: {e.Message}");
                    return;
                };
            });

            return(result);
        }
Esempio n. 15
0
        public User getUserByGuid(string guid)
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "getUserByGuid invoked");
            UPSBrowserLogger.LogDebug(loggingCategory, $"guid: {guid}");
            User userToReturn = null;

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    UPSBrowserLogger.LogDebug(loggingCategory, "Running with elevated privileges");

                    // Save the original HttpContext and set it to null
                    // solution to enable impersonated access to UPS from here:
                    // https://weblogs.asp.net/sreejukg/access-denied-error-when-retrieving-user-profiles-count-from-sharepoint
                    HttpContext savedHttpContext = HttpContext.Current;
                    HttpContext.Current          = null;

                    // Access the User Profile Service
                    try
                    {
                        SPServiceContext serviceContext = SPServiceContext.GetContext(SPServiceApplicationProxyGroup.Default, SPSiteSubscriptionIdentifier.Default);
                        UPSBrowserLogger.LogDebug(loggingCategory, "Reference to SPServiceContext obtained");
                        UserProfileManager userProfileManager = new UserProfileManager(serviceContext);
                        UPSBrowserLogger.LogDebug(loggingCategory, "Reference to UserProfileManager obtained");
                        UserProfile userProfile = userProfileManager.GetUserProfile(new Guid(guid));
                        if (userProfile == null)
                        {
                            UPSBrowserLogger.LogError(loggingCategory, $"User profile with guid {guid} not found in User Profile Service");
                            return; //exit delegate block
                        }
                        ;

                        UPSBrowserLogger.LogDebug(loggingCategory, $"userProfile.AccountName: {userProfile.AccountName}, userProfile.DisplayName: {userProfile.DisplayName}");

                        userToReturn        = UserProfileToUser(userProfile);
                        string outputString = $"Retrieved user properties - Email: {userToReturn.WorkEmail}, Username: {userToReturn.AccountName}, DisplayName: {userToReturn.DisplayName}, Department: {userToReturn.Department}, JobTitle: {userToReturn.JobTitle}";
                        UPSBrowserLogger.LogDebug(loggingCategory, outputString);
                    }
                    catch (System.Exception e)
                    {
                        UPSBrowserLogger.LogError(loggingCategory, e.Message);
                    }
                    finally
                    {
                        // Restore HttpContext
                        HttpContext.Current = savedHttpContext;
                    };
                });
            }
            catch (System.Exception e)
            {
                UPSBrowserLogger.LogError(loggingCategory, $"Error while trying to elevate privileges: {e.Message}");
            };

            return(userToReturn);
        }
Esempio n. 16
0
        private void ImportUsersSearchButton_Click(object sender, EventArgs e)
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "ImportUsersSearchButton_Click invoked");
            string searchText = upsbrowser_import_users_searchtextbox.Text;

            UPSBrowserLogger.LogDebug(loggingCategory, $"searchText: {searchText}");

            BindImportUsersSearchResultsGridView();
        }
Esempio n. 17
0
 private void InitUserProfilesDatasource()
 {
     UPSBrowserLogger.LogDebug(loggingCategory, "InitUserProfilesDatasource invoked");
     UserProfilesDatasource                 = new ObjectDataSource();
     UserProfilesDatasource.ID              = UserProfiles_datasource_ID;
     UserProfilesDatasource.SelectMethod    = "GetFilteredUserProfiles";
     UserProfilesDatasource.TypeName        = this.GetType().AssemblyQualifiedName; // data access methods are in this same classs
     UserProfilesDatasource.ObjectCreating += new ObjectDataSourceObjectEventHandler(UserProfilesDatasource_ObjectCreating);
     this.Controls.Add(UserProfilesDatasource);
 }
Esempio n. 18
0
        private void ConfigureUserProfilesGridView()
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "ConfigureUserProfilesGridView invoked");

            UserProfilesGridView.Sorting           += new GridViewSortEventHandler(UserProfilesGridView_Sorting);
            UserProfilesGridView.PageIndexChanging += new GridViewPageEventHandler(UserProfilesGridView_PageIndexChanging);
            UserProfilesGridView.RowDataBound      += new GridViewRowEventHandler(UserProfilesGridView_RowDataBound);
            UserProfilesGridView.PagerTemplate      = null;
            UserProfilesGridView.PageSize           = 10;
        }
Esempio n. 19
0
        public List <IdentityProvider> getIdentityProviders()
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "getIdentityProviders invoked");
            List <IdentityProvider> identityProvidersToReturn = new List <IdentityProvider>();

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    UPSBrowserLogger.LogDebug(loggingCategory, "Running with elevated privileges");

                    try
                    {
                        SPContext spContext                  = Microsoft.SharePoint.SPContext.Current;
                        SPWebApplication webApp              = spContext.Site.WebApplication;
                        SPUrlZone spUrlZone                  = spContext.Site.Zone;
                        SPIisSettings spIisSettings          = webApp.GetIisSettingsWithFallback(spUrlZone);
                        SPSecurityTokenServiceManager sptMgr = SPSecurityTokenServiceManager.Local;

                        foreach (SPAuthenticationProvider prov in spIisSettings.ClaimsAuthenticationProviders)
                        {
                            if (prov.GetType() == typeof(Microsoft.SharePoint.Administration.SPTrustedAuthenticationProvider))
                            {
                                var lp =
                                    from SPTrustedLoginProvider spt in
                                    sptMgr.TrustedLoginProviders
                                    where spt.DisplayName == prov.DisplayName
                                    select spt;

                                if ((lp != null) && (lp.Count() > 0))
                                {
                                    SPTrustedLoginProvider loginProv = lp.First();
                                    identityProvidersToReturn.Add(new IdentityProvider
                                    {
                                        Name        = loginProv.Name,
                                        DisplayName = loginProv.DisplayName,
                                        Description = loginProv.Description,
                                    });
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        UPSBrowserLogger.LogError(loggingCategory, e.Message);
                    };
                });
            }
            catch (System.Exception e)
            {
                UPSBrowserLogger.LogError(loggingCategory, $"Error while trying to elevate privileges: {e.Message}");
            };

            return(identityProvidersToReturn);
        }
Esempio n. 20
0
        public string getAccountNameForEmail(string email, string indentityProviderName)
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "getIdentityProviders invoked");
            UPSBrowserLogger.LogDebug(loggingCategory, $"email: {email}, indentityProviderName: {indentityProviderName}");
            string originalIssuer      = SPOriginalIssuers.Format(SPOriginalIssuerType.TrustedProvider, indentityProviderName);
            SPClaimProviderManager mgr = SPClaimProviderManager.Local;
            SPClaim claim       = new SPClaim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress", email, System.Security.Claims.ClaimValueTypes.String, originalIssuer);
            string  accountName = mgr.EncodeClaim(claim);

            return(accountName);
        }
Esempio n. 21
0
        private void InitImportUsersSearchResultsDatasource()
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "InitImportUsersSearchResultsDatasource invoked");

            ImportUsersSearchResultsDatasource                 = new ObjectDataSource();
            ImportUsersSearchResultsDatasource.ID              = ImportUsersSearchResults_datasource_ID;
            ImportUsersSearchResultsDatasource.SelectMethod    = "GetFilteredExternalUsers";
            ImportUsersSearchResultsDatasource.TypeName        = this.GetType().AssemblyQualifiedName; // data access methods are in this same classs
            ImportUsersSearchResultsDatasource.ObjectCreating += new ObjectDataSourceObjectEventHandler(ImportUsersSearchResultsDatasource_ObjectCreating);
            this.Controls.Add(ImportUsersSearchResultsDatasource);
        }
Esempio n. 22
0
        public List <TokenSigningCertificate> getTokenSigningCertificates()
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "TokenSigningCertificatesHelper.getTokenSigningCertificates invoked");
            List <TokenSigningCertificate> certsToReturn = new List <TokenSigningCertificate>();

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    UPSBrowserLogger.LogDebug(loggingCategory, "Running with elevated privileges");

                    try
                    {
                        X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                        store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
                        UPSBrowserLogger.LogDebug(loggingCategory, "LocalMachine cert store open");

                        SPContext spContext = Microsoft.SharePoint.SPContext.Current;
                        string siteHostName = (new Uri(spContext.Site.Url)).Host.ToLower();

                        UPSBrowserLogger.LogDebug(loggingCategory, $"Current SP site URL host part: {siteHostName}");

                        foreach (X509Certificate2 cert in store.Certificates)
                        {
                            UPSBrowserLogger.LogDebug(loggingCategory, $"cert.FriendlyName: {cert.FriendlyName}, cert.HasPrivateKey: {cert.HasPrivateKey}, cert.NotAfter: {cert.NotAfter}");
                            if (cert.HasPrivateKey && (cert.NotAfter > DateTime.Now))
                            {
                                TokenSigningCertificate certToAdd = new TokenSigningCertificate
                                {
                                    friendlyName = cert.FriendlyName,
                                    subject      = cert.Subject,
                                    thumbprint   = cert.Thumbprint,
                                    rank         = cert.Subject.ToLower().Equals($"cn={siteHostName}") ? 1 : 0,
                                    cert         = cert
                                };
                                certsToReturn.Add(certToAdd);
                                UPSBrowserLogger.LogDebug(loggingCategory, $"Cert added - friendly name: {certToAdd.friendlyName}; subject: {certToAdd.subject}, rank: {certToAdd.rank}");
                            }
                            ;
                        }
                    }
                    catch (Exception e)
                    {
                        UPSBrowserLogger.LogError(loggingCategory, e.Message);
                    };
                });
            }
            catch (System.Exception e)
            {
                UPSBrowserLogger.LogError(loggingCategory, $"Error while trying to elevate privileges: {e.Message}");
            };

            return(certsToReturn.OrderByDescending(cert => cert.rank).ToList());
        }
Esempio n. 23
0
        void DisplayCriticalError(string errorMessage, bool showBackButton)
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "DisplayCriticalError invoked");

            MainViewTabButton.Visible    = false;
            ImportUsersTabButton.Visible = false;
            SettingsTabButton.Visible    = false;

            CriticalErrorMessage.Text          = errorMessage;
            CriticalErrorBackButton.Visible    = showBackButton;
            MultiViewContainer.ActiveViewIndex = 3;
        }
Esempio n. 24
0
        public User createUser(User newUser, string identityProviderName)
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "createUser invoked");
            UPSBrowserLogger.LogDebug(loggingCategory, $"newUser.UserGuid: {newUser.UserGuid}");
            newUser.UserGuid = Guid.NewGuid().ToString();
            _users.Add(newUser);

            // log completed activity
            //UPSBrowserLogger.LogActivity(newUser.Username, UPSBrowserLogger.LogActivityActionEnum.Create, UPSBrowserLogger.LogActivityResultEnum.Success);
            ActivityLogger.LogActivity(newUser.AccountName, LogActivityActionEnum.Create, LogActivityResultEnum.Success);
            return(newUser);
        }
Esempio n. 25
0
        static void AddActivityToList(string user, LogActivityActionEnum action, LogActivityResultEnum result, string additionalInfo = "")
        {
            // Add activity info record to the list stored in the session storage so that it will available for display

            /*
             * HttpContext currentContext = HttpContext.Current;
             * if (currentContext == null)
             * {
             *  UPSBrowserLogger.LogError(loggingCategory, "Current HttpContext is null");
             *  return;
             * };
             */
            string currentSiteUrl = SPContext.Current.Site.Url;
            string initiator      = SPContext.Current.Web.CurrentUser.LoginName;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                try
                {
                    using (SPSite site = new SPSite(currentSiteUrl))
                        using (SPWeb rootWeb = site.OpenWeb())
                        {
                            rootWeb.AllowUnsafeUpdates = true;

                            SPList list = rootWeb.Lists.TryGetList(ActivityLoggerListTitle);
                            if (list == null)
                            {
                                UPSBrowserLogger.LogError(loggingCategory, $"List '{ActivityLoggerListTitle}' not found in the root web at {currentSiteUrl}");
                                return;
                            }

                            SPListItem item        = list.Items.Add();
                            item["RegisteredDate"] = DateTime.Now;
                            item["Initiator"]      = initiator;
                            item["User"]           = user;
                            item["Action"]         = action.ToString();
                            item["Result"]         = result.ToString();
                            item["AdditionalInfo"] = additionalInfo;
                            item.Update();

                            rootWeb.AllowUnsafeUpdates = false;
                        };
                }
                catch (Exception e)
                {
                    UPSBrowserLogger.LogError(loggingCategory, $"Error adding record to the list list {ActivityLoggerListTitle} in the root web at {currentSiteUrl}. Exception: {e.Message}");
                    return;
                };
            });
        }
Esempio n. 26
0
        public User getUserByGuid(string guid)
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "getUserByGuid invoked");
            UPSBrowserLogger.LogDebug(loggingCategory, $"guid: {guid}");
            User userToReturn = _users.SingleOrDefault(user => user.UserGuid == guid);

            if (userToReturn == null)
            {
                UPSBrowserLogger.LogError(loggingCategory, $"User profile not found");
                return(null);
            }

            UPSBrowserLogger.LogDebug(loggingCategory, $"userToReturn.AccountName: {userToReturn.AccountName}, userToReturn.WorkEmail: {userToReturn.WorkEmail}");
            return(userToReturn);
        }
Esempio n. 27
0
        private void SaveSettingsButton_Click(object sender, EventArgs e)
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "SaveSettingsButton_Click invoked");

            UPSBrowserSettings.setStringProperty(settings, "identityProviderName", IdentityProvidersDropDownList.SelectedValue);
            UPSBrowserSettings.setStringProperty(settings, "tokenSigningCertificateThumbprint", TokenSigningCertificatesDropDownList.SelectedValue);
            UPSBrowserSettings.setStringProperty(settings, "wsExternalUsersSourceUrl", WSExternalUsersSourceURLTextBox.Text);

            bool result = SaveSettings();

            if (!result)
            {
                DisplayCriticalError("Error saving settings!", true);
            }
        }
Esempio n. 28
0
        public upsbrowser() : base()
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "upsbrowser constructor invoked");

            //upsUsersDAL = FakeUPSUsersDAL.getInstance();
            upsUsersDAL = new UPSUsersDAL();

            //externalUsersSource = FakeWSExternalUsersSource.getInstance();
            externalUsersSource = new WSExternalUsersSource();

            identityProvidersHelper = new IdentityProvidersHelper();
            certsHelper             = new TokenSigningCertificatesHelper();

            LoadSettings();
        }
Esempio n. 29
0
        public List <User> getUsersBySearchString(string searchString)
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "getUsersBySearchString invoked");
            UPSBrowserLogger.LogDebug(loggingCategory, $"searchString: {searchString}");
            UPSBrowserLogger.LogDebug(loggingCategory, $"_users.Count: {_users.Count}");

            if (searchString.Length < 3)
            {
                return(null);
            }

            List <User> usersToReturn = _users.Where((user) => String.Concat(user.WorkEmail, user.AccountName, "|", user.FirstName, " ", user.LastName, "|", user.DisplayName).ToLower().Contains(searchString.ToLower())).ToList <User>();

            UPSBrowserLogger.LogDebug(loggingCategory, $"usersToReturn.Count: {usersToReturn.Count}");
            return(usersToReturn);
        }
Esempio n. 30
0
        private void ImportUsersStartImportButton_Click(object sender, EventArgs evt)
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "ImportUsersStartImportButton_Click invoked");

            string        resolvedUsersEmails = upsbrowser_import_users_resolved_hiddeninput.Text;
            List <string> emails = new List <string>(resolvedUsersEmails.Split(';'));

            emails = emails.Where(email => !string.IsNullOrEmpty(email)).ToList <string>(); //filter out empty emails

            string wsBaseUrl             = UPSBrowserSettings.getStringProperty(this.settings, "wsExternalUsersSourceUrl");
            string certThumbprint        = UPSBrowserSettings.getStringProperty(this.settings, "tokenSigningCertificateThumbprint");
            string identityProviderName  = UPSBrowserSettings.getStringProperty(this.settings, "identityProviderName");
            TokenSigningCertificate cert = certs.FirstOrDefault(c => c.thumbprint == certThumbprint);

            List <User> users = null;

            try
            {
                externalUsersSource.Init(wsBaseUrl, cert);
                users = externalUsersSource.getUsersByEmails(emails);
            }
            catch (Exception e)
            {
                DisplayCriticalError($"Error getting users from external source: {e.Message}", true);
                return;
            };


            if ((users != null) && (users.Count > 0))
            {
                foreach (User user in users)
                {
                    User createdUser = upsUsersDAL.createUser(user, identityProviderName);
                    if (createdUser != null)
                    {
                        string hiddenInputValue = upsbrowser_import_users_resolved_hiddeninput.Text.ToLower();
                        hiddenInputValue = hiddenInputValue.Replace(createdUser.WorkEmail.ToLower() + ";", "");
                        upsbrowser_import_users_resolved_hiddeninput.Text = hiddenInputValue;
                    }
                }
                ;
            }
            ;
        }