예제 #1
0
        private static async Task <string> GetAccessToken(string key, string secret)
        {
            if (!string.IsNullOrEmpty(Settings.Default.USER_TOKEN))
            {
                return(Settings.Default.USER_TOKEN);
            }

            Console.WriteLine(
                "You'll need to authorize this account with PneumaticTube; a browser window will now open asking you to log into Dropbox and allow the app. When you've done that, you'll be given an access key. Enter the key here and hit Enter:");

            var oauth2State = Guid.NewGuid().ToString("N");

            // Pop open the authorization page in the default browser
            var url = DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Code, key, (Uri)null, oauth2State);

            Process.Start(url.ToString());

            // Wait for the user to enter the key
            var token = Console.ReadLine();

            var response = await DropboxOAuth2Helper.ProcessCodeFlowAsync(token, key, secret);

            // Save the token
            Settings.Default.USER_TOKEN = response.AccessToken;
            Settings.Default.Save();

            return(response.AccessToken);
        }
예제 #2
0
        async Task <string> GetToken()
        {
            var redirectUri = new Uri(REDIRECT_URI);

            var authorizeUrl = DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Code, APP_KEY, new Uri(REDIRECT_URI));

            OpenBrowser(authorizeUrl.ToString());

            var http = new HttpListener();

            http.Prefixes.Add(REDIRECT_URI);
            http.Start();

            var context = await http.GetContextAsync();

            while (context.Request.Url.AbsolutePath != redirectUri.AbsolutePath)
            {
                context = await http.GetContextAsync();
            }

            http.Stop();

            var code = Uri.UnescapeDataString(context.Request.QueryString["code"]);

            var response = await DropboxOAuth2Helper.ProcessCodeFlowAsync(code, APP_KEY, APP_SECRET, REDIRECT_URI);

            return(response.AccessToken);
        }
예제 #3
0
        public async Task Authorize(int userId, string code, string state)
        {
            var existingState = preferenceRepository.FirstOrDefault(x => x.UserId.Equals(userId) && x.Key.Equals(Constants.DropboxState));

            if (existingState == null)
            {
                throw new Exception("Missing access token for dropbox.");
            }

            configuration = GetDropboxConfig();

            var response = await DropboxOAuth2Helper.ProcessCodeFlowAsync(
                code,
                configuration.AppId,
                configuration.AppSecret,
                RedirectUri);

            preferenceRepository.Add(new Domain.Preferences
            {
                UserId = userId,
                Key    = Constants.DropboxAccessToken,
                Value  = response.AccessToken
            });

            var statePreference = preferenceRepository.FirstOrDefault(x => x.UserId.Equals(userId) && x.Key.Equals(Constants.DropboxState));

            preferenceRepository.Remove(statePreference);
        }
예제 #4
0
        /// <summary>
        /// *** This Function is used to get DropBox Access Token and set static variable with it
        /// *** Incase of error it set static variable MsgError with error details
        /// </summary>
        /// <param name="ResponseCode">Response Code returned from drop Box</param>
        /// <param name="dropBoxAppKey">The Dropbox Application Key</param>
        /// <param name="dropBoxAppSecret">The Dropbox Application Secret.</param>
        /// <param name="returnBackURL">The Dropbox Return Back URL.</param>
        /// <returns></returns>
        public static async Task getAccessTokenFromResponse(string ResponseCode, string dropBoxAppKey,
                                                            string dropBoxAppSecret, string returnBackURL)
        {
            //*** Initialization
            MsgError = "";

            try
            {
                var response = await DropboxOAuth2Helper.ProcessCodeFlowAsync(
                    ResponseCode,
                    dropBoxAppKey,
                    dropBoxAppSecret,
                    returnBackURL);

                dropBoxAccessToken = response.AccessToken;
            }
            catch (Exception e)
            {
                var message = string.Format(
                    "code: {0}\nAppKey: {1}\nAppSecret: {2}\nRedirectUri: {3}\nException : {4}",
                    ResponseCode,
                    dropBoxAppKey,
                    dropBoxAppSecret,
                    returnBackURL,
                    e);
                MsgError = message.ToString();
            }
        }
예제 #5
0
        // GET: /Home/Auth
        public async Task <ActionResult> AuthAsync(string code, string state)
        {
            try
            {
                var response = await DropboxOAuth2Helper.ProcessCodeFlowAsync(
                    code,
                    MvcApplication.AppKey,
                    MvcApplication.AppSecret,
                    this.RedirectUri);

                MvcApplication.AccessToken = response.AccessToken;

                this.Flash("This account has been connected to Dropbox.", FlashLevel.Success);
                return(RedirectToAction("Index"));
            }
            catch (Exception e)
            {
                var message = string.Format(
                    "code: {0}\nAppKey: {1}\nAppSecret: {2}\nRedirectUri: {3}\nException : {4}",
                    code,
                    MvcApplication.AppKey,
                    MvcApplication.AppSecret,
                    this.RedirectUri,
                    e);
                this.Flash(message, FlashLevel.Danger);
                return(RedirectToAction("Index"));
            }
        }
예제 #6
0
        public static async Task <string> GetUserAuthorisationCode(string userAccessCode, AuthorisationSettings authSettings)
        {
            var message = "";

            try
            {
                OAuth2Response response = await DropboxOAuth2Helper.ProcessCodeFlowAsync(userAccessCode,
                                                                                         authSettings.DropboxAppKey,
                                                                                         authSettings.DropboxSecretKey,
                                                                                         authSettings.DropboxRedirectURI.ToString());

                if (response != null)
                {
                    //if (response.State != null && response.State.Equals(authSettings.SecurityToken))
                    //{
                    return(response.AccessToken);
                    //}
                }
                else
                {
                    message = "Failed: Access code is not secure.";
                }
            }
            catch (ArgumentException ex)
            {
                message = "Failed: " + ex.Message;
            }

            return(message);
        }
예제 #7
0
        /// <summary>
        /// Get a working provider (so, an access token) from Dropbox.
        /// </summary>
        /// <param name="savedState"></param>
        /// <param name="silent"></param>
        public async Task <string> Register(string savedState = null, bool silent = false)
        {
            var result = new TaskCompletionSource <string>();

            // Check if the saved token is still usable
            if (await ClientFactory(savedState))
            {
                result.SetResult(savedState);
                return(await result.Task);
            }

            // If the saved token was not usable and silent is true, return with failure
            if (silent)
            {
                result.SetResult(null);
                return(await result.Task);
            }

            // If it is not, try to get a new one
            var url = DropboxOAuth2Helper.GetAuthorizeUri(
                OAuthResponseType.Code,
                Obscure.CaesarDecode(Config.AppKey),
                (string)null);

            var form    = new CodeForm(url.ToString(), 43);
            var success = false;

            form.OnResult += async code =>
            {
                success = true;
                form.Close();

                var response = await DropboxOAuth2Helper.ProcessCodeFlowAsync(
                    code,
                    Obscure.CaesarDecode(Config.AppKey),
                    Obscure.CaesarDecode(Config.AppSecret));

                if (response?.AccessToken != null && await ClientFactory(response.AccessToken))
                {
                    result.SetResult(response.AccessToken);
                }
                else
                {
                    result.SetResult(null);
                }
            };

            form.FormClosed += (sender, args) =>
            {
                if (!success)
                {
                    result.SetResult(null);
                }
            };

            Process.Start(url.ToString());
            form.Show();

            return(await result.Task);
        }
        public async Task <bool> DropboxAuthenticationSecondStep(ApplicationUser user, string code, string state, string redirectUri)
        {
            try
            {
                if (user.PhotographerInfo.ConnectState != state)
                {
                    return(false);
                }

                var response = await DropboxOAuth2Helper.ProcessCodeFlowAsync(
                    code,
                    MvcApplication.AppKey,
                    MvcApplication.AppSecret,
                    redirectUri);

                user.PhotographerInfo.DropboxAccessToken = response.AccessToken;
                await userManager.UpdateAsync(user);

                await signInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
예제 #9
0
        ///<summary>Called by Open Dental Proper to get the real access code form the code given by Dropbox.  Returns empty string if something went wrong.</summary>
        public static string GetDropboxAccessToken(string code, string appkey, string appsecret)
        {
            string ret = "";
            ApplicationException ae   = null;
            ManualResetEvent     wait = new ManualResetEvent(false);

            new Task(async() => {
                try {
                    OAuth2Response resp = await DropboxOAuth2Helper.ProcessCodeFlowAsync(code, appkey, appsecret);
                    if (string.IsNullOrEmpty(resp.AccessToken))
                    {
                        throw new Exception("Empty token returned by Dropbox.");
                    }
                    ret = resp.AccessToken;
                }
                catch (Exception ex) {
                    ae = new ApplicationException(ex.Message, ex);
                }
                wait.Set();
            }).Start();
            wait.WaitOne(10000);
            if (ae != null)
            {
                throw ae;
            }
            return(ret);
        }
예제 #10
0
        public static string ProcessCodeFlow(string code)
        {
            var task = DropboxOAuth2Helper.ProcessCodeFlowAsync(code, appKey, appSecret, client: httpClient);
            var resp = task.Result;

            return(resp.AccessToken);
        }
예제 #11
0
        public async Task <ActionResult> Authentication(string code, string state)
        {
            var response = await DropboxOAuth2Helper.ProcessCodeFlowAsync(code, _dropboxOptions.SmallSqliteKitAppKey, _dropboxOptions.SmallSqliteKitAppSecret, RedirectUri.ToString());

            _logger.LogInformation($"Got user token from Dropbox: {response.AccessToken}");

            await _configRepository.SetDropboxTokensAsync(response.AccessToken, response.RefreshToken);

            return(Redirect("~/"));
        }
예제 #12
0
        public async Task <ActionResult> DropboxCallback(string code, string state)
        {
            var settings = _settingsService.GetSiteSettings();
            var response = await DropboxOAuth2Helper.ProcessCodeFlowAsync(code, settings.DropBoxSettings.ApplicationKey, settings.DropBoxSettings.ApplicationSecret, "http://localhost:43729/Settings/Settings/DropboxCallback");

            settings.DropBoxSettings.AccessToken = response.AccessToken;
            _settingsService.UpdateSiteSettings(settings);

            return(RedirectToAction("Index", "Home", new { Area = "" }));
        }
예제 #13
0
        public void FinishAuthorisation(string code)
        {
            string clientId = this.context.Settings.Dropbox_ClientId;
            string secret   = this.context.Settings.Dropbox_Secret;

            // There's no point in making this async - it blocks everything anyway
            Task <OAuth2Response> task = DropboxOAuth2Helper.ProcessCodeFlowAsync(code, clientId, secret);

            task.Wait();
            string accessToken = task.Result.AccessToken;

            this.context.LocalStorage.SettingsWrite("Dropbox_AccessToken", accessToken);
        }
    public static async Task <OAuth2Response> ValidateAccessCode(string code)
    {
        try
        {
            OAuth2Response response = await DropboxOAuth2Helper.ProcessCodeFlowAsync(code, _AppKey, _AppSecret);

            return(response);
        }
        catch (OAuth2Exception e)
        {
            Debug.Log(e.Message);
            return(null);
        }
    }
예제 #15
0
        public async Task <ActionResult> DropboxAuthentication(string code, string state)
        {
            var response = await DropboxOAuth2Helper.ProcessCodeFlowAsync(code, dropboxAppKey, dropboxAppSecret, RedirectUri.ToString());

            logger.LogInformation($"Got user tokens from Dropbox: {response.AccessToken} / {response.RefreshToken}");

            var userAccount = await userAccountRepository.GetUserAccountAsync(User);

            userAccount.DropboxAccessToken  = response.AccessToken;
            userAccount.DropboxRefreshToken = response.RefreshToken;
            await userAccountRepository.SaveUserAccountAsync(userAccount);

            return(Redirect("~/"));
        }
예제 #16
0
        public bool FinishFromUri(Uri uri)
        {
            try
            {
                string   url = uri.ToString();
                string[] param = url.Substring(url.IndexOf('?') + 1).Split('&');
                string   state, code;
                if (param[0].StartsWith("state"))
                {
                    state = param[0].Substring(param[0].IndexOf('=') + 1);
                    code  = param[1].Substring(param[1].IndexOf('=') + 1);
                }
                else
                {
                    code  = param[0].Substring(param[0].IndexOf('=') + 1);
                    state = param[1].Substring(param[1].IndexOf('=') + 1);
                }

                if (state != oauth2State)
                {
                    return(false);
                }

                HttpClientHandler handler = new HttpClientHandler();
                if (Arg.ProxyState != 0)
                {
                    handler.Proxy = new System.Net.WebProxy(Arg.ProxyHost, Arg.ProxyPort);
                }
                OAuth2Response result = DropboxOAuth2Helper.ProcessCodeFlowAsync(code, App_key, App_secret, RedirectUri, new HttpClient(handler)).Result;

                this.AccessToken = result.AccessToken;
                Arg.AccessToken  = result.AccessToken;
                this.Uid         = result.Uid;

                DropboxClientConfig config = new DropboxClientConfig("ConfDoctor");
                config.HttpClient = new HttpClient(handler);
                client            = new DropboxClient(AccessToken, config);

                FullAccount account = client.Users.GetCurrentAccountAsync().Result;
                Arg.UserName = account.Name.DisplayName;

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
        public async Task <IActionResult> Authorize([FromQuery] string code, [FromQuery] string state)
        {
            var response = await DropboxOAuth2Helper.ProcessCodeFlowAsync(code, "bwhwa6n4oglbqu6", "vlpo8i1p3bzj0u4",
                                                                          $"{Request.Scheme}://{Request.Host}/api/account/authorize");

            if (_appData.SessionCache.ContainsKey(state))
            {
                _appData.SessionCache[state] = response.AccessToken;
            }
            else
            {
                _appData.SessionCache.Add(state, response.AccessToken);
            }

            return(RedirectPermanent($"{Request.Scheme}://{Request.Host}"));
        }
예제 #18
0
        public async void ProcessCodeFlow(string appKey, string appSecret, Action <string> onSuccess,
                                          Action <Exception> onFailure)
        {
            //continue code flow
            try
            {
                OAuth2Response result = await DropboxOAuth2Helper.ProcessCodeFlowAsync(AccessToken, appKey, appSecret);

                AccessToken = result.AccessToken;
                onSuccess(AccessToken);
            }
            catch (Exception e)
            {
                onFailure(e);
            }
        }
        private const string AppSecret = "2a3si3j0kvgrush"; // <- not that secret in that case

        /// <summary>
        /// Initializes the Dropbox library, and ignites the authorization process if needed.
        /// </summary>
        /// <returns>Returns a task to be awaited until the initialization process is done.</returns>
        public async Task Initialize()
        {
            string accessToken;

            config = ConfigurationUtility.ReadConfigurationFile(GetType());

            if (config.TryGetValue("AccessToken", out accessToken) && string.IsNullOrWhiteSpace(accessToken) == false)
            {
                accessToken = SecurityUtility.UnprotectString(accessToken, DataProtectionScope.CurrentUser);
            }

            if (string.IsNullOrWhiteSpace(accessToken))
            {
                Uri authorizeUri = DropboxOAuth2Helper.GetAuthorizeUri(AppKey, false);
                var url          = authorizeUri.ToString();

                MessageBox.Show("After you click the OK button on this dialog, a web page asking you to allow the application will open, and then another one containing a code.\r\n\r\nOnce you see the code, please copy it to the clipboard by selecting it and pressing Ctrl+C, or right click and 'Copy' menu.", "Authorization", MessageBoxButton.OK, MessageBoxImage.Information);
                Process.Start(url);
                MessageBox.Show("Please proceed by closing this dialog once you copied the code.", "Authorization", MessageBoxButton.OK, MessageBoxImage.Information);

                string code = null;

                try
                {
                    code = Clipboard.GetText();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("An error occured:\r\n" + ex.Message, "Authorization Failed", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                OAuth2Response response = await DropboxOAuth2Helper.ProcessCodeFlowAsync(code, AppKey, AppSecret);

                accessToken = response.AccessToken;

                ConfigurationUtility.CreateConfigurationFile(GetType(), new Dictionary <string, string>
                {
                    { "AccessToken", SecurityUtility.ProtectString(accessToken, DataProtectionScope.CurrentUser) },
                });

                MessageBox.Show("Authorization process succeeded.", "Authorization", MessageBoxButton.OK, MessageBoxImage.Information);
            }

            dropboxClient = new DropboxClient(accessToken);
        }
예제 #20
0
        // GET: /Home/Auth
        public async Task <ActionResult> Auth(string code, string state)
        {
            try
            {
                var response = await DropboxOAuth2Helper.ProcessCodeFlowAsync(
                    code,
                    appKey,
                    appSecret,
                    this.RedirectUri);

                var dropboxAccessToken = response.AccessToken;
                Session["Token"] = dropboxAccessToken;
            }
            catch (Exception e)
            {
            }
            return(RedirectToAction("IndexSuccess"));
        }
예제 #21
0
        // GET: /Home/Auth
        public async Task <string> AuthAsync(string code)
        {
            try
            {
                var response = await DropboxOAuth2Helper.ProcessCodeFlowAsync(
                    code,
                    clientId,
                    secret,
                    RedirectUri);

                return(response.AccessToken);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Get token error:" + ex.ToString());
                return("");
            }
        }
예제 #22
0
        async private void NextBtn_Click(object sender, EventArgs e)
        {
            if (StorageList.SelectedIndices.Count > 0)
            {
                if (StorageList.SelectedIndices[0].Equals(0))
                {
                    if (!IsDropboxEnable)
                    {
                        Process.Start(DropboxOAuth2Helper.GetAuthorizeUri("jj2eyo41xn837y7", false).ToString()); //вызов страницы для подтверждения доступа и получения кода
                        CodeConfirmForm LetMeConfirm = new CodeConfirmForm();
                        LetMeConfirm.ShowDialog();
                        OAuth2Response resp = await DropboxOAuth2Helper.ProcessCodeFlowAsync(LetMeConfirm.CodeConfirm, "jj2eyo41xn837y7", "ldfel2pg0e7yery", null, null);

                        DropboxCode = resp.AccessToken;
                        LetMeConfirm.Close();
                        SQLiteConnection    db = new SQLiteConnection(DataBasePath);
                        List <StorageClass> DataStorageImport = new List <StorageClass>();
                        DataStorageImport = db.Query <StorageClass>("SELECT * FROM StorageKeys WHERE UserId='" + UserId + "'");
                        if (DataStorageImport.Count > 0)
                        {
                            DataStorageImport = db.Query <StorageClass>("UPDATE StorageKeys SET DropboxKey='" + DropboxCode + "'" + "WHERE UserId='" + UserId + "'");
                        }
                        else
                        {
                            StorageClass RegUserInfo = new StorageClass()
                            {
                                Id      = UserId,
                                DropBox = DropboxCode
                            };
                            db.Insert(RegUserInfo);
                        }
                        IsDropboxEnable = true;
                    }
                    //using (DropboxClient dbx = new DropboxClient(DropboxCode))
                    //{
                    //    var full = await dbx.Users.GetCurrentAccountAsync();
                    //    MessageBox.Show("Username: "******"\n E-mail: " + full.Email);
                    //}
                    WorkDirectioryForm WorkDirectory = new WorkDirectioryForm();
                    WorkDirectory.Show();
                    this.Hide();
                }
            }
        }
예제 #23
0
        private async Task <OAuth2Response> HandleJSRedirect()
        {
            var context = await http.GetContextAsync();

            // We only care about request to TokenRedirectUri endpoint.
            while (context.Request.Url.AbsolutePath != JSRedirectUri.AbsolutePath)
            {
                context = await http.GetContextAsync();
            }

            String redirectUri = new Uri(context.Request.QueryString["url_with_fragment"]).ToString();

            //retrieve code from redirectUri
            int            index    = redirectUri.IndexOf("code=");
            String         code     = redirectUri.Substring(index + 5);
            OAuth2Response response = await DropboxOAuth2Helper.ProcessCodeFlowAsync(code, _appKey, _appSecret, RedirectUri.ToString());

            return(response);
        }
예제 #24
0
        public async Task <string> GetToken()
        {
            Console.WriteLine("Za chwilę otworzona zostanie przeglądarka na stronie Dropbox w celu utworzenia kodu autoryzacyjnego.");
            Console.WriteLine("Zezwól aplikacji na dostęp do twojego konta dropbox i");

            var builder = new ConfigurationBuilder().AddUserSecrets <Secrets.DropboxSecrets>();
            var secret  = builder.Build().GetSection(nameof(Secrets.DropboxSecrets)).Get <Secrets.DropboxSecrets>();

            var q = DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Code, clientId: secret.AppKey, redirectUri: (string)null);

            Process.Start(new ProcessStartInfo {
                UseShellExecute = true, FileName = q.ToString()
            });
            Console.Write("Wprowadź kod autoryzacyjny: ");
            string code = Console.ReadLine();
            var    auth = await DropboxOAuth2Helper.ProcessCodeFlowAsync(code, secret.AppKey, secret.AppSecret);

            return(auth.AccessToken);
        }
예제 #25
0
        private async Task <OAuth2Response> GetAuthToken(string code)
        {
            OAuth2Response response = null;

            try
            {
                response = await DropboxOAuth2Helper.ProcessCodeFlowAsync(
                    code,
                    dropboxAuthAppKey,
                    dropboxAuthAppSecret,
                    RedirectURI);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex.InnerException);
            }

            return(response);
        }
예제 #26
0
        public async Task <ActionResult> AuthAsync(string code, string state)
        {
            string AppKey      = _config.Value.AppKey;
            string AppSecret   = _config.Value.AppSecret;
            string RedirectUri = _config.Value.Redirect_Url;

            try
            {
                var response = await DropboxOAuth2Helper.ProcessCodeFlowAsync(
                    code,
                    AppKey,
                    AppSecret,
                    RedirectUri);

                HttpContext.Session.SetString(AccessToken, response.AccessToken);
                return(RedirectPermanent("/"));
            }
            catch (Exception e)
            {
                return(Json(""));
            }
        }
예제 #27
0
        /// <summary>
        /// Asynchronously checks the provider authentication code.
        /// </summary>
        /// <param name="code">The code.</param>
        protected override async Task <SerializableAPIResult <SerializableAPICredentials> > CheckProviderAuthCodeAsync(
            string code)
        {
            if (m_result == null)
            {
                m_result = new SerializableAPIResult <SerializableAPICredentials>();
            }

            try
            {
                OAuth2Response response = await DropboxOAuth2Helper.ProcessCodeFlowAsync(code,
                                                                                         Util.Decrypt(DropboxCloudStorageServiceSettings.Default.AppKey,
                                                                                                      CultureConstants.InvariantCulture.NativeName),
                                                                                         Util.Decrypt(DropboxCloudStorageServiceSettings.Default.AppSecret,
                                                                                                      CultureConstants.InvariantCulture.NativeName)).ConfigureAwait(false);

                await CheckAuthenticationAsync().ConfigureAwait(false);

                if (!m_result.HasError)
                {
                    DropboxCloudStorageServiceSettings.Default.AccessToken = response.AccessToken;
                }
            }
            catch (OAuth2Exception exc)
            {
                m_result.Error = new SerializableAPIError {
                    ErrorMessage = exc.Message
                };
            }
            catch (Exception exc)
            {
                m_result.Error = new SerializableAPIError {
                    ErrorMessage = exc.Message
                };
            }

            return(m_result);
        }
예제 #28
0
        // GET: /IntegratedOptions/Auth
        public async Task <ActionResult> Auth(string code, string state)
        {
            try
            {
                var response = await DropboxOAuth2Helper.ProcessCodeFlowAsync(
                    code,
                    appKey,
                    appSecret,
                    RedirectUri);

                using (var dbx = new DropboxClient(response.AccessToken))
                {
                    var full = await dbx.Users.GetCurrentAccountAsync();

                    var list = await dbx.Files.ListFolderAsync(string.Empty);

                    var checkexisting = db.CoDropbox.Where(p => p.SiteCoID == siteusercompanyid).FirstOrDefault();
                    if (checkexisting == null)
                    {
                        db.InsertDropbox(base.siteusercompanyid, appKey, appSecret, Encoding.ASCII.GetBytes(response.AccessToken), full.Email, "", DateTime.UtcNow.Date, RedirectUri);
                        db.SaveChanges();
                    }
                }
                return(RedirectToAction("Index"));
            }
            catch (Exception e)
            {
                var message = string.Format(
                    "code: {0}\nAppKey: {1}\nAppSecret: {2}\nRedirectUri: {3}\nException : {4}",
                    code,
                    appKey,
                    appSecret,
                    this.RedirectUri,
                    e);
                return(RedirectToAction("error"));
            }
        }
예제 #29
0
        public async Task <ActionResult> Auth(string code, string state)
        {
            try
            {
                if (this.currentUser.ConnectState != state)
                {
                    this.Flash("There was an error connecting to Dropbox.");
                    return(this.RedirectToAction("Index"));
                }

                var response = await DropboxOAuth2Helper.ProcessCodeFlowAsync(
                    code,
                    MvcApplication.AppKey,
                    MvcApplication.AppSecret,
                    this.RedirectUri);

                this.currentUser.DropboxAccessToken = response.AccessToken;
                this.currentUser.ConnectState       = string.Empty;
                await this.store.SaveChangesAsync();

                this.Flash("This account has been connected to Dropbox.", FlashLevel.Success);
                return(RedirectToAction("Profile"));
            }
            catch (Exception e)
            {
                var message = string.Format(
                    "code: {0}\nAppKey: {1}\nAppSecret: {2}\nRedirectUri: {3}\nException : {4}",
                    code,
                    MvcApplication.AppKey,
                    MvcApplication.AppSecret,
                    this.RedirectUri,
                    e);
                this.Flash(message, FlashLevel.Danger);
                return(RedirectToAction("Profile"));
            }
        }
예제 #30
0
        /// <summary>
        /// Acquires a dropbox access token and saves it to the default settings for the app.
        /// <para>
        /// This fetches the access token from the applications settings, if it is not found there
        /// (or if the user chooses to reset the settings) then the UI in <see cref="LoginForm"/> is
        /// displayed to authorize the user.
        /// </para>
        /// </summary>
        /// <returns>A valid uid if a token was acquired or null.</returns>
        private async Task <string> AcquireAccessToken(string[] scopeList, IncludeGrantedScopes includeGrantedScopes)
        {
            Console.Write("Reset settings (Y/N) ");
            if (Console.ReadKey().Key == ConsoleKey.Y)
            {
                Settings.Default.Reset();
            }
            Console.WriteLine();

            var accessToken  = Settings.Default.AccessToken;
            var refreshToken = Settings.Default.RefreshToken;

            if (string.IsNullOrEmpty(accessToken))
            {
                try
                {
                    Console.WriteLine("Waiting for credentials.");
                    var state        = Guid.NewGuid().ToString("N");
                    var authorizeUri = DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Code, ApiKey, RedirectUri, state: state, tokenAccessType: TokenAccessType.Offline, scopeList: scopeList, includeGrantedScopes: includeGrantedScopes);
                    var http         = new HttpListener();
                    http.Prefixes.Add(LoopbackHost);

                    http.Start();

                    System.Diagnostics.Process.Start(authorizeUri.ToString());

                    // Handle OAuth redirect and send URL fragment to local server using JS.
                    await HandleOAuth2Redirect(http);

                    // Handle redirect from JS and process OAuth response.
                    var redirectUri = await HandleJSRedirect(http);

                    Console.WriteLine("Exchanging code for token");
                    var tokenResult = await DropboxOAuth2Helper.ProcessCodeFlowAsync(redirectUri, ApiKey, ApiSecret, RedirectUri.ToString(), state);

                    Console.WriteLine("Finished Exchanging Code for Token");
                    // Bring console window to the front.
                    SetForegroundWindow(GetConsoleWindow());
                    accessToken  = tokenResult.AccessToken;
                    refreshToken = tokenResult.RefreshToken;
                    var uid = tokenResult.Uid;
                    Console.WriteLine("Uid: {0}", uid);
                    Console.WriteLine("AccessToken: {0}", accessToken);
                    if (tokenResult.RefreshToken != null)
                    {
                        Console.WriteLine("RefreshToken: {0}", refreshToken);
                        Settings.Default.RefreshToken = refreshToken;
                    }
                    if (tokenResult.ExpiresAt != null)
                    {
                        Console.WriteLine("ExpiresAt: {0}", tokenResult.ExpiresAt);
                    }
                    if (tokenResult.ScopeList != null)
                    {
                        Console.WriteLine("Scopes: {0}", String.Join(" ", tokenResult.ScopeList));
                    }
                    Settings.Default.AccessToken = accessToken;
                    Settings.Default.Uid         = uid;
                    Settings.Default.Save();
                    http.Stop();
                    return(uid);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error: {0}", e.Message);
                    return(null);
                }
            }

            return(null);
        }