diff options
author | crupest <crupest@outlook.com> | 2020-01-29 23:13:15 +0800 |
---|---|---|
committer | crupest <crupest@outlook.com> | 2020-01-29 23:13:15 +0800 |
commit | dd0097af5c4ccbe25a1faca2286d729c93fd4116 (patch) | |
tree | c9131a7b95fffd64bf2c26527d7f62fbdefa7e2c /Timeline/Controllers/ControllerAuthExtensions.cs | |
parent | 401a0c86054711bf5ebdce7d7717c9b59bffc2fa (diff) | |
download | timeline-dd0097af5c4ccbe25a1faca2286d729c93fd4116.tar.gz timeline-dd0097af5c4ccbe25a1faca2286d729c93fd4116.tar.bz2 timeline-dd0097af5c4ccbe25a1faca2286d729c93fd4116.zip |
...
Diffstat (limited to 'Timeline/Controllers/ControllerAuthExtensions.cs')
-rw-r--r-- | Timeline/Controllers/ControllerAuthExtensions.cs | 30 |
1 files changed, 30 insertions, 0 deletions
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.");
+ }
+ }
+}
|