class CreateNewOrAuthenticateUser

Authentication implementation mostly copied and slightly adapted from paweljw.github.io/2017/07/rails-5.1-api-app-part-4-authentication-and-authorization/ Big thanks!

Attributes

email[R]
password[R]

Public Class Methods

new(email, password) click to toggle source
# File natural-backend/app/commands/create_new_or_authenticate_user.rb, line 13
def initialize(email, password)
  @email = email
  @password = password
end

Private Instance Methods

content() click to toggle source
# File natural-backend/app/commands/create_new_or_authenticate_user.rb, line 54
def content
  {
    user_id: user.id,
    exp: 24.hours.from_now.to_i
  }
end
find_or_create_user() click to toggle source
# File natural-backend/app/commands/create_new_or_authenticate_user.rb, line 22
def find_or_create_user
  u = User.find_or_initialize_by(email: email)

  if u.new_record?
    persist_user(u)
  end

  u
end
password_valid?() click to toggle source
# File natural-backend/app/commands/create_new_or_authenticate_user.rb, line 41
def password_valid?
  user && user.authenticate(password)
end
persist_user(u) click to toggle source
# File natural-backend/app/commands/create_new_or_authenticate_user.rb, line 32
def persist_user(u)
  u.password = @password
  unless u.save
    self.errors += u.errors
    self.status = 500
    raise UserNotPersistedError
  end
end
run() click to toggle source
# File natural-backend/app/commands/create_new_or_authenticate_user.rb, line 45
def run
  if password_valid?
    @result = JwtService.encode(content)
  else
    errors.add(:base, "Invalid credentials")
  end
rescue UserNotPersistedError
end
user() click to toggle source
# File natural-backend/app/commands/create_new_or_authenticate_user.rb, line 18
def user
  @user ||= find_or_create_user
end