本家サイトに行ってみると、user認証の仕組みをもっているらしい、ということで試しみた。なんせdeviseは私の用途には高尚すぎるから。
Gemfile経由でインストールしただけで、
rails g nifty:scafold post title:string content:text
てな感じで使えた。最後に --hamlなどとオプションをつけるとhamlファイルを生成してくれるのが吉。rails g nifty:authentication account
とアカウントを作ってみる。(userはもうdeviseで使っているので避けた)出来上がるmigrateファイルはシンプル。
class CreateAccounts < ActiveRecord::Migration
def self.up
create_table :accounts do |t|
t.string :username
t.string :email
t.string :password_hash
t.string :password_salt
t.timestamps
end
end
def self.down
drop_table :accounts
end
end
モデルはvalidationがたくさんあります。
class Account < ActiveRecord::Base
# new columns need to be added here to be writable through mass assignment
attr_accessible :username, :email, :password, :password_confirmation
attr_accessor :password
before_save :prepare_password
validates_presence_of :username
validates_uniqueness_of :username, :email, :allow_blank => true
validates_format_of :username, :with => /^[-\w\._@]+$/i, :allow_blank => true, :message => "should only contain letters, numbers, or .-_@"
validates_format_of :email, :with => /^[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$/i
validates_presence_of :password, :on => :create
validates_confirmation_of :password
validates_length_of :password, :minimum => 4, :allow_blank => true
# login can be either username or email address
def self.authenticate(login, pass)
account = find_by_username(login) || find_by_email(login)
return account if account && account.matching_password?(pass)
end
def matching_password?(pass)
self.password_hash == encrypt_password(pass)
end
private
def prepare_password
unless password.blank?
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = encrypt_password(password)
end
end
def encrypt_password(pass)
BCrypt::Engine.hash_secret(pass, password_salt)
end
end
nameもemailもmodel側でvalidateしているのでいじりやすいですね。私の用途にはちょうどいい感じ。うむ、手っ取り早く整った見た目をhamlで作ってくれる点といい、かなり好印象。aplication.cssという形でcssが生成されていくらでもいじれるので、これも便利。
0 件のコメント:
コメントを投稿