2019-07-09 18:39:29 +00:00
|
|
|
using System.Linq;
|
|
|
|
using System.Threading.Tasks;
|
2020-06-13 17:44:01 +00:00
|
|
|
|
|
|
|
using Dapper;
|
|
|
|
|
2019-07-09 18:39:29 +00:00
|
|
|
using Microsoft.AspNetCore.Http;
|
|
|
|
|
2020-02-12 14:16:19 +00:00
|
|
|
using PluralKit.Core;
|
|
|
|
|
2019-07-09 18:39:29 +00:00
|
|
|
namespace PluralKit.API
|
|
|
|
{
|
|
|
|
public class TokenAuthService: IMiddleware
|
|
|
|
{
|
|
|
|
public PKSystem CurrentSystem { get; set; }
|
|
|
|
|
2020-06-13 17:44:01 +00:00
|
|
|
private readonly IDatabase _db;
|
2019-07-09 18:39:29 +00:00
|
|
|
|
2020-06-13 17:44:01 +00:00
|
|
|
public TokenAuthService(IDatabase db)
|
2019-07-09 18:39:29 +00:00
|
|
|
{
|
2020-06-13 17:44:01 +00:00
|
|
|
_db = db;
|
2019-07-09 18:39:29 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
|
|
|
|
{
|
|
|
|
var token = context.Request.Headers["Authorization"].FirstOrDefault();
|
|
|
|
if (token != null)
|
|
|
|
{
|
2020-06-13 17:44:01 +00:00
|
|
|
CurrentSystem = await _db.Execute(c => c.QueryFirstOrDefaultAsync("select * from systems where token = @token", new { token }));
|
2019-07-09 18:39:29 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
await next.Invoke(context);
|
|
|
|
CurrentSystem = null;
|
|
|
|
}
|
2020-01-11 15:49:20 +00:00
|
|
|
|
|
|
|
public LookupContext ContextFor(PKSystem system) =>
|
|
|
|
system.Id == CurrentSystem?.Id ? LookupContext.ByOwner : LookupContext.API;
|
|
|
|
|
|
|
|
public LookupContext ContextFor(PKMember member) =>
|
|
|
|
member.System == CurrentSystem?.Id ? LookupContext.ByOwner : LookupContext.API;
|
2019-07-09 18:39:29 +00:00
|
|
|
}
|
|
|
|
}
|