Skip to content

Instantly share code, notes, and snippets.

@phensalves
Created August 11, 2015 07:17
Show Gist options
  • Save phensalves/e6df329fb57225a8f7ad to your computer and use it in GitHub Desktop.
Save phensalves/e6df329fb57225a8f7ad to your computer and use it in GitHub Desktop.
class User < ActiveRecord::Base
scope :email_exist, -> { where.not(email: nil) }
attr_accessor :password
validates :nome, presence: true, length: { maximum: 50 }
before_save { self.email = email.downcase }
validates :email, presence: true, format: {with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, on: :create}, uniqueness: {case_sensitive: false}
validates :password, presence: true, length: { minimum: 6 }
def self.authenticate(email, password)
user = email_exist.find_by(email: email)
try(:authenticate, password)
end
end
class UserSession
include ActiveModel::Model
attr_accessor :email, :password
validates_presence_of :email, :password
def initialize(session, attributes={})
@session = session
@email = attributes[:email]
@password = attributes[:password]
end
def authenticate!
user = User.authenticate(@email, @password)
if user.present?
store(user)
else
errors.add(:base, :invalid_login)
false
end
end
def store(user)
@session[:user_id] = user.id
end
end
class UserSessionsController < ApplicationController
def new
@user_session = UserSession.new(session)
end
def create
@user_session = UserSession.new(session, params[:user_session])
if @user_session.authenticate!
redirect_to root_path, notice: t('flash.notice.signed_in')
else
render :new
end
end
def destroy
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment