Webiant Logo Webiant Logo
  1. No results found.

    Try your search with a different keyword or use * as a wildcard.

CurrentOSUser.cs

using System.Diagnostics;
using System.Runtime.Versioning;
using System.Security.Principal;

namespace Nop.Web.Framework.Security;

/// 
/// Represent information about current OS user 
/// 
public static class CurrentOSUser
{
    #region Ctor

    static CurrentOSUser()
    {
        Name = Environment.UserName;

        DomainName = Environment.UserDomainName;

        switch (Environment.OSVersion.Platform)
        {
            case PlatformID.Win32NT:
                if (OperatingSystem.IsWindows())
                    PopulateWindowsUser();
                break;
            case PlatformID.Unix:
                PopulateLinuxUser();
                break;
            default:
                UserId = Name;
                Groups = new List();
                break;
        }
    }

    #endregion

    #region Methods

    /// 
    /// Populate information about windows user
    /// 
    [SupportedOSPlatform("windows")]
    public static void PopulateWindowsUser()
    {
        Groups = WindowsIdentity.GetCurrent().Groups?.Select(p => p.Value).ToList();
        UserId = Name;
    }

    /// 
    /// Populate information about linux user
    /// 
    public static void PopulateLinuxUser()
    {
        var process = new Process
        {
            StartInfo = new ProcessStartInfo
            {
                RedirectStandardInput = true,
                RedirectStandardOutput = true,
                UseShellExecute = false,
                FileName = "sh",
                Arguments = "-c \" id -u ; id -G \""
            }
        };

        process.Start();
        process.WaitForExit();

        var res = process.StandardOutput.ReadToEnd();

        var respars = res.Split("\n");

        UserId = respars[0];
        Groups = respars[1].Split(" ").ToList();
    }

    #endregion

    #region Properties

    /// 
    /// Returns user name
    /// 
    public static string Name { get; }

    /// 
    /// Returns user domain name for Windows or group for Linux
    /// 
    public static string DomainName { get; }

    /// 
    /// Returns user groups
    /// 
    public static List Groups { get; private set; }

    /// 
    /// Returns user name for Windows or user Id  for Linux like 1001
    /// 
    public static string UserId { get; private set; }

    /// 
    /// Returns full user name
    /// 
    public static string FullName => $@"{DomainName}\{Name}";

    #endregion
}