Utilize already existing method 'find_by_username_or_email'

check presence of email using include, dont use =~
This commit is contained in:
Manoj 2013-10-24 13:29:58 +05:30
parent 89f801ac04
commit 96ae3cdacc
3 changed files with 21 additions and 18 deletions

View file

@ -11,13 +11,10 @@ class SessionController < ApplicationController
params.require(:password)
login = params[:login].strip
password = params[:password]
login = login[1..-1] if login[0] == "@"
if login =~ /@/
@user = User.where(email: Email.downcase(login)).first
else
@user = User.where(username_lower: login.downcase).first
end
@user = User.find_by_username_or_email(login)
if @user.present?
@ -28,7 +25,7 @@ class SessionController < ApplicationController
end
# If their password is correct
if @user.confirm_password?(params[:password])
if @user.confirm_password?(password)
if @user.is_banned?
render json: { error: I18n.t("login.banned", {date: I18n.l(@user.banned_till, format: :date_only)}) }
@ -57,7 +54,7 @@ class SessionController < ApplicationController
def forgot_password
params.require(:login)
user = User.where('username_lower = :username or email = :email', username: params[:login].downcase, email: Email.downcase(params[:login])).first
user = User.find_by_username_or_email(params[:login])
if user.present?
email_token = user.email_tokens.create(email: user.email)
Jobs.enqueue(:user_email, type: :forgot_password, user_id: user.id, email_token: email_token.token)

View file

@ -124,14 +124,12 @@ class User < ActiveRecord::Base
end
def self.find_by_username_or_email(username_or_email)
conditions = if username_or_email.include?('@')
{ email: Email.downcase(username_or_email) }
users = if username_or_email.include?('@')
find_by_email(username_or_email)
else
{ username_lower: username_or_email.downcase }
find_by_username(username_or_email)
end
users = User.where(conditions).to_a
if users.size > 1
raise Discourse::TooManyMatches
else
@ -139,6 +137,14 @@ class User < ActiveRecord::Base
end
end
def self.find_by_email(email)
where(email: Email.downcase(email))
end
def self.find_by_username(username)
where(username_lower: username.downcase)
end
def enqueue_welcome_message(message_type)
return unless SiteSetting.send_welcome_message?
Jobs.enqueue(:send_system_message, user_id: id, message_type: message_type)

View file

@ -829,8 +829,8 @@ describe User do
context 'when multiple users are found' do
it 'raises an exception' do
user_query = stub(to_a: [stub, stub])
User.stubs(:where).with(username_lower: 'bob').returns(user_query)
user_query = [stub, stub]
User.stubs(:find_by_username).with('bob').returns(user_query)
expect { User.find_by_username_or_email('bob') }.to raise_error(Discourse::TooManyMatches)
end