Skip to content

Instantly share code, notes, and snippets.

@KELiON
Last active April 14, 2021 09:58
Show Gist options
  • Save KELiON/bfbd7e42f2c5778ffe7c39fa33a7a800 to your computer and use it in GitHub Desktop.
Save KELiON/bfbd7e42f2c5778ffe7c39fa33a7a800 to your computer and use it in GitHub Desktop.
Rails app
class ApplicationController < ActionController::Base
before_action :authenticate!
end
module AuthHelper
def authenticate!
error!('Unauthorized', 401) unless current_user
end
def current_user
user = Rails.cache.fetch(cookies[:guid]) { User.find_by_guid(cookies[:guid]) } if cookies[:guid]
if user.nil?
Rails.cache.delete(cookies[:guid]) if cookies[:guid]
return nil
end
Rails.cache.write("#{user.guid}_online", true, expires_in: 20.minutes)
user.auth_updates
User.current_user = user
@current_user = user
end
end
class User < ApplicationRecord
has_many :received_likes, class_name: 'Like', foreign_key: :to_user_id
has_many :sended_likes, class_name: 'Like', foreign_key: :from_user_id
has_many :activities
has_many :photos, :foreign_key => 'guid', :primary_key => 'guid'
belongs_to :city
belongs_to :country
cattr_accessor :current_user
validates_presence_of :guid, :name
validates_uniqueness_of :guid
def online
Rails.cache.read("#{guid}_online") || false
end
def all_photos
Photo.where(guid: guid).order(:order_num).pluck(:name)
end
def json_response
{id: id, name: name, city_id: city_id, country_id: country_id, gender: gender, photos: all_photos,
online: online, liked: liked_from_current_user?, like_current_user: like_to_current_user?}
end
def liked_from_current_user?
received_likes.where(from: User.current_user).exists?
end
def like_to_current_user?
sended_likes.where(to: User.current_user).exists?
end
def unread_count
unread_activities_count + unread_messages_count
end
def unread_activities_count
activities.unread.count
end
def unread_messages_count
Message.unread.where(to_user_id: id).group(:chat_id).count.size
end
end
class UsersController < ApplicationController
def me
render json: current_user.json_response
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment