akissa/vagrant-rimu

View on GitHub
lib/vagrant-rimu/actions/setup_user.rb

Summary

Maintainability
A
0 mins
Test Coverage
require 'log4r'

require 'vagrant-rimu/actions/ssh_utils'
require 'vagrant-rimu/actions/abstract_action'

module VagrantPlugins
  module Rimu
    module Actions
      class SetupUser < AbstractAction
        include VagrantPlugins::Rimu::Actions::SshUtils

        def initialize(app, env)
          @app = app
          @machine = env[:machine]
          @logger = Log4r::Logger.new('vagrant::rimu::setup_user')
        end

        # rubocop:disable Metrics/AbcSize
        def execute(env)
          # check if setup is enabled
          return @app.call(env) unless @machine.provider_config.setup?

          # check if a username has been specified
          return @app.call(env) unless @machine.config.ssh.username

          # override ssh username to root temporarily
          user = @machine.config.ssh.username
          @machine.config.ssh.username = 'root'

          # create user account
          create_user(env, user)

          # create the .ssh directory in the users home
          @machine.communicate.execute("su #{user} -c 'mkdir -p ~/.ssh'")

          # add the specified key to the authorized keys file
          upload_key(env, user)

          # reset username
          @machine.config.ssh.username = user

          @app.call(env)
        end
        
        # def upload_key(user)
        #   path = @machine.config.ssh.private_key_path
        #   path = path[0] if path.is_a?(Array)
        #   path = File.expand_path(path, @machine.env.root_path)
        #   pub_key = public_key(path)
        #   @machine.communicate.execute(<<-BASH)
        #     if ! grep '#{pub_key}' /home/#{user}/.ssh/authorized_keys; then
        #       echo '#{pub_key}' >> /home/#{user}/.ssh/authorized_keys;
        #     fi
        #
        #     chown -R #{user} /home/#{user}/.ssh;
        #   BASH
        # end
        
        def create_user(env, user)
          env[:ui].info I18n.t('vagrant_rimu.creating_user', {
            :user => user
          })
          
          @machine.communicate.execute(<<-BASH)
            if ! (grep ^#{user}: /etc/passwd); then
              useradd -m -s /bin/bash #{user};
            fi
          BASH

          # grant user sudo access with no password requirement
          @machine.communicate.execute(<<-BASH)
            if ! (grep #{user} /etc/sudoers); then
              echo "#{user} ALL=(ALL:ALL) NOPASSWD: ALL" >> /etc/sudoers;
            else
              sed -i -e "/#{user}/ s/=.*/=(ALL:ALL) NOPASSWD: ALL/" /etc/sudoers;
            fi
          BASH
        end
        
        # def public_key(private_key_path)
        #   File.read("#{private_key_path}.pub")
        # rescue
        #   raise Errors::PublicKeyError, :path => "#{private_key_path}.pub"
        # end
      end
    end
  end
end