This guide covers adding functionality provided by Refinery CMS to an existing application, while retaining the existing application’s control over configuration and use of the Devise authentication gem. After reading it, you should be familiar with:
- Getting Refinery CMS + a Rails 3.1.x app
- Adding the authentication (and authorization) rules from your app to Refinery’s back end administration content.
- Ensuring your existing app’s tests still runs
endprologue.
TIP. This guide is based on Edge Refinery, on the way to support Rails 3.1
This guide assumes you are starting with a working Ruby On Rails v3.1.x application that is using Devise for authentication. It does not assume you are using any particular authorization gem like CanCan. The instructions have been tested with Devise v1.4.0.
This guides takes an approach of leaving the Refinery Gems unmodified to make it easier to upgrade them without re-merging in your necessary modifications. You’d just have to keep an eye on the User model.
Refinery CMS edge assumes you want a content management system to control your site, which makes it very easy to build a Refinery CMS based application from scratch, and modify that. Fortunately, it is also flexible enough to take on a smaller role to add functionality to your existing application. This guides focuses on those situations where there are large areas of your existing application that Refinery CMS should not be involved with at all. For example, you want to add a blog using refinery’s blog extension, to your existing site, but don’t want to otherwise alter your existing, perhaps complex, site.
Since this guide can’t anticipate the unique integration issues with your situation, we’ll create a minimal Rails + Devise application to reference. We’ll assume that the existing application already handles authentication and authorization in a way that must be maintained to avoid breaking existing functionality, and that there are models, controllers and views that you don’t want Refinery CMS to be involved with. Specifically, we’ll assume that the ExistingApp will handle administration of the User table records through a non-refinery interface (perhaps the console, perhaps some ExistingApp controller).
In creating the existing application, we’ll make the following convenient, but not required asumptions:
- you’re using ruby version manager. The particular ruby version and gemset used here can be whatever you need and are just placeholders.
- you’re using older versions of some gems than refinery also expects, to demonstrate one way to deal with that situation.
- you’re using git for source code control.
TIP. Attaching Refinery CMS to an existing Rails application has further details about integrating with an existing application in general.
These commands should speak for themselves if you previously created your own rails + devise app to integrate with.
$ mkdir ExistingApp
$ cd ExistingApp
$ rvm use 1.9.2 # for example, could be another ruby compatible with Rails 3.1.x
$ rvm gemset create ‘existing’
$ echo “rvm use 1.9.2@existing” > .rvmrc
$ cd . #to trigger rvm to approve and start using .rvmrc setting
$ git init #if you are using git for source code control. Git commit steps will be left out of this guide to keep it focused.
$ cd ..
$ rails -v #probably want to ensure >= 3.1.0
$ #if the rails gem isn’t there to get your app generated you might do the following two steps..
$ rvm use 1.9.2@existing #if necessary
$ gem install rails #if necessary
$ rails new ExistingApp
$ cd ExistingApp
Gemfile
…
gem ‘devise’, ‘~> 1.4.0’ #Not recommending a specific version, just saying perhaps your app used an older version than refinery requires, and you aren’t quite ready to upgrade, just to demonstrate…
…
$ bundle install
$ rails generate devise:install
$ rails generate devise User #Devise might be using another model name in your existing app
$ rake db:migrate
Next we’ll add a static, unrestricted home page, the notice and alert flashes to the application default layout, and a restricted_content controller and view.
We’ll also add a simple stylesheet, which in a real existing app, would be what we would like Refinery to integrate with on the front end, rather than refinery overriding it.
To demonstrate another wrinkle you might discover, let’s customize our use of Devise a tiny bit, by overriding the session controller to handle a before_filter to prevent logging in when the database is undergoing maintenance.
app/views/layouts/application.html.erb
<!DOCTYPE html>
ExistingApp
<%= stylesheet_link_tag “application” >
<= javascript_include_tag “application” >
<= csrf_meta_tags %>
<%= notice %>
<%= alert %>
<%= yield %>app/controllers/static_controller.rb
class StaticController < ApplicationController
#using default layouts and views, so don’t need to define methods here.
end
app/views/static/home.html.erb
app/controllers/users/sessions_controller.rb
class Users::SessionsController < Devise::SessionsController
before_filter :block_login_during_maintenance
def block_login_during_maintenance
return if !DB_UNDER_MAINTENANCE
redirect_to db_maintenance_message_path
return false
end
config/initializers/db_maintenance.rb
DB_UNDER_MAINTENANCE = false
app/views/static/db_maintenance.html.erb
app/controllers/restricted_content_controller.rb
class RestrictedContentController < ApplicationController
before_filter :authenticate_user!
end
app/views/restricted_content/vault.html.erb
config/routes.rb
…
match “vault” =>"restricted_content#vault"
get “static/db_maintenance”, :as=>"db_maintenance_message"
root :to => “static#home”
…
app/assets/stylesheets/front_end_styles.css
/* not pretty, but you’ll know it when you see it*/
body {
background-color: #1100aa
}
p, a, h1, h2, h3, h4 {
color: white
}
$ rm public/index.html
$ rails generate devise:views
$ mkdir app/views/users
$ mkdir app/views/users/sessions
$ cp app/views/devise/sessions/new.html.erb app/views/users/sessions/.
app/views/users/sessions/new.html.erb
…
Our custom new session view
#Leave the rest unchanged
…
$ rails c
ruby> me = User.create(:email=>"my_email@my_company.com", :password=>"my_pa$$word")
…
ruby> exit
$ rails s
Go to http://localhost:3000 and you should see the home page.
Go to http://localhost:3000/vault and you should be able to sign in and then see the vault page.
$ git add -A
$ git commit
Now that we have a baseline example working ExistingApp using Devise, it’s time to integrate Refinery, using our existing front end styles, existing user models, and whatever specialized authentication and authorization code we may already have in place.
Gemfile
…
gem ‘devise’ #temporarily commented out,‘~> 1.4.0’
…
$ bundle # or bundle update if you have version conflicts
$ rails generate refinery:cms # you will be asked whether or not you want to override your devise.rb file. Simply say no to keep your config.
Now we have to undo some of what the refinery generator did, to keep control of the front end, and let refinery still handle the admin backend, as well as not squashing our existing user table.
$ mv app/views/layouts/application.html.erb.backup app/views/layouts/application.html.erb
TODO don’t really know how you handle the asset pipeline, but obviously the following lines don’t have anymore sense
$ mkdir public/stylesheets/hide
$ mv public/stylesheets/*.css public/stylesheets/hide/.
$ mv public/stylesheets/hide/front_end_styles.css public/stylesheets/.
Now we need to setup up:
- a Role model
- an additional model to get our many to many association working: RolesUsers
- a model used to list all Refinery plugins belonging to someone: UserPlugin
These are created by default when you add the refinerycms-authentication gem so we won’t reinvent the wheel and use the existing code taken from github. Be aware that your existing models could do the trick (except for UserPlugin), as long as you implement some methods but we’ll see that later.
WARNING. Beware of raw code: models are usually namespaced. Ex: replace ::Refinery::Role with ::Role or simply Role
With inspiration from https://github.com/refinery/refinerycms/blob/master/authentication/db/migrate/, refinery_cms_authentication_schema:
$ rails g model RolesUsers user_id:integer role_id:integer # add the index directly within the migration file
$ rails g model Role title:string
$ rails g model UserPlugin user_id:integer name:string position:integer
Now we have to fill in our models. Once again, we won’t reinvent the wheel so we’ll pick the code from here: https://github.com/refinery/refinerycms/blob/master/authentication/app/models/refinery/
app/model/role.rb
class Role < Refinery::Core::BaseModel
- TODO: This works around a bug in rails habtm with namespaces.
has_and_belongs_to_many :users, :join_table => ::RolesUsers.table_name
end
app/model/roles_users.rb
class RolesUsers < Refinery::Core::BaseModel
belongs_to :role
belongs_to :user
end
app/model/user_plugin.rb
class UserPlugin < Refinery::Core::BaseModel
belongs_to :user
attr_accessible :user_id, :name, :position
end
app/model/user.rb
class User < Refinery::Core::BaseModel
#Your stuff
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
$ rake db:migrate
Now we need to add authentication goodness manually, it will just consist in telling refinery to use your devise helpers.
We’ll add this in your lib directory
$ mkdir lib/refinery
$ touch lib/refinery/refinery_patch.rb
$ touch lib/refinery/restrict_refinery_to_refinery_users.rb
Then open the files and put the content from this gist inside: https://gist.github.com/1272720
Next, we’ll have to load the content of these files in your app.
config/application.rb
module ExistingApp
class Application < Rails::Application
…
config.autoload_paths += Dir[“#{config.root}/lib/**/”] # to load files from lib directory, including subfolders
config.before_initialize do
require ‘refinery_patch’
require ‘restrict_refinery_to_refinery_users’
end
end
Next we need to give refinerycms-core/lib/controllers/application_controller.rb a valid refinery user so it won’t take over with a “show welcome” view.
$ rails c
ruby> su = Role.create(:title=>"Superuser")
ruby> re = Role.create(:title=>"Refinery")
ruby> me = User.first #created above to test devise
ruby> me.roles << su
ruby> me.roles << re
ruby> me.save
true
ruby> exit
We need to also avoid the show_welcome page in test mode or our ExistingApp existing integration tests will suddenly stop working.
app/controllers/application_controller
class ApplicationController < ActionController::Base
…
def show_welcome_page?
#overriding refinery initialization wizard behavior, so unpopulated test
#database will successfully run.
false
end
…
end
Ok. We should be ready to give it a spin.
If you try to access http://localhost:3000/, you should get first an error “undefined method ‘refinery_user?’”. Just reload the page, it should now be fine.
If you try to access http://localhost:3000/refinery (the refinery administrative backend), boom again: “undefined method `destroy_refinery_user_session_path’”.
Indeed, we have to correct one view to set the proper url helper.
$ rake refinery:override view=refinery/_site_bar
Now the partial has been moved to your app, change “destroy_refinery_user_session_path”, with “destroy_user_session_path”.
Also important, add “:method => :delete” if it’s not in the link_to helper.
TODO: bug in refinery?
Retry http://localhost:3000/refinery, it should be fine now.
Last advice: in your routes, map your root with “refinery/pages#home” if you want refinery to handle your homepage.