Skip to content

Instantly share code, notes, and snippets.

@exastencil
Created August 24, 2020 09:08
Show Gist options
  • Select an option

  • Save exastencil/90b208ede00902cdb11d62c5309c5239 to your computer and use it in GitHub Desktop.

Select an option

Save exastencil/90b208ede00902cdb11d62c5309c5239 to your computer and use it in GitHub Desktop.
Stellenbosch University OmniAuth Strategy
# Usage:
#
# # config/initializers/devise.rb
# require 'omniauth/strategies/stellenbosch_university'
#
# Devise.setup do |config|
# config.omniauth :stellenbosch_university,
# Rails.application.credentials.sun_auth_client,
# Rails.application.credentials.sun_auth_secret,
# scope: 'info-comprehensive academic-record',
# token_params: { redirect_uri: "http://localhost:3000/users/auth/stellenbosch_university/callback" }
# end
#
module OmniAuth
module Strategies
class StellenboschUniversity < OmniAuth::Strategies::OAuth2
# Name to use in your Devise initializer
option :name, 'stellenbosch_university'
# Setup specific to SU's OAuth implementation
option :client_options, {
site: 'https://api-sandbox.sun.ac.za',
authorize_url: 'https://oauth-sandbox.sun.ac.za/oauth/authorize',
token_url: 'https://oauth-sandbox.sun.ac.za/oauth/token',
scope: 'info-comprehensive', # NOTE: At least info-comprehensive is needed for email
}
option :pkce, false
# Unique Identifier for Users
uid { raw_info['usNumber'] }
# By default fetch name and email
# See https://app.swaggerhub.com/apis/StellenboschUni/person-api/1.0.0#/Person for more fields
info do
{
name: "#{raw_info['givenName']} #{raw_info['familyName']}",
email: raw_info['emailPersonal'] || raw_info['emailOfficial'],
}
end
extra do
{
'raw_info' => raw_info
}
end
# Fetch the user info from the `/info` endpoint
def raw_info
@raw_info ||= access_token.get('/info', headers: {
'Accept' => 'application/json',
}).parsed
end
# Override build_access_token to add the Authorization header needed when requesting the token
def build_access_token
options.token_params.merge! headers: {
'Authorization' => "Basic " + Base64.strict_encode64("#{options[:client_id]}:#{options[:client_secret]}")
}
super
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment