#coding=utf-8

require 'base64'
require 'json'
require 'openssl'

## 单点登录 <=> 北斗
class SsosController < ApplicationController

  skip_before_filter :check_if_login_required
  layout false

  def show
    begin
      # suRh2nFEJd0Ai_TFbqZ-1yQXnGfIB-YD_f4KTA3O4dQGSBMiXfOMt-0mzizgXekWTjHKfn62nJ60iHM3_eY_KS0Qn8SF8vANfa46GhzZRt4T0iC5ZOSs4cWeK43OU0RoekQLZZAo5OyOVibxabmiPGzEFCnVVtdmRk9d7X_B0Is=
      @auth = params[:auth]
      @options = parse(params[:auth])

      if params[:login].present?
        @options["name"] = params[:login]
      end

      logger.debug @options
      ## 认证
      sso = login(@options)

      ## 加入组织
      @organization = Organization.find(82)
      unless @organization.org_members.exists?(user_id: sso.user_id)
        member =  OrgMember.create(:user_id => sso.user_id, :created_at => Time.now)
        # member = OrgMember.new(:user_id => sso.user_id)
        @organization.org_members << member
        OrgMemberRole.create(:org_member_id => member.id, :role_id => 12)
      end

      ## 选择性跳转
      redirect_to @organization
    rescue => e
      logger.error e
      if e.message == "exist user"
        render 'ssos/show', :layout => false
      else
        raise e
      end
    end
  end

  ## 改用户名
  def create
    show and return
  end

  private
  def base64_safe(content)
    content = content.gsub('-', '+')
    content.gsub('_', '/')
  end

  def parse(auth)
    content = decrypt(auth)
    ActiveSupport::JSON.decode(content)
  end

  def login(opt)
    sso = Sso.sync_user(opt)
    start_user_session(sso.user)
    sso
  end

  def decrypt(auth)
    crypted_str = Base64.decode64(base64_safe(auth))
    pkey = OpenSSL::PKey::RSA.new(File.new(File.join(Rails.root,"config/private.key")))

    #to large
    max_dec_len = 1024/8
    size = (crypted_str.size + max_dec_len-1) / max_dec_len

    content = ''
    size.times do |time|
      tmps =  crypted_str[time*max_dec_len, max_dec_len]
      content += pkey.private_decrypt(tmps,OpenSSL::PKey::RSA::PKCS1_PADDING)
    end
    content
  end

end
