From e8e1e28649789defc80873b7bf37b9da068d418c Mon Sep 17 00:00:00 2001 From: Michael Mulich Date: Wed, 9 Dec 2015 10:39:07 -0800 Subject: [PATCH] Add task to create the an admin user. --- lib/tasks/create_admin.rake | 30 +++++++++++++++++++++++++ spec/lib/tasks/create_admin_spec.rb | 35 +++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 lib/tasks/create_admin.rake create mode 100644 spec/lib/tasks/create_admin_spec.rb diff --git a/lib/tasks/create_admin.rake b/lib/tasks/create_admin.rake new file mode 100644 index 0000000000..1da848a878 --- /dev/null +++ b/lib/tasks/create_admin.rake @@ -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 diff --git a/spec/lib/tasks/create_admin_spec.rb b/spec/lib/tasks/create_admin_spec.rb new file mode 100644 index 0000000000..534bd54061 --- /dev/null +++ b/spec/lib/tasks/create_admin_spec.rb @@ -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