예제 #1
0
    private async void GetFreshAuth()
    {
        if (PKCEConfig == null)
        {
            return;
        }

        // Load PKCE verifier/challenge with any config changes
        var(verifier, challenge) = LoadConfigPKCECodes();

        await _server.Start();

        // On auth is recieved, save and start service
        try
        {
            _server.AuthorizationCodeReceived += (sender, response) => this.OnAuthCodeRecieved(sender, response, verifier);
        }
        catch (Exception e)
        {
            Debug.LogError(e.ToString());
        }

        // Create login request
        LoginRequest request = new LoginRequest(_server.BaseUri, _clientID, LoginRequest.ResponseType.Code)
        {
            CodeChallenge       = challenge,
            CodeChallengeMethod = "S256",
            Scope = PKCEConfig.APIScopes,
        };

        // Build Uri and open in browser
        Uri uri = request.ToUri();

        try
        {
            BrowserUtil.Open(uri);
        }
        catch (Exception e)
        {
            Debug.LogError($"Exception opening browser for auth: '{e.ToString()}'");
        }
    }
예제 #2
0
        /// <inheritdoc/>
        public async Task <JsonResult> GetSpotifyAuthenticationToken()
        {
            var authToken = string.Empty;

            var(verifier, challenge) = PKCEUtil.GenerateCodes();
            await SpotifyAuthServer.Start();

            // Temporary auth server lsitens for Spotify callback.
            SpotifyAuthServer.AuthorizationCodeReceived += async(sender, response) =>
            {
                await SpotifyAuthServer.Stop();

                PKCETokenResponse token = await new OAuthClient().RequestToken(
                    new PKCETokenRequest(SpotifyClientId, response.Code, SpotifyAuthServer.BaseUri, verifier));
                authToken = JsonConvert.SerializeObject(token);
            };

            // Make spotify auth call.
            var request = new LoginRequest(SpotifyAuthServer.BaseUri, SpotifyClientId, LoginRequest.ResponseType.Code)
            {
                CodeChallenge       = challenge,
                CodeChallengeMethod = "S256",
                Scope = new List <string> {
                    UserReadPrivate, UserReadRecentlyPlayed
                }
            };

            Uri uri = request.ToUri();

            try
            {
                BrowserUtil.Open(uri);
                Task.Delay(10000).Wait();
            }
            catch (Exception)
            {
                Console.WriteLine("Unable to open URL, manually open: {0}", uri);
            }

            return(new JsonResult(authToken));
        }
예제 #3
0
        private void StartAuthentication()
        {
            var(verifier, challenge) = PKCEUtil.GenerateCodes();

            Task.WaitAll(_server.Start());

            _server.AuthorizationCodeReceived += async(sender, response) =>
            {
                await _server.Stop();

                PKCETokenResponse dataTask = await new OAuthClient().RequestToken(
                    new PKCETokenRequest(clientId, response.Code, _server.BaseUri, verifier)
                    );

                File.WriteAllText(CredentialsPath, JsonConvert.SerializeObject(dataTask));
                File.SetAttributes(CredentialsPath, FileAttributes.ReadOnly);
                Start();
            };

            var request = new LoginRequest(_server.BaseUri, clientId, LoginRequest.ResponseType.Code)
            {
                CodeChallenge       = challenge,
                CodeChallengeMethod = "S256",
                Scope = new List <string> {
                    UgcImageUpload, UserReadRecentlyPlayed, UserReadPlaybackPosition, UserTopRead, UserLibraryRead, UserLibraryModify, PlaylistModifyPrivate, PlaylistReadPrivate, UserFollowRead, PlaylistModifyPublic, UserReadPrivate, UserReadEmail, AppRemoteControl, Streaming, UserReadCurrentlyPlaying, UserModifyPlaybackState, UserReadPlaybackState, PlaylistReadCollaborative, UserFollowModify
                }
            };

            Uri uri = request.ToUri();

            try
            {
                BrowserUtil.Open(uri);
            }
            catch (Exception)
            {
                Console.WriteLine("Unable to open URL, manually open: {0}", uri);
            }
        }
예제 #4
0
        private static async Task StartAuthentication()
        {
            var(verifier, challenge) = PKCEUtil.GenerateCodes();

            await _server.Start();

            _server.AuthorizationCodeReceived += async(sender, response) =>
            {
                await _server.Stop();

                PKCETokenResponse token = await new OAuthClient().RequestToken(
                    new PKCETokenRequest(clientId !, response.Code, _server.BaseUri, verifier)
                    );

                await File.WriteAllTextAsync(CredentialsPath, JsonConvert.SerializeObject(token));
                await Start();
            };

            var request = new LoginRequest(_server.BaseUri, clientId !, LoginRequest.ResponseType.Code)
            {
                CodeChallenge       = challenge,
                CodeChallengeMethod = "S256",
                Scope = new List <string> {
                    UserReadEmail, UserReadPlaybackPosition, UserReadCurrentlyPlaying, UserModifyPlaybackState, UserReadPlaybackState, UserReadPlaybackState, UserReadPrivate, PlaylistReadPrivate, PlaylistModifyPublic, PlaylistModifyPrivate, Streaming, AppRemoteControl, PlaylistReadCollaborative
                }
            };

            Uri uri = request.ToUri();

            try
            {
                BrowserUtil.Open(uri);
            }
            catch (Exception)
            {
                Console.WriteLine("Unable to open URL, manually open: {0}", uri);
            }
        }
    }
예제 #5
0
        public async void StartAuth()
        {
            GenerateCode();

            await _server.Start();

            _server.AuthorizationCodeReceived += async(sender, response) =>
            {
                await _server.Stop();

                TokenResponse = await new OAuthClient().RequestToken(
                    new PKCETokenRequest(_clientId !, response.Code, _server.BaseUri, _verifier)
                    );

                Start();
            };

            CreateLoginRequest();
            var uri = _loginRequest.ToUri();

            BrowserUtil.Open(uri);
        }
예제 #6
0
        private static async Task StartAuthentication()
        {
            await _server.Start();

            _server.ImplictGrantReceived += OnImplictGrantReceived;

            var request = new LoginRequest(_server.BaseUri, _clientId !, LoginRequest.ResponseType.Token)
            {
                Scope = new List <string> {
                    UserLibraryModify, UserLibraryRead, UserFollowModify
                }
            };

            Uri uri = request.ToUri();

            try
            {
                BrowserUtil.Open(uri);
            }
            catch (Exception)
            {
                Console.WriteLine("Unable to open URL, manually open: {0}", uri);
            }
        }
예제 #7
0
        private static async Task StartAuthentication()
        {
            await _server.Start();

            _server.AuthorizationCodeReceived += OnAuthorizationCodeReceived;

            var request = new LoginRequest(_server.BaseUri, clientId !, LoginRequest.ResponseType.Code)
            {
                Scope = new List <string> {
                    UserReadEmail, UserReadPrivate, PlaylistReadPrivate
                }
            };

            Uri uri = request.ToUri();

            try
            {
                BrowserUtil.Open(uri);
            }
            catch (Exception)
            {
                Console.WriteLine("Unable to open URL, manually open: {0}", uri);
            }
        }
예제 #8
0
 private void MailingListButton_Click(object sender, EventArgs e)
 {
     BrowserUtil.Open(new Uri("https://emu.freenetproject.org/cgi-bin/mailman/listinfo/support/"));
 }
예제 #9
0
 private void SupportChatButton_Click(object sender, EventArgs e)
 {
     BrowserUtil.Open(new Uri("https://freenetproject.org/irc.html"));
 }
        async void SpotifyWebAuth()
        {
            try
            {
                if (File.Exists(_path))
                {
                    var token_response = DeserializeConfig(_path, _rsaKey);

                    var authenticator = new PKCEAuthenticator(_clientID, token_response, _path);

                    var config = SpotifyClientConfig.CreateDefault()
                                 .WithAuthenticator(authenticator);
                    _spotify = new SpotifyClient(config);

                    SerializeConfig(token_response, _path, _rsaKey);


                    // This appears to be the easiest way to check if the Spotify client works, but it's not great:
                    try
                    {
                        await _spotify.Search.Item(new SearchRequest(SearchRequest.Types.Track, "fasdofimasdofiasdnfaosnf"));

                        _auth = 1;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Spotify agent dead: " + e);
                        throw new System.NullReferenceException();
                    }
                }
                else
                {
                    throw new System.NullReferenceException("Token.xml not found!");
                }
            }
            catch (System.NullReferenceException)
            {
                var(verifier, challenge) = PKCEUtil.GenerateCodes(120);

                var loginRequest = new LoginRequest(
                    new Uri("http://localhost:5000/callback"), _clientID, LoginRequest.ResponseType.Code)
                {
                    CodeChallengeMethod = "S256",
                    CodeChallenge       = challenge,
                    Scope = new[] { Scopes.UserLibraryModify, Scopes.UserFollowModify, Scopes.UserFollowRead, Scopes.UserLibraryRead }
                };
                var uri = loginRequest.ToUri();

                var server = new EmbedIOAuthServer(new Uri("http://localhost:5000/callback"), 5000);

                server.PkceReceived += async(sender, response) =>
                {
                    await server.Stop();

                    var initialResponse = await new OAuthClient().RequestToken(
                        new PKCETokenRequest(_clientID, response.Code, server.BaseUri, verifier)
                        );

                    //WriteOutput(initialResponse);

                    var authenticator = new PKCEAuthenticator(_clientID, initialResponse, _path);

                    var config = SpotifyClientConfig.CreateDefault()
                                 .WithAuthenticator(authenticator);
                    _spotify = new SpotifyClient(config);

                    //WriteOutput(initialResponse);
                    SerializeConfig(initialResponse, _path, _rsaKey);
                };
                await server.Start();

                try
                {
                    BrowserUtil.Open(uri);
                }
                catch (Exception)
                {
                    Console.WriteLine("Unable to open URL, manually open: {0}", uri);
                }

                _auth = 1;
            }
            catch (System.Net.WebException)
            {
                _auth = 0;
            }
            finally
            {
                mbApiInterface.MB_RefreshPanels();
                panel.Invalidate();
            }
        }
예제 #11
0
        public void Register(CommandLineApplication app)
        {
            app.Command("login", (login) =>
            {
                login.Description = "Log into a user account via OAuth2. Only required when accessing user related data.";

                var addressCmd = login.OptionalOption <Uri?>(
                    "-a|--address",
                    $"URI of the webserver used to authenticate. Also needs to be added as redirect uri to your spotify app",
                    addressDefault,
                    CommandOptionType.SingleValue
                    );
                addressCmd.Validators.Add(new AbsoluteURIValidator());

                var portOpt = login.OptionalOption <int?>(
                    "-p|--port",
                    $"Listen port of the authentication webserver",
                    portDefault,
                    CommandOptionType.SingleValue
                    );

                var scopesOpt = login.OptionalOption <List <string>?>(
                    "-s|--scopes",
                    $"A comma seperated list of scopes to request",
                    "All",
                    CommandOptionType.SingleValue
                    );

                var timeoutOpt = login.OptionalOption <int?>(
                    "-t|--timeout",
                    $"Timeout of command in seconds",
                    timeoutDefault,
                    CommandOptionType.SingleValue
                    );

                var stateOpt = login.OptionalOption <int?>(
                    "--state",
                    $"State value used for the authentcation",
                    "random generated string",
                    CommandOptionType.SingleValue
                    );

                login.OnExecuteAsync(async(cancel) =>
                {
                    if (
                        string.IsNullOrEmpty(_appConfig.SpotifyApp.ClientId) ||
                        string.IsNullOrEmpty(_appConfig.SpotifyApp.ClientSecret))
                    {
                        _console.WriteLine("client-id or client-secret not set. Please run `spotify-cli config` before logging in");
                        Environment.Exit(1);
                    }

                    var state   = stateOpt.Value() ?? Guid.NewGuid().ToString();
                    var address = addressCmd.ParsedValue ?? addressDefault;
                    var port    = portOpt.ParsedValue ?? portDefault;
                    var timeout = TimeSpan.FromSeconds(timeoutOpt.ParsedValue ?? timeoutDefault);
                    var scopes  = scopesOpt.ParsedValue ?? new List <string> {
                        Scopes.AppRemoteControl,
                        Scopes.PlaylistModifyPrivate,
                        Scopes.PlaylistModifyPublic,
                        Scopes.PlaylistReadCollaborative,
                        Scopes.PlaylistReadPrivate,
                        Scopes.Streaming,
                        Scopes.UgcImageUpload,
                        Scopes.UserFollowModify,
                        Scopes.UserFollowRead,
                        Scopes.UserLibraryModify,
                        Scopes.UserLibraryRead,
                        Scopes.UserModifyPlaybackState,
                        Scopes.UserReadCurrentlyPlaying,
                        Scopes.UserReadEmail,
                        Scopes.UserReadPlaybackPosition,
                        Scopes.UserReadPlaybackState,
                        Scopes.UserReadPrivate,
                        Scopes.UserReadRecentlyPlayed,
                        Scopes.UserTopRead,
                    };

                    var uri = _login.GenerateLoginURI(address, _appConfig.SpotifyApp.ClientId, scopes, state);
                    BrowserUtil.Open(uri);

                    _console.WriteLine("If no browser opened, visit the following URL manually:\n");
                    _console.WithColor(ConsoleColor.Cyan, () => _console.WriteLine($"{uri}\n"));

                    var logginError = await _login.WaitForLogin(address, port, timeout, state);

                    if (logginError == null)
                    {
                        _console.WithColor(ConsoleColor.Green, () =>
                        {
                            _console.WriteLine($"You're now logged in as {_appConfig.Account.DisplayName} ({_appConfig.Account.Id})");
                        });
                    }
                    else
                    {
                        _console.WithColor(ConsoleColor.Red, () => _console.WriteLine($"Login failed: {logginError}"));
                    }
                });
            });
        }
        public async Task ConnectWebClient(bool keepRefreshToken = true)
        {
            _securityStore = SecurityStore.Load(pluginDirectory);

            EmbedIOAuthServer _server = new EmbedIOAuthServer(new Uri("http://localhost:4002/callback"), 4002);

            if (_securityStore.HasRefreshToken && keepRefreshToken)
            {
                var refreshRequest = new AuthorizationCodeRefreshRequest(_securityStore.ClientId,
                                                                         _securityStore.ClientSecret,
                                                                         _securityStore.RefreshToken);
                var refreshResponse = await new OAuthClient().RequestToken(refreshRequest);
                lock (_lock)
                {
                    _spotifyClient = new SpotifyClient(refreshResponse.AccessToken);
                }
            }
            else
            {
                await _server.Start();

                _server.AuthorizationCodeReceived += async(object sender, AuthorizationCodeResponse response) =>
                {
                    await _server.Stop();

                    AuthorizationCodeTokenResponse token = await new OAuthClient().RequestToken(
                        new AuthorizationCodeTokenRequest(_securityStore.ClientId,
                                                          _securityStore.ClientSecret,
                                                          response.Code,
                                                          _server.BaseUri));
                    lock (_lock)
                    {
                        _securityStore.RefreshToken = token.RefreshToken;
                        _securityStore.Save(pluginDirectory);
                        _spotifyClient = new SpotifyClient(token.AccessToken);
                    }
                };

                _server.ErrorReceived += async(object sender, string error, string state) =>
                {
                    Console.WriteLine($"Aborting authorization, error received: {error}");
                    await _server.Stop();
                };

                var request = new LoginRequest(_server.BaseUri, _securityStore.ClientId, LoginRequest.ResponseType.Code)
                {
                    Scope = new List <string> {
                        UserLibraryRead,
                        UserReadEmail,
                        UserReadPrivate,
                        UserReadPlaybackPosition,
                        UserReadCurrentlyPlaying,
                        UserReadPlaybackState,
                        UserModifyPlaybackState,
                        AppRemoteControl,
                        PlaylistReadPrivate
                    }
                };

                Uri uri = request.ToUri();
                try {
                    BrowserUtil.Open(uri);
                } catch (Exception) {
                    Console.WriteLine("Unable to open URL, manually open: {0}", uri);
                };
            };
        }
