This repository has been archived on 2021-03-09. You can view files and clone it, but cannot push or open issues or pull requests.
graf-uloh/server/Ksp.WebServer/Controllers/TasksController.cs

92 lines
2.8 KiB
C#
Raw Permalink Normal View History

2020-09-27 13:08:37 +02:00
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting;
2020-09-27 13:08:37 +02:00
using Microsoft.Extensions.Logging;
namespace Ksp.WebServer.Controllers
{
[ApiController]
2020-11-30 11:47:52 +01:00
[Route("/kurz/tasks.json")]
2020-09-27 13:08:37 +02:00
public class TasksController : ControllerBase
{
private readonly ILogger<TasksController> logger;
private readonly IWebHostEnvironment env;
private readonly KspAuthenticator auth;
2020-09-27 13:08:37 +02:00
public TasksController(ILogger<TasksController> logger, IWebHostEnvironment env, KspAuthenticator auth)
2020-09-27 13:08:37 +02:00
{
this.auth = auth;
2020-09-27 13:08:37 +02:00
this.env = env;
this.logger = logger;
}
string TasksJsonFile(string suffix) => Path.Combine(env.ContentRootPath, $"../../tasks{suffix}.json");
string KspAuthCookie => this.HttpContext.Request.Cookies["ksp_auth"];
2020-09-27 22:36:00 +02:00
2020-09-27 13:08:37 +02:00
[HttpGet]
public IActionResult Get()
{
string file = null;
if (KspAuthCookie is object)
{
var user = KspAuthenticator.ParseAuthCookie(KspAuthCookie);
file = TasksJsonFile("-" + user.Id.Value);
if (!System.IO.File.Exists(file))
file = null;
}
file ??= TasksJsonFile("");
return this.PhysicalFile(file, "text/json");
2020-09-27 22:36:00 +02:00
}
[HttpPost]
public async Task<IActionResult> Post()
{
string suffix;
if (env.IsDevelopment())
{
suffix = "";
}
else
{
if (KspAuthCookie is null)
return StatusCode(401);
var user = await auth.VerifyUser(KspAuthCookie);
if (user == null)
return StatusCode(403);
suffix = "-" + user.Id.Value;
}
2020-09-27 22:36:00 +02:00
using var rdr = new StreamReader(HttpContext.Request.Body);
await System.IO.File.WriteAllTextAsync(TasksJsonFile(suffix), await rdr.ReadToEndAsync());
2020-09-27 22:36:00 +02:00
return Ok();
2020-09-27 13:08:37 +02:00
}
[HttpDelete]
public async Task<IActionResult> Delete()
{
if (env.IsDevelopment())
{
return BadRequest();
}
else
{
if (KspAuthCookie is null)
return StatusCode(401);
var user = await auth.VerifyUser(KspAuthCookie);
if (user == null)
return StatusCode(403);
System.IO.File.Delete(TasksJsonFile("-" + user.Id.Value));
return Ok();
}
}
2020-09-27 13:08:37 +02:00
}
}