private async Task <SharePointAccessInfo> AcquireSharePointAuthentication(
            AuthenticationContext authContext, AuthenticationResult authResult)
        {
            var authToken =
                await GetAuthorisationTokenAsync(authContext, SettingsHelper.DISCOVERY_SVC_RESOURCE_ID, authResult);

            string webUrl;

            try
            {
                var discoveryClient = new DiscoveryClient(SettingsHelper.DiscoveryServiceEndpointUri, () => (authToken.AccessToken));

                var capability = await discoveryClient.DiscoverCapabilityAsync("RootSite");

                webUrl = capability.ServiceResourceId ?? String.Empty;
            }
            catch (Exception ex)
            {
                _loggingService.LogException(ex);
                throw;
            }

            if (String.IsNullOrEmpty(webUrl))
            {
                return(null);
            }

            var sharePointAuthResult = await GetAuthorisationTokenAsync(authContext, webUrl, authResult);

            var accessInfo = new SharePointAccessInfo(webUrl, sharePointAuthResult);

            accessInfo.Update();

            return(accessInfo);
        }
        public LibraryConnectionResult Connect(string tenantWebUrl, Library library, string userId, string accessToken = "")
        {
            accessToken = GetAccessToken(accessToken);
            var userEmail = GetCurrentUserEmail();

            //check with provisioning service that they are authoriesed to connect
            var libraryId = library.LibraryId;

            var libraryIdWithReadPermission = _provisioningService.GetWebWhereUserHasPermissions(
                library.HostWebUrl, accessToken, SPBasePermissions.ViewListItems);

            if (libraryIdWithReadPermission == null || libraryIdWithReadPermission.Id == null || new Guid(libraryIdWithReadPermission.Id) != libraryId)
            {
                return(null);
            }

            // update db connected User if they have connection
            var user = _loginSettingsService.GetUserById(new Guid(userId));

            if (user != null)
            {
                user.DefaultLibraryId = library.LibraryId;
                _loginSettingsService.Save();

                var accessInfo = new SharePointAccessInfo(library.HostWebUrl)
                {
                    AccessToken = accessToken,
                    UserEmail   = userEmail
                };
                accessInfo.Update();

                var libraryConnectionResult = new LibraryConnectionResult
                {
                    Library    = library,
                    AccessInfo = accessInfo
                };

                return(libraryConnectionResult);
            }
            return(null);
        }