Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Doorkeeper integration. #133

Merged
merged 1 commit into from
Sep 30, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions app/controllers/api/api_controller.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
class Api::ApiController < ActionController::Base
include CamaleonHelper
include SessionHelper
include SiteHelper
include HtmlHelper
include UserRolesHelper
include ShortCodeHelper
include PluginsHelper
include ThemeHelper
include HooksHelper
include ContentHelper
include CaptchaHelper
include UploaderHelper

before_action -> { doorkeeper_authorize! :client }
respond_to :json

def account
render json: current_resource_owner
end

private

def current_resource_owner
User.find(doorkeeper_token.resource_owner_id) if doorkeeper_token
end

end
7 changes: 7 additions & 0 deletions app/controllers/api/v1/category_controller.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
class Api::V1::CategoryController < Api::ApiController

def categories
render json: current_site.full_categories
end

end
21 changes: 18 additions & 3 deletions app/helpers/session_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ module SessionHelper
# user: User model
# remember_me: true/false (remember session permanently)
def login_user(user, remember_me = false, redirect_url = nil)
c = {value: [user.auth_token, request.user_agent, request.ip], expires: 24.hours.from_now }
c = {value: [user.auth_token, request.user_agent, request.ip], expires: 24.hours.from_now}
# c[:domain] = :all if PluginRoutes.system_info["users_share_sites"].present? && Site.main_site.get_meta("share_sessions", true) && !cookies[:login].present?
c[:domain] = :all if PluginRoutes.system_info["users_share_sites"].present? && Site.count > 1
c[:expires] = 1.month.from_now if remember_me
Expand All @@ -33,9 +33,24 @@ def login_user(user, remember_me = false, redirect_url = nil)
end
end

def login_user_with_password(username, password, remember_me=false, redirect_url = nil)
data_user = {}
cipher = Gibberish::AES::CBC.new(get_session_id)
data_user[:password] = cipher.decrypt(password) rescue nil
@user = current_site.users.find_by_username(username)
r = {user: @user, params: params, password: data_user[:password], captcha_validate: true}; hooks_run('user_before_login', r)
if @user && @user.authenticate(data_user[:password])
login_user(@user, remember_me, redirect_url)
else
#TODO change flash error
#flash[:error] = t('admin.login.message.fail')
end
@user if @user
end

# check if current host is heroku
def on_heroku?
ENV.keys.any? {|var_name| var_name.match(/(heroku|dyno)/i) }
ENV.keys.any? { |var_name| var_name.match(/(heroku|dyno)/i) }
end

# switch current session user into other (user)
Expand Down Expand Up @@ -73,7 +88,7 @@ def signin?
# return the role for current user
# if not logged in, then return 'public'
def current_role
(signin?)? current_user.role : 'public'
(signin?) ? current_user.role : 'public'
end

# return current user logged in
Expand Down
3 changes: 3 additions & 0 deletions camaleon_cms.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,7 @@ Gem::Specification.new do |s|
s.add_dependency 'rufus-scheduler'
s.add_dependency 'will_paginate'
s.add_dependency 'will_paginate-bootstrap'
s.add_dependency 'doorkeeper', '~> 3.0'
s.add_dependency 'responders', '~> 2.0'

end
128 changes: 128 additions & 0 deletions config/initializers/doorkeeper.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
include SessionHelper
include SiteHelper
include HooksHelper

Doorkeeper.configure do
# Change the ORM that doorkeeper will use (needs plugins)
orm :active_record
default_scopes :public, :admin, :client

resource_owner_from_credentials do |routes|
login_user_with_password(params[:username], params[:password])
end

# This block will be called to check whether the resource owner is authenticated or not.
# resource_owner_authenticator do
# User.find_by_id(session[:current_user_id]) || redirect_to(login_url)
# fail "Please configure doorkeeper resource_owner_authenticator block located in #{__FILE__}"
# Put your resource owner authentication logic here.
# Example implementation:
# User.find_by_id(session[:user_id]) || redirect_to(new_user_session_url)
# end

