Use sorcery for logins
This gives us more flexibility and allows us to use password authentication later. Also we don't need to build the login functionality ourself.
This commit is contained in:
1 parent
73c184a4a0
commit
c478cfc7af
12 files changed
+642
-62
No files matched your search
@@ -1,6 +1,8 @@
|
||||
class Authentication < ApplicationRecord
|
||||
belongs_to :user
|
||||
|
||||
scope :for, -> (provider) { where(provider: provider) }
|
||||
|
||||
encrypts :access_token
|
||||
encrypts :refresh_token
|
||||
|
||||
@@ -9,6 +11,7 @@ class Authentication < ApplicationRecord
|
||||
end
|
||||
|
||||
def google_authorization
|
||||
return nil unless provider == 'google'
|
||||
@google_authorization ||= CLIENT_SECRETS.to_authorization.tap do |c|
|
||||
c.access_token = self.access_token
|
||||
c.refresh_token = self.refresh_token
|
||||
|
||||
+3
-25
@@ -1,40 +1,18 @@
|
||||
class User < ApplicationRecord
|
||||
authenticates_with_sorcery!
|
||||
has_many :authentications, dependent: :destroy
|
||||
has_many :forms, dependent: :destroy
|
||||
|
||||
def self.find_by_oauth_info(auth_client)
|
||||
oauth = Google::Apis::Oauth2V2::Oauth2Service.new
|
||||
oauth.authorization = auth_client
|
||||
user_info = oauth.get_userinfo
|
||||
|
||||
if user = User.find_by(google_id: user_info.id)
|
||||
authentication = user.authentications.last
|
||||
authentication.access_token = auth_client.access_token if auth_client.access_token.present?
|
||||
authentication.refresh_token = auth_client.refresh_token if auth_client.refresh_token.present?
|
||||
authentication.expires_at = Time.at(auth_client.expires_at) if auth_client.expires_at.present?
|
||||
authentication.save
|
||||
return user, authentication
|
||||
else
|
||||
user = User.create(name: user_info.name, email: user_info.email, google_id: user_info.id)
|
||||
authentication = user.authentications.create(
|
||||
access_token: auth_client.access_token,
|
||||
refresh_token: auth_client.refresh_token,
|
||||
expires_at: Time.at(auth_client.expires_at)
|
||||
)
|
||||
return user, authentication
|
||||
end
|
||||
end
|
||||
|
||||
def deactivate!(reason = nil)
|
||||
# currently we only use deactivate if we get an authentication exception appending data to a spreadsheet
|
||||
authentications.last&.update(expires_at: Time.current)
|
||||
end
|
||||
|
||||
def active?
|
||||
authentications.last.present? && !authentications.last.expired?
|
||||
authentications.any? { |a| !a.expired? }
|
||||
end
|
||||
|
||||
def google_authorization
|
||||
authentications.last.google_authorization
|
||||
authentications.for(:google).last.google_authorization
|
||||
end
|
||||
end
|
||||
Reference in new issue
Block a user