# encoding: utf-8

class SessionsController < Devise::SessionsController
	prepend_before_filter :require_no_authentication, :only => [ :new, :create ]


  def create 
	  @site = Site.first

      private_key = OpenSSL::PKey::RSA.new(@site.private_key)
      wresult = private_key.private_decrypt(request.params['wresult'])

  	  @ids = wresult.split("@")

      login_uid = @ids[0]

  	  resource = User.first(conditions:{user_id: login_uid})

	  if !resource.blank?
	     resource_name = resource.class.to_s.downcase
	     sign_in(resource_name, resource)
	     session[:user_id_type] = "myntu"
	     redirect_to after_sign_in_path_for(resource)
	  else
	     flash[:error] = "很抱歉,您無此權限或帳號登入本站,請洽本站管理員<br />Sorry, you don't have the account or authority to login. Please contact the website administrator."
	     redirect_to :root
	  end
  end

  def destroy
  	@user_id_type = session[:user_id_type]
    sign_out
    if @user_id_type == "myntu"
      redirect_to "https://adfs.ntu.edu.tw/adfs/ls/?wa=wsignout1.0&wreply=https://galogin.ntu.edu.tw"
    else
      redirect_to root_path
    end
  end

end