Restful Authentication on Multi-Databases
Recently, we had a need to pull out the users table into a separate database for security reasons. So I’ve heard that DHH isn’t down with multiple databases (?), but last year he mentioned a cool new gem called Magic Multi-Connections.
I might try it out at some point, but it still seems like jumping through more hoops than I really need. After completing the RESTful Authentication tutorial, I instead referred to Recipe #15 from Rails Recipes and defined a parent class called Security:
class Security < ActiveRecord::Base
self.abstract_class = true
set_table_name "users"
set_primary_key "id"
establish_connection :security
end
Modified the existing User:
class User < Security
And that’s basically it. It just kind of worked.
I did have some problems with the redirect_to root_path line in the update method of the accounts_controller, had to change it to render :action => ‘edit’. But this was just a quirk from the tutorial.
My new concern is migrations. If you rake db:migrate, it migrates your tables to your primary database and that’s it. I’ve seen a way to fix this on the net, but I haven’t gone down that road yet. In the meantime you’ll find the SQL to create the 2nd database and user table below:
CREATE DATABASE security
CREATE TABLE users
(id int,
login char(40),
email char(40),
crypted_password char(40),
salt char(40),
created_at datetime,
updated_at datetime,
remember_token char(40),
remember_token_expires_at datetime,
activation_code char(40),
activated_at datetime,
password_reset_code char(40),
enabled boolean,
PRIMARY KEY (id)
);
So far so good. Everything seems to be working in Application 1. Since I don’t really need to worry about sharing sessions, this implementation should work fine for us. I’ll need to reimplement everything in Application 2 but not only can I keep my user table secure but my users can login with the same username and password used in App 1. I’ll let you know how it all pans out.


