Load users from passwd, proper management of users array

This commit is contained in:
Christoffer Müller Madsen 2017-05-27 01:28:27 +02:00
parent 101d4e5cd4
commit 0ab9081564

View File

@ -2,7 +2,6 @@ require 'fileutils'
POSIX_NAME_PREFIX = "emacs"
$user_count = 0
$users = []
$id_map = {}
@ -12,7 +11,7 @@ $id_map = {}
class User
attr_accessor :id, :path, :posixname
def to_s
"#{@id}, #{@path}"
end
@ -22,7 +21,12 @@ def get_user(id)
$id_map[id]
end
def add_user(id)
def add_user(user)
$users << user
$id_map[user.id] = user
end
def create_user(id)
if not system("useradd -m #{POSIX_NAME_PREFIX}#{id}") then
raise "User creation failed"
end
@ -31,7 +35,6 @@ def add_user(id)
user.id = id
user.path = "/home/#{POSIX_NAME_PREFIX}#{id}"
user.posixname = "#{POSIX_NAME_PREFIX}#{id}"
$user_count += 1
$users << user
$id_map[id] = user
@ -42,9 +45,18 @@ def add_user(id)
user
end
def remove_user(id)
system("userdel -r #{POSIX_NAME_PREFIX}#{id}")
$user_count -= 1
def remove_user(user)
system("userdel -r #{user.posixname}")
$users.remove(user)
$id_map[id] = nil
end
def user_by_posix_name(posix_name)
user = User.new
user.id = posix_name[POSIX_NAME_PREFIX.length..-1]
user.path = "/home/#{posix_name}"
user.posixname = posix_name
user
end
####################
@ -133,9 +145,27 @@ def extract_ssh_pubkeys(file)
end
end
##################
################
remove_user 5
add_user 5
add_ssh_pubkey(get_user(5), "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC7ZKN2fKcUQUaQqDjNCQQBSdqBVGX7lprNCJmceDBfybhbnuZJ8KvzJJIJIIbzqheW5BVCfkWJY6OgkpAumLWSRCS5n2+AnDHwQgpKDS93OeV+9/kattVtsVUBZaghymyJ2UfA0r918dkxcT9SZbNSl9raiDUUmj3JY8UM219BQP7BRqoZ6e/YZz9lO7ORy6yQT6fIMaVOaZcoDPr6oyNJfadm9POvS/Wl63onoRI9dzpHQG9RuHCcUhHJhkGtzY7GeRWc85WqA9Q4vYo0SK5Je9BG1cvAAVTfV+eYEJEiSDMwWj60roH0C3/ipmzxD/kWqg6YBJWL+XAyQkDnmbuD christoffermadsen@strawberry.thedevcave.net")
###########
# User DB #
###########
def reload_users_from_passwd
$users = []
`cut -d: -f1 /etc/passwd`.split("\n").
select{|u| u.start_with? POSIX_NAME_PREFIX}.
map{|u| user_by_posix_name(u)}.
each{|u| add_user(u)}
end
################################################
reload_users_from_passwd
#remove_user 5
#create_user 3
#add_ssh_pubkey(get_user(3), "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC7ZKN2fKcUQUaQqDjNCQQBSdqBVGX7lprNCJmceDBfybhbnuZJ8KvzJJIJIIbzqheW5BVCfkWJY6OgkpAumLWSRCS5n2+AnDHwQgpKDS93OeV+9/kattVtsVUBZaghymyJ2UfA0r918dkxcT9SZbNSl9raiDUUmj3JY8UM219BQP7BRqoZ6e/YZz9lO7ORy6yQT6fIMaVOaZcoDPr6oyNJfadm9POvS/Wl63onoRI9dzpHQG9RuHCcUhHJhkGtzY7GeRWc85WqA9Q4vYo0SK5Je9BG1cvAAVTfV+eYEJEiSDMwWj60roH0C3/ipmzxD/kWqg6YBJWL+XAyQkDnmbuD christoffermadsen@strawberry.thedevcave.net")