class SessionsController < ApplicationController
  layout "blank"

  skip_before_action :authentication_required, :verify_authenticity_token
  skip_after_action :verify_authorized

  before_action :skip_twofa, only: [:twofa], if: -> { %w[development development-docker test-features].include?(Rails.env) }
  before_action :login_required, only: [:twofa, :twofa_callback, :destroy]

  def twofa
    @signed_request = Duo.sign_request *Settings.secrets.duo.values_at("ikey", "skey", "akey"), current_user.ldap_login
  end

  def twofa_callback
    twofa_success = Duo.verify_response *Settings.secrets.duo.values_at("ikey", "skey", "akey"), params["sig_response"]

    if twofa_success
      twofa_performed
      log_event('twofa_success', current_user)
      return redirect_back_or_default
    end

    flash[:error] = "2FA failed"
    log_event('twofa_failure', current_user)
    redirect_to login_status_path
  end

  def oauth2_callback
    auth = request.env['omniauth.auth']
    login = auth.uid
    realm_name = auth.info['realm']

    email = if realm_name == 'twitch'
              "#{login}@twitch.tv"
            else
              login
            end

    login = "#{realm_name}:#{login}" unless realm_name == 'twitch'

    user = BeefCake::User.find(login, email: email)

    if user.any_permission?
      log_in user
      log_event('login_success', user)
      bake_session_notifications(user: user)
      return skip_twofa
    end

    flash[:error] = "You don't have any permissions to view admin panel"
    log_event('login_failure', user)
    redirect_to login_status_path
  end

  def auth_failure
    flash[:error] = auth_failure_message
    redirect_to login_status_path
  end

  def login_status
  end

  def destroy
    log_out
    flash[:success] = "Signed out"
    redirect_to login_status_path
  end

  private

  def auth_failure_message
    reason = {
      "missing_credentials" => "your credentials are missing",
      "invalid_credentials" => "you entered invalid credentials"
    }[params[:message]] || "unknown error"

    "Login failed because #{reason}. Please try again."
  end

  def skip_twofa
    twofa_performed
    redirect_back_or_default
  end

  def log_event(event_type, user)
    Rails.logger.info("[ldap_login=#{user.ldap_login}] #{event_type}")
  end
end