# If you want to restrict access to the web interface for adding oauth authorized applications, you need to declare the block below.
admin_authenticator do
begin
authorize! :manager, :comments
rescue CanCan::AccessDenied
redirect_to admin_dashboard_path
end
end

# Authorization Code expiration time (default 10 minutes).
# authorization_code_expires_in 10.minutes

# Access token expiration time (default 2 hours).
# If you want to disable expiration, set this to nil.
# access_token_expires_in 2.hours

# Assign a custom TTL for implicit grants.
# custom_access_token_expires_in do |oauth_client|
# oauth_client.application.additional_settings.implicit_oauth_expiration
# end

# Use a custom class for generating the access token.
# https://github.com/doorkeeper-gem/doorkeeper#custom-access-token-generator
# access_token_generator "::Doorkeeper::JWT"

# Reuse access token for the same resource owner within an application (disabled by default)
# Rationale: https://github.com/doorkeeper-gem/doorkeeper/issues/383
# reuse_access_token

# Issue access tokens with refresh token (disabled by default)
# use_refresh_token

# Provide support for an owner to be assigned to each registered application (disabled by default)
# Optional parameter :confirmation => true (default false) if you want to enforce ownership of
# a registered application
# Note: you must also run the rails g doorkeeper:application_owner generator to provide the necessary support
# enable_application_owner :confirmation => false

# Define access token scopes for your provider
# For more information go to
# https://github.com/doorkeeper-gem/doorkeeper/wiki/Using-Scopes
# default_scopes :public
# optional_scopes :write, :update

# Change the way client credentials are retrieved from the request object.
# By default it retrieves first from the `HTTP_AUTHORIZATION` header, then
# falls back to the `:client_id` and `:client_secret` params from the `params` object.
# Check out the wiki for more information on customization
# client_credentials :from_basic, :from_params

# Change the way access token is authenticated from the request object.
# By default it retrieves first from the `HTTP_AUTHORIZATION` header, then
# falls back to the `:access_token` or `:bearer_token` params from the `params` object.
# Check out the wiki for more information on customization
# access_token_methods :from_bearer_authorization, :from_access_token_param, :from_bearer_param

# Change the native redirect uri for client apps
# When clients register with the following redirect uri, they won't be redirected to any server and the authorization code will be displayed within the provider
# The value can be any string. Use nil to disable this feature. When disabled, clients must provide a valid URL
# (Similar behaviour: https://developers.google.com/accounts/docs/OAuth2InstalledApp#choosingredirecturi)
#
# native_redirect_uri 'urn:ietf:wg:oauth:2.0:oob'

# Forces the usage of the HTTPS protocol in non-native redirect uris (enabled
# by default in non-development environments). OAuth2 delegates security in
# communication to the HTTPS protocol so it is wise to keep this enabled.
#
# force_ssl_in_redirect_uri !Rails.env.development?

# Specify what grant flows are enabled in array of Strings. The valid
# strings and the flows they enable are:

#
# "authorization_code" => Authorization Code Grant Flow
# "implicit" => Implicit Grant Flow
# "password" => Resource Owner Password Credentials Grant Flow
# "client_credentials" => Client Credentials Grant Flow
#
# If not specified, Doorkeeper enables authorization_code and
# client_credentials.
#
# implicit and password grant flows have risks that you should understand
# before enabling:
# http://tools.ietf.org/html/rfc6819#section-4.4.2
# http://tools.ietf.org/html/rfc6819#section-4.4.3
#
grant_flows %w(password)

# Under some circumstances you might want to have applications auto-approved,
# so that the user skips the authorization step.
# For example if dealing with a trusted application.
skip_authorization do |resource_owner, client|
# client.superapp? or resource_owner.admin?
true
end

# skip_authorization do |resource_owner, client|
# client.superapp? or resource_owner.admin?
# true
# end

# WWW-Authenticate Realm (default "Doorkeeper").
# realm "Doorkeeper"

# configuration.token_grant_types << 'password'
end
123 changes: 123 additions & 0 deletions config/locales/doorkeeper.en.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
en:
activerecord:
attributes:
doorkeeper/application:
name: 'Name'
redirect_uri: 'Redirect URI'
errors:
models:
doorkeeper/application:
attributes:
redirect_uri:
fragment_present: 'cannot contain a fragment.'
invalid_uri: 'must be a valid URI.'
relative_uri: 'must be an absolute URI.'
secured_uri: 'must be an HTTPS/SSL URI.'

doorkeeper:
applications:
confirmations:
destroy: 'Are you sure?'
buttons:
edit: 'Edit'
destroy: 'Destroy'
submit: 'Submit'
cancel: 'Cancel'
authorize: 'Authorize'
form:
error: 'Whoops! Check your form for possible errors'
help:
redirect_uri: 'Use one line per URI'
native_redirect_uri: 'Use %{native_redirect_uri} for local tests'
scopes: 'Separate scopes with spaces. Leave blank to use the default scopes.'
edit:
title: 'Edit application'
index:
title: 'Your applications'
new: 'New Application'
name: 'Name'
callback_url: 'Callback URL'
new:
title: 'New Application'
show:
title: 'Application: %{name}'
application_id: 'Application Id'
secret: 'Secret'
scopes: 'Scopes'
callback_urls: 'Callback urls'
actions: 'Actions'

authorizations:
buttons:
authorize: 'Authorize'
deny: 'Deny'
error:
title: 'An error has occurred'
new:
title: 'Authorization required'
prompt: 'Authorize %{client_name} to use your account?'
able_to: 'This application will be able to'
show:
title: 'Authorization code'

authorized_applications:
confirmations:
revoke: 'Are you sure?'
buttons:
revoke: 'Revoke'
index:
title: 'Your authorized applications'
application: 'Application'
created_at: 'Created At'
date_format: '%Y-%m-%d %H:%M:%S'

errors:
messages:
# Common error messages
invalid_request: 'The request is missing a required parameter, includes an unsupported parameter value, or is otherwise malformed.'
invalid_redirect_uri: 'The redirect uri included is not valid.'
unauthorized_client: 'The client is not authorized to perform this request using this method.'
access_denied: 'The resource owner or authorization server denied the request.'
invalid_scope: 'The requested scope is invalid, unknown, or malformed.'
server_error: 'The authorization server encountered an unexpected condition which prevented it from fulfilling the request.'
temporarily_unavailable: 'The authorization server is currently unable to handle the request due to a temporary overloading or maintenance of the server.'

#configuration error messages
credential_flow_not_configured: 'Resource Owner Password Credentials flow failed due to Doorkeeper.configure.resource_owner_from_credentials being unconfigured.'
resource_owner_authenticator_not_configured: 'Resource Owner find failed due to Doorkeeper.configure.resource_owner_authenticator being unconfiged.'

# Access grant errors
unsupported_response_type: 'The authorization server does not support this response type.'

# Access token errors
invalid_client: 'Client authentication failed due to unknown client, no client authentication included, or unsupported authentication method.'
invalid_grant: 'The provided authorization grant is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client.'
unsupported_grant_type: 'The authorization grant type is not supported by the authorization server.'

# Password Access token errors
invalid_resource_owner: 'The provided resource owner credentials are not valid, or resource owner cannot be found'

invalid_token:
revoked: "The access token was revoked"
expired: "The access token expired"
unknown: "The access token is invalid"

flash:
applications:
create:
notice: 'Application created.'
destroy:
notice: 'Application deleted.'
update:
notice: 'Application updated.'
authorized_applications:
destroy:
notice: 'Application revoked.'

layouts:
admin:
nav:
oauth2_provider: 'OAuth2 Provider'
applications: 'Applications'
application:
title: 'OAuth authorization required'
10 changes: 10 additions & 0 deletions config/routes.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,14 @@
Rails.application.routes.draw do
use_doorkeeper

namespace :api do
get 'account' => 'api#account'

namespace :v1 do
get 'categories' => 'category#categories'
end
end

# root "application#index"
default_url_options :host => PluginRoutes.system_info["base_domain"]

Expand Down
Loading