summaryrefslogtreecommitdiffstats
path: root/src/server/Api/V1/BaseV1Route.cs
blob: 21c8128396776402ac42d73135c6c586c7b8b3d5 (plain) (blame)
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
using System.Net.Http.Headers;

namespace IOL.BookmarkThing.Server.Api.V1;

/// <inheritdoc />
[Authorize(AuthenticationSchemes = AuthSchemes)]
[ApiController]
public class BaseV1Route : ControllerBase
{
	private const string AuthSchemes = CookieAuthenticationDefaults.AuthenticationScheme + "," + Constants.BASIC_AUTH_SCHEME;

	/// <summary>
	/// User data for the currently logged on user.
	/// </summary>
	protected LoggedInV1User LoggedInUser => new() {
			Username = User.Identity?.Name,
			Id = User.Claims.SingleOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value.ToGuid() ?? default
	};

	protected bool IsApiCall() {
		if (!Request.Headers.ContainsKey("Authorization")) return false;
		try {
			var authHeader = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]);
			if (authHeader.Parameter == null) return false;
		} catch (Exception e) {
			Console.WriteLine(e);
			return false;
		}

		return true;
	}

	protected bool HasApiPermission(string permission_key) {
		var permission_claim = User.Claims.SingleOrDefault(c => c.Type == permission_key);
		return permission_claim is {
				Value: "True"
		};
	}
}