Skip to content

Instantly share code, notes, and snippets.

@jpluscplusm
Forked from thommay/user-manage.rb
Created April 13, 2011 23:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpluscplusm/918681 to your computer and use it in GitHub Desktop.
Save jpluscplusm/918681 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'sinatra'
require "sinatra/reloader" if development?
require 'chef'
require 'rack/flash'
require 'haml'
POSSIBLE = [('a'..'z'),('A'..'Z'),(0..9),'.','/'].inject([]) {|s,r| s+Array(r)}
set :sessions, true
set :haml, {:format => :html5, :escape_html => true}
use Rack::Flash
configure :production do
set :haml, {:ugly => true}
end
before do
require 'chef/knife'
Chef::Knife.new.configure_chef
@q ||= Chef::Search::Query.new
@rest ||= Chef::REST.new(Chef::Config[:chef_server_url])
end
helpers do
def partial(name, opts={})
haml name, opts.merge!(:layout=>false)
end
def user_link(u)
partial "%a{:href=>'/users/#{u[:id]}', :title=>'#{u[:full_name]}'} #{u[:full_name]} "
end
end
#stolen from http://d.strelau.net/post/220354423/shadow-passwords-in-ruby
def shadow(pass)
salt = Array.new(8) { POSSIBLE[ rand(POSSIBLE.size) ] }
pass.crypt("$1$#{salt}")
end
# URL Scheme:
# Get / -- list of users by group
# Get /users/<name> -- display a user
# Get /users/<name>/edit -- edit a user
# Post /users/<name> -- update a user
# Get /users/new -- create a user
# Post /users/create -- create a user
#
#
#get "/users/new/?"
#post "/users/create"
post "/users/:name/newkey" do
@user = Chef::DataBagItem.load("users", params[:name])
@user["ssh_keys"] ||= []
@user["ssh_keys"] << params["public_key"]
@rest.put_rest("data/users/#{@user["id"]}", @user)
flash[:notice] = "User #{params[:name]} updated successfully"
redirect "/users/#{params[:name]}"
end
post "/users/:name" do
@user = Chef::DataBagItem.load("users", params[:name])
@user["shell"] = params[:shell]
pp params
if not params[:password].empty?
if params[:password] == params[:pass_confirm]
@user["password"] = shadow params[:password]
else
flash[:err] = "Password and confirmation don't match!"
redirect "/users/#{params[:name]}"
end
end
@rest.put_rest("data/users/#{@user["id"]}", @user)
flash[:notice] = "User #{params[:name]} updated successfully"
redirect "/users/#{params[:name]}"
end
get "/users/:name/?" do
@user = Chef::DataBagItem.load("users", params[:name])
halt 404 unless @user
haml :user
end
get "/" do
@users = {}
Chef::DataBag.load("groups").keys.each do |group|
@users[group] ||= []
@q.search(:users, "groups:#{group}") { |u| @users[group] << {:id => u[:id], :full_name => u[:full_name]} }
end
haml :index
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment