|
| 1 | +using System; |
| 2 | +using System.Linq; |
| 3 | +using System.Security.Claims; |
| 4 | +using System.Security.Principal; |
| 5 | +using System.Threading; |
| 6 | +using System.Threading.Tasks; |
| 7 | +using Finite.Commands; |
| 8 | +using Microsoft.Extensions.Logging; |
| 9 | + |
| 10 | +namespace ConsoleCommands.Authentication |
| 11 | +{ |
| 12 | + internal class PlatformUserMiddleware : ICommandMiddleware |
| 13 | + { |
| 14 | + private static readonly Random Rng = new Random(); |
| 15 | + private readonly ILogger _logger; |
| 16 | + |
| 17 | + public PlatformUserMiddleware(ILogger<PlatformUserMiddleware> logger) |
| 18 | + { |
| 19 | + _logger = logger; |
| 20 | + } |
| 21 | + |
| 22 | + public ValueTask<ICommandResult> ExecuteAsync(CommandMiddleware next, |
| 23 | + CommandContext context, CancellationToken cancellationToken) |
| 24 | + { |
| 25 | + cancellationToken.ThrowIfCancellationRequested(); |
| 26 | + |
| 27 | + if (OperatingSystem.IsWindows()) |
| 28 | + { |
| 29 | + var identity = WindowsIdentity.GetCurrent(); |
| 30 | + |
| 31 | + context.User.AddIdentity(identity); |
| 32 | + } |
| 33 | + else |
| 34 | + { |
| 35 | + context.User.AddIdentity( |
| 36 | + new ClaimsIdentity( |
| 37 | + new[] |
| 38 | + { |
| 39 | + new Claim(ClaimTypes.Name, Environment.UserName), |
| 40 | + } |
| 41 | + )); |
| 42 | + } |
| 43 | + |
| 44 | + if (Rng.NextDouble() > 0.5) |
| 45 | + { |
| 46 | + _logger.LogDebug("Adding cool role"); |
| 47 | + context.User.AddIdentity( |
| 48 | + new ClaimsIdentity( |
| 49 | + new[] |
| 50 | + { |
| 51 | + new Claim(ClaimTypes.Role, "Cool") |
| 52 | + } |
| 53 | + )); |
| 54 | + } |
| 55 | + |
| 56 | + var nameClaim = context.User |
| 57 | + .FindFirst(x => x.Type == ClaimTypes.Name); |
| 58 | + |
| 59 | + if (nameClaim != null) |
| 60 | + _logger.LogInformation("Loaded user identity as {name}", |
| 61 | + nameClaim.Value); |
| 62 | + else |
| 63 | + _logger.LogWarning("Unable to load user identity"); |
| 64 | + |
| 65 | + return next(); |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments