/// <summary>
        /// Stores the access token.
        /// </summary>
        public void StoreAccessToken(SharePointAccessInfo accessInfo, HttpContextBase context)
        {
            // always store encypted refresh token.
            var cookie = new HttpCookie(RefreshTokenCookieKey, accessInfo.RefreshToken.Encrypt());
            cookie.Expires = DateTime.Now.AddMonths(1);

            context.Response.Cookies.Add(cookie);
            accessInfo.RefreshToken = string.Empty;
        }
 /// <summary>
 /// Stores the access token.
 /// </summary>
 public void StoreAccessToken(SharePointAccessInfo accessInfo, HttpContextBase context)
 {
     accessInfo.RefreshToken = accessInfo.RefreshToken.Encrypt();
 }
        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;
        }
        private User EnsureLoginSettings(SharePointAccessInfo accessInfo)
        {
            //Persist user and Tenant data if it doesn't already exist and update refresh token
            var user = new User();
            using (var loginService = _loginSettingsService)
            {
                var tenantGuid = new Guid(accessInfo.TenantId);
                var tenant = loginService.GetTenantById(tenantGuid);

                if (tenant == null)
                {
                    tenant = new Tenant
                    {
                        TenantId = tenantGuid
                    };

                    loginService.Add(tenant);
                }

                var userGuid = new Guid(accessInfo.UserId);
                user = loginService.GetUserById(userGuid);

                if (user == null)
                {
                    user = new User
                    {
                        UserId = new Guid(accessInfo.UserId),
                        TenantId = tenant.TenantId,
                        RefreshToken = accessInfo.RefreshToken
                    };

                    loginService.Add(user);
                }
                else
                {
                    user.RefreshToken = accessInfo.RefreshToken;
                }

                loginService.Save();
            }
            return user;
        }
        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;
        }
        /// <summary>
        /// Contacts the parent page to navigate away.
        /// </summary>
        /// <param name="parentId">The parent identifier.</param>
        /// <param name="accessInfo">The access information.</param>
        private ActionResult ContactParentPageToNavigateAway(string parentId, SharePointAccessInfo accessInfo)
        {
            var hasSent = false;
            var retryCount = 0;
            const int maximumRetryCount = 3;
            while (!hasSent && retryCount < maximumRetryCount)
            {
                try
                {
                    IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<AuthenticationHub>();
                    hubContext.Clients.Client(parentId)
                        .onLoginSuccess(parentId, JsonConvert.SerializeObject(accessInfo));
                    hasSent = true;
                }
                catch (Exception exception)
                {
                    Console.Write(exception);
                    retryCount++;
                    if (retryCount < maximumRetryCount)
                    {
                        // unfortunately the parent page will require a refresh.
                    }
                }
            }

            return View(new ProcessCodeViewModel {ParentId = parentId});
        }