require 'ipaddr'

class Token
	include Mongoid::Document
	include Mongoid::Timestamps::Created

	index({ token: 1 })

	field :token, type: String
	field :date_expiring, type: DateTime
	field :ip, type: Integer

	def self.authenticate(session)
		if session[:created_at] == nil
			return false
		end

		matched_token = self.where(:token				=> session[:token],
								   :ip					=> IPAddr.new(session[:ip]).to_i,
								   :date_expiring.lte	=> session[:created_at] + Rails.application.config.max_lifetime,
								   :created_at			=> session[:created_at]
				).limit(1).first

		matched_token
	end

	def self.save_session(session)
		date_expiring = session[:created_at] + Rails.application.config.max_lifetime

		self.create!(:token 		=> session[:token],
					 :date_expiring	=> date_expiring,
					 :created_at	=> session[:created_at],
					 :ip			=> IPAddr.new(session[:ip]).to_i)
	end

	def self.remove_old_session(token)
		self.delete_all(token: token)
	end

	private

	def self.generate_token
		begin
			token = SecureRandom.urlsafe_base64
		end while Token.where(token: token).exists?

		token
	end
end