users: refactor login and authentication logic.

* Make authentication methods into User instance methods instead of
  class methods.
* Fix API key authentication to use a secure string comparison. Fixes a
  hypothetical (unlikely to be exploitable) timing attack.
* Move login logic from SessionCreator to SessionLoader.
This commit is contained in:
evazion
2020-03-25 03:41:27 -05:00
parent 64af957031
commit b2cf765d6d
14 changed files with 68 additions and 100 deletions

View File

@@ -14,7 +14,7 @@ class EmailsController < ApplicationController
def update
@user = authorize User.find(params[:user_id]), policy_class: EmailAddressPolicy
if User.authenticate(@user.name, params[:user][:password])
if @user.authenticate_password(params[:user][:password])
@user.update(email_address_attributes: { address: params[:user][:email] })
else
@user.errors[:base] << "Password was incorrect"

View File

@@ -27,7 +27,7 @@ module Maintenance
end
def authenticate!
if ::User.authenticate(CurrentUser.user.name, params[:user][:password]) == CurrentUser.user
if CurrentUser.user.authenticate_password(params[:user][:password])
@api_key = CurrentUser.user.api_key || ApiKey.generate!(CurrentUser.user)
@password = params[:user][:password]
else

View File

@@ -9,9 +9,7 @@ class PasswordsController < ApplicationController
def update
@user = authorize User.find(params[:user_id]), policy_class: PasswordPolicy
if User.authenticate(@user.name, params[:user][:old_password])
@user.update(password: params[:user][:password], password_confirmation: params[:user][:password_confirmation])
elsif @user.authenticate_login_key(params[:user][:signed_user_id])
if @user.authenticate_password(params[:user][:old_password]) || @user.authenticate_login_key(params[:user][:signed_user_id])
@user.update(password: params[:user][:password], password_confirmation: params[:user][:password_confirmation])
else
@user.errors[:base] << "Incorrect password"

View File

@@ -7,13 +7,12 @@ class SessionsController < ApplicationController
end
def create
session_params = params[:session].presence || params
session_creator = SessionCreator.new(session, session_params[:name], session_params[:password], request.remote_ip)
name, password, url = params.fetch(:session, params).slice(:name, :password, :url).values
user = SessionLoader.new(request).login(name, password)
if session_creator.authenticate
url = session_params[:url]
url = posts_path if !url&.start_with?("/")
respond_with(session_creator.user, location: url, methods: [:api_token])
if user
url = posts_path unless url&.start_with?("/")
respond_with(user, location: url, methods: [:api_token])
else
flash.now[:notice] = "Password was incorrect"
raise SessionLoader::AuthenticationFailure