-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.cs
206 lines (173 loc) · 5.66 KB
/
api.cs
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
using auth;
using static util.Util;
using static System.Configuration.ConfigurationManager;
using System;
using System.Net;
using System.Data;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using System.Data.SqlClient;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Net.Http.Formatting;
using System.ComponentModel.DataAnnotations;
using Owin;
using Newtonsoft.Json.Linq;
using Microsoft.Owin.Hosting;
sealed class XXX {
public static async Task Main(string[] args) {
cl(String.Join("", collatz(new int[]{(new Random()).Next(1, 79)})
.Select(e => $@"[;38;5;{e % 256};1m|")) + @"[0m");
var url = $"http://{AppSettings["host"]}:{AppSettings["port"]}";
using (WebApp.Start<Startup>(url)) {
Console.WriteLine(":: listening on " + url);
await Task.Delay(-1);
}
}
}
sealed class Startup {
private static readonly string[] noauth = {
"login", "hailstone", "echo", "env", "now"
};
public void Configuration(IAppBuilder app) {
var config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
config.Formatters.Clear();
config.Formatters.Add(new JsonMediaTypeFormatter());
app.Use(async (ctx, next) => {
if ((await Auth.SessionUser(ctx.Request.Cookies["_id"]) != null)
|| noauth.Contains(ctx.Request.Path.ToString().Substring(1))) {
cl($"[;38;5;27;1m[{ctx.Request.Path}][0m");
await next();
} else {
cl($"[;38;5;9;1m[{ctx.Request.Path}][0m");
ctx.Response.StatusCode = 403;
ctx.Response.ReasonPhrase = "Not Authorized";
ctx.Response.ContentType = "application/json";
await ctx.Response.WriteAsync("{\"error\": \"verboten\"}");
}
});
config.EnsureInitialized();
app.UseWebApi(config);
}
}
public sealed class XXXController: ApiController {
[HttpPost]
[Route("env")]
public async Task<IHttpActionResult> _env() =>
Ok(await Task.Run(() => env()));
[HttpPost]
[Route("echo")]
public async Task<IHttpActionResult> _echo(JObject o) {
if (o.Value<int>("delay") is int n && n > 0) {
await Task.Delay(n);
}
return Ok(
new {t = DateTimeOffset.UtcNow.ToLocalTime().ToString(), o}
);
}
[HttpPost]
[Route("hailstone")]
public IHttpActionResult _hailstone(JObject o) =>
Ok((o.Value<int>("n") is int n && n > 0) ? collatz(new int[]{n}) : null);
[HttpPost]
[Route("now")]
public async Task<IHttpActionResult> _now() {
IDictionary<string, object> database;
using (var conn = new SqlConnection(
ConnectionStrings["dbconn"].ConnectionString)) {
await conn.OpenAsync();
using (var cmd = conn.CreateCommand()) {
cmd.CommandText = @"
select
current_timezone() as tz,
sysdatetimeoffset() as local,
datediff(second, '19700101', sysutcdatetime()) as unix_timestamp,
sysutcdatetime() as unix_timestamp_str";
database = (await cmd.ExecuteReaderAsync())
.ToDictArray().FirstOrDefault();
}
}
var ut = DateTimeOffset.UtcNow;
return Ok(new {
user = await Auth.SessionUser(Request),
server = new {
tz = TimeZoneInfo.Local.DisplayName,
local = ut.ToLocalTime().ToString(),
unix_timestamp = ut.ToUnixTimeSeconds(),
unix_timestamp_str = ut.ToString()
},
database
});
}
[HttpPost]
[Route("login")]
public async Task<HttpResponseMessage> _login(ModelLogin login) {
if (await Auth.SessionUser(Request) != null) {
return Request.CreateResponse(HttpStatusCode.OK);
}
if (!ModelState.IsValid) {
return Request.CreateResponse(
HttpStatusCode.Forbidden,
ModelState
.Values.SelectMany(v => v.Errors.Select(b => b.ErrorMessage))
.Where(e => e != "")
);
}
IDictionary<string, object> user;
using (var conn = new SqlConnection(
ConnectionStrings["dbconn"].ConnectionString)) {
await conn.OpenAsync();
using (var user_cmd = conn.CreateCommand()) {
user_cmd.CommandText
= "select id, passwd from usuario where username=@u";
user_cmd.Parameters.Add(
new SqlParameter("u", SqlDbType.VarChar){Value = login.username});
user = (await user_cmd.ExecuteReaderAsync())
.ToDictArray().FirstOrDefault();
}
}
if(user is null
|| (user["passwd"]?.ToString()?.Split(':') is string[] arr
&& !FixedTimeEquals(
deriveKey(
password: login.passwd,
salt: Convert.FromBase64String(arr[0])
),
Convert.FromBase64String(arr[1])
))
) {
return Request.CreateResponse(
HttpStatusCode.Forbidden,
new {error = "incorrect user/pass"}
);
}
int userid = (int) user["id"];
Auth.SessionClear(userid);
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Headers.Add("set-cookie", "_id="
+ await Auth.SessionSet(userid)
+ ";domain=" + AppSettings["host"]
+ ";path=/;httponly;samesite=lax;max-age=604800"
);
return response;
}
[HttpPost]
[Route("logout")]
public async Task<HttpResponseMessage> _logout() {
Auth.SessionClear(await Auth.SessionUser(Request));
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Headers.Add("set-cookie", "_id="
+ ";domain=" + AppSettings["host"]
+ ";path=/;httponly;samesite=lax;max-age=0"
);
return response;
}
}
public struct ModelLogin {
[Required(ErrorMessage = "username cannot be blank")]
public string username {get; set;}
[Required(ErrorMessage = "password cannot be blank")]
public string passwd {get; set;}
}