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
 
81ab4d54
             if controller_name != 'chat' and (controller_name != 'sessions' and action_name != 'destroy')
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
 
81ab4d54
     def remove_session
         reset_session()
         cookies.delete :iv
         cookies.delete :key
     end
 
882090fc
     private
 
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
882090fc
             encrypted_pass = Security::encrypt(user_credentials[:password])
ef74b9ea
             #TODO: pridat do sifry aj nieco z konfigov
882090fc
             cookies[:key] = Security::cipher_key
             cookies[:iv]  = Security::cipher_iv
 
0c651ead
             user = create_new_user(user_credentials)
             user.update_pass(user_credentials[:jid], encrypted_pass)
             user_id = user.id
dc85eaba
         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)
1b9ff864
     end
5fa8b94d
 end