require 'securerandom'
require 'P4'
class AuthController < ApplicationController
skip_before_action :verify_authenticity_token, except: [ :user ]
before_action :validate_session, except: [ :login, :nothing ]
# this is used as a dummy endpoint to validate they are authenticated
def user
render :json => @@sessions[cookies[:hws_token]]
end
def login
render :nothing => true, status: 401 and return if params['user'].nil? || params['user']['name'].nil? || params['user']['password'].nil?
p4ticket = nil
# for funsies, auth to a perforce server
begin
p4 = P4.new
p4.port = ENV['P4PORT'] || 'qaplay:1999'
p4.user = params['user']['name']
p4.password = params['user']['password']
p4.connect
p4ticket = p4.run_login('-p')
rescue P4Exception => e
puts e.message
render :nothing => true, status: 403 and return
end
# good to go, store the metadata and make a token
token = SecureRandom.hex
# TODO: add more metadata
user_data = { :user => params['user']['name'], :expires => DateTime.current + 5.minutes, :p4ticket => p4ticket[0] }
@@sessions[token] = user_data
# done
render :text => "hws_token=#{token}"
end
def logout
puts params
@@sessions.delete(session_key)
render :nothing => 'true'
end
end