| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="IdentityHelper.cs" company="Stéphane ANDRE"> |
| | | 3 | | // Copyright (c) Stéphane ANDRE. All rights reserved. |
| | | 4 | | // </copyright> |
| | | 5 | | // ----------------------------------------------------------------------- |
| | | 6 | | |
| | | 7 | | using System; |
| | | 8 | | |
| | | 9 | | namespace MyNet.Utilities.Authentication; |
| | | 10 | | |
| | | 11 | | /// <summary> |
| | | 12 | | /// Provides helper methods for parsing identity names in the format "DOMAIN\Username". |
| | | 13 | | /// </summary> |
| | | 14 | | public static class IdentityHelper |
| | | 15 | | { |
| | | 16 | | /// <summary> |
| | | 17 | | /// Extracts the domain part from the identity name, assuming the format "DOMAIN\Username". |
| | | 18 | | /// </summary> |
| | | 19 | | /// <param name="identity">The identity name, usually in the format "DOMAIN\Username".</param> |
| | | 20 | | /// <returns>The domain part of the identity name, or an empty string when no domain is present.</returns> |
| | | 21 | | public static string GetDomain(string? identity) |
| | | 22 | | { |
| | 40 | 23 | | var (domain, _) = SplitIdentity(identity); |
| | 40 | 24 | | return domain; |
| | | 25 | | } |
| | | 26 | | |
| | | 27 | | /// <summary> |
| | | 28 | | /// Extracts the username part from the identity name, assuming the format "DOMAIN\Username". |
| | | 29 | | /// </summary> |
| | | 30 | | /// <param name="identity">The identity name, usually in the format "DOMAIN\Username".</param> |
| | | 31 | | /// <returns>The username part of the identity name, or an empty string when unavailable.</returns> |
| | | 32 | | public static string GetName(string? identity) |
| | | 33 | | { |
| | 40 | 34 | | var (_, name) = SplitIdentity(identity); |
| | 40 | 35 | | return name; |
| | | 36 | | } |
| | | 37 | | |
| | | 38 | | private static (string Domain, string Name) SplitIdentity(string? identity) |
| | | 39 | | { |
| | 80 | 40 | | if (string.IsNullOrWhiteSpace(identity)) |
| | 22 | 41 | | return (string.Empty, string.Empty); |
| | | 42 | | |
| | 58 | 43 | | var separatorIndex = identity.AsSpan().IndexOf('\\'); |
| | | 44 | | |
| | 58 | 45 | | return separatorIndex switch |
| | 58 | 46 | | { |
| | 16 | 47 | | < 0 => (string.Empty, identity), |
| | 6 | 48 | | 0 => (string.Empty, identity[1..]), |
| | 36 | 49 | | _ => separatorIndex == identity.Length - 1 ? (identity[..separatorIndex], string.Empty) : (identity[..separa |
| | 58 | 50 | | }; |
| | | 51 | | } |
| | | 52 | | } |
| | | 53 | | |