aboutsummaryrefslogtreecommitdiff
path: root/Timeline/Controllers/ControllerAuthExtensions.cs
diff options
context:
space:
mode:
author杨宇千 <crupest@outlook.com>2020-02-01 00:26:35 +0800
committerGitHub <noreply@github.com>2020-02-01 00:26:35 +0800
commit7b962cd876719fb871569ba3c97fb5545721a3f8 (patch)
treef02f8d57440c777d4732bc4439f82e8b25c6732c /Timeline/Controllers/ControllerAuthExtensions.cs
parent289c7e1fada1f4dae6ce5e421e997ebddd55c2df (diff)
parentbcb0a2361467614531a337282da1fd23996924f1 (diff)
downloadtimeline-7b962cd876719fb871569ba3c97fb5545721a3f8.tar.gz
timeline-7b962cd876719fb871569ba3c97fb5545721a3f8.tar.bz2
timeline-7b962cd876719fb871569ba3c97fb5545721a3f8.zip
Merge pull request #56 from crupest/dev
Refactor API to be RESTful.
Diffstat (limited to 'Timeline/Controllers/ControllerAuthExtensions.cs')
-rw-r--r--Timeline/Controllers/ControllerAuthExtensions.cs40
1 files changed, 40 insertions, 0 deletions
diff --git a/Timeline/Controllers/ControllerAuthExtensions.cs b/Timeline/Controllers/ControllerAuthExtensions.cs
new file mode 100644
index 00000000..00a65454
--- /dev/null
+++ b/Timeline/Controllers/ControllerAuthExtensions.cs
@@ -0,0 +1,40 @@
+using Microsoft.AspNetCore.Mvc;
+using System;
+using System.Security.Claims;
+using Timeline.Auth;
+using static Timeline.Resources.Controllers.ControllerAuthExtensions;
+
+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)
+ {
+ var claim = controller.User.FindFirst(ClaimTypes.NameIdentifier);
+ if (claim == null)
+ throw new InvalidOperationException(ExceptionNoUserIdentifierClaim);
+
+ if (long.TryParse(claim.Value, out var value))
+ return value;
+
+ throw new InvalidOperationException(ExceptionUserIdentifierClaimBadFormat);
+ }
+
+ public static long? GetOptionalUserId(this ControllerBase controller)
+ {
+ var claim = controller.User.FindFirst(ClaimTypes.NameIdentifier);
+ if (claim == null)
+ return null;
+
+ if (long.TryParse(claim.Value, out var value))
+ return value;
+
+ throw new InvalidOperationException(ExceptionUserIdentifierClaimBadFormat);
+ }
+ }
+}