require 'account_controller'
require 'json'

class RedmineOauthController < AccountController
  include Helpers::MailHelper
  include Helpers::Checker
  def oauth_myecp
    if Setting.plugin_redmine_omniauth_myecp[:oauth_authentification]
      session[:back_url] = params[:back_url]
      redirect_to oauth_client.auth_code.authorize_url(:redirect_uri => oauth_myecp_callback_url, :scope => scopes, :state => 'okok')
    else
      password_authentication
    end
  end

  def oauth_myecp_callback
    if params[:error]
      flash[:error] = l(:notice_access_denied)
      redirect_to signin_path
    else
      token = oauth_client.auth_code.get_token(params[:code], :redirect_uri => oauth_myecp_callback_url, :state => 'okok')
      result = token.get('https://my.ecp.fr/m')
      info = JSON.parse(result.body)
      if info
        allowed_domain = allowed_domain_for?(info["mail"])
        for mail in info["other_mails"]
          allowed_domain ||= allowed_domain_for?(mail)
        end
        if allowed_domain
          try_to_login info
        else
          flash[:error] = l(:notice_domain_not_allowed, :domain => parse_email(info["email"])[:domain])
          redirect_to signin_path
        end
      else
        flash[:error] = l(:notice_unable_to_obtain_myecp_credentials)
        redirect_to signin_path
      end
    end
  end

  def try_to_login info
    params[:back_url] = session[:back_url]
    session.delete(:back_url)
    for mail in info["other_mails"]+[info["mail"]]
      user = User.find_by_mail mail
      break if user.is_a? User
    end
    user = User.initialize unless user.is_a? User
    if user.new_record?
      # Self-registration off
      redirect_to(home_url) && return unless Setting.self_registration?
      # Create on the fly
      user.firstname = info['first_name']
      user.lastname = info['last_name']
      user.mail = info['mail']
      user.login = info['login']
      user.random_password
      user.register
      case Setting.self_registration
        when '1'
          register_by_email_activation(user) do
            onthefly_creation_failed(user)
          end
        when '3'
          register_automatically(user) do
            onthefly_creation_failed(user)
          end
        else
          register_manually_by_administrator(user) do
            onthefly_creation_failed(user)
          end
      end
    else
      # Existing record
      if user.active?
        successful_authentication(user)
      else
        # Redmine 2.4 adds an argument to account_pending
        if Redmine::VERSION::MAJOR > 2 or
          (Redmine::VERSION::MAJOR == 2 and Redmine::VERSION::MINOR >= 4)
          account_pending(user)
        else
          account_pending
        end
      end
    end
  end

  def oauth_client
    @client ||= OAuth2::Client.new(settings[:client_id], settings[:client_secret],
      :site => 'https://my.ecp.fr',
      :authorize_url => '/oauth/v2/auth',
      :token_url => '/oauth/v2/token')
  end

  def settings
    @settings ||= Setting.plugin_redmine_omniauth_myecp
  end

  def scopes
    'default_scope'
  end
end