Skip to content

Commit

Permalink
Add task to create the an admin user.
Browse files Browse the repository at this point in the history
  • Loading branch information
mmulich authored and karenc committed Dec 9, 2015
1 parent fc1fd2d commit e8e1e28
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
30 changes: 30 additions & 0 deletions lib/tasks/create_admin.rake
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
namespace :accounts do
desc 'Create an administrative user and/or set the password for said user'
# Task specifically to create an administrative user and/or set the
# password for said user. This task accepts to arguments, the username
# and optionally a password. If the password is not supplied, the
# username will be used for the password.
task :create_admin, [:username, :password] => :environment do |t, args|
ActiveRecord::Base.transaction do
begin
username = args[:username]
password = args[:password] || args[:username]
user = User.find_or_create_by_username(username)
identity = Identity.find_or_create_by_user_id(user.id) do |identity|
identity.password = password
identity.password_confirmation = password
identity.save!
end
user.is_administrator = true
auth = Authentication.find_or_create_by_uid(user.identity.id.to_s) do |auth|
auth.provider = 'identity'
auth.user_id = user.id
auth.save!
end
rescue Exception => e
puts e
raise ActiveRecord::Rollback
end
end
end
end
35 changes: 35 additions & 0 deletions spec/lib/tasks/create_admin_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
require 'spec_helper'
require 'rake'


describe 'accounts:create_admin rake task' do
before :all do
Accounts::Application.load_tasks
end

before :each do
Rake::Task['accounts:create_admin'].reenable
end

it 'creates an admin user' do
expect {
Rake::Task['accounts:create_admin'].invoke('admin', 'password')
}.to change { User.count }.by(1)
user = User.order(:id).last
expect(user.username).to eq('admin')
expect(user.is_administrator).to be true
expect(user.identity.authenticate('password')).to eq(user.identity)
expect(user.authentications.first.provider).to eq('identity')
end

it 'makes an existing user an admin user' do
user = FactoryGirl.create :user
expect {
Rake::Task['accounts:create_admin'].invoke(user.username, 'passw0rd')
}.to_not change { User.count }
user.reload
expect(user.is_administrator).to be true
expect(user.identity.authenticate('passw0rd')).to eq(user.identity)
expect(user.authentications.first.provider).to eq('identity')
end
end

0 comments on commit e8e1e28

Please sign in to comment.