#include "DeviceUtils.h"

#include "Utils/MemoryUtils.h"

auto Utils::Device::getUserSid() -> std::string {
	HANDLE token;
	if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token))
		return _(" ");

	DWORD dwLength = 0;
	GetTokenInformation(token, TokenUser, NULL, 0, &dwLength);

	if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
		CloseHandle(token);
		return _(" ");
	}

	PTOKEN_USER tokenuser = static_cast<PTOKEN_USER>(LocalAlloc(LPTR, dwLength));
	if (!tokenuser) {
		LocalFree(tokenuser);
		CloseHandle(token);

		return _(" ");
	}

	if (!GetTokenInformation(token, TokenUser, tokenuser, dwLength, &dwLength)) {
		LocalFree(tokenuser);
		CloseHandle(token);

		return _(" ");
	}

	LPWSTR lstring;
	if (!ConvertSidToStringSidW(tokenuser->User.Sid, &lstring)) {
		LocalFree(tokenuser);
		CloseHandle(token);

		return _(" ");
	}


	std::wstring wstr(lstring);
	
	LocalFree(lstring);
	LocalFree(tokenuser);
	CloseHandle(token);

	return std::string(wstr.begin(), wstr.end());
}
