AuthenticationFactory

This commit is contained in:
Jürgen 2016-07-19 21:15:22 +02:00
parent 0130c96c54
commit d21e84476c
3 changed files with 100 additions and 2 deletions

View File

@ -58,6 +58,7 @@
</Compile>
<Compile Include="Local\Models\SpotifyUri.cs" />
<Compile Include="Local\VolumeMixerControl.cs" />
<Compile Include="Web\Auth\AuthenticationFactory.cs" />
<Compile Include="Web\Enums\TimeRangeType.cs" />
<Compile Include="Web\IClient.cs" />
<Compile Include="Local\Models\CFID.cs" />

View File

@ -0,0 +1,85 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using SpotifyAPI.Web.Enums;
using SpotifyAPI.Web.Models;
namespace SpotifyAPI.Web.Auth
{
public class AuthenticationFactory
{
private readonly string m_RedirectUrl;
private readonly int m_ListeningPort;
private readonly string m_ClientId;
private readonly TimeSpan m_Timeout;
private Scope m_Scope;
public AuthenticationFactory(string redirectUrl, int listeningPort, string clientId, Scope scope, TimeSpan timeout)
{
m_RedirectUrl = redirectUrl;
m_ListeningPort = listeningPort;
m_ClientId = clientId;
m_Scope = scope;
m_Timeout = timeout;
}
public Task<SpotifyWebAPI> GetWebApi()
{
var authentication = new ImplicitGrantAuth
{
RedirectUri = $"{m_RedirectUrl}:{m_ListeningPort}",
ClientId = m_ClientId,
Scope = m_Scope,
State = "XSS"
};
AutoResetEvent authenticationWaitFlag = new AutoResetEvent(false);
SpotifyWebAPI spotifyWebApi = null;
authentication.OnResponseReceivedEvent += (token, state) =>
{
spotifyWebApi = HandleSpotifyResponse(state, token);
authenticationWaitFlag.Set();
};
authentication.StartHttpServer(m_ListeningPort);
authentication.DoAuth();
authenticationWaitFlag.WaitOne(m_Timeout);
if (spotifyWebApi == null)
throw new TimeoutException($"No valid response received for the last {m_Timeout.TotalSeconds} seconds");
authentication.StopHttpServer();
return Task.FromResult(spotifyWebApi);
}
private static SpotifyWebAPI HandleSpotifyResponse(string state, Token token)
{
if (state != "XSS")
throw new SpotifyWebApiException($"Wrong state '{state}' received.");
if (token.Error != null)
throw new SpotifyWebApiException($"Error: {token.Error}");
var spotifyWebApi = new SpotifyWebAPI
{
UseAuth = true,
AccessToken = token.AccessToken,
TokenType = token.TokenType
};
return spotifyWebApi;
}
}
[Serializable]
public class SpotifyWebApiException : Exception
{
public SpotifyWebApiException(string message) : base(message)
{ }
}
}

View File

@ -223,8 +223,20 @@ namespace SpotifyAPI.Web
{
while (IsActive)
{
TcpClient s = _listener.AcceptTcpClient();
processor.Process(s);
_listener.BeginAcceptTcpClient(ar =>
{
try
{
TcpListener listener = (TcpListener)ar.AsyncState;
var tcpCLient = listener.EndAcceptTcpClient(ar);
processor.Process(tcpCLient);
}
catch (ObjectDisposedException)
{
// Ignore
}
}, _listener);
}
}
}