exilon / QuickLib

Quick development library (AutoMapper, LinQ, IOC Dependency Injection, MemoryCache, Scheduled tasks, Json and Yml Config and Options pattern, Serializers, etc) with crossplatform support for Delphi/Firemonkey (Windows,Linux,OSX/IOS/Android) and freepascal (Windows/Linux).
Apache License 2.0
633 stars 185 forks source link

GetLoggedUserName returns empty string on WSL (include possible fix) #127

Open vesnx opened 7 months ago

vesnx commented 7 months ago

I tested the GetLoggedUserName and found that it is possebly not implemented the right way as for me getlogin reurns a $0000000000000000 (empty string)

I left the original code , removed the cast error for UTF8ToString and look at the "GetEnvironmentVariable" for USER or LOGINNAME

This seems to reflect my user name on all system WSL, VM or physical

Perhaps you consider it in your update

function GetLoggedUserName: string;
{$IFDEF MSWINDOWS}
const
  cnMaxUserNameLen = 254;
var
  sUserName: string;
  dwUserNameLen: DWORD;
begin
  dwUserNameLen := cnMaxUserNameLen - 1;
  SetLength(sUserName, cnMaxUserNameLen);
  GetUserName(PChar(sUserName), dwUserNameLen);
  SetLength(sUserName, dwUserNameLen);
  Result := sUserName;
end;
{$ELSE}
{$IF DEFINED(FPC) AND DEFINED(LINUX)}

begin
  Result := GetEnvironmentVariable('USERNAME');
end;
{$ELSE}

var
{$IFNDEF NEXTGEN}
  plogin: PAnsiChar;
{$ELSE}
  plogin: MarshaledAString;
{$ENDIF}
begin
{$IFDEF POSIX}
  try
    plogin := getlogin;
{$IFDEF NEXTGEN}
    Result := string(plogin);
    // NEXTGEN platforms handle strings differently, so direct assignment might be fine.
{$ELSE}
    if Length(plogin) > 0 then
    begin
      // Assuming UTF-8 encoding for plogin. If the encoding is different, adjust accordingly.
      Result := UTF8ToString(plogin);
      // Correct way to convert UTF-8 encoded PAnsiChar to UnicodeString
    end
    else
    begin
      if GetEnvironmentVariable('USER') <> '' then
      begin
        Result := GetEnvironmentVariable('USER');
      end
      else if GetEnvironmentVariable('LOGNAME') <> '' then
      begin
        Result := GetEnvironmentVariable('LOGNAME');
      end;

    end;

{$ENDIF}
  except
    Result := 'N/A';
  end;
{$ELSE}
  Result := 'N/A';
{$ENDIF}
  // raise ENotImplemented.Create('Not Android GetLoggedUserName implemented!');
end;
{$ENDIF}
{$ENDIF}
{$IFDEF IOS}
vesnx commented 6 months ago

My sample would add an extra #0 to the end of the user name under windows, this fixes it

dwUserNameLen := cnMaxUserNameLen;
  SetLength(sUserName, cnMaxUserNameLen);
  if GetUserName(PChar(sUserName), dwUserNameLen) then
  begin
    // Subtract 1 to exclude the null terminator from the length
    SetLength(sUserName, dwUserNameLen - 1);
  end
  else
    // Handle the error case where GetUserName fails
    SetLength(sUserName, 0);
  Result := sUserName;
exilon commented 3 months ago

Thanks, i will update it.