From abde51b167f17301c25e32ae247e7909c0dc9367 Mon Sep 17 00:00:00 2001 From: crupest Date: Wed, 29 Jan 2020 23:13:15 +0800 Subject: ... --- Timeline/Controllers/ControllerAuthExtensions.cs | 30 ++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Timeline/Controllers/ControllerAuthExtensions.cs (limited to 'Timeline/Controllers/ControllerAuthExtensions.cs') diff --git a/Timeline/Controllers/ControllerAuthExtensions.cs b/Timeline/Controllers/ControllerAuthExtensions.cs new file mode 100644 index 00000000..81fd2428 --- /dev/null +++ b/Timeline/Controllers/ControllerAuthExtensions.cs @@ -0,0 +1,30 @@ +using Microsoft.AspNetCore.Mvc; +using System.Security.Claims; +using Timeline.Auth; +using System; + +namespace Timeline.Controllers +{ + public static class ControllerAuthExtensions + { + public static bool IsAdministrator(this ControllerBase controller) + { + return controller.User != null && controller.User.IsAdministrator(); + } + + public static long GetUserId(this ControllerBase controller) + { + if (controller.User == null) + throw new InvalidOperationException("Failed to get user id because User is null."); + + var claim = controller.User.FindFirst(ClaimTypes.NameIdentifier); + if (claim == null) + throw new InvalidOperationException("Failed to get user id because User has no NameIdentifier claim."); + + if (long.TryParse(claim.Value, out var value)) + return value; + + throw new InvalidOperationException("Failed to get user id because NameIdentifier claim is not a number."); + } + } +} -- cgit v1.2.3