Add latest changes from gitlab-org/gitlab@master

This commit is contained in:
GitLab Bot 2022-10-14 00:10:41 +00:00
parent 9f4c898b9d
commit dcd075c981
47 changed files with 533 additions and 2335 deletions

View File

@ -1573,12 +1573,6 @@
changes: ["vendor/gems/omniauth-gitlab/**/*"]
- <<: *if-merge-request-labels-run-all-rspec
.vendor:rules:omniauth-google-oauth2:
rules:
- <<: *if-merge-request
changes: ["vendor/gems/omniauth-google-oauth2/**/*"]
- <<: *if-merge-request-labels-run-all-rspec
.vendor:rules:omniauth-salesforce:
rules:
- <<: *if-merge-request

View File

@ -62,14 +62,6 @@ vendor omniauth-gitlab:
include: vendor/gems/omniauth-gitlab/.gitlab-ci.yml
strategy: depend
vendor omniauth-google-oauth2:
extends:
- .vendor:rules:omniauth-google-oauth2
needs: []
trigger:
include: vendor/gems/omniauth-google-oauth2/.gitlab-ci.yml
strategy: depend
vendor omniauth-salesforce:
extends:
- .vendor:rules:omniauth-salesforce

View File

@ -58,15 +58,15 @@ gem 'rexml', '~> 3.2.5'
gem 'ruby-saml', '~> 1.13.0'
gem 'omniauth', '~> 2.1.0'
gem 'omniauth-auth0', '~> 2.0.0'
gem 'omniauth-azure-activedirectory-v2', '~> 1.0'
gem 'omniauth-azure-activedirectory-v2', '~> 2.0'
gem 'omniauth-azure-oauth2', '~> 0.0.9', path: 'vendor/gems/omniauth-azure-oauth2' # See gem README.md
gem 'omniauth-cas3', '~> 1.1.4', path: 'vendor/gems/omniauth-cas3' # See vendor/gems/omniauth-cas3/README.md
gem 'omniauth-dingtalk-oauth2', '~> 1.0'
gem 'omniauth-alicloud', '~> 1.0.1'
gem 'omniauth-alicloud', '~> 2.0.0'
gem 'omniauth-facebook', '~> 4.0.0'
gem 'omniauth-github', '2.0.0'
gem 'omniauth-github', '2.0.1'
gem 'omniauth-gitlab', '~> 4.0.0', path: 'vendor/gems/omniauth-gitlab' # See vendor/gems/omniauth-gitlab/README.md
gem 'omniauth-google-oauth2', '~> 1.0.1', path: 'vendor/gems/omniauth-google-oauth2' # See gem README.md
gem 'omniauth-google-oauth2', '~> 1.1'
gem 'omniauth-oauth2-generic', '~> 0.2.2'
gem 'omniauth-saml', '~> 2.0.0'
gem 'omniauth-shibboleth', '~> 1.3.0'

View File

@ -371,17 +371,18 @@
{"name":"ohai","version":"16.10.6","platform":"ruby","checksum":"b835806e585faea4ac8346b68c722fb5fc29a29f73fd7e3a022f9073132dec22"},
{"name":"oj","version":"3.13.21","platform":"ruby","checksum":"aef31a8dcc6f0b9b4bb5cc7ac6cc5272b2d851deb11a1804c2ed6b5501b50e46"},
{"name":"omniauth","version":"2.1.0","platform":"ruby","checksum":"bff7234f5ec9323622b217c7f26d52f850de0b0e2b8c807c3358fc79fe572300"},
{"name":"omniauth-alicloud","version":"1.0.1","platform":"ruby","checksum":"2f81ec0b8f98d2ab5e5d64555c75ace46582cf27c4ef4207aa59f15331dd697a"},
{"name":"omniauth-alicloud","version":"2.0.0","platform":"ruby","checksum":"8ecf369d51cd5317c1e7c6b80276891f76cff210a534ec654326af5c62265de3"},
{"name":"omniauth-atlassian-oauth2","version":"0.2.0","platform":"ruby","checksum":"eb07574a188ab8a03376ce288bce86bc2dd4a1382ffa5781cb5e2b7bc15d76c9"},
{"name":"omniauth-auth0","version":"2.0.0","platform":"ruby","checksum":"823769be7883b45b2fa94367c2f6a17f7b3b1333986016089c016d45827da545"},
{"name":"omniauth-authentiq","version":"0.3.3","platform":"ruby","checksum":"11b3791085a130782bf14b0088653beeb085638a9548d7110a57d3cbbb54fb4c"},
{"name":"omniauth-azure-activedirectory-v2","version":"1.0.0","platform":"ruby","checksum":"edcdd77ace89ae3a0ed4b3d350b64a0c81b5a2435dff6f8eda8cbce15cbf69df"},
{"name":"omniauth-azure-activedirectory-v2","version":"2.0.0","platform":"ruby","checksum":"c484cedd52cd233e3c216c4b3ed667ec07d20e51c550a613b65a0f90fe8ad072"},
{"name":"omniauth-dingtalk-oauth2","version":"1.0.1","platform":"ruby","checksum":"6545670f1c38344eaf960df9750c550a9534f790f888af088761a9e04269139b"},
{"name":"omniauth-facebook","version":"4.0.0","platform":"ruby","checksum":"05ae3565c8fdb38df8dab04eb8ca854ea6c18e81591d3e6598ce101293a2f20f"},
{"name":"omniauth-github","version":"2.0.0","platform":"ruby","checksum":"1ca26576125a97e27d3f8dc39cd98853d7382dd0fc04a40d3b9ec345ee378649"},
{"name":"omniauth-github","version":"2.0.1","platform":"ruby","checksum":"8ff8e70ac6d6db9d52485eef52cfa894938c941496e66b52b5e2773ade3ccad4"},
{"name":"omniauth-google-oauth2","version":"1.1.1","platform":"ruby","checksum":"4496f126e84eaf760f9c6a5c69e5e7511f98092d7f25ad79fd2c0ae5e09b5039"},
{"name":"omniauth-oauth","version":"1.2.0","platform":"ruby","checksum":"e7a78658498dc83aa3f3be1a776425c0f06a60d45d9236dbe5e98e61fadf827b"},
{"name":"omniauth-oauth2","version":"1.7.3","platform":"ruby","checksum":"3f5a8f99fa72e0f91d2abd7475ceb972a4ae67ed59e049f314c0c1bad81f4745"},
{"name":"omniauth-oauth2-generic","version":"0.2.2","platform":"ruby","checksum":"e30814f6c472e04f3d9e4a3ddc03bc9a46f53f9333f8d443bf3ad43c6ebcdbd4"},
{"name":"omniauth-oauth2","version":"1.8.0","platform":"ruby","checksum":"b2f8e9559cc7e2d4efba57607691d6d2b634b879fc5b5b6ccfefa3da85089e78"},
{"name":"omniauth-oauth2-generic","version":"0.2.8","platform":"ruby","checksum":"ce6e8539019d5ebf2f48867072b9f248f148bb4cbe7166dee655865abfae7613"},
{"name":"omniauth-saml","version":"2.0.0","platform":"ruby","checksum":"02594fd6630de26a9e65a2e64223e9ad32324fa97a6c7f1f22a1553ea3dd44c7"},
{"name":"omniauth-shibboleth","version":"1.3.0","platform":"ruby","checksum":"b0bb725ced5cb76fbfc187ddbb8ad6864d0cd5df714cab36a528df8ee4b1d113"},
{"name":"omniauth-twitter","version":"1.4.0","platform":"ruby","checksum":"c5cc6c77cd767745ffa9ebbd5fbd694a3fa99d1d2d82a4d7def0bf3b6131b264"},

View File

@ -65,16 +65,7 @@ PATH
specs:
omniauth-gitlab (4.0.0)
omniauth (~> 2.0)
omniauth-oauth2 (~> 1.7.1)
PATH
remote: vendor/gems/omniauth-google-oauth2
specs:
omniauth-google-oauth2 (1.0.1)
jwt (>= 2.0)
oauth2 (~> 2.0)
omniauth (~> 2.0)
omniauth-oauth2 (~> 1.7.1)
omniauth-oauth2 (~> 1.8)
PATH
remote: vendor/gems/omniauth-salesforce
@ -940,8 +931,8 @@ GEM
hashie (>= 3.4.6)
rack (>= 2.2.3)
rack-protection
omniauth-alicloud (1.0.1)
omniauth-oauth2 (~> 1.7.1)
omniauth-alicloud (2.0.0)
omniauth-oauth2 (~> 1.8)
omniauth-atlassian-oauth2 (0.2.0)
omniauth (>= 1.1.1)
omniauth-oauth2 (>= 1.5)
@ -950,23 +941,29 @@ GEM
omniauth-authentiq (0.3.3)
jwt (>= 1.5)
omniauth-oauth2 (>= 1.5)
omniauth-azure-activedirectory-v2 (1.0.0)
omniauth-oauth2 (~> 1.7)
omniauth-azure-activedirectory-v2 (2.0.0)
omniauth-oauth2 (~> 1.8)
omniauth-dingtalk-oauth2 (1.0.1)
omniauth-oauth2 (~> 1.7)
omniauth-facebook (4.0.0)
omniauth-oauth2 (~> 1.2)
omniauth-github (2.0.0)
omniauth-github (2.0.1)
omniauth (~> 2.0)
omniauth-oauth2 (~> 1.7.1)
omniauth-oauth2 (~> 1.8)
omniauth-google-oauth2 (1.1.1)
jwt (>= 2.0)
oauth2 (~> 2.0.6)
omniauth (~> 2.0)
omniauth-oauth2 (~> 1.8.0)
omniauth-oauth (1.2.0)
oauth
omniauth (>= 1.0, < 3)
omniauth-oauth2 (1.7.3)
omniauth-oauth2 (1.8.0)
oauth2 (>= 1.4, < 3)
omniauth (>= 1.9, < 3)
omniauth-oauth2-generic (0.2.2)
omniauth (~> 2.0)
omniauth-oauth2-generic (0.2.8)
omniauth-oauth2 (~> 1.0)
rake
omniauth-saml (2.0.0)
omniauth (~> 2.0)
ruby-saml (~> 1.9)
@ -1699,18 +1696,18 @@ DEPENDENCIES
ohai (~> 16.10)
oj (~> 3.13.21)
omniauth (~> 2.1.0)
omniauth-alicloud (~> 1.0.1)
omniauth-alicloud (~> 2.0.0)
omniauth-atlassian-oauth2 (~> 0.2.0)
omniauth-auth0 (~> 2.0.0)
omniauth-authentiq (~> 0.3.3)
omniauth-azure-activedirectory-v2 (~> 1.0)
omniauth-azure-activedirectory-v2 (~> 2.0)
omniauth-azure-oauth2 (~> 0.0.9)!
omniauth-cas3 (~> 1.1.4)!
omniauth-dingtalk-oauth2 (~> 1.0)
omniauth-facebook (~> 4.0.0)
omniauth-github (= 2.0.0)
omniauth-github (= 2.0.1)
omniauth-gitlab (~> 4.0.0)!
omniauth-google-oauth2 (~> 1.0.1)!
omniauth-google-oauth2 (~> 1.1)
omniauth-oauth2-generic (~> 0.2.2)
omniauth-salesforce (~> 1.0.5)!
omniauth-saml (~> 2.0.0)

View File

@ -201,7 +201,7 @@ export default {
data-testid="internalNoteIndicator"
variant="warning"
size="sm"
class="gl-mb-3 gl-ml-2"
class="gl-ml-2"
:title="internalNoteTooltip"
>
{{ __('Internal note') }}

View File

@ -0,0 +1,100 @@
# frozen_string_literal: true
module Import
module GithubOauth
extend ActiveSupport::Concern
OAuthConfigMissingError = Class.new(StandardError)
included do
rescue_from OAuthConfigMissingError, with: :missing_oauth_config
end
private
def provider_auth
return if session[access_token_key].present?
go_to_provider_for_permissions unless ci_cd_only?
end
def ci_cd_only?
%w[1 true].include?(params[:ci_cd_only])
end
def go_to_provider_for_permissions
redirect_to authorize_url
end
def oauth_client
raise OAuthConfigMissingError unless oauth_config
oauth_client_from_config
end
def oauth_client_from_config
@oauth_client_from_config ||= ::OAuth2::Client.new(
oauth_config.app_id,
oauth_config.app_secret,
oauth_options.merge(ssl: { verify: oauth_config['verify_ssl'] })
)
end
def oauth_config
@oauth_config ||= Gitlab::Auth::OAuth::Provider.config_for('github')
end
def oauth_options
return unless oauth_config
oauth_config.dig('args', 'client_options').deep_symbolize_keys
end
def authorize_url
state = SecureRandom.base64(64)
session[auth_state_key] = state
if Feature.enabled?(:remove_legacy_github_client)
oauth_client.auth_code.authorize_url(
redirect_uri: callback_import_url,
scope: 'repo, user, user:email',
state: state
)
else
client.authorize_url(callback_import_url, state)
end
end
def get_token(code)
if Feature.enabled?(:remove_legacy_github_client)
oauth_client.auth_code.get_token(code).token
else
client.get_token(code)
end
end
def missing_oauth_config
session[access_token_key] = nil
message = _('Missing OAuth configuration for GitHub.')
respond_to do |format|
format.json do
render json: { errors: message }, status: :unauthorized
end
format.any do
redirect_to new_import_url,
alert: message
end
end
end
def callback_import_url
public_send("users_import_#{provider_name}_callback_url", extra_import_params.merge({ namespace_id: params[:namespace_id] })) # rubocop:disable GitlabSecurity/PublicSend
end
def extra_import_params
{}
end
end
end

View File

@ -5,14 +5,12 @@ class Import::GithubController < Import::BaseController
include ImportHelper
include ActionView::Helpers::SanitizeHelper
include Import::GithubOauth
before_action :verify_import_enabled
before_action :provider_auth, only: [:status, :realtime_changes, :create]
before_action :expire_etag_cache, only: [:status, :create]
OAuthConfigMissingError = Class.new(StandardError)
rescue_from OAuthConfigMissingError, with: :missing_oauth_config
rescue_from Octokit::Unauthorized, with: :provider_unauthorized
rescue_from Octokit::TooManyRequests, with: :provider_rate_limit
rescue_from Gitlab::GithubImport::RateLimitError, with: :rate_limit_threshold_exceeded
@ -154,58 +152,10 @@ class Import::GithubController < Import::BaseController
@filter = @filter&.tr(' ', '')&.tr(':', '')
end
def oauth_client
raise OAuthConfigMissingError unless oauth_config
@oauth_client ||= ::OAuth2::Client.new(
oauth_config.app_id,
oauth_config.app_secret,
oauth_options.merge(ssl: { verify: oauth_config['verify_ssl'] })
)
end
def oauth_config
@oauth_config ||= Gitlab::Auth::OAuth::Provider.config_for('github')
end
def oauth_options
if oauth_config
oauth_config.dig('args', 'client_options').deep_symbolize_keys
else
OmniAuth::Strategies::GitHub.default_options[:client_options].symbolize_keys
end
end
def authorize_url
state = SecureRandom.base64(64)
session[auth_state_key] = state
if Feature.enabled?(:remove_legacy_github_client)
oauth_client.auth_code.authorize_url(
redirect_uri: callback_import_url,
scope: 'repo, user, user:email',
state: state
)
else
client.authorize_url(callback_import_url, state)
end
end
def get_token(code)
if Feature.enabled?(:remove_legacy_github_client)
oauth_client.auth_code.get_token(code).token
else
client.get_token(code)
end
end
def verify_import_enabled
render_404 unless import_enabled?
end
def go_to_provider_for_permissions
redirect_to authorize_url
end
def import_enabled?
__send__("#{provider_name}_import_enabled?") # rubocop:disable GitlabSecurity/PublicSend
end
@ -222,10 +172,6 @@ class Import::GithubController < Import::BaseController
public_send("status_import_#{provider_name}_url", extra_import_params.merge({ namespace_id: params[:namespace_id].presence })) # rubocop:disable GitlabSecurity/PublicSend
end
def callback_import_url
public_send("users_import_#{provider_name}_callback_url", extra_import_params.merge({ namespace_id: params[:namespace_id] })) # rubocop:disable GitlabSecurity/PublicSend
end
def provider_unauthorized
session[access_token_key] = nil
redirect_to new_import_url,
@ -239,12 +185,6 @@ class Import::GithubController < Import::BaseController
alert: _("GitHub API rate limit exceeded. Try again after %{reset_time}") % { reset_time: reset_time }
end
def missing_oauth_config
session[access_token_key] = nil
redirect_to new_import_url,
alert: _('Missing OAuth configuration for GitHub.')
end
def auth_state_key
:"#{provider_name}_auth_state_key"
end
@ -263,24 +203,10 @@ class Import::GithubController < Import::BaseController
end
# rubocop: enable CodeReuse/ActiveRecord
def provider_auth
if !ci_cd_only? && session[access_token_key].blank?
go_to_provider_for_permissions
end
end
def ci_cd_only?
%w[1 true].include?(params[:ci_cd_only])
end
def client_options
{ wait_for_rate_limit_reset: false }
end
def extra_import_params
{}
end
def rate_limit_threshold_exceeded
head :too_many_requests
end

View File

@ -0,0 +1,57 @@
# frozen_string_literal: true
module Import
class GithubGroupsController < ApplicationController
include Import::GithubOauth
before_action :provider_auth, only: [:status]
feature_category :importers
PAGE_LENGTH = 25
def status
respond_to do |format|
format.json do
render json: { provider_groups: serialized_provider_groups }
end
end
end
private
def serialized_provider_groups
Import::GithubOrgSerializer.new.represent(importable_orgs)
end
def importable_orgs
client_orgs.to_a
end
def client_orgs
@client_orgs ||= client.octokit.organizations(nil, pagination_options)
end
def client
@client ||= Gitlab::GithubImport::Client.new(session[access_token_key])
end
def pagination_options
{
page: [1, params[:page].to_i].max,
per_page: PAGE_LENGTH
}
end
def auth_state_key
:"#{provider_name}_auth_state_key"
end
def access_token_key
:"#{provider_name}_access_token"
end
def provider_name
:github
end
end
end

View File

@ -198,6 +198,8 @@ class User < ApplicationRecord
has_many :snippets, dependent: :destroy, foreign_key: :author_id # rubocop:disable Cop/ActiveRecordDependent
has_many :notes, dependent: :destroy, foreign_key: :author_id # rubocop:disable Cop/ActiveRecordDependent
has_many :issues, dependent: :destroy, foreign_key: :author_id # rubocop:disable Cop/ActiveRecordDependent
has_many :legacy_assigned_merge_requests, class_name: 'MergeRequest', dependent: :nullify, foreign_key: :assignee_id # rubocop:disable Cop/ActiveRecordDependent
has_many :updated_merge_requests, class_name: 'MergeRequest', dependent: :nullify, foreign_key: :updated_by_id # rubocop:disable Cop/ActiveRecordDependent
has_many :updated_issues, class_name: 'Issue', dependent: :nullify, foreign_key: :updated_by_id # rubocop:disable Cop/ActiveRecordDependent
has_many :closed_issues, class_name: 'Issue', dependent: :nullify, foreign_key: :closed_by_id # rubocop:disable Cop/ActiveRecordDependent
has_many :merge_requests, dependent: :destroy, foreign_key: :author_id # rubocop:disable Cop/ActiveRecordDependent

View File

@ -0,0 +1,8 @@
# frozen_string_literal: true
module Import
class GithubOrgEntity < Grape::Entity
expose :login, as: :name
expose :description
end
end

View File

@ -0,0 +1,7 @@
# frozen_string_literal: true
module Import
class GithubOrgSerializer < BaseSerializer
entity Import::GithubOrgEntity
end
end

View File

@ -11,17 +11,6 @@ if Gitlab::Auth::Ldap::Config.enabled?
end
end
module OmniAuth
module Strategies
class AzureActivedirectoryV2
# override until https://github.com/RIPAGlobal/omniauth-azure-activedirectory-v2/pull/6 is merged
def callback_url
full_host + callback_path
end
end
end
end
OmniAuth.config.full_host = Gitlab::OmniauthInitializer.full_host
OmniAuth.config.allowed_request_methods = [:post]

View File

@ -69,6 +69,10 @@ namespace :import do
post :authorize
end
resource :github_group, only: [] do
get :status
end
resource :bulk_imports, only: [:create] do
post :configure
get :status

View File

@ -103,7 +103,7 @@ rule in the defined policy are met.
| Field | Type | Possible values | Description |
|-------|------|-----------------|-------------|
| `scan` | `string` | `dast`, `secret_detection`, `sast`, `container_scanning`, `cluster_image_scanning` | The action's type. |
| `scan` | `string` | `dast`, `secret_detection`, `sast`, `container_scanning` | The action's type. |
| `site_profile` | `string` | Name of the selected [DAST site profile](../dast/index.md#site-profile). | The DAST site profile to execute the DAST scan. This field should only be set if `scan` type is `dast`. |
| `scanner_profile` | `string` or `null` | Name of the selected [DAST scanner profile](../dast/index.md#scanner-profile). | The DAST scanner profile to execute the DAST scan. This field should only be set if `scan` type is `dast`.|
| `variables` | `object` | | A set of CI variables, supplied as an array of `key: value` pairs, to apply and enforce for the selected scan. The `key` is the variable name, with its `value` provided as a string. This parameter supports any variable that the GitLab CI job supports for the specified scan. |
@ -124,7 +124,7 @@ Note the following:
- A secret detection scan runs in `normal` mode when executed as part of a pipeline, and in
[`historic`](../secret_detection/index.md#full-history-secret-detection)
mode when executed as part of a scheduled scan.
- A container scanning and cluster image scanning scans configured for the `pipeline` rule type ignores the cluster defined in the `clusters` object.
- A container scanning scan configured for the `pipeline` rule type ignores the cluster defined in the `clusters` object.
They use predefined CI/CD variables defined for your project. Cluster selection with the `clusters` object is supported for the `schedule` rule type.
A cluster with a name provided in the `clusters` object must be created and configured for the project.
- The SAST scan uses the default template and runs in a [child pipeline](../../../ci/pipelines/downstream_pipelines.md#parent-child-pipelines).
@ -184,8 +184,6 @@ In this example:
and `Site Profile D`.
- Secret detection, container scanning, and SAST scans run for every pipeline executed on the `main`
branch. The SAST scan runs with the `SAST_EXCLUDED_ANALYZER` variable set to `"brakeman"`.
- Cluster Image Scanning scan runs every 24h. The scan runs on the `production-cluster` cluster and fetches vulnerabilities
from the container with the name `database` configured for deployment with the name `production-application` in the `production-namespace` namespace.
## Example for scan execution policy editor

View File

@ -125,7 +125,7 @@ when more changes are added to it:
1. On the left sidebar, select **Settings > Merge requests**.
1. In the **Merge request approvals** section, scroll to **Approval settings** and
select **Remove all approvals when commits are added to the source branch**.
select **Remove all approvals**.
1. Select **Save changes**.
Approvals aren't removed when a merge request is [rebased from the UI](../methods/index.md#rebasing-in-semi-linear-merge-methods)

View File

@ -221,6 +221,8 @@ module Gitlab
end
if token.user.can_log_in_with_non_expired_password? || token.user.project_bot?
::PersonalAccessTokens::LastUsedService.new(token).execute
Gitlab::Auth::Result.new(token.user, nil, :personal_access_token, abilities_for_scopes(token.scopes))
end
end

View File

@ -20,8 +20,12 @@ module Gitlab
::Gitlab::Ci::Variables::Collection.new.tap do |variables|
next variables unless release
variables.append(
key: 'CI_RELEASE_DESCRIPTION', value: release.description.truncate(DESCRIPTION_LIMIT), raw: true)
if release.description
variables.append(
key: 'CI_RELEASE_DESCRIPTION',
value: release.description.truncate(DESCRIPTION_LIMIT),
raw: true)
end
end
end
end

View File

@ -28,6 +28,12 @@ module QA
element :service_jira_project_key_field
end
view 'ee/app/assets/javascripts/integrations/edit/components/jira_issue_creation_vulnerabilities.vue' do
element :service_jira_enable_vulnerabilities_checkbox
element :service_jira_issue_types_fetch_retry_button
element :service_jira_select_issue_type_dropdown
end
def setup_service_with(url:)
QA::Runtime::Logger.info "Setting up JIRA"
@ -41,10 +47,7 @@ module QA
yield self if block_given?
click_save_changes_button
wait_until(reload: false) do
has_element?(:save_changes_button, wait: 1) ? !find_element(:save_changes_button).disabled? : true
end
click_save_changes_and_wait
end
def enable_jira_issues
@ -55,12 +58,31 @@ module QA
fill_element(:service_jira_project_key_field, key)
end
def enable_jira_vulnerabilities
check_element(:service_jira_enable_vulnerabilities_checkbox, true)
end
def select_vulnerability_bug_type(bug_type)
click_retry_vulnerabilities
select_jira_bug_type(bug_type)
click_save_changes_and_wait
end
private
def set_jira_server_url(url)
fill_element(:service_url_field, url)
end
def click_retry_vulnerabilities
click_element(:service_jira_issue_types_fetch_retry_button)
end
def select_jira_bug_type(option)
click_element(:service_jira_select_issue_type_dropdown)
click_element(:service_jira_type, service_type: option)
end
def set_username(username)
fill_element(:service_username_field, username)
end
@ -85,6 +107,13 @@ module QA
fill_element(:service_jira_issue_transition_id_field, transition_ids)
end
def click_save_changes_and_wait
click_save_changes_button
wait_until(reload: false) do
has_element?(:save_changes_button, wait: 1) ? !find_element(:save_changes_button).disabled? : true
end
end
def click_save_changes_button
click_element(:save_changes_button)
end

47
qa/qa/vendor/jira/jira_issue_page.rb vendored Normal file
View File

@ -0,0 +1,47 @@
# frozen_string_literal: true
require 'capybara/dsl'
module QA
module Vendor
module Jira
class JiraIssuePage < JiraAPI
include Capybara::DSL
include Scenario::Actable
def login(username, password)
QA::Runtime::Logger.debug("Logging into JIRA with username: #{username} and password:#{password}")
fill_in 'login-form-username', with: username
fill_in 'login-form-password', with: password
click_on 'login-form-submit'
end
def go_to_login_page
click_on 'log in'
end
def login_if_required(username, password)
return unless login_required?
go_to_login_page
login(username, password)
end
def summary_field
page.find('#summary').value
end
def issue_description
page.find('#description', visible: false).value
end
def login_required?
login_required = page.has_text?('You are not logged in')
QA::Runtime::Logger.debug("login_required: #{login_required}")
login_required
end
end
end
end
end

View File

@ -44,13 +44,6 @@ RSpec.describe Import::GithubController do
end
describe "GET callback" do
before do
allow(controller).to receive(:get_token).and_return(token)
allow(controller).to receive(:oauth_options).and_return({})
stub_omniauth_provider('github')
end
context "when auth state param is missing from session" do
it "reports an error" do
get :callback
@ -63,17 +56,31 @@ RSpec.describe Import::GithubController do
context "when auth state param is present in session" do
let(:valid_auth_state) { "secret-state" }
before do
session[:github_auth_state_key] = valid_auth_state
end
context 'when remove_legacy_github_client feature is disabled' do
before do
stub_feature_flags(remove_legacy_github_client: false)
allow_next_instance_of(Gitlab::LegacyGithubImport::Client) do |client|
allow(client).to receive(:get_token).and_return(token)
end
session[:github_auth_state_key] = valid_auth_state
end
it "updates access token if state param is valid" do
token = "asdasd12345"
it "updates access token if state param is valid" do
token = "asdasd12345"
get :callback, params: { state: valid_auth_state }
get :callback, params: { state: valid_auth_state }
expect(session[:github_access_token]).to eq(token)
expect(controller).to redirect_to(status_import_github_url)
expect(session[:github_access_token]).to eq(token)
expect(controller).to redirect_to(status_import_github_url)
end
it "includes namespace_id from query params if it is present" do
namespace_id = 1
get :callback, params: { state: valid_auth_state, namespace_id: namespace_id }
expect(controller).to redirect_to(status_import_github_url(namespace_id: namespace_id))
end
end
it "reports an error if state param is invalid" do
@ -83,12 +90,31 @@ RSpec.describe Import::GithubController do
expect(flash[:alert]).to eq('Access denied to your GitHub account.')
end
it "includes namespace_id from query params if it is present" do
namespace_id = 1
context 'when remove_legacy_github_client feature is enabled' do
before do
stub_feature_flags(remove_legacy_github_client: true)
allow_next_instance_of(OAuth2::Client) do |client|
allow(client).to receive_message_chain(:auth_code, :get_token, :token).and_return(token)
end
session[:github_auth_state_key] = valid_auth_state
end
get :callback, params: { state: valid_auth_state, namespace_id: namespace_id }
it "updates access token if state param is valid" do
token = "asdasd12345"
expect(controller).to redirect_to(status_import_github_url(namespace_id: namespace_id))
get :callback, params: { state: valid_auth_state }
expect(session[:github_access_token]).to eq(token)
expect(controller).to redirect_to(status_import_github_url)
end
it "includes namespace_id from query params if it is present" do
namespace_id = 1
get :callback, params: { state: valid_auth_state, namespace_id: namespace_id }
expect(controller).to redirect_to(status_import_github_url(namespace_id: namespace_id))
end
end
end
end

View File

@ -5,7 +5,7 @@ require 'spec_helper'
RSpec.describe 'OmniAuth::Strategies::OAuth2' do
it 'verifies the gem version' do
current_version = OmniAuth::OAuth2::VERSION
expected_version = '1.7.3'
expected_version = '1.8.0'
expect(current_version).to eq(expected_version), <<~EOF
New version #{current_version} of the `omniauth-oauth2` gem detected!

View File

@ -495,6 +495,12 @@ RSpec.describe Gitlab::Auth, :use_clean_rails_memory_store_caching do
end
end
end
it 'updates last_used_at column if token is valid' do
personal_access_token = create(:personal_access_token, scopes: ['write_repository'])
expect { gl_auth.find_for_git_client('', personal_access_token.token, project: nil, ip: 'ip') }.to change { personal_access_token.reload.last_used_at }
end
end
context 'while using regular user and password' do

View File

@ -39,6 +39,19 @@ RSpec.describe Gitlab::Ci::Variables::Builder::Release do
expect(subject['CI_RELEASE_DESCRIPTION'].value.length).to eq(1024)
end
end
context 'when description is nil' do
before do
release.update_attribute(:description, nil)
end
it 'returns without error' do
builder = subject
expect(builder).to match_array([])
expect(builder.errors).to be_nil
end
end
end
context 'when the release is not present' do

View File

@ -0,0 +1,69 @@
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe Import::GithubGroupsController do
describe 'GET status' do
subject(:status) { get '/import/github_group/status', params: params, headers: headers }
let_it_be(:user) { create(:user) }
let(:headers) { { 'Accept' => 'application/json' } }
let(:params) { {} }
before do
login_as(user)
end
context 'when OAuth config is missing' do
before do
allow(Gitlab::Auth::OAuth::Provider).to receive(:config_for).with('github').and_return(nil)
end
it 'returns missing config error' do
status
expect(json_response['errors']).to eq('Missing OAuth configuration for GitHub.')
end
end
context 'when OAuth config present' do
let(:github_access_token) { 'asdasd12345' }
before do
post '/import/github/personal_access_token', params: { personal_access_token: github_access_token }
end
it 'fetches organizations' do
expect_next_instance_of(Octokit::Client) do |client|
expect(client).to receive(:organizations).and_return([].to_enum)
end
status
end
context 'with pagination' do
context 'when no page is specified' do
it 'requests first page' do
expect_next_instance_of(Octokit::Client) do |client|
expect(client).to receive(:organizations).with(nil, { page: 1, per_page: 25 }).and_return([].to_enum)
end
status
end
end
context 'when page is specified' do
let(:params) { { page: 2 } }
it 'responds with organizations with specified page' do
expect_next_instance_of(Octokit::Client) do |client|
expect(client).to receive(:organizations).with(nil, { page: 2, per_page: 25 }).and_return([].to_enum)
end
status
end
end
end
end
end
end

View File

@ -177,3 +177,10 @@ RSpec.describe Import::PhabricatorController, 'routing' do
expect(get("/import/phabricator/new")).to route_to("import/phabricator#new")
end
end
# status_import_github_group GET /import/github_group/status(.:format) import/github_groups#status
RSpec.describe Import::GithubGroupsController, 'routing' do
it 'to #status' do
expect(get('/import/github_group/status')).to route_to('import/github_groups#status')
end
end

View File

@ -0,0 +1,25 @@
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe Import::GithubOrgEntity do
let(:org_data) do
{
'id' => 12345,
'login' => 'org-name',
'url' => 'https://api.github.com/orgs/org-name',
'avatar_url' => 'https://avatars.githubusercontent.com/u/12345?v=4',
'node_id' => 'O_teStT',
'description' => ''
}
end
subject { described_class.new(org_data).as_json }
it 'exposes correct attributes' do
expect(subject.keys).to contain_exactly(
:description,
:name
)
end
end

View File

@ -0,0 +1,47 @@
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe Import::GithubOrgSerializer do
it 'represents GithubOrgEntity entities' do
expect(described_class.entity_class).to eq(Import::GithubOrgEntity)
end
describe '#represent' do
let(:org_data) do
{
id: 123456,
login: 'org-name',
node_id: 'O_teStT',
url: 'https://api.github.com/orgs/org-name',
repos_url: 'https://api.github.com/orgs/org-name/repos',
events_url: 'https://api.github.com/orgs/org-name/events',
hooks_url: 'https://api.github.com/orgs/org-name/hooks',
issues_url: 'https://api.github.com/orgs/org-name/issues',
members_url: 'https://api.github.com/orgs/org-name/members{/member}',
public_members_url: 'https://api.github.com/orgs/org-name/public_members{/member}',
avatar_url: 'avatar_url',
description: 'description'
}
end
subject { described_class.new.represent(resource) }
context 'when a single object is being serialized' do
let(:resource) { org_data }
it 'serializes organization object' do
expect(subject).to eq({ name: 'org-name', description: 'description' })
end
end
context 'when multiple objects are being serialized' do
let(:count) { 3 }
let(:resource) { Array.new(count, org_data) }
it 'serializes array of organizations' do
expect(subject).to all(eq({ name: 'org-name', description: 'description' }))
end
end
end
end

View File

@ -407,6 +407,21 @@ RSpec.describe Users::DestroyService do
expect(issue.updated_by).to be_nil
expect(resource_label_event.user).to be_nil
end
it 'nullifies assigned_merge_requests, last_updated_merge_requests' do
merge_request = create(:merge_request, source_project: project, target_project: project,
assignee: other_user, updated_by: other_user, merge_user: other_user)
described_class.new(user).execute(other_user, skip_authorization: true)
merge_request.reload
aggregate_failures do
expect(merge_request.updated_by).to be_nil
expect(merge_request.assignee).to be_nil
expect(merge_request.assignee_id).to be_nil
end
end
end
end

View File

@ -3,7 +3,7 @@ PATH
specs:
omniauth-gitlab (4.0.0)
omniauth (~> 2.0)
omniauth-oauth2 (~> 1.7.1)
omniauth-oauth2 (~> 1.8)
GEM
remote: https://rubygems.org/
@ -28,9 +28,9 @@ GEM
hashie (>= 3.4.6)
rack (>= 2.2.3)
rack-protection
omniauth-oauth2 (1.7.3)
omniauth-oauth2 (1.8.0)
oauth2 (>= 1.4, < 3)
omniauth (>= 1.9, < 3)
omniauth (~> 2.0)
rack (2.2.4)
rack-protection (2.2.2)
rack

View File

@ -17,7 +17,7 @@ Gem::Specification.new do |gem|
gem.require_paths = ['lib']
gem.add_dependency 'omniauth', '~> 2.0'
gem.add_dependency 'omniauth-oauth2', '~> 1.7.1'
gem.add_dependency 'omniauth-oauth2', '~> 1.8'
gem.add_development_dependency 'rspec', '~> 3.1'
gem.add_development_dependency 'rspec-its', '~> 1.0'
gem.add_development_dependency 'simplecov'

View File

@ -1,28 +0,0 @@
workflow:
rules:
- if: $CI_MERGE_REQUEST_ID
.rspec:
cache:
key: omniauth-google-oauth2
paths:
- vendor/gems/omniauth-google-oauth2/vendor/ruby
before_script:
- cd vendor/gems/omniauth-google-oauth2
- ruby -v # Print out ruby version for debugging
- gem install bundler --no-document # Bundler is not installed with the image
- bundle config set --local path 'vendor' # Install dependencies into ./vendor/ruby
- bundle config set with 'development'
- bundle config set --local frozen 'true' # Disallow Gemfile.lock changes on CI
- bundle config # Show bundler configuration
- bundle install -j $(nproc)
script:
- bundle exec rspec
rspec-2.7:
image: "ruby:2.7"
extends: .rspec
rspec-3.0:
image: "ruby:3.0"
extends: .rspec

View File

@ -1,354 +0,0 @@
# Changelog
All notable changes to this project will be documented in this file.
## 1.0.1 - 2022-03-10
### Added
- Output granted scopes in credentials block of the auth hash.
- Migrated to GitHub actions.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- Overriding the `redirect_uri` via params or JSON request body.
## 1.0.0 - 2021-03-14
### Added
- Support for Omniauth 2.x!
### Deprecated
- Nothing.
### Removed
- Support for Omniauth 1.x.
### Fixed
- Nothing.
## 0.8.2 - 2021-03-14
### Added
- Constrains the version to Omniauth 1.x.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- Nothing.
## 0.8.1 - 2020-12-12
### Added
- Support reading the access token from a json request body.
### Deprecated
- Nothing.
### Removed
- No longer verify the iat claim for JWT.
### Fixed
- A few minor issues with .rubocop.yml.
- Issues with image resizing code when the image came with size information from Google.
## 0.8.0 - 2019-08-21
### Added
- Updated omniauth-oauth2 to v1.6.0 for security fixes.
### Deprecated
- Nothing.
### Removed
- Ruby 2.1 support.
### Fixed
- Nothing.
## 0.7.0 - 2019-06-03
### Added
- Ensure `info[:email]` is always verified, and include `unverified_email`
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- Nothing.
## 0.6.1 - 2019-03-07
### Added
- Return `email` and `email_verified` keys in response.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- Nothing.
## 0.6.0 - 2018-12-28
### Added
- Support for JWT 2.x.
### Deprecated
- Nothing.
### Removed
- Support for JWT 1.x.
- Support for `raw_friend_info` and `raw_image_info`.
- Stop using Google+ API endpoints.
### Fixed
- Nothing.
## 0.5.4 - 2018-12-07
### Added
- New recommended endpoints for Google OAuth.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- Nothing.
## 0.5.3 - 2018-01-25
### Added
- Added support for the JWT 2.x gem.
- Now fully qualifies the `JWT` class to prevent conflicts with the `Omniauth::JWT` strategy.
### Deprecated
- Nothing.
### Removed
- Removed the `multijson` dependency.
- Support for versions of `omniauth-oauth2` < 1.5.
### Fixed
- Nothing.
## 0.5.2 - 2017-07-30
### Added
- Nothing.
### Deprecated
- Nothing.
### Removed
- New `authorize_url` and `token_url` endpoints are reverted until JWT 2.0 ships.
### Fixed
- Nothing.
## 0.5.1 - 2017-07-19
### Added
- *Breaking* JWT iss verification can be enabled/disabled with the `verify_iss` flag - see the README for more details.
- Authorize options now includes `device_id` and `device_name` for private ip ranges.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- Updated `authorize_url` and `token_url` to new endpoints.
## 0.5.0 - 2017-05-29
### Added
- Rubocop checks to specs.
- Defaulted dev environment to ruby 2.3.4.
### Deprecated
- Nothing.
### Removed
- Testing support for older versions of ruby not supported by OmniAuth 1.5.
- Key `[:urls]['Google']` no longer exists, it has been renamed to `[:urls][:google]`.
### Fixed
- Updated all code to rubocop conventions. This includes the Ruby 1.9 hash syntax when appropriate.
- Example javascript flow now picks up ENV vars for google key and secret.
## 0.4.1 - 2016-03-14
### Added
- Nothing.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- Fixed JWT iat leeway by requiring ruby-jwt 1.5.2
## 0.4.0 - 2016-03-11
### Added
- Addedd ability to specify multiple hosted domains.
- Added a default leeway of 1 minute to JWT token validation.
- Now requires ruby-jwt 1.5.x.
### Deprecated
- Nothing.
### Removed
- Removed support for ruby 1.9.3 as ruby-jwt 1.5.x does not support it.
### Fixed
- Nothing.
## 0.3.1 - 2016-01-28
### Added
- Verify Hosted Domain if hd is set in options.
### Deprecated
- Nothing.
### Removed
- Dependency on addressable.
### Fixed
- Nothing.
## 0.3.0 - 2016-01-09
### Added
- Updated verify_token to use the v3 tokeninfo endpoint.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- Compatibility with omniauth-oauth2 1.4.0
## 0.2.10 - 2015-11-05
### Added
- Nothing.
### Deprecated
- Nothing.
### Removed
- Removed some checks on the id_token. Now only parses the id_token in the JWT processing.
### Fixed
- Nothing.
## 0.2.9 - 2015-10-29
### Added
- Nothing.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- Issue with omniauth-oauth2 where redirect_uri was handled improperly. We now lock the dependency to ~> 1.3.1
## 0.2.8 - 2015-10-01
### Added
- Added skip_jwt option to bypass JWT decoding in case you get decoding errors.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- Resolved JWT::InvalidIatError. https://github.com/zquestz/omniauth-google-oauth2/issues/195
## 0.2.7 - 2015-09-25
### Added
- Now strips out the 'sz' parameter from profile image urls.
- Now uses 'addressable' gem for URI actions.
- Added image data to extras hash.
- Override validation on JWT token for open_id token.
- Handle authorization codes coming from an installed applications.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- Fixes double slashes in google image urls.
## 0.2.6 - 2014-10-26
### Added
- Nothing.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- Hybrid authorization issues due to bad method alias.
## 0.2.5 - 2014-07-09
### Added
- Support for versions of omniauth past 1.0.x.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- Nothing.
## 0.2.4 - 2014-04-25
### Added
- Now requiring the "Contacts API" and "Google+ API" to be enabled in your Google API console.
### Deprecated
- The old Google OAuth API support was removed without deprecation.
### Removed
- Support for the old Google OAuth API. `OAuth2::Error` will be thrown and state that access is not configured when you attempt to authenticate using the old API. See Added section for this release.
### Fixed
- Nothing.

View File

@ -1,5 +0,0 @@
# frozen_string_literal: true
source 'https://rubygems.org'
gemspec

View File

@ -1,87 +0,0 @@
PATH
remote: .
specs:
omniauth-google-oauth2 (1.0.1)
jwt (>= 2.0)
oauth2 (~> 2.0)
omniauth (~> 2.0)
omniauth-oauth2 (~> 1.7.1)
GEM
remote: https://rubygems.org/
specs:
ast (2.4.2)
diff-lcs (1.5.0)
faraday (2.5.2)
faraday-net_http (>= 2.0, < 3.1)
ruby2_keywords (>= 0.0.4)
faraday-net_http (3.0.0)
hashie (5.0.0)
jwt (2.4.1)
multi_xml (0.6.0)
oauth2 (2.0.3)
faraday (>= 0.17.3, < 3.0)
jwt (>= 1.0, < 3.0)
multi_xml (~> 0.5)
rack (>= 1.2, < 3)
rash_alt (>= 0.4, < 1)
version_gem (~> 1.0)
omniauth (2.1.0)
hashie (>= 3.4.6)
rack (>= 2.2.3)
rack-protection
omniauth-oauth2 (1.7.3)
oauth2 (>= 1.4, < 3)
omniauth (>= 1.9, < 3)
parallel (1.22.1)
parser (3.1.2.0)
ast (~> 2.4.1)
rack (2.2.4)
rack-protection (2.2.2)
rack
rainbow (3.1.1)
rake (12.3.3)
rash_alt (0.4.12)
hashie (>= 3.4)
regexp_parser (2.5.0)
rexml (3.2.5)
rspec (3.11.0)
rspec-core (~> 3.11.0)
rspec-expectations (~> 3.11.0)
rspec-mocks (~> 3.11.0)
rspec-core (3.11.0)
rspec-support (~> 3.11.0)
rspec-expectations (3.11.0)
diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.11.0)
rspec-mocks (3.11.1)
diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.11.0)
rspec-support (3.11.0)
rubocop (0.93.1)
parallel (~> 1.10)
parser (>= 2.7.1.5)
rainbow (>= 2.2.2, < 4.0)
regexp_parser (>= 1.8)
rexml
rubocop-ast (>= 0.6.0)
ruby-progressbar (~> 1.7)
unicode-display_width (>= 1.4.0, < 2.0)
rubocop-ast (1.19.1)
parser (>= 3.1.1.0)
ruby-progressbar (1.11.0)
ruby2_keywords (0.0.5)
unicode-display_width (1.8.0)
version_gem (1.1.0)
PLATFORMS
ruby
DEPENDENCIES
omniauth-google-oauth2!
rake (~> 12.0)
rspec (~> 3.6)
rubocop (~> 0.49)
BUNDLED WITH
2.3.21

View File

@ -1,368 +0,0 @@
[![Gem Version](https://badge.fury.io/rb/omniauth-google-oauth2.svg)](https://badge.fury.io/rb/omniauth-google-oauth2)
# OmniAuth Google OAuth2 Strategy
Strategy to authenticate with Google via OAuth2 in OmniAuth.
Get your API key at: https://code.google.com/apis/console/ Note the Client ID and the Client Secret.
For more details, read the Google docs: https://developers.google.com/accounts/docs/OAuth2
## Installation
Add to your `Gemfile`:
```ruby
gem 'omniauth-google-oauth2'
```
Then `bundle install`.
## Google API Setup
* Go to 'https://console.developers.google.com'
* Select your project.
* Go to Credentials, then select the "OAuth consent screen" tab on top, and provide an 'EMAIL ADDRESS' and a 'PRODUCT NAME'
* Wait 10 minutes for changes to take effect.
## Usage
Here's an example for adding the middleware to a Rails app in `config/initializers/omniauth.rb`:
```ruby
Rails.application.config.middleware.use OmniAuth::Builder do
provider :google_oauth2, ENV['GOOGLE_CLIENT_ID'], ENV['GOOGLE_CLIENT_SECRET']
end
OmniAuth.config.allowed_request_methods = %i[get]
```
You can now access the OmniAuth Google OAuth2 URL: `/auth/google_oauth2`
For more examples please check out `examples/omni_auth.rb`
NOTE: While developing your application, if you change the scope in the initializer you will need to restart your app server. Remember that either the 'email' or 'profile' scope is required!
## Configuration
You can configure several options, which you pass in to the `provider` method via a hash:
* `scope`: A comma-separated list of permissions you want to request from the user. See the [Google OAuth 2.0 Playground](https://developers.google.com/oauthplayground/) for a full list of available permissions. Caveats:
* The `email` and `profile` scopes are used by default. By defining your own `scope`, you override these defaults, but Google requires at least one of `email` or `profile`, so make sure to add at least one of them to your scope!
* Scopes starting with `https://www.googleapis.com/auth/` do not need that prefix specified. So while you can use the smaller scope `books` since that permission starts with the mentioned prefix, you should use the full scope URL `https://docs.google.com/feeds/` to access a user's docs, for example.
* `redirect_uri`: Override the redirect_uri used by the gem.
* `prompt`: A space-delimited list of string values that determines whether the user is re-prompted for authentication and/or consent. Possible values are:
* `none`: No authentication or consent pages will be displayed; it will return an error if the user is not already authenticated and has not pre-configured consent for the requested scopes. This can be used as a method to check for existing authentication and/or consent.
* `consent`: The user will always be prompted for consent, even if they have previously allowed access a given set of scopes.
* `select_account`: The user will always be prompted to select a user account. This allows a user who has multiple current account sessions to select one amongst them.
If no value is specified, the user only sees the authentication page if they are not logged in and only sees the consent page the first time they authorize a given set of scopes.
* `image_aspect_ratio`: The shape of the user's profile picture. Possible values are:
* `original`: Picture maintains its original aspect ratio.
* `square`: Picture presents equal width and height.
Defaults to `original`.
* `image_size`: The size of the user's profile picture. The image returned will have width equal to the given value and variable height, according to the `image_aspect_ratio` chosen. Additionally, a picture with specific width and height can be requested by setting this option to a hash with `width` and `height` as keys. If only `width` or `height` is specified, a picture whose width or height is closest to the requested size and requested aspect ratio will be returned. Defaults to the original width and height of the picture.
* `name`: The name of the strategy. The default name is `google_oauth2` but it can be changed to any value, for example `google`. The OmniAuth URL will thus change to `/auth/google` and the `provider` key in the auth hash will then return `google`.
* `access_type`: Defaults to `offline`, so a refresh token is sent to be used when the user is not present at the browser. Can be set to `online`. More about [offline access](https://developers.google.com/identity/protocols/OAuth2WebServer#offline)
* `hd`: (Optional) Limit sign-in to a particular Google Apps hosted domain. This can be simply string `'domain.com'` or an array `%w(domain.com domain.co)`. More information at: https://developers.google.com/accounts/docs/OpenIDConnect#hd-param
* `jwt_leeway`: Number of seconds passed to the JWT library as leeway. Defaults to 60 seconds. Note this only works if you use jwt 2.1, as the leeway option was removed in later versions.
* `skip_jwt`: Skip JWT processing. This is for users who are seeing JWT decoding errors with the `iat` field. Always try adjusting the leeway before disabling JWT processing.
* `login_hint`: When your app knows which user it is trying to authenticate, it can provide this parameter as a hint to the authentication server. Passing this hint suppresses the account chooser and either pre-fill the email box on the sign-in form, or select the proper session (if the user is using multiple sign-in), which can help you avoid problems that occur if your app logs in the wrong user account. The value can be either an email address or the sub string, which is equivalent to the user's Google+ ID.
* `include_granted_scopes`: If this is provided with the value true, and the authorization request is granted, the authorization will include any previous authorizations granted to this user/application combination for other scopes. See Google's [Incremental Authorization](https://developers.google.com/accounts/docs/OAuth2WebServer#incrementalAuth) for additional details.
* `openid_realm`: Set the OpenID realm value, to allow upgrading from OpenID based authentication to OAuth 2 based authentication. When this is set correctly an `openid_id` value will be set in `['extra']['id_info']` in the authentication hash with the value of the user's OpenID ID URL.
* `provider_ignores_state`: You will need to set this to `true` when using the `One-time Code Flow` below. In this flow there is no server side redirect that would set the state.
Here's an example of a possible configuration where the strategy name is changed, the user is asked for extra permissions, the user is always prompted to select their account when logging in and the user's profile picture is returned as a thumbnail:
```ruby
Rails.application.config.middleware.use OmniAuth::Builder do
provider :google_oauth2, ENV['GOOGLE_CLIENT_ID'], ENV['GOOGLE_CLIENT_SECRET'],
{
scope: 'userinfo.email, userinfo.profile, http://gdata.youtube.com',
prompt: 'select_account',
image_aspect_ratio: 'square',
image_size: 50
}
end
```
## Auth Hash
Here's an example of an authentication hash available in the callback by accessing `request.env['omniauth.auth']`:
```ruby
{
"provider" => "google_oauth2",
"uid" => "100000000000000000000",
"info" => {
"name" => "John Smith",
"email" => "john@example.com",
"first_name" => "John",
"last_name" => "Smith",
"image" => "https://lh4.googleusercontent.com/photo.jpg",
"urls" => {
"google" => "https://plus.google.com/+JohnSmith"
}
},
"credentials" => {
"token" => "TOKEN",
"refresh_token" => "REFRESH_TOKEN",
"expires_at" => 1496120719,
"expires" => true
},
"extra" => {
"id_token" => "ID_TOKEN",
"id_info" => {
"azp" => "APP_ID",
"aud" => "APP_ID",
"sub" => "100000000000000000000",
"email" => "john@example.com",
"email_verified" => true,
"at_hash" => "HK6E_P6Dh8Y93mRNtsDB1Q",
"iss" => "accounts.google.com",
"iat" => 1496117119,
"exp" => 1496120719
},
"raw_info" => {
"sub" => "100000000000000000000",
"name" => "John Smith",
"given_name" => "John",
"family_name" => "Smith",
"profile" => "https://plus.google.com/+JohnSmith",
"picture" => "https://lh4.googleusercontent.com/photo.jpg?sz=50",
"email" => "john@example.com",
"email_verified" => "true",
"locale" => "en",
"hd" => "company.com"
}
}
}
```
### Devise
First define your application id and secret in `config/initializers/devise.rb`. Do not use the snippet mentioned in the [Usage](https://github.com/zquestz/omniauth-google-oauth2#usage) section.
Configuration options can be passed as the last parameter here as key/value pairs.
```ruby
config.omniauth :google_oauth2, 'GOOGLE_CLIENT_ID', 'GOOGLE_CLIENT_SECRET', {}
```
NOTE: If you are using this gem with devise with above snippet in `config/initializers/devise.rb` then do not create `config/initializers/omniauth.rb` which will conflict with devise configurations.
Then add the following to 'config/routes.rb' so the callback routes are defined.
```ruby
devise_for :users, controllers: { omniauth_callbacks: 'users/omniauth_callbacks' }
```
Make sure your model is omniauthable. Generally this is "/app/models/user.rb"
```ruby
devise :omniauthable, omniauth_providers: [:google_oauth2]
```
Then make sure your callbacks controller is setup.
```ruby
# app/controllers/users/omniauth_callbacks_controller.rb:
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def google_oauth2
# You need to implement the method below in your model (e.g. app/models/user.rb)
@user = User.from_omniauth(request.env['omniauth.auth'])
if @user.persisted?
flash[:notice] = I18n.t 'devise.omniauth_callbacks.success', kind: 'Google'
sign_in_and_redirect @user, event: :authentication
else
session['devise.google_data'] = request.env['omniauth.auth'].except('extra') # Removing extra as it can overflow some session stores
redirect_to new_user_registration_url, alert: @user.errors.full_messages.join("\n")
end
end
end
```
and bind to or create the user
```ruby
def self.from_omniauth(access_token)
data = access_token.info
user = User.where(email: data['email']).first
# Uncomment the section below if you want users to be created if they don't exist
# unless user
# user = User.create(name: data['name'],
# email: data['email'],
# password: Devise.friendly_token[0,20]
# )
# end
user
end
```
For your views you can login using:
```erb
<%# omniauth-google-oauth2 1.0.x uses OmniAuth 2 and requires using HTTP Post to initiate authentication: %>
<%= link_to "Sign in with Google", user_google_oauth2_omniauth_authorize_path, method: :post %>
<%# omniauth-google-oauth2 prior 1.0.0: %>
<%= link_to "Sign in with Google", user_google_oauth2_omniauth_authorize_path %>
<%# Devise prior 4.1.0: %>
<%= link_to "Sign in with Google", user_omniauth_authorize_path(:google_oauth2) %>
```
An overview is available at https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview
### One-time Code Flow (Hybrid Authentication)
Google describes the One-time Code Flow [here](https://developers.google.com/identity/sign-in/web/server-side-flow). This hybrid authentication flow has significant functional and security advantages over a pure server-side or pure client-side flow. The following steps occur in this flow:
1. The client (web browser) authenticates the user directly via Google's JS API. During this process assorted modals may be rendered by Google.
2. On successful authentication, Google returns a one-time use code, which requires the Google client secret (which is only available server-side).
3. Using a AJAX request, the code is POSTed to the Omniauth Google OAuth2 callback.
4. The Omniauth Google OAuth2 gem will validate the code via a server-side request to Google. If the code is valid, then Google will return an access token and, if this is the first time this user is authenticating against this application, a refresh token. Both of these should be stored on the server. The response to the AJAX request indicates the success or failure of this process.
This flow is immune to replay attacks, and conveys no useful information to a man in the middle.
The omniauth-google-oauth2 gem supports this mode of operation when `provider_ignores_state` is set to `true`. Implementors simply need to add the appropriate JavaScript to their web page, and they can take advantage of this flow. An example JavaScript snippet follows.
```javascript
// Basic hybrid auth example following the pattern at:
// https://developers.google.com/identity/sign-in/web/reference
<script src="https://apis.google.com/js/platform.js?onload=init" async defer></script>
...
function init() {
gapi.load('auth2', function() {
// Ready.
$('.google-login-button').click(function(e) {
e.preventDefault();
gapi.auth2.authorize({
client_id: 'YOUR_CLIENT_ID',
cookie_policy: 'single_host_origin',
scope: 'email profile',
response_type: 'code'
}, function(response) {
if (response && !response.error) {
// google authentication succeed, now post data to server.
jQuery.ajax({type: 'POST', url: '/auth/google_oauth2/callback', data: response,
success: function(data) {
// response from server
}
});
} else {
// google authentication failed
}
});
});
});
};
```
#### Note about mobile clients (iOS, Android)
The documentation at https://developers.google.com/identity/sign-in/ios/offline-access specifies the _REDIRECT_URI_ to be either a set value or an EMPTY string for mobile logins to work. Else, you will run into _redirect_uri_mismatch_ errors.
In that case, ensure to send an additional parameter `redirect_uri=` (empty string) to the `/auth/google_oauth2/callback` URL from your mobile device.
#### Note about CORS
If you're making POST requests to `/auth/google_oauth2/callback` from another domain, then you need to make sure `'X-Requested-With': 'XMLHttpRequest'` header is included with your request, otherwise your server might respond with `OAuth2::Error, : Invalid Value` error.
#### Getting around the `redirect_uri_mismatch` error (See [Issue #365](https://github.com/zquestz/omniauth-google-oauth2/issues/365))
If you are struggling with a persistent `redirect_uri_mismatch`, you can instead pass the `access_token` from [`getAuthResponse`](https://developers.google.com/identity/sign-in/web/reference#googleusergetauthresponseincludeauthorizationdata) directly to the `auth/google_oauth2/callback` endpoint, like so:
```javascript
// Initialize the GoogleAuth object
let googleAuth;
gapi.load('client:auth2', async () => {
await gapi.client.init({ scope: '...', client_id: '...' });
googleAuth = gapi.auth2.getAuthInstance();
});
// Call this when the Google Sign In button is clicked
async function signInGoogle() {
const googleUser = await googleAuth.signIn(); // wait for the user to authorize through the modal
const { access_token } = googleUser.getAuthResponse();
const data = new FormData();
data.append('access_token', access_token);
const response = await api.post('/auth/google_oauth2/callback', data)
console.log(response);
}
```
#### Using Axios
If you're making a GET resquests from another domain using `access_token`.
```
axios
.get(
'url(path to your callback}',
{ params: { access_token: 'token' } },
headers....
)
```
If you're making a POST resquests from another domain using `access_token`.
```
axios
.post(
'url(path to your callback}',
{ access_token: 'token' },
headers....
)
--OR--
axios
.post(
'url(path to your callback}',
null,
{
params: {
access_token: 'token'
},
headers....
}
)
```
## Fixing Protocol Mismatch for `redirect_uri` in Rails
Just set the `full_host` in OmniAuth based on the Rails.env.
```
# config/initializers/omniauth.rb
OmniAuth.config.full_host = Rails.env.production? ? 'https://domain.com' : 'http://localhost:3000'
```
## License
Copyright (c) 2018 by Josh Ellithorpe
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -1,8 +0,0 @@
# frozen_string_literal: true
require File.join('bundler', 'gem_tasks')
require File.join('rspec', 'core', 'rake_task')
RSpec::Core::RakeTask.new(:spec)
task default: :spec

View File

@ -1,8 +0,0 @@
# frozen_string_literal: true
source 'https://rubygems.org'
gem 'omniauth-google-oauth2', '~> 0.8.1'
gem 'rubocop'
gem 'sinatra', '~> 1.4'
gem 'webrick'

View File

@ -1,120 +0,0 @@
# frozen_string_literal: true
# Sample app for Google OAuth2 Strategy
# Make sure to setup the ENV variables GOOGLE_KEY and GOOGLE_SECRET
# Run with "bundle exec rackup"
require 'rubygems'
require 'bundler'
require 'sinatra'
require 'omniauth'
require 'omniauth-google-oauth2'
# Do not use for production code.
# This is only to make setup easier when running through the sample.
#
# If you do have issues with certs in production code, this could help:
# http://railsapps.github.io/openssl-certificate-verify-failed.html
OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE
# Main example app for omniauth-google-oauth2
class App < Sinatra::Base
get '/' do
<<-HTML
<!DOCTYPE html>
<html>
<head>
<title>Google OAuth2 Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
jQuery(function() {
return $.ajax({
url: 'https://apis.google.com/js/client:plus.js?onload=gpAsyncInit',
dataType: 'script',
cache: true
});
});
window.gpAsyncInit = function() {
gapi.auth.authorize({
immediate: true,
response_type: 'code',
cookie_policy: 'single_host_origin',
client_id: '#{ENV['GOOGLE_KEY']}',
scope: 'email profile'
}, function(response) {
return;
});
$('.googleplus-login').click(function(e) {
e.preventDefault();
gapi.auth.authorize({
immediate: false,
response_type: 'code',
cookie_policy: 'single_host_origin',
client_id: '#{ENV['GOOGLE_KEY']}',
scope: 'email profile'
}, function(response) {
if (response && !response.error) {
// google authentication succeed, now post data to server.
jQuery.ajax({type: 'POST', url: "/auth/google_oauth2/callback", data: response,
success: function(data) {
// Log the data returning from google.
console.log(data)
}
});
} else {
// google authentication failed.
console.log("FAILED")
}
});
});
};
</script>
</head>
<body>
<ul>
<li><a href='/auth/google_oauth2'>Sign in with Google</a></li>
<li><a href='#' class="googleplus-login">Sign in with Google via AJAX</a></li>
</ul>
</body>
</html>
HTML
end
post '/auth/:provider/callback' do
content_type 'text/plain'
begin
request.env['omniauth.auth'].to_hash.inspect
rescue StandardError
'No Data'
end
end
get '/auth/:provider/callback' do
content_type 'text/plain'
begin
request.env['omniauth.auth'].to_hash.inspect
rescue StandardError
'No Data'
end
end
get '/auth/failure' do
content_type 'text/plain'
begin
request.env['omniauth.auth'].to_hash.inspect
rescue StandardError
'No Data'
end
end
end
use Rack::Session::Cookie, secret: ENV['RACK_COOKIE_SECRET']
use OmniAuth::Builder do
# For additional provider examples please look at 'omni_auth.rb'
# The key provider_ignores_state is only for AJAX flows. It is not recommended for normal logins.
provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'], access_type: 'offline', prompt: 'consent', provider_ignores_state: true, scope: 'email,profile,calendar'
end
run App.new

View File

@ -1,37 +0,0 @@
# frozen_string_literal: true
# Google's OAuth2 docs. Make sure you are familiar with all the options
# before attempting to configure this gem.
# https://developers.google.com/accounts/docs/OAuth2Login
Rails.application.config.middleware.use OmniAuth::Builder do
# Default usage, this will give you offline access and a refresh token
# using default scopes 'email' and 'profile'
#
provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'], scope: 'email,profile'
# Custom redirect_uri
#
# provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'], scope: 'email,profile', redirect_uri: 'https://localhost:3000/redirect'
# Manual setup for offline access with a refresh token.
#
# provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'], access_type: 'offline'
# Custom scope supporting youtube. If you are customizing scopes, remember
# to include the default scopes 'email' and 'profile'
#
# provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'], scope: 'http://gdata.youtube.com,email,profile,plus.me'
# Custom scope for users only using Google for account creation/auth and do not require a refresh token.
#
# provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'], access_type: 'online', prompt: ''
# To include information about people in your circles you must include the 'plus.login' scope.
#
# provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'], skip_friends: false, scope: 'email,profile,plus.login'
# If you need to acquire whether user picture is a default one or uploaded by user.
#
# provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'], skip_image_info: false
end

View File

@ -1,3 +0,0 @@
# frozen_string_literal: true
require 'omniauth/google_oauth2'

View File

@ -1,3 +0,0 @@
# frozen_string_literal: true
require 'omniauth/strategies/google_oauth2'

View File

@ -1,7 +0,0 @@
# frozen_string_literal: true
module OmniAuth
module GoogleOauth2
VERSION = '1.0.1'
end
end

View File

@ -1,254 +0,0 @@
# frozen_string_literal: true
require 'jwt'
require 'oauth2'
require 'omniauth/strategies/oauth2'
require 'uri'
module OmniAuth
module Strategies
# Main class for Google OAuth2 strategy.
class GoogleOauth2 < OmniAuth::Strategies::OAuth2
ALLOWED_ISSUERS = ['accounts.google.com', 'https://accounts.google.com'].freeze
BASE_SCOPE_URL = 'https://www.googleapis.com/auth/'
BASE_SCOPES = %w[profile email openid].freeze
DEFAULT_SCOPE = 'email,profile'
USER_INFO_URL = 'https://www.googleapis.com/oauth2/v3/userinfo'
IMAGE_SIZE_REGEXP = /(s\d+(-c)?)|(w\d+-h\d+(-c)?)|(w\d+(-c)?)|(h\d+(-c)?)|c/
option :name, 'google_oauth2'
option :skip_friends, true
option :skip_image_info, true
option :skip_jwt, false
option :jwt_leeway, 60
option :authorize_options, %i[access_type hd login_hint prompt request_visible_actions scope state redirect_uri include_granted_scopes openid_realm device_id device_name]
option :authorized_client_ids, []
option :client_options,
site: 'https://oauth2.googleapis.com',
authorize_url: 'https://accounts.google.com/o/oauth2/auth',
token_url: '/token'
def authorize_params
super.tap do |params|
options[:authorize_options].each do |k|
params[k] = request.params[k.to_s] unless [nil, ''].include?(request.params[k.to_s])
end
params[:scope] = get_scope(params)
params[:access_type] = 'offline' if params[:access_type].nil?
params['openid.realm'] = params.delete(:openid_realm) unless params[:openid_realm].nil?
session['omniauth.state'] = params[:state] if params[:state]
end
end
uid { raw_info['sub'] }
info do
prune!(
name: raw_info['name'],
email: verified_email,
unverified_email: raw_info['email'],
email_verified: raw_info['email_verified'],
first_name: raw_info['given_name'],
last_name: raw_info['family_name'],
image: image_url,
urls: {
google: raw_info['profile']
}
)
end
credentials do
# Tokens and expiration will be used from OAuth2 strategy credentials block
prune!({ 'scope' => token_info(access_token.token)['scope'] })
end
extra do
hash = {}
hash[:id_token] = access_token['id_token']
if !options[:skip_jwt] && !access_token['id_token'].nil?
decoded = ::JWT.decode(access_token['id_token'], nil, false).first
# We have to manually verify the claims because the third parameter to
# JWT.decode is false since no verification key is provided.
::JWT::Verify.verify_claims(decoded,
verify_iss: true,
iss: ALLOWED_ISSUERS,
verify_aud: true,
aud: options.client_id,
verify_sub: false,
verify_expiration: true,
verify_not_before: true,
verify_iat: false,
verify_jti: false,
leeway: options[:jwt_leeway])
hash[:id_info] = decoded
end
hash[:raw_info] = raw_info unless skip_info?
prune! hash
end
def raw_info
@raw_info ||= access_token.get(USER_INFO_URL).parsed
end
def custom_build_access_token
access_token = get_access_token(request)
verify_hd(access_token)
access_token
end
alias build_access_token custom_build_access_token
private
def callback_url
options[:redirect_uri] || (full_host + callback_path)
end
def get_access_token(request)
verifier = request.params['code']
redirect_uri = request.params['redirect_uri']
access_token = request.params['access_token']
if verifier && request.xhr?
client_get_token(verifier, redirect_uri || 'postmessage')
elsif verifier
client_get_token(verifier, redirect_uri || callback_url)
elsif access_token && verify_token(access_token)
::OAuth2::AccessToken.from_hash(client, request.params.dup)
elsif request.content_type =~ /json/i
begin
body = JSON.parse(request.body.read)
request.body.rewind # rewind request body for downstream middlewares
verifier = body && body['code']
access_token = body && body['access_token']
redirect_uri ||= body && body['redirect_uri']
if verifier
client_get_token(verifier, redirect_uri || 'postmessage')
elsif verify_token(access_token)
::OAuth2::AccessToken.from_hash(client, body.dup)
end
rescue JSON::ParserError => e
warn "[omniauth google-oauth2] JSON parse error=#{e}"
end
end
end
def client_get_token(verifier, redirect_uri)
client.auth_code.get_token(verifier, get_token_options(redirect_uri), get_token_params)
end
def get_token_params
deep_symbolize(options.auth_token_params || {})
end
def get_scope(params)
raw_scope = params[:scope] || DEFAULT_SCOPE
scope_list = raw_scope.split(' ').map { |item| item.split(',') }.flatten
scope_list.map! { |s| s =~ %r{^https?://} || BASE_SCOPES.include?(s) ? s : "#{BASE_SCOPE_URL}#{s}" }
scope_list.join(' ')
end
def verified_email
raw_info['email_verified'] ? raw_info['email'] : nil
end
def get_token_options(redirect_uri = '')
{ redirect_uri: redirect_uri }.merge(token_params.to_hash(symbolize_keys: true))
end
def prune!(hash)
hash.delete_if do |_, v|
prune!(v) if v.is_a?(Hash)
v.nil? || (v.respond_to?(:empty?) && v.empty?)
end
end
def image_url
return nil unless raw_info['picture']
u = URI.parse(raw_info['picture'].gsub('https:https', 'https'))
path_index = u.path.to_s.index('/photo.jpg')
if path_index && image_size_opts_passed?
u.path.insert(path_index, image_params)
u.path = u.path.gsub('//', '/')
# Check if the image is already sized!
split_path = u.path.split('/')
u.path = u.path.sub("/#{split_path[-3]}", '') if split_path[-3] =~ IMAGE_SIZE_REGEXP
end
u.query = strip_unnecessary_query_parameters(u.query)
u.to_s
end
def image_size_opts_passed?
options[:image_size] || options[:image_aspect_ratio]
end
def image_params
image_params = []
if options[:image_size].is_a?(Integer)
image_params << "s#{options[:image_size]}"
elsif options[:image_size].is_a?(Hash)
image_params << "w#{options[:image_size][:width]}" if options[:image_size][:width]
image_params << "h#{options[:image_size][:height]}" if options[:image_size][:height]
end
image_params << 'c' if options[:image_aspect_ratio] == 'square'
'/' + image_params.join('-')
end
def strip_unnecessary_query_parameters(query_parameters)
# strip `sz` parameter (defaults to sz=50) which overrides `image_size` options
return nil if query_parameters.nil?
params = CGI.parse(query_parameters)
stripped_params = params.delete_if { |key| key == 'sz' }
# don't return an empty Hash since that would result
# in URLs with a trailing ? character: http://image.url?
return nil if stripped_params.empty?
URI.encode_www_form(stripped_params)
end
def token_info(access_token)
return nil unless access_token
@token_info ||= Hash.new do |h, k|
h[k] = client.request(:get, 'https://www.googleapis.com/oauth2/v3/tokeninfo', params: { access_token: access_token }).parsed
end
@token_info[access_token]
end
def verify_token(access_token)
return false unless access_token
token_info = token_info(access_token)
token_info['aud'] == options.client_id || options.authorized_client_ids.include?(token_info['aud'])
end
def verify_hd(access_token)
return true unless options.hd
@raw_info ||= access_token.get(USER_INFO_URL).parsed
options.hd = options.hd.call if options.hd.is_a? Proc
allowed_hosted_domains = Array(options.hd)
raise CallbackError.new(:invalid_hd, 'Invalid Hosted Domain') unless allowed_hosted_domains.include?(@raw_info['hd']) || options.hd == '*'
true
end
end
end
end

View File

@ -1,31 +0,0 @@
# frozen_string_literal: true
require File.expand_path(
File.join('..', 'lib', 'omniauth', 'google_oauth2', 'version'),
__FILE__
)
Gem::Specification.new do |gem|
gem.name = 'omniauth-google-oauth2'
gem.version = OmniAuth::GoogleOauth2::VERSION
gem.license = 'MIT'
gem.summary = %(A Google OAuth2 strategy for OmniAuth 1.x)
gem.description = %(A Google OAuth2 strategy for OmniAuth 1.x. This allows you to login to Google with your ruby app.)
gem.authors = ['Josh Ellithorpe', 'Yury Korolev']
gem.email = ['quest@mac.com']
gem.homepage = 'https://github.com/zquestz/omniauth-google-oauth2'
gem.files = Dir.glob("lib/**/*.*")
gem.require_paths = ['lib']
gem.required_ruby_version = '>= 2.2'
gem.add_runtime_dependency 'jwt', '>= 2.0'
gem.add_runtime_dependency 'oauth2', '~> 2.0'
gem.add_runtime_dependency 'omniauth', '~> 2.0'
gem.add_runtime_dependency 'omniauth-oauth2', '~> 1.7.1'
gem.add_development_dependency 'rake', '~> 12.0'
gem.add_development_dependency 'rspec', '~> 3.6'
gem.add_development_dependency 'rubocop', '~> 0.49'
end

View File

@ -1,850 +0,0 @@
# frozen_string_literal: true
require 'spec_helper'
require 'json'
require 'omniauth-google-oauth2'
require 'stringio'
describe OmniAuth::Strategies::GoogleOauth2 do
let(:request) { double('Request', params: {}, cookies: {}, env: {}) }
let(:app) do
lambda do
[200, {}, ['Hello.']]
end
end
subject do
OmniAuth::Strategies::GoogleOauth2.new(app, 'appid', 'secret', @options || {}).tap do |strategy|
allow(strategy).to receive(:request) do
request
end
end
end
before do
OmniAuth.config.test_mode = true
end
after do
OmniAuth.config.test_mode = false
end
describe '#client_options' do
it 'has correct site' do
expect(subject.client.site).to eq('https://oauth2.googleapis.com')
end
it 'has correct authorize_url' do
expect(subject.client.options[:authorize_url]).to eq('https://accounts.google.com/o/oauth2/auth')
end
it 'has correct token_url' do
expect(subject.client.options[:token_url]).to eq('/token')
end
describe 'overrides' do
context 'as strings' do
it 'should allow overriding the site' do
@options = { client_options: { 'site' => 'https://example.com' } }
expect(subject.client.site).to eq('https://example.com')
end
it 'should allow overriding the authorize_url' do
@options = { client_options: { 'authorize_url' => 'https://example.com' } }
expect(subject.client.options[:authorize_url]).to eq('https://example.com')
end
it 'should allow overriding the token_url' do
@options = { client_options: { 'token_url' => 'https://example.com' } }
expect(subject.client.options[:token_url]).to eq('https://example.com')
end
end
context 'as symbols' do
it 'should allow overriding the site' do
@options = { client_options: { site: 'https://example.com' } }
expect(subject.client.site).to eq('https://example.com')
end
it 'should allow overriding the authorize_url' do
@options = { client_options: { authorize_url: 'https://example.com' } }
expect(subject.client.options[:authorize_url]).to eq('https://example.com')
end
it 'should allow overriding the token_url' do
@options = { client_options: { token_url: 'https://example.com' } }
expect(subject.client.options[:token_url]).to eq('https://example.com')
end
end
end
end
describe '#authorize_options' do
%i[access_type hd login_hint prompt scope state device_id device_name].each do |k|
it "should support #{k}" do
@options = { k => 'http://someval' }
expect(subject.authorize_params[k.to_s]).to eq('http://someval')
end
end
describe 'redirect_uri' do
it 'should default to nil' do
@options = {}
expect(subject.authorize_params['redirect_uri']).to eq(nil)
end
it 'should set the redirect_uri parameter if present' do
@options = { redirect_uri: 'https://example.com' }
expect(subject.authorize_params['redirect_uri']).to eq('https://example.com')
end
end
describe 'access_type' do
it 'should default to "offline"' do
@options = {}
expect(subject.authorize_params['access_type']).to eq('offline')
end
it 'should set the access_type parameter if present' do
@options = { access_type: 'online' }
expect(subject.authorize_params['access_type']).to eq('online')
end
end
describe 'hd' do
it 'should default to nil' do
expect(subject.authorize_params['hd']).to eq(nil)
end
it 'should set the hd (hosted domain) parameter if present' do
@options = { hd: 'example.com' }
expect(subject.authorize_params['hd']).to eq('example.com')
end
it 'should set the hd parameter and work with nil hd (gmail)' do
@options = { hd: nil }
expect(subject.authorize_params['hd']).to eq(nil)
end
it 'should set the hd parameter to * if set (only allows G Suite emails)' do
@options = { hd: '*' }
expect(subject.authorize_params['hd']).to eq('*')
end
end
describe 'login_hint' do
it 'should default to nil' do
expect(subject.authorize_params['login_hint']).to eq(nil)
end
it 'should set the login_hint parameter if present' do
@options = { login_hint: 'john@example.com' }
expect(subject.authorize_params['login_hint']).to eq('john@example.com')
end
end
describe 'prompt' do
it 'should default to nil' do
expect(subject.authorize_params['prompt']).to eq(nil)
end
it 'should set the prompt parameter if present' do
@options = { prompt: 'consent select_account' }
expect(subject.authorize_params['prompt']).to eq('consent select_account')
end
end
describe 'request_visible_actions' do
it 'should default to nil' do
expect(subject.authorize_params['request_visible_actions']).to eq(nil)
end
it 'should set the request_visible_actions parameter if present' do
@options = { request_visible_actions: 'something' }
expect(subject.authorize_params['request_visible_actions']).to eq('something')
end
end
describe 'include_granted_scopes' do
it 'should default to nil' do
expect(subject.authorize_params['include_granted_scopes']).to eq(nil)
end
it 'should set the include_granted_scopes parameter if present' do
@options = { include_granted_scopes: 'true' }
expect(subject.authorize_params['include_granted_scopes']).to eq('true')
end
end
describe 'scope' do
it 'should expand scope shortcuts' do
@options = { scope: 'calendar' }
expect(subject.authorize_params['scope']).to eq('https://www.googleapis.com/auth/calendar')
end
it 'should leave base scopes as is' do
@options = { scope: 'profile' }
expect(subject.authorize_params['scope']).to eq('profile')
end
it 'should join scopes' do
@options = { scope: 'profile,email' }
expect(subject.authorize_params['scope']).to eq('profile email')
end
it 'should deal with whitespace when joining scopes' do
@options = { scope: 'profile, email' }
expect(subject.authorize_params['scope']).to eq('profile email')
end
it 'should set default scope to email,profile' do
expect(subject.authorize_params['scope']).to eq('email profile')
end
it 'should support space delimited scopes' do
@options = { scope: 'profile email' }
expect(subject.authorize_params['scope']).to eq('profile email')
end
it 'should support extremely badly formed scopes' do
@options = { scope: 'profile email,foo,steve yeah http://example.com' }
expect(subject.authorize_params['scope']).to eq('profile email https://www.googleapis.com/auth/foo https://www.googleapis.com/auth/steve https://www.googleapis.com/auth/yeah http://example.com')
end
end
describe 'state' do
it 'should set the state parameter' do
@options = { state: 'some_state' }
expect(subject.authorize_params['state']).to eq('some_state')
expect(subject.authorize_params[:state]).to eq('some_state')
expect(subject.session['omniauth.state']).to eq('some_state')
end
it 'should set the omniauth.state dynamically' do
allow(subject).to receive(:request) { double('Request', params: { 'state' => 'some_state' }, env: {}) }
expect(subject.authorize_params['state']).to eq('some_state')
expect(subject.authorize_params[:state]).to eq('some_state')
expect(subject.session['omniauth.state']).to eq('some_state')
end
end
describe 'overrides' do
it 'should include top-level options that are marked as :authorize_options' do
@options = { authorize_options: %i[scope foo request_visible_actions], scope: 'http://bar', foo: 'baz', hd: 'wow', request_visible_actions: 'something' }
expect(subject.authorize_params['scope']).to eq('http://bar')
expect(subject.authorize_params['foo']).to eq('baz')
expect(subject.authorize_params['hd']).to eq(nil)
expect(subject.authorize_params['request_visible_actions']).to eq('something')
end
describe 'request overrides' do
%i[access_type hd login_hint prompt scope state].each do |k|
context "authorize option #{k}" do
let(:request) { double('Request', params: { k.to_s => 'http://example.com' }, cookies: {}, env: {}) }
it "should set the #{k} authorize option dynamically in the request" do
@options = { k: '' }
expect(subject.authorize_params[k.to_s]).to eq('http://example.com')
end
end
end
describe 'custom authorize_options' do
let(:request) { double('Request', params: { 'foo' => 'something' }, cookies: {}, env: {}) }
it 'should support request overrides from custom authorize_options' do
@options = { authorize_options: [:foo], foo: '' }
expect(subject.authorize_params['foo']).to eq('something')
end
end
end
end
end
describe '#authorize_params' do
it 'should include any authorize params passed in the :authorize_params option' do
@options = { authorize_params: { request_visible_actions: 'something', foo: 'bar', baz: 'zip' }, hd: 'wow', bad: 'not_included' }
expect(subject.authorize_params['request_visible_actions']).to eq('something')
expect(subject.authorize_params['foo']).to eq('bar')
expect(subject.authorize_params['baz']).to eq('zip')
expect(subject.authorize_params['hd']).to eq('wow')
expect(subject.authorize_params['bad']).to eq(nil)
end
end
describe '#token_params' do
it 'should include any token params passed in the :token_params option' do
@options = { token_params: { foo: 'bar', baz: 'zip' } }
expect(subject.token_params['foo']).to eq('bar')
expect(subject.token_params['baz']).to eq('zip')
end
end
describe '#token_options' do
it 'should include top-level options that are marked as :token_options' do
@options = { token_options: %i[scope foo], scope: 'bar', foo: 'baz', bad: 'not_included' }
expect(subject.token_params['scope']).to eq('bar')
expect(subject.token_params['foo']).to eq('baz')
expect(subject.token_params['bad']).to eq(nil)
end
end
describe '#callback_url' do
let(:base_url) { 'https://example.com' }
it 'has the correct default callback path' do
allow(subject).to receive(:full_host) { base_url }
allow(subject).to receive(:script_name) { '' }
expect(subject.send(:callback_url)).to eq(base_url + '/auth/google_oauth2/callback')
end
it 'should set the callback path with script_name if present' do
allow(subject).to receive(:full_host) { base_url }
allow(subject).to receive(:script_name) { '/v1' }
expect(subject.send(:callback_url)).to eq(base_url + '/v1/auth/google_oauth2/callback')
end
it 'should set the callback_path parameter if present' do
@options = { callback_path: '/auth/foo/callback' }
allow(subject).to receive(:full_host) { base_url }
allow(subject).to receive(:script_name) { '' }
expect(subject.send(:callback_url)).to eq(base_url + '/auth/foo/callback')
end
end
describe '#info' do
let(:client) do
OAuth2::Client.new('abc', 'def') do |builder|
builder.request :url_encoded
builder.adapter :test do |stub|
stub.get('/oauth2/v3/userinfo') { [200, { 'content-type' => 'application/json' }, response_hash.to_json] }
end
end
end
let(:access_token) { OAuth2::AccessToken.from_hash(client, {}) }
before { allow(subject).to receive(:access_token).and_return(access_token) }
context 'with verified email' do
let(:response_hash) do
{ email: 'something@domain.invalid', email_verified: true }
end
it 'should return equal email and unverified_email' do
expect(subject.info[:email]).to eq('something@domain.invalid')
expect(subject.info[:unverified_email]).to eq('something@domain.invalid')
end
end
context 'with unverified email' do
let(:response_hash) do
{ email: 'something@domain.invalid', email_verified: false }
end
it 'should return nil email, and correct unverified email' do
expect(subject.info[:email]).to eq(nil)
expect(subject.info[:unverified_email]).to eq('something@domain.invalid')
end
end
end
describe '#credentials' do
let(:client) { OAuth2::Client.new('abc', 'def') }
let(:access_token) { OAuth2::AccessToken.from_hash(client, access_token: 'valid_access_token', expires_at: 123_456_789, refresh_token: 'valid_refresh_token') }
before(:each) do
allow(subject).to receive(:access_token).and_return(access_token)
subject.options.client_options[:connection_build] = proc do |builder|
builder.request :url_encoded
builder.adapter :test do |stub|
stub.get('/oauth2/v3/tokeninfo?access_token=valid_access_token') do
[200, { 'Content-Type' => 'application/json; charset=UTF-8' }, JSON.dump(
aud: '000000000000.apps.googleusercontent.com',
sub: '123456789',
scope: 'profile email'
)]
end
end
end
end
it 'should return access token and (optionally) refresh token' do
expect(subject.credentials.to_h).to \
match(hash_including(
'token' => 'valid_access_token',
'refresh_token' => 'valid_refresh_token',
'scope' => 'profile email',
'expires_at' => 123_456_789,
'expires' => true
))
end
end
describe '#extra' do
let(:client) do
OAuth2::Client.new('abc', 'def') do |builder|
builder.request :url_encoded
builder.adapter :test do |stub|
stub.get('/oauth2/v3/userinfo') { [200, { 'content-type' => 'application/json' }, '{"sub": "12345"}'] }
end
end
end
let(:access_token) { OAuth2::AccessToken.from_hash(client, {}) }
before { allow(subject).to receive(:access_token).and_return(access_token) }
describe 'id_token' do
shared_examples 'id_token issued by valid issuer' do |issuer|
context 'when the id_token is passed into the access token' do
let(:token_info) do
{
'abc' => 'xyz',
'exp' => Time.now.to_i + 3600,
'nbf' => Time.now.to_i - 60,
'iat' => Time.now.to_i,
'aud' => 'appid',
'iss' => issuer
}
end
let(:id_token) { JWT.encode(token_info, 'secret') }
let(:access_token) { OAuth2::AccessToken.from_hash(client, 'id_token' => id_token) }
it 'should include id_token when set on the access_token' do
expect(subject.extra).to include(id_token: id_token)
end
it 'should include id_info when id_token is set on the access_token and skip_jwt is false' do
subject.options[:skip_jwt] = false
expect(subject.extra).to include(id_info: token_info)
end
it 'should not include id_info when id_token is set on the access_token and skip_jwt is true' do
subject.options[:skip_jwt] = true
expect(subject.extra).not_to have_key(:id_info)
end
it 'should include id_info when id_token is set on the access_token by default' do
expect(subject.extra).to include(id_info: token_info)
end
end
end
it_behaves_like 'id_token issued by valid issuer', 'accounts.google.com'
it_behaves_like 'id_token issued by valid issuer', 'https://accounts.google.com'
context 'when the id_token is issued by an invalid issuer' do
let(:token_info) do
{
'abc' => 'xyz',
'exp' => Time.now.to_i + 3600,
'nbf' => Time.now.to_i - 60,
'iat' => Time.now.to_i,
'aud' => 'appid',
'iss' => 'fake.google.com'
}
end
let(:id_token) { JWT.encode(token_info, 'secret') }
let(:access_token) { OAuth2::AccessToken.from_hash(client, 'id_token' => id_token) }
it 'raises JWT::InvalidIssuerError' do
expect { subject.extra }.to raise_error(JWT::InvalidIssuerError)
end
end
context 'when the id_token is missing' do
it 'should not include id_token' do
expect(subject.extra).not_to have_key(:id_token)
end
it 'should not include id_info' do
expect(subject.extra).not_to have_key(:id_info)
end
end
end
describe 'raw_info' do
context 'when skip_info is true' do
before { subject.options[:skip_info] = true }
it 'should not include raw_info' do
expect(subject.extra).not_to have_key(:raw_info)
end
end
context 'when skip_info is false' do
before { subject.options[:skip_info] = false }
it 'should include raw_info' do
expect(subject.extra[:raw_info]).to eq('sub' => '12345')
end
end
end
end
describe 'populate auth hash urls' do
it 'should populate url map in auth hash if link present in raw_info' do
allow(subject).to receive(:raw_info) { { 'name' => 'Foo', 'profile' => 'https://plus.google.com/123456' } }
expect(subject.info[:urls][:google]).to eq('https://plus.google.com/123456')
end
it 'should not populate url map in auth hash if no link present in raw_info' do
allow(subject).to receive(:raw_info) { { 'name' => 'Foo' } }
expect(subject.info).not_to have_key(:urls)
end
end
describe 'image options' do
it 'should have no image if a picture is not present' do
@options = { image_aspect_ratio: 'square' }
allow(subject).to receive(:raw_info) { { 'name' => 'User Without Pic' } }
expect(subject.info[:image]).to be_nil
end
describe 'when a picture is returned from google' do
it 'should return the image with size specified in the `image_size` option' do
@options = { image_size: 50 }
allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url/photo.jpg' } }
expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/s50/photo.jpg')
end
it 'should return the image with size specified in the `image_size` option when sizing is in the picture' do
@options = { image_size: 50 }
allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh4.googleusercontent.com/url/s96-c/photo.jpg' } }
expect(subject.info[:image]).to eq('https://lh4.googleusercontent.com/url/s50/photo.jpg')
end
it 'should handle a picture with too many slashes correctly' do
@options = { image_size: 50 }
allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url//photo.jpg' } }
expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/s50/photo.jpg')
end
it 'should handle a picture with a size query parameter correctly' do
@options = { image_size: 50 }
allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url/photo.jpg?sz=50' } }
expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/s50/photo.jpg')
end
it 'should handle a picture with a size query parameter and other valid query parameters correctly' do
@options = { image_size: 50 }
allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url/photo.jpg?sz=50&hello=true&life=42' } }
expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/s50/photo.jpg?hello=true&life=42')
end
it 'should handle a picture with other valid query parameters correctly' do
@options = { image_size: 50 }
allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url/photo.jpg?hello=true&life=42' } }
expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/s50/photo.jpg?hello=true&life=42')
end
it 'should return the image with width and height specified in the `image_size` option' do
@options = { image_size: { width: 50, height: 40 } }
allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url/photo.jpg' } }
expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/w50-h40/photo.jpg')
end
it 'should return the image with width and height specified in the `image_size` option when sizing is in the picture' do
@options = { image_size: { width: 50, height: 40 } }
allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url/w100-h80-c/photo.jpg' } }
expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/w50-h40/photo.jpg')
end
it 'should return square image when `image_aspect_ratio` is specified' do
@options = { image_aspect_ratio: 'square' }
allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url/photo.jpg' } }
expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/c/photo.jpg')
end
it 'should return square image when `image_aspect_ratio` is specified and sizing is in the picture' do
@options = { image_aspect_ratio: 'square' }
allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url/c/photo.jpg' } }
expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/c/photo.jpg')
end
it 'should return square sized image when `image_aspect_ratio` and `image_size` is set' do
@options = { image_aspect_ratio: 'square', image_size: 50 }
allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url/photo.jpg' } }
expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/s50-c/photo.jpg')
end
it 'should return square sized image when `image_aspect_ratio` and `image_size` is set and sizing is in the picture' do
@options = { image_aspect_ratio: 'square', image_size: 50 }
allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url/s90/photo.jpg' } }
expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/s50-c/photo.jpg')
end
it 'should return square sized image when `image_aspect_ratio` and `image_size` has height and width' do
@options = { image_aspect_ratio: 'square', image_size: { width: 50, height: 40 } }
allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url/photo.jpg' } }
expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/w50-h40-c/photo.jpg')
end
it 'should return square sized image when `image_aspect_ratio` and `image_size` has height and width and sizing is in the picture' do
@options = { image_aspect_ratio: 'square', image_size: { width: 50, height: 40 } }
allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url/w100-h80/photo.jpg' } }
expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/w50-h40-c/photo.jpg')
end
it 'should return original image if image url does not end in `photo.jpg`' do
@options = { image_size: 50 }
allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url/photograph.jpg' } }
expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/photograph.jpg')
end
end
it 'should return original image if no options are provided' do
allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url/photo.jpg' } }
expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/photo.jpg')
end
it 'should return correct image if google image url has double https' do
allow(subject).to receive(:raw_info) { { 'picture' => 'https:https://lh3.googleusercontent.com/url/photo.jpg' } }
expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/photo.jpg')
end
end
describe 'build_access_token' do
it 'should use a hybrid authorization request_uri if this is an AJAX request with a code parameter' do
allow(request).to receive(:xhr?).and_return(true)
allow(request).to receive(:params).and_return('code' => 'valid_code')
client = double(:client)
auth_code = double(:auth_code)
allow(client).to receive(:auth_code).and_return(auth_code)
expect(subject).to receive(:client).and_return(client)
expect(auth_code).to receive(:get_token).with('valid_code', { redirect_uri: 'postmessage' }, {})
expect(subject).not_to receive(:orig_build_access_token)
subject.build_access_token
end
it 'should use a hybrid authorization request_uri if this is an AJAX request (mobile) with a code parameter' do
allow(request).to receive(:xhr?).and_return(true)
allow(request).to receive(:params).and_return('code' => 'valid_code', 'redirect_uri' => '')
client = double(:client)
auth_code = double(:auth_code)
allow(client).to receive(:auth_code).and_return(auth_code)
expect(subject).to receive(:client).and_return(client)
expect(auth_code).to receive(:get_token).with('valid_code', { redirect_uri: '' }, {})
expect(subject).not_to receive(:orig_build_access_token)
subject.build_access_token
end
it 'should use the request_uri from params if this not an AJAX request (request from installed app) with a code parameter' do
allow(request).to receive(:xhr?).and_return(false)
allow(request).to receive(:params).and_return('code' => 'valid_code', 'redirect_uri' => 'redirect_uri')
client = double(:client)
auth_code = double(:auth_code)
allow(client).to receive(:auth_code).and_return(auth_code)
expect(subject).to receive(:client).and_return(client)
expect(auth_code).to receive(:get_token).with('valid_code', { redirect_uri: 'redirect_uri' }, {})
expect(subject).not_to receive(:orig_build_access_token)
subject.build_access_token
end
it 'should read access_token from hash if this is not an AJAX request with a code parameter' do
allow(request).to receive(:xhr?).and_return(false)
allow(request).to receive(:params).and_return('access_token' => 'valid_access_token')
expect(subject).to receive(:verify_token).with('valid_access_token').and_return true
expect(subject).to receive(:client).and_return(:client)
token = subject.build_access_token
expect(token).to be_instance_of(::OAuth2::AccessToken)
expect(token.token).to eq('valid_access_token')
expect(token.client).to eq(:client)
end
it 'reads the code from a json request body' do
body = StringIO.new(%({"code":"json_access_token"}))
client = double(:client)
auth_code = double(:auth_code)
allow(request).to receive(:xhr?).and_return(false)
allow(request).to receive(:content_type).and_return('application/json')
allow(request).to receive(:body).and_return(body)
allow(client).to receive(:auth_code).and_return(auth_code)
expect(subject).to receive(:client).and_return(client)
expect(auth_code).to receive(:get_token).with('json_access_token', { redirect_uri: 'postmessage' }, {})
subject.build_access_token
end
it 'reads the redirect uri from a json request body' do
body = StringIO.new(%({"code":"json_access_token", "redirect_uri":"sample"}))
client = double(:client)
auth_code = double(:auth_code)
allow(request).to receive(:xhr?).and_return(false)
allow(request).to receive(:content_type).and_return('application/json')
allow(request).to receive(:body).and_return(body)
allow(client).to receive(:auth_code).and_return(auth_code)
expect(subject).to receive(:client).and_return(client)
expect(auth_code).to receive(:get_token).with('json_access_token', { redirect_uri: 'sample' }, {})
subject.build_access_token
end
it 'reads the access token from a json request body' do
body = StringIO.new(%({"access_token":"valid_access_token"}))
allow(request).to receive(:xhr?).and_return(false)
allow(request).to receive(:content_type).and_return('application/json')
allow(request).to receive(:body).and_return(body)
expect(subject).to receive(:client).and_return(:client)
expect(subject).to receive(:verify_token).with('valid_access_token').and_return true
token = subject.build_access_token
expect(token).to be_instance_of(::OAuth2::AccessToken)
expect(token.token).to eq('valid_access_token')
expect(token.client).to eq(:client)
end
it 'should use callback_url without query_string if this is not an AJAX request' do
allow(request).to receive(:xhr?).and_return(false)
allow(request).to receive(:params).and_return('code' => 'valid_code')
allow(request).to receive(:content_type).and_return('application/x-www-form-urlencoded')
client = double(:client)
auth_code = double(:auth_code)
allow(client).to receive(:auth_code).and_return(auth_code)
allow(subject).to receive(:callback_url).and_return('redirect_uri_without_query_string')
expect(subject).to receive(:client).and_return(client)
expect(auth_code).to receive(:get_token).with('valid_code', { redirect_uri: 'redirect_uri_without_query_string' }, {})
subject.build_access_token
end
end
describe 'verify_token' do
before(:each) do
subject.options.client_options[:connection_build] = proc do |builder|
builder.request :url_encoded
builder.adapter :test do |stub|
stub.get('/oauth2/v3/tokeninfo?access_token=valid_access_token') do
[200, { 'Content-Type' => 'application/json; charset=UTF-8' }, JSON.dump(
aud: '000000000000.apps.googleusercontent.com',
sub: '123456789',
email_verified: 'true',
email: 'example@example.com',
access_type: 'offline',
scope: 'profile email',
expires_in: 436
)]
end
stub.get('/oauth2/v3/tokeninfo?access_token=invalid_access_token') do
[400, { 'Content-Type' => 'application/json; charset=UTF-8' }, JSON.dump(error_description: 'Invalid Value')]
end
end
end
end
it 'should verify token if access_token is valid and app_id equals' do
subject.options.client_id = '000000000000.apps.googleusercontent.com'
expect(subject.send(:verify_token, 'valid_access_token')).to eq(true)
end
it 'should verify token if access_token is valid and app_id authorized' do
subject.options.authorized_client_ids = ['000000000000.apps.googleusercontent.com']
expect(subject.send(:verify_token, 'valid_access_token')).to eq(true)
end
it 'should not verify token if access_token is valid but app_id is false' do
expect(subject.send(:verify_token, 'valid_access_token')).to eq(false)
end
it 'should raise error if access_token is invalid' do
expect do
subject.send(:verify_token, 'invalid_access_token')
end.to raise_error(OAuth2::Error)
end
end
describe 'verify_hd' do
let(:client) do
OAuth2::Client.new('abc', 'def') do |builder|
builder.request :url_encoded
builder.adapter :test do |stub|
stub.get('/oauth2/v3/userinfo') do
[200, { 'Content-Type' => 'application/json; charset=UTF-8' }, JSON.dump(
hd: 'example.com'
)]
end
end
end
end
let(:access_token) { OAuth2::AccessToken.from_hash(client, {}) }
context 'when domain is nil' do
let(:client) do
OAuth2::Client.new('abc', 'def') do |builder|
builder.request :url_encoded
builder.adapter :test do |stub|
stub.get('/oauth2/v3/userinfo') do
[200, { 'Content-Type' => 'application/json; charset=UTF-8' }, JSON.dump({})]
end
end
end
end
it 'should verify hd if options hd is set and correct' do
subject.options.hd = nil
expect(subject.send(:verify_hd, access_token)).to eq(true)
end
it 'should verify hd if options hd is set as an array and is correct' do
subject.options.hd = ['example.com', 'example.co', nil]
expect(subject.send(:verify_hd, access_token)).to eq(true)
end
it 'should raise an exception if nil is not included' do
subject.options.hd = ['example.com', 'example.co']
expect do
subject.send(:verify_hd, access_token)
end.to raise_error(OmniAuth::Strategies::OAuth2::CallbackError)
end
end
it 'should verify hd if options hd is not set' do
expect(subject.send(:verify_hd, access_token)).to eq(true)
end
it 'should verify hd if options hd is set and correct' do
subject.options.hd = 'example.com'
expect(subject.send(:verify_hd, access_token)).to eq(true)
end
it 'should verify hd if options hd is set as an array and is correct' do
subject.options.hd = ['example.com', 'example.co', nil]
expect(subject.send(:verify_hd, access_token)).to eq(true)
end
it 'should verify hd if options hd is set as an Proc and is correct' do
subject.options.hd = proc { 'example.com' }
expect(subject.send(:verify_hd, access_token)).to eq(true)
end
it 'should verify hd if options hd is set as an Proc returning an array and is correct' do
subject.options.hd = proc { ['example.com', 'example.co'] }
expect(subject.send(:verify_hd, access_token)).to eq(true)
end
it 'should raise error if options hd is set and wrong' do
subject.options.hd = 'invalid.com'
expect do
subject.send(:verify_hd, access_token)
end.to raise_error(OmniAuth::Strategies::GoogleOauth2::CallbackError)
end
it 'should raise error if options hd is set as an array and is not correct' do
subject.options.hd = ['invalid.com', 'invalid.co']
expect do
subject.send(:verify_hd, access_token)
end.to raise_error(OmniAuth::Strategies::GoogleOauth2::CallbackError)
end
end
end

View File

@ -1,4 +0,0 @@
# frozen_string_literal: true
require File.join('bundler', 'setup')
require 'rspec'