· 7 years ago · Jul 11, 2018, 03:04 PM
1module Oauthable
2 extend ActiveSupport::Concern
3
4 included do |base|
5
6 def self.find_or_create_with_oauth(oauth_data, user_data={})
7 find_with_oauth(oauth_data) || create_with_oauth(oauth_data)
8 end
9
10 def self.find_with_oauth(oauth_data)
11 find_through_authorization(oauth_data.provider, oauth_data.uid)
12 end
13
14 def self.find_through_authorization(service_name, uid)
15 social_profile = SocialProfile.where(service_name: service_name, uid: uid).first
16 social_profile && social_profile.user
17 end
18
19 def self.create_with_oauth(oauth_data)
20 User.create(password: SecureRandom.base64(6), profile_attributes: { name: oauth_data.extra.raw_info.name })
21 end
22
23 def self.find_or_create_by_social_profiles(social_profiles, user_data)
24 social_profiles.each do |profile|
25 user = find_with_oauth(profile)
26 return user if user.present?
27 end
28
29 create_with_oauth(user_data)
30 end
31
32 def register_social_profile(data)
33 profile = SocialProfile.where(service_name: data[:service_name], uid: data[:uid]).first_or_create
34 if profile.user_id.present? && profile.user_id != id
35 return false
36 else
37 profile.update_attributes(access_token: data[:access_token], secret_key: data[:secret_key], active: true, user_id: id)
38 end
39
40 profile.persisted? ? profile : false
41 end
42
43 def password_required?
44 encrypted_password.nil? && social_profiles.to_a.count < 1
45 end
46
47 def email_required?
48 social_profiles.to_a.count < 1
49 end
50
51 def remember_me
52 true
53 end
54
55 end
56end