Skip to content
Extraits de code Groupes Projets
Valider 73cc5594 rédigé par Augier's avatar Augier Validation de theworldbright
Parcourir les fichiers

Fix travis errors and refactor

parent c6eb7225
Aucune branche associée trouvée
Aucune étiquette associée trouvée
Aucune requête de fusion associée trouvée
Affichage de
avec 133 ajouts et 188 suppressions
class Api::V0::UsersController < Api::V0::BaseController
def show
render json: user
end
private
private
def user
current_token.user
end
......
This code is based on https://github.com/nov/openid_connect_sample
Copyright (c) 2011 nov matake
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.
class OpenidConnect::AuthorizationsController < ApplicationController
rescue_from Rack::OAuth2::Server::Authorize::BadRequest do |e|
logger.info e.backtrace[0,10].join("\n")
render json: {error: e.message || :error, status: e.status}
render json: { error: e.message || :error, status: e.status }
end
before_action :authenticate_user!
......@@ -14,50 +14,49 @@ class OpenidConnect::AuthorizationsController < ApplicationController
process_authorization_consent(params[:approve])
end
private
private
def request_authorization_consent_form
endpoint = OpenidConnect::Authorization::EndpointStartPoint.new(current_user)
handleStartPointResponse(endpoint)
handle_startpoint_response(endpoint)
end
def handleStartPointResponse(endpoint)
status, header, response = *endpoint.call(request.env)
def handle_startpoint_response(endpoint)
_status, header, response = *endpoint.call(request.env)
if response.redirect?
redirect_to header['Location']
redirect_to header["Location"]
else
@client, @response_type, @redirect_uri, @scopes, @request_object = *[
endpoint.client, endpoint.response_type, endpoint.redirect_uri, endpoint.scopes, endpoint.request_object
]
saveRequestParameters
save_request_parameters
render :new
end
end
def process_authorization_consent(approvedString)
endpoint = OpenidConnect::Authorization::EndpointConfirmationPoint.new(current_user, to_boolean(approvedString))
restoreRequestParameters(endpoint)
handleConfirmationPointResponse(endpoint)
restore_request_parameters(endpoint)
handle_confirmation_endpoint_response(endpoint)
end
def handleConfirmationPointResponse(endpoint)
status, header, response = *endpoint.call(request.env)
redirect_to header['Location']
def handle_confirmation_endpoint_response(endpoint)
_status, header, _response = *endpoint.call(request.env)
redirect_to header["Location"]
end
def saveRequestParameters
def save_request_parameters
session[:client_id], session[:response_type], session[:redirect_uri], session[:scopes], session[:request_object] =
@client.client_id, @response_type, @redirect_uri, @scopes.collect { |scope| scope.name }, @request_object
@client.client_id, @response_type, @redirect_uri, @scopes.map(&:name), @request_object
end
def restoreRequestParameters(endpoint)
def restore_request_parameters(endpoint)
req = Rack::Request.new(request.env)
req.update_param("client_id", session[:client_id])
req.update_param("redirect_uri", session[:redirect_uri])
req.update_param("response_type", session[:response_type])
endpoint.scopes, endpoint.request_object =
session[:scopes].collect {|scope| Scope.find_by_name(scope)}, session[:request_object]
session[:scopes].map {|scope| Scope.find_by_name(scope) }, session[:request_object]
end
def to_boolean(str)
......
class OpenidConnect::ClientsController < ApplicationController
rescue_from OpenIDConnect::HttpError do |e|
rewriteHTTPErrorPageAsJSON(e)
http_error_page_as_json(e)
end
rescue_from OpenIDConnect::ValidationFailed do |e|
rewriteValidationFailErrorPageAsJSON(e)
validation_fail_as_json(e)
end
def create
......@@ -13,18 +13,21 @@ class OpenidConnect::ClientsController < ApplicationController
render json: client
end
private
private
def rewriteHTTPErrorPageAsJSON(e)
render json: {
error: :invalid_request,
error_description: e.message
}, status: 400
def http_error_page_as_json(e)
render json:
{
error: :invalid_request,
error_description: e.message
}, status: 400
end
def rewriteValidationFailErrorPageAsJSON(e)
render json: {
error: :invalid_client_metadata,
error_description: e.message
}, status: 400
def validation_fail_as_json(e)
render json:
{
error: :invalid_client_metadata,
error_description: e.message
}, status: 400
end
end
class DiscoveryController < ApplicationController
def show
case params[:id]
when 'webfinger'
webfinger_discovery
when 'openid-configuration'
openid_configuration
else
raise HttpError::NotFound
when "webfinger"
webfinger_discovery
when "openid-configuration"
openid_configuration
else
raise HttpError::NotFound
end
end
......@@ -15,7 +15,7 @@ class DiscoveryController < ApplicationController
def webfinger_discovery
jrd = {
links: [{
rel: OpenIDConnect::Discovery::Provider::Issuer::REL_VALUE,
rel: OpenIDConnect::Discovery::Provider::Issuer::REL_VALUE,
href: root_path
}]
}
......@@ -25,20 +25,20 @@ class DiscoveryController < ApplicationController
def openid_configuration
config = OpenIDConnect::Discovery::Provider::Config::Response.new(
issuer: root_path,
authorization_endpoint: "#{authorizations_url}/new",
token_endpoint: access_tokens_url,
userinfo_endpoint: user_info_url,
jwks_uri: "#{authorizations_url}/jwks.json",
registration_endpoint: "#{root_path}/connect",
scopes_supported: "iss",
response_types_supported: "Client.available_response_types",
grant_types_supported: "Client.available_grant_types",
request_object_signing_alg_values_supported: [:HS256, :HS384, :HS512],
subject_types_supported: ['public', 'pairwise'],
id_token_signing_alg_values_supported: [:RS256],
token_endpoint_auth_methods_supported: ['client_secret_basic', 'client_secret_post'],
claims_supported: ['sub', 'iss', 'name', 'email']
issuer: root_path,
authorization_endpoint: "#{authorizations_url}/new",
token_endpoint: access_tokens_url,
userinfo_endpoint: user_info_url,
jwks_uri: "#{authorizations_url}/jwks.json",
registration_endpoint: "#{root_path}/connect",
scopes_supported: "iss",
response_types_supported: "Client.available_response_types",
grant_types_supported: "Client.available_grant_types",
request_object_signing_alg_values_supported: %i(HS256 HS384 HS512),
subject_types_supported: %w(public pairwise),
id_token_signing_alg_values_supported: %i(RS256),
token_endpoint_auth_methods_supported: %w(client_secret_basic client_secret_post),
claims_supported: %w(sub iss name email)
)
render json: config
end
......
......@@ -3,8 +3,7 @@
# the COPYRIGHT file.
class UsersController < ApplicationController
before_action :authenticate_user!, except: [:new, :create, :public, :user_photo]
before_action :authenticate_user!, except: %i(new create public user_photo)
respond_to :html
def edit
......
class Authorization < ActiveRecord::Base
belongs_to :user
belongs_to :o_auth_application
has_and_belongs_to_many :scopes
has_many :scopes, through: :authorization_scopes
# TODO: Incomplete class
end
class AuthorizationScope < ActiveRecord::Base
belongs_to authorization
belongs_to scope
validates authorization, presence: true
validates scope, presence: true
end
......@@ -19,25 +19,13 @@ class OAuthApplication < ActiveRecord::Base
["id_token"]
end
def register!(registrarHash)
registrarHash.validate!
buildClientApplication(registrarHash)
def register!(registrar)
registrar.validate!
build_client_application(registrar)
end
def buildClientApplication(registrarHash)
client = OAuthApplication.create!
client.attributes = filterNilValues(registrarHash)
client.save!
client
end
def filterNilValues(registrarHash)
{
name: registrarHash.client_name,
redirect_uris: registrarHash.redirect_uris
}.delete_if do |key, value|
value.nil?
end
def build_client_application(registrar)
create! redirect_uris: registrar.redirect_uris
end
end
end
class Scope < ActiveRecord::Base
has_and_belongs_to_many :tokens
has_and_belongs_to_many :authorizations
has_many :tokens, through: :scope_tokens
has_many :authorizations, through: :authorization_scopes
validates :name, presence: true, uniqueness: true
......
class ScopeToken < ActiveRecord::Base
belongs_to :scope
belongs_to :token
validates :scope, presence: true
validates :token, presence: true
end
class Token < ActiveRecord::Base
belongs_to :user
has_and_belongs_to_many :scopes
has_many :scopes, through: :scope_tokens
before_validation :setup, on: :create
......@@ -16,11 +16,11 @@ class Token < ActiveRecord::Base
def bearer_token
@bearer_token ||= Rack::OAuth2::AccessToken::Bearer.new(
access_token: token,
expires_in: (expires_at - Time.now.utc).to_i
expires_in: (expires_at - Time.now.utc).to_i
)
end
def accessible?(_scopes_or_claims_ = nil)
def accessible?(_scopes_or_claims_=nil)
true # TODO: For now don't support scopes
end
end
......@@ -108,7 +108,7 @@ module Diaspora
}
config.action_mailer.asset_host = AppConfig.pod_uri.to_s
config.middleware.use Rack::OAuth2::Server::Resource::Bearer, 'OpenID Connect' do |req|
config.middleware.use Rack::OAuth2::Server::Resource::Bearer, "OpenID Connect" do |req|
Token.valid(Time.now.utc).find_by(token: req.access_token) || req.invalid_token!
end
end
......
......@@ -233,17 +233,17 @@ Diaspora::Application.routes.draw do
# Startpage
root :to => 'home#show'
#OpenID Connect & OAuth
# OpenID Connect & OAuth
namespace :openid_connect do
resources :clients, only: :create
post 'access_tokens', to: proc { |env| OpenidConnect::TokenEndpoint.new.call(env) }
post "access_tokens", to: proc {|env| OpenidConnect::TokenEndpoint.new.call(env) }
# Authorization Servers MUST support the use of the HTTP GET and POST methods at the Authorization Endpoint (see http://openid.net/specs/openid-connect-core-1_0.html#AuthResponseValidation).
resources :authorizations, only: [:new, :create]
post 'authorizations/new', to: 'authorizations#new'
resources :authorizations, only: %i(new create)
post "authorizations/new", to: "authorizations#new"
end
api_version(module: "Api::V0", path: {value: "api/v0"}, default: true) do
match 'user', to: 'users#show', via: [:get, :post]
match "user", to: "users#show", via: [:get, :post]
end
end
class CreateOAuthApplications < ActiveRecord::Migration
def self.up
def change
create_table :o_auth_applications do |t|
t.belongs_to :user, index: true
t.string :client_id
......
When /^I register a new client$/ do
clientRegistrationURL = "/openid_connect/clients"
post clientRegistrationURL,
{
redirect_uris: ["http://localhost:3000"] # Not actually used
}
client_registration_url = "/openid_connect/clients"
post client_registration_url, redirect_uris: ["http://localhost:3000"] # Not actually used
end
Given /^I send a post request from that client to the token endpoint using "([^\"]*)"'s credentials$/ do |username|
clientJSON = JSON.parse(last_response.body)
client_json = JSON.parse(last_response.body)
user = User.find_by(username: username)
tokenEndpointURL = "/openid_connect/access_tokens"
post tokenEndpointURL,
{
grant_type: "password",
username: user.username,
token_endpoint_url = "/openid_connect/access_tokens"
post token_endpoint_url, grant_type: "password", username: user.username,
password: "password", # Password has been hard coded as all test accounts seem to have a password of "password"
client_id: clientJSON["o_auth_application"]["client_id"],
client_secret: clientJSON["o_auth_application"]["client_secret"]
}
client_id: client_json["o_auth_application"]["client_id"],
client_secret: client_json["o_auth_application"]["client_secret"]
end
Given /^I send a post request from that client to the token endpoint using invalid credentials$/ do
clientJSON = JSON.parse(last_response.body)
tokenEndpointURL = "/openid_connect/access_tokens"
post tokenEndpointURL,
{
grant_type: "password",
username: User.find_by(username: "bob"),
password: "wrongpassword",
client_id: clientJSON["o_auth_application"]["client_id"],
client_secret: clientJSON["o_auth_application"]["client_secret"]
}
client_json = JSON.parse(last_response.body)
token_endpoint_url = "/openid_connect/access_tokens"
post token_endpoint_url, grant_type: "password", username: "bob", password: "wrongpassword",
client_id: client_json["o_auth_application"]["client_id"],
client_secret: client_json["o_auth_application"]["client_secret"]
end
When /^I use received valid bearer tokens to access user info$/ do
accessTokenJson = JSON.parse(last_response.body)
userInfoEndPointURL = "/api/v0/user/"
get userInfoEndPointURL,
{
access_token: accessTokenJson["access_token"]
}
access_token_json = JSON.parse(last_response.body)
user_info_endpoint_url = "/api/v0/user/"
get user_info_endpoint_url, access_token: access_token_json["access_token"]
end
When /^I use invalid bearer tokens to access user info$/ do
userInfoEndPointURL = "/api/v0/user/"
get userInfoEndPointURL,
{
access_token: SecureRandom.hex(32)
}
user_info_endpoint_url = "/api/v0/user/"
get user_info_endpoint_url, access_token: SecureRandom.hex(32)
end
Then /^I should receive "([^\"]*)"'s id, username, and email$/ do |username|
userInfoJson = JSON.parse(last_response.body)
user_info_json = JSON.parse(last_response.body)
user = User.find_by_username(username)
expect(userInfoJson["username"]).to have_content(user.username)
expect(userInfoJson["language"]).to have_content(user.language)
expect(userInfoJson["email"]).to have_content(user.email)
expect(user_info_json["username"]).to have_content(user.username)
expect(user_info_json["language"]).to have_content(user.language)
expect(user_info_json["email"]).to have_content(user.email)
end
Then /^I should receive an "([^\"]*)" error$/ do |error_message|
userInfoJson = JSON.parse(last_response.body)
expect(userInfoJson["error"]).to have_content(error_message)
user_info_json = JSON.parse(last_response.body)
expect(user_info_json["error"]).to have_content(error_message)
end
......@@ -46,7 +46,8 @@ class AccountDeleter
#user deletions
def normal_ar_user_associates_to_delete
[:tag_followings, :invitations_to_me, :services, :aspects, :user_preferences, :notifications, :blocks]
%i(tag_followings invitations_to_me services aspects user_preferences
notifications blocks authorizations o_auth_applications tokens)
end
def special_ar_user_associations
......
This code is based on https://github.com/nov/openid_connect_sample
Copyright (c) 2011 nov matake
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.
module OpenidConnect
module Authorization
class Endpoint
attr_accessor :app, :user, :client, :redirect_uri, :response_type, :scopes, :_request_, :request_uri, :request_object
attr_accessor :app, :user, :client, :redirect_uri, :response_type,
:scopes, :_request_, :request_uri, :request_object
delegate :call, to: :app
def initialize(current_user)
@user = current_user
@app = Rack::OAuth2::Server::Authorize.new do |req, res|
buildAttributes(req, res)
if OAuthApplication.available_response_types.include? Array(req.response_type).collect(&:to_s).join(' ')
handleResponseType(req, res)
build_attributes(req, res)
if OAuthApplication.available_response_types.include? Array(req.response_type).map(&:to_s).join(" ")
handle_response_type(req, res)
else
req.unsupported_response_type!
end
end
end
def buildAttributes(req, res)
buildClient(req)
buildRedirectURI(req, res)
def build_attributes(req, res)
build_client(req)
build_redirect_uri(req, res)
end
def handleResponseType(req, res)
def handle_response_type(req, res)
# Implemented by subclass
end
private
private
def buildClient(req)
def build_client(req)
@client = OAuthApplication.find_by_client_id(req.client_id) || req.bad_request!
end
def buildRedirectURI(req, res)
def build_redirect_uri(req, res)
res.redirect_uri = @redirect_uri = req.verify_redirect_uri!(@client.redirect_uris)
end
end
......
module OpenidConnect
module Authorization
class EndpointConfirmationPoint < Endpoint
def initialize(current_user, approved = false)
def initialize(current_user, approved=false)
super(current_user)
@approved = approved
end
def buildAttributes(req, res)
def build_attributes(req, res)
super(req, res)
# TODO: buildResponseType(req)
end
def handleResponseType(req, res)
handleApproval(@approved, req, res)
def handle_response_type(req, res)
handle_approval(@approved, req, res)
end
def handleApproval(approved, req, res)
def handle_approval(approved, req, res)
if approved
approved!(req, res)
else
......
0% Chargement en cours ou .
You are about to add 0 people to the discussion. Proceed with caution.
Terminez d'abord l'édition de ce message.
Veuillez vous inscrire ou vous pour commenter