slik-dispenser/backend/Controllers/DispenserController.cs

40 lines
1.1 KiB
C#
Raw Normal View History

using Microsoft.AspNetCore.Mvc;
using MQTTnet;
using backend.Application;
2023-12-05 22:43:02 +00:00
using backend.Models;
2023-12-19 12:37:13 +00:00
using backend.Middleware;
namespace backend.Controllers;
[ApiController]
public class DispenserController : ControllerBase
{
[HttpPost("Dispense")]
2023-12-19 12:37:13 +00:00
[MiddlewareFilter(typeof(AuthenticationMiddlewareBuilder))]
public IActionResult Dispense()
{
2023-12-19 12:37:13 +00:00
var user = ApplicationState.DbContext!.Users.FirstOrDefault(user => user.SessionToken == Request.Cookies["session"]!.ToString());
if (user == null) {
return BadRequest("Invalid session token");
}
if (user.Dispenses == 0) {
Console.WriteLine("Poorfag");
return BadRequest("Not enough dispenses on account");
}
user.Dispenses--;
Console.WriteLine("Dispensing..");
var message = new MqttApplicationMessageBuilder()
.WithTopic("dispense")
.WithPayload("dispense")
.Build();
2023-12-05 22:43:02 +00:00
ApplicationState.DbContext!.Add(new DispenserLog { Timestamp = DateTime.Now });
ApplicationState.DbContext!.SaveChanges();
ApplicationState.MqttClient!.PublishAsync(message, CancellationToken.None);
2023-12-19 12:37:13 +00:00
return Ok();
}
}