This repository was archived by the owner on Dec 2, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathOAuthHelper.cs
More file actions
230 lines (194 loc) · 8.88 KB
/
OAuthHelper.cs
File metadata and controls
230 lines (194 loc) · 8.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
using AniAPI.NET.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace AniAPI.NET.Helpers
{
internal class OAuthHelper
{
private readonly string _authPath = "https://api.aniapi.com/v1/oauth";
private readonly string _codePath = "https://api.aniapi.com/v1/oauth/token";
private string _clientId;
private string _clientSecret;
private string _redirectUri;
private AuthType _type;
public OAuthHelper(string clientId, string redirectUri)
{
_clientId = clientId;
_redirectUri = redirectUri;
_type = AuthType.IMPLICIT_GRANT;
}
public OAuthHelper(string clientId, string clientSecret, string redirectUri)
{
_clientId = clientId;
_clientSecret = clientSecret;
_redirectUri = redirectUri;
_type = AuthType.AUTHORIZATION_CODE;
}
public async Task<string> Login()
{
string token = null;
string url = _authPath;
string state = generateRandomState();
switch (_type)
{
case AuthType.IMPLICIT_GRANT:
if (string.IsNullOrEmpty(_clientId))
{
throw new ArgumentException("Could not be null", "clientId");
}
if (string.IsNullOrEmpty(_redirectUri))
{
throw new ArgumentException("Could not be null", "redirectUri");
}
url += $"?response_type=token&client_id={_clientId}&redirect_uri={_redirectUri}&state={state}";
break;
case AuthType.AUTHORIZATION_CODE:
if (string.IsNullOrEmpty(_clientId))
{
throw new ArgumentException("Could not be null", "clientId");
}
if (string.IsNullOrEmpty(_clientSecret))
{
throw new ArgumentException("Could not be null", "clientSecret");
}
if (string.IsNullOrEmpty(_clientId))
{
throw new ArgumentException("Could not be null", "clientId");
}
url += $"?response_type=code&client_id={_clientId}&redirect_uri={_redirectUri}&state={state}";
break;
}
openAuthPage(url);
bool canExit = false;
int timeout = 1000 * 60 * 3;
using (ManualResetEvent canExitHandle = new ManualResetEvent(canExit))
{
Task.Factory.StartNew(() =>
{
while (true)
{
if (timeout <= 0 || !string.IsNullOrEmpty(token))
{
canExit = true;
canExitHandle.Set();
break;
}
Thread.Sleep(1000);
timeout -= 1000;
}
});
using (HttpListener listener = new HttpListener())
{
listener.Prefixes.Add($"{_redirectUri}/");
listener.Start();
while (!canExit)
{
IAsyncResult waitResult = listener.BeginGetContext((IAsyncResult result) =>
{
try
{
HttpListenerContext context = listener.EndGetContext(result);
switch (_type)
{
case AuthType.IMPLICIT_GRANT:
if (context.Request.QueryString.Count <= 0)
{
using (StreamWriter writer = new StreamWriter(context.Response.OutputStream))
{
writer.WriteLine($@"
<html><body><script type=""text/javascript"">
if(window.location.hash) {{
const hashes = window.location.hash.substring(1).split('&');
const token = hashes[0].split('=')[1];
const state = hashes[1].split('=')[1];
fetch('{_redirectUri}?token=' + token + '&state=' + state, {{
method: 'GET'
}});
}}
</script></body></html>
");
}
}
else
{
if (context.Request.QueryString["state"] != state)
{
throw new ArgumentException("Value must match with the generated one!", "state");
}
token = context.Request.QueryString["token"];
}
break;
case AuthType.AUTHORIZATION_CODE:
if (context.Request.QueryString.Count > 0)
{
if (context.Request.QueryString["state"] != state)
{
throw new ArgumentException("Value must match with the generated one!", "state");
}
string code = context.Request.QueryString["code"];
HttpClient client = new HttpClient();
string url = $"{_codePath}?client_id={_clientId}&client_secret={_clientSecret}&code={code}&redirect_uri={_redirectUri}";
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
HttpResponseMessage response = client.SendAsync(request).Result;
APIResponse<string> tokenResult= JsonConvert.DeserializeObject<APIResponse<string>>(response.Content.ReadAsStringAsync().Result);
if(tokenResult.StatusCode == 200)
{
token = tokenResult.Data;
}
}
break;
}
}
catch { }
}, null);
WaitHandle.WaitAny(new WaitHandle[]
{
waitResult.AsyncWaitHandle,
canExitHandle
});
}
listener.Stop();
}
}
return token;
}
private void openAuthPage(string url)
{
if(RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Process.Start(new ProcessStartInfo(url) { UseShellExecute = true });
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
Process.Start("xdg-open", url);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
Process.Start("open", url);
}
else
{
throw new Exception("OS not supported!");
}
}
private string generateRandomState()
{
return Guid.NewGuid().ToString();
}
private enum AuthType
{
IMPLICIT_GRANT,
AUTHORIZATION_CODE
}
}
}