-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApiController.cs
440 lines (362 loc) · 13.2 KB
/
ApiController.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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using SearchAThing.Util;
using SearchAThing.EFUtil;
using SearchAThing.PsqlUtil;
namespace WorkedHoursTrackerWebapi.Controllers
{
[Route("[controller]/[action]")]
public class ApiController : Controller
{
private readonly IGlobal global;
private readonly ILogger logger;
private readonly MyDbContext ctx;
#region constructor
public ApiController(MyDbContext ctx, ILogger<ApiController> logger)
{
this.logger = logger;
this.ctx = ctx;
logger.LogDebug($"ApiController created");
EnsureAdminAccount();
}
void EnsureAdminAccount()
{
if (!ctx.Users.Any(w => w.username == "admin"))
{
ctx.Users.Add(new User()
{
username = "admin",
password = "admin",
create_timestamp = DateTime.Now
});
ctx.SaveChanges();
}
}
#endregion
#region helpers
CommonResponse InvalidAuthResponse()
{
return new CommonResponse() { ExitCode = CommonResponseExitCodes.InvalidAuth };
}
CommonResponse SuccessfulResponse()
{
return new CommonResponse() { ExitCode = CommonResponseExitCodes.Successful };
}
CommonResponse ErrorResponse(string errMsg)
{
return new CommonResponse()
{
ExitCode = CommonResponseExitCodes.Error,
ErrorMsg = errMsg
};
}
bool CheckAuth(string username, string password)
{
var qdb = ctx.Users.FirstOrDefault(w => w.username == username);
var is_valid = qdb != null && qdb.password == password;
if (!is_valid)
{
var q = HttpContext.Request.Headers["X-Real-IP"];
var url = "";
if (q.Count > 0) url = q.First();
logger.LogWarning($"invalid login attempt from [{url}]");
// todo : autoban
}
return is_valid;
}
#endregion
#region USERS
[HttpPost]
public CommonResponse SaveUser(string username, string password, User jUser)
{
try
{
// disallow non admin
if (jUser == null || username != "admin" || !CheckAuth(username, password)) return InvalidAuthResponse();
User user = null;
if (jUser.id == 0)
{
if (jUser.username == "admin") throw new Exception($"cannot create builtin admin account");
user = new User()
{
username = jUser.username,
create_timestamp = DateTime.UtcNow
};
ctx.Users.Add(user);
}
else
{
user = ctx.Users.FirstOrDefault(w => w.id == jUser.id);
if (user == null) throw new Exception($"unable to find [{jUser.id}] entry");
user.modify_timestamp = DateTime.UtcNow;
}
user.password = jUser.password?.Trim();
user.cost = jUser.cost;
ctx.SaveChanges();
return SuccessfulResponse();
}
catch (Exception ex)
{
return ErrorResponse(ex.Message);
}
}
[HttpPost]
public CommonResponse LoadUser(string username, string password, int id)
{
try
{
// disallow non admin
if (username != "admin" || !CheckAuth(username, password)) return InvalidAuthResponse();
var response = new UserResponse();
response.User = ctx.Users.FirstOrDefault(w => w.id == id);
return response;
}
catch (Exception ex)
{
return ErrorResponse(ex.Message);
}
}
[HttpPost]
public CommonResponse DeleteUser(string username, string password, int id)
{
try
{
// disallow non admin
if (username != "admin" || !CheckAuth(username, password)) return InvalidAuthResponse();
var q = ctx.Users.FirstOrDefault(w => w.id == id);
if (q != null)
{
ctx.Users.Remove(q);
ctx.SaveChanges();
}
return SuccessfulResponse();
}
catch (Exception ex)
{
return ErrorResponse(ex.Message);
}
}
[HttpPost]
public CommonResponse UserList(string username, string password, string filter)
{
try
{
// disallow non admin
if (username != "admin" || !CheckAuth(username, password)) return InvalidAuthResponse();
var response = new UserListResponse();
response.UserList = ctx.Users.ToList().Where(r => new[] { r.username }.MatchesFilter(filter)).ToList();
return response;
}
catch (Exception ex)
{
return ErrorResponse(ex.Message);
}
}
#endregion
#region JOBS
[HttpPost]
public CommonResponse SaveJob(string username, string password, Job jJob)
{
try
{
if (username != "admin" || !CheckAuth(username, password)) return InvalidAuthResponse();
Job job = null;
if (jJob.id == 0)
{
job = new Job()
{
create_timestamp = DateTime.UtcNow
};
ctx.Jobs.Add(job);
}
else
{
job = ctx.Jobs.FirstOrDefault(w => w.id == jJob.id);
if (job == null) throw new Exception($"unable to find [{jJob.id}] entry");
}
job.name = jJob.name.Trim();
job.base_cost = jJob.base_cost;
job.min_cost = jJob.min_cost;
job.cost_factor = jJob.cost_factor;
job.minutes_round = jJob.minutes_round;
ctx.SaveChanges();
return SuccessfulResponse();
}
catch (Exception ex)
{
return ErrorResponse(ex.Message);
}
}
[HttpPost]
public CommonResponse LoadJob(string username, string password, int id_job)
{
try
{
if (username != "admin" || !CheckAuth(username, password)) return InvalidAuthResponse();
var response = new ContactInfoResponse();
response.Job = ctx.Jobs.FirstOrDefault(w => w.id == id_job);
return response;
}
catch (Exception ex)
{
return ErrorResponse(ex.Message);
}
}
[HttpPost]
public CommonResponse DeleteJob(string username, string password, int id_job)
{
try
{
if (username != "admin" || !CheckAuth(username, password)) return InvalidAuthResponse();
var q = ctx.Jobs.FirstOrDefault(w => w.id == id_job);
if (q != null)
{
ctx.Jobs.Remove(q);
ctx.SaveChanges();
}
return SuccessfulResponse();
}
catch (Exception ex)
{
return ErrorResponse(ex.Message);
}
}
public class tmptype
{
public long id_job;
public double? hours_sum;
}
[HttpPost]
public CommonResponse JobList(string username, string password, string filter)
{
try
{
if (!CheckAuth(username, password)) return InvalidAuthResponse();
var response = new JobListResponse();
var user = ctx.Users.First(w => w.username == username);
var query = $@"
select uj.id_job, sum(uj.hours_increment) hours_sum from ""user"" u
left join userjob uj on u.id = uj.id_user
where uj.id_user={user.id}
group by uj.id_job";
var resTotalHours = ctx.ExecSQL<tmptype>(query).ToDictionary(w => w.id_job, w => w.hours_sum);
if (resTotalHours.Count > 0)
{
query = $@"
select uj.id_job, sum(uj.hours_increment) hours_sum from ""user"" u
left join userjob uj on u.id = uj.id_user
where uj.id_user={user.id} and uj.trigger_timestamp>{(DateTime.UtcNow - TimeSpan.FromDays(1)).ToPsql()}
group by uj.id_job";
var resLast24Hours = ctx.ExecSQL<tmptype>(query).ToDictionary(w => w.id_job, w => w.hours_sum);
// build job_ids
var job_ids = string.Join(',', resTotalHours.Select(w => w.Key.ToString()));
// retrieve is_active
query = $@"
select a.id_job from
(
select uj.id_job, first(uj.is_active order by uj.trigger_timestamp desc) is_active from userjob uj
where uj.id_user={user.id} and uj.id_job in ({job_ids})
group by id_job
) a where a.is_active";
var resActiveJobs = ctx.ExecSQL<long>(query).ToHashSet();
query = $"select * from job where id in ({job_ids})";
response.jobList = ctx.Jobs.AsNoTracking().FromSql(query).ToList();
foreach (var x in response.jobList)
{
x.total_hours = resTotalHours[x.id].GetValueOrDefault();
double? last24h = null;
if (resLast24Hours.TryGetValue(x.id, out last24h))
x.last_24_hours = last24h.GetValueOrDefault();
x.is_active = resActiveJobs.Contains(x.id);
}
if (username != "admin")
{
foreach (var x in response.jobList)
{
x.base_cost = 0;
x.min_cost = 0;
x.cost_factor = 0;
x.minutes_round = 0;
}
}
}
else
response.jobList = new List<Job>();
return response;
}
catch (Exception ex)
{
return ErrorResponse(ex.Message);
}
}
#endregion
#region USER JOB
[HttpPost]
public CommonResponse TriggerJob(string username, string password, int id_job)
{
try
{
if (!CheckAuth(username, password)) return InvalidAuthResponse();
var user = ctx.Users.First(w => w.username == username);
var id_user = user.id;
var job = ctx.Jobs.First(w => w.id == id_job);
var last = ctx.UserJobs.Where(r => r.user.id == id_user).OrderByDescending(w => w.trigger_timestamp).FirstOrDefault();
UserJob newEntry = null;
newEntry = new UserJob()
{
user = user,
job = job,
trigger_timestamp = DateTime.UtcNow
};
if (last == null)
{
newEntry.is_active = true;
}
else
{
switch (last.is_active)
{
case true:
{
newEntry.is_active = false;
newEntry.hours_increment = (newEntry.trigger_timestamp - last.trigger_timestamp).TotalHours;
}
break;
case false:
{
newEntry.is_active = true;
}
break;
}
}
ctx.UserJobs.Add(newEntry);
ctx.SaveChanges();
return SuccessfulResponse();
}
catch (Exception ex)
{
return ErrorResponse(ex.Message);
}
}
#endregion
[HttpPost]
public CommonResponse IsAuthValid(string username, string password)
{
try
{
if (!CheckAuth(username, password)) return InvalidAuthResponse();
return SuccessfulResponse();
}
catch (Exception ex)
{
return ErrorResponse(ex.Message);
}
}
}
}