Sha256: d589453af7c62031a29bcaf89e64f6bbdb12ed21bc56e38ff1583bfe9e13862b

Contents?: true

Size: 1.09 KB

Versions: 3

Compression:

Stored size: 1.09 KB

Contents

# frozen_string_literal: true

require "fusuma/custom_process"
require "etc"

module Fusuma
  module Plugin
    module Appmatcher
      # Drop sudo privileges
      class UserSwitcher
        include CustomProcess
        User = Struct.new(:username, :uid, :gid)

        attr_reader :login_user

        def initialize
          username = ENV["SUDO_USER"] || Etc.getlogin
          uid = `id -u #{username}`.chomp.to_i
          gid = `id -g #{username}`.chomp.to_i
          @login_user = User.new(username, uid, gid)
        end

        # Drops privileges to that of the specified user
        def drop_priv(user)
          # Process.initgroups(user.username, user.gid)
          Process::Sys.setegid(user.gid)
          Process::Sys.setgid(user.gid)
          Process::Sys.setuid(user.uid)
        end

        # Execute the provided block in a child process as the specified user
        # The parent blocks until the child finishes.
        def as_user(user = @login_user)
          fork do
            drop_priv(user)
            yield(user) if block_given?
          end
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
fusuma-plugin-appmatcher-0.2.3 lib/fusuma/plugin/appmatcher/user_switcher.rb
fusuma-plugin-appmatcher-0.2.2 lib/fusuma/plugin/appmatcher/user_switcher.rb
fusuma-plugin-appmatcher-0.2.0 lib/fusuma/plugin/appmatcher/user_switcher.rb