Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class User < ApplicationRecord
- has_many :songs #set song user relations
- attr_accessor :login #attr_accessor can login with username and email
- # Include default devise modules. Others available are:
- devise :database_authenticatable, :registerable,
- :recoverable, :rememberable, :trackable, :validatable, :confirmable,
- :authentication_keys => [:login]
- #Facebook Login Authentcation devise module
- devise :omniauthable, :omniauth_providers => [:facebook]
- validates :avatar, presence: true
- def self.find_for_database_authentication(warden_conditions)
- conditions = warden_conditions.dup
- if login = conditions.delete(:login)
- where(conditions.to_h).where(["lower(username) = :value OR lower(email) = :value", { :value => login.downcase }]).first
- elsif conditions.has_key?(:username) || conditions.has_key?(:email)
- where(conditions.to_h).first
- end
- end
- validates :username,
- :presence => true,
- :uniqueness => {
- :case_sensitive => false
- }
- #validate username
- validates_format_of :username, with: /^[a-zA-Z0-9_\.]*$/, :multiline => true
- #Add avatar attachment file for paperclip, offer 2 styles
- has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100#" }, :default_url => "/images/:style/missing.png"
- validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/
- #Facebook Auth handler
- def facebook
- @user = User.from_omniauth(request.env["omniauth.auth"])
- if @user.persisted?
- sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated
- set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?
- else
- session["devise.facebook_data"] = request.env["omniauth.auth"]
- redirect_to new_user_registration_url
- end
- end
- def failure
- redirect_to root_path
- end
- def self.from_omniauth(auth)
- where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
- user.email = auth.info.email
- user.username = auth.info.name
- user.password = Devise.friendly_token[0,20]
- #user.name = auth.info.name # assuming the user model has a name
- #user.image = auth.info.image # assuming the user model has an image
- # If you are using confirmable and the provider(s) you use validate emails,
- # uncomment the line below to skip the confirmation emails.
- # user.skip_confirmation!
- end
- end
- def self.new_with_session(params, session)
- super.tap do |user|
- if data = session["devise.facebook_data"] && session["devise.facebook_data"]["extra"]["raw_info"]
- user.email = data["email"] if user.email.blank?
- end
- end
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement