Advertisement
YarikHrom

Untitled

Mar 24th, 2022
953
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 2.31 KB | None | 0 0
  1. class User < ApplicationRecord
  2.   devise :database_authenticatable, :recoverable, :rememberable, :validatable,
  3.          :omniauthable, omniauth_providers: %i[alfred google facebook developer github]
  4.  
  5.   has_many :cards, foreign_key: :author_id
  6.   has_many :comments, foreign_key: :author_id
  7.   has_many :memberships
  8.   has_many :boards, through: :memberships
  9.   has_many :board_permissions_users, dependent: :destroy
  10.   has_many :board_permissions, through: :board_permissions_users, source: :permission
  11.   has_many :card_permissions_users, dependent: :destroy
  12.   has_many :card_permissions, through: :card_permissions_users, source: :permission
  13.   has_many :comment_permissions_users, dependent: :destroy
  14.   has_many :comment_permissions, through: :comment_permissions_users, source: :permission
  15.   has_many :action_items, foreign_key: 'assignee_id', class_name: 'ActionItem'
  16.  
  17.   has_and_belongs_to_many :teams
  18.  
  19.   validates :provider, presence: true
  20.   validates :uid, presence: true, uniqueness: { scope: :provider }
  21.   validates :nickname, presence: true, uniqueness: true
  22.  
  23.   mount_uploader :avatar, AvatarUploader
  24.  
  25.   def self.from_omniauth(provider, uid, info)
  26.     user = find_by(provider: provider, uid: uid) || find_by(email: info[:email]) || new
  27.  
  28.     user.tap do |u|
  29.       u.provider = provider
  30.       u.uid = uid
  31.       u.email = info[:email]
  32.       u.remote_avatar_url = info[:image] || info[:avatar_url] if u.changed?
  33.  
  34.       u.send :new_user_settings, info
  35.       u.save
  36.     end
  37.   end
  38.  
  39.   def allowed?(identifier, resource)
  40.     permission = Permission.find_by(identifier: identifier)
  41.     resource_name = resource.class.to_s.downcase
  42.  
  43.     public_send("#{resource_name}_permissions_users").where("#{resource_name}": resource,
  44.                                                             permission: permission).any?
  45.   end
  46.  
  47.   def creator?(board)
  48.     board_permissions_users
  49.       .exists?(permission: Permission.find_by_identifier(Permission::MASTER_CREATOR_ID),
  50.                board: board)
  51.   end
  52.  
  53.   private
  54.  
  55.   def new_user_settings(info)
  56.     return unless new_record?
  57.  
  58.     self.password = Devise.friendly_token[0, 20]
  59.     self.nickname = info[:nickname] || (email && email[/^[^@]+/])
  60.     self.first_name = info[:first_name] if info[:first_name]
  61.     self.last_name = info[:last_name] if info[:last_name]
  62.   end
  63. end
  64.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement