Ruby: Get currently logged in user on windows

前端 未结 6 1495
不思量自难忘°
不思量自难忘° 2021-01-13 04:20

In C# I can get the current user of a web app using the HttpContext, however, I can\'t figure out how to do this in Ruby. Is there any way of doing this?

FOR

6条回答
  •  佛祖请我去吃肉
    2021-01-13 04:55

    Well, to get the current username, there's this:

    puts ENV['USERNAME']
    

    Or go to the Win32API.

    require 'dl/win32'
    
    def get_user_name
      api = Win32API.new(
        'advapi32.dll',
        'GetUserName',
        'PP',
        'i'
      )
    
      buf = "\0" * 512
      len = [512].pack('L')
      api.call(buf,len)
    
      buf[0..(len.unpack('L')[0])]
    end
    
    puts get_user_name
    

    Edit: And I'm an idiot. This isn't what you asked for at all. Oh well, it took me time to dig this out of my code, so it might as well stay here for anyone else wondering :P

    Edit again: OK, it turns out I'm not an idiot after all. This is what you want. When I went back and re-read your question, the HttpContext threw me off, and I thought it was the current username from HTTP auth or something.

提交回复
热议问题