예제 #13
0
        public void RetryLogin()
        {
            var uri = _loginRequest.ToUri();

            BrowserUtil.Open(uri);
        }
예제 #14
0
        private void openFreenetMenuItem_Click(object sender = null, EventArgs e = null)
        {
            Start();

            var pollFproxy = new Thread(() =>
            {
                var fproxyListening = false;
                var showSlowOpen    = Settings.Default.ShowSlowOpenTip;
                var openArgs        = e as OpenArgs;
                if (openArgs != null)
                {
                    showSlowOpen = openArgs.ShowSlow;
                }

                /*
                 * TODO: Programatic way to get loopback address? This would not support IPv6.
                 * Use FProxy bind interface?
                 */
                var loopback = new IPAddress(new byte[] { 127, 0, 0, 1 });

                var timer = new Stopwatch();

                using (var sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                {
                    timer.Start();
                    while (_node.IsRunning())
                    {
                        try
                        {
                            sock.Connect(loopback, _node.FProxyPort);
                            fproxyListening = true;
                            break;
                        }
                        catch (SocketException ex)
                        {
                            FNLog.Debug("Connecting got error: {0}",
                                        Enum.GetName(typeof(SocketError), ex.SocketErrorCode));
                            Thread.Sleep(SocketPollInterval);
                        }

                        // Show a startup notification if it's taking a while.
                        if (showSlowOpen && timer.ElapsedMilliseconds > SlowOpenThreshold)
                        {
                            BeginInvoke(new Action(() =>
                            {
                                trayIcon.BalloonTipText = strings.FreenetStarting;
                                trayIcon.ShowBalloonTip(SlowOpenTimeout);
                            }));
                            showSlowOpen = false;
                        }
                    }
                    timer.Stop();
                }

                if (fproxyListening)
                {
                    FNLog.Debug("FProxy listening after {0}", timer.Elapsed);
                    BrowserUtil.Open(new Uri(String.Format("http://localhost:{0:d}", _node.FProxyPort)), true);
                }
            });

            pollFproxy.Start();
        }