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
dc85eaba
             user_id = nil
1b9ff864
         end
7aef87db
 
1b9ff864
         @token = Token.new
7aef87db
 
dc85eaba
         save_session(user_id, user_credentials)
1b9ff864
     end
 
dc85eaba
     def save_session(user_id, user_credentials)
         session[:token]      = Token.generate_token()
1b9ff864
         session[:created_at] = Time.now
dc85eaba
         session[:ip]         = request.remote_ip
 
         if user_credentials
             session[:users] = {} unless session[:users]
             session[:users][user_credentials[:jid]] = user_credentials[:password]
         end
1b9ff864
 
         @token.save_session(session, user_id)
     end
 
10098bcb
     def create_new_user(user_credentials)
         jid  = user_credentials[:jid]
         user = User.existing_jid(jid) || User.create_jid(jid)
 
         user.id
1b9ff864
     end
5fa8b94d
 end