app/controllers/application_controller.rb
5fa8b94d
 class ApplicationController < ActionController::Base
7aef87db
 
120b99ea
 	before_filter :require_login
7aef87db
 
 	def require_login
 		if authenticated?
1b9ff864
 			create_new_authentication()
f835d40d
 
             unless controller_name == 'chat'
333715b4
                 redirect_to chat_path
f835d40d
             end
7aef87db
 		else
120b99ea
 			unless controller_name == 'sessions' && (action_name == 'new' || action_name == 'create')
31d1a3aa
                 redirect_to root_url, flash: {error: I18n.t('login.access-denied')}
120b99ea
 			end
7aef87db
 		end
 	end
 
 	protected
 
 	def authenticated?
1b9ff864
         @token = Token.authenticate(session)
7aef87db
 	end
 
10098bcb
 	def create_new_authentication(user_credentials = nil)
1b9ff864
         if @token
             user_id = @token.user_id
             @token.delete
         else
10098bcb
             user_id = !user_credentials ? nil : create_new_user(user_credentials)
1b9ff864
         end
7aef87db
 
1b9ff864
         @token = Token.new
7aef87db
 
10098bcb
         save_session(user_id) if not user_id
1b9ff864
     end
 
     def save_session(user_id)
         session[:token] = Token.generate_token()
         session[:created_at] = Time.now
         session[:ip] = request.remote_ip
 
         @token.save_session(session, user_id)
     end
 
10098bcb
     def create_new_user(user_credentials)
         jid  = user_credentials[:jid]
         pass = user_credentials[:password]
 
         user = User.existing_jid(jid) || User.create_jid(jid)
         user.update_pass(jid, pass)
 
         user.id
1b9ff864
     end
5fa8b94d
 end