aboutsummaryrefslogtreecommitdiff
path: root/Timeline/Controllers/ControllerAuthExtensions.cs
blob: 90da8a9346c4a5ffb4071d4a2cc1624c10cf34f7 (plain)
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
40
41
42
43
44
45
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.");
        }

        public static long? GetOptionalUserId(this ControllerBase controller)
        {
            if (controller.User == null)
                return 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.");
        }
    }
}