Skip to content
This repository has been archived by the owner on Jan 29, 2022. It is now read-only.

Commit

Permalink
Merge pull request #94 from dhollinger/authentication
Browse files Browse the repository at this point in the history
Added authentication model, controller, and tasks
  • Loading branch information
dhollinger authored Mar 11, 2019
2 parents 66b487c + 3e1703f commit 0b21187
Show file tree
Hide file tree
Showing 15 changed files with 100 additions and 8 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ coverage
webhook.lock
vendor/

# SQLite Databases
**/*.sqlite
**/*.sqlite3

# App Ignores
logs/*.log
config/config.yml
Expand Down
2 changes: 2 additions & 0 deletions .rubocop.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ AllCops:
TargetRubyVersion: 2.2
Exclude:
- 'vendor/**/*'
- 'db/schema.rb'
- 'db/migrate/**/*'

Metrics/LineLength:
Max: 140
Expand Down
1 change: 1 addition & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ before_script:
- curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter
- chmod +x ./cc-test-reporter
- ./cc-test-reporter before-build
- 'bundle exec rake db:migrate SINATRA_ENV=test'
script:
- 'bundle exec rake $CHECK'
after_script:
Expand Down
1 change: 1 addition & 0 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ gem 'slack-notifier'
gem 'sqlite3'
gem 'thin'
gem 'tux'
gem 'warden'

group :development do
gem 'debase'
Expand Down
3 changes: 3 additions & 0 deletions Gemfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,8 @@ GEM
tzinfo (1.2.5)
thread_safe (~> 0.1)
unicode-display_width (1.4.1)
warden (1.2.7)
rack (>= 1.0)
webmock (3.5.1)
addressable (>= 2.3.6)
crack (>= 0.3.2)
Expand Down Expand Up @@ -261,6 +263,7 @@ DEPENDENCIES
sqlite3
thin
tux
warden
webmock
yard

Expand Down
18 changes: 17 additions & 1 deletion Rakefile
Original file line number Diff line number Diff line change
@@ -1,7 +1,23 @@
ENV['SINATRA_ENV'] ||= 'development'

require 'sinatra/activerecord/rake'
require 'securerandom'

namespace :db do
task :load_config do
require './app/controllers/application_controller'
end

desc 'Generate auth token for the application'
task :generate_token do
token = SecureRandom.urlsafe_base64
AuthToken.delete_all
AuthToken.create(token: token).save!
puts token
end
end

require_relative './config/environment'
# require 'sinatra/activerecord/rake'

require 'rubocop/rake_task'
RuboCop::RakeTask.new
Expand Down
10 changes: 3 additions & 7 deletions app/controllers/application_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
# Main sinatra app class
class ApplicationController < Sinatra::Base
configure do
register Sinatra::ActiveRecordExtension
set :database, "sqlite3:db/#{ENV['SINATRA_ENV']}.sqlite3"
set :public_folder, 'public'
set :views, 'app/views'
set :logger, Logger.new(STDOUT)
Expand All @@ -23,13 +25,7 @@ class ApplicationController < Sinatra::Base
private

def protected!
if authorized?
logger.info("Authenticated as user #{APP_CONFIG.user} from IP #{request.ip}")
else
response['WWW-Authenticate'] = %(Basic realm="Restricted Area")
logger.error("Authentication failure from IP #{request.ip}")
throw(:halt, [401, "Not authorized\n"])
end
env['warden'].authenticate!(:access_token)
end

def authorized?
Expand Down
36 changes: 36 additions & 0 deletions app/controllers/authentication_controller.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# This class handles application authentication.
class AuthenticationController < ApplicationController
post '/unauthenticated' do
content_type :json
status 401
json(message: 'Sorry, this request can not be authenticated. Try again.')
end

use Warden::Manager do |config|
config.scope_defaults :default,
strategies: [:access_token],
action: '/unauthenticated'
config.failure_app = self
end

Warden::Manager.before_failure do |env, opts|
logger.error("Authentication failed to `#{opts[:attempted_path]}`\nReason: #{opts[:message]}")
env['REQUEST_METHOD'] = 'POST'
end

Warden::Strategies.add(:access_token) do
def valid?
# Validate that the access token is properly formatted.
# Currently only checks that it's actually a string.
request.env['HTTP_ACCESS_TOKEN'].is_a?(String)
end

def authenticate!
access_granted = request.env['HTTP_ACCESS_TOKEN'] == AuthToken.first.token

!access_granted ? fail!('Invalid authentication token!') : success!(access_granted)
rescue NoMethodError
fail!('No token created! Please create a token with `rake db:generate_token` or set protected to `false` in the config.')
end
end
end
Empty file removed app/models/.gitkeep
Empty file.
1 change: 1 addition & 0 deletions app/models/auth_token.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
class AuthToken < ActiveRecord::Base; end
1 change: 1 addition & 0 deletions config.ru
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@ require './config/environment'
raise 'Migrations are pending. Run `rake db:migrate` to resolve the issue.' if ActiveRecord::Migrator.needs_migration?

run ApplicationController
use AuthenticationController
use Api::V1::R10K::EnvironmentController
use Api::V1::R10K::ModuleController
Empty file removed db/development.sqlite
Empty file.
9 changes: 9 additions & 0 deletions db/migrate/20190305055755_auth_tokens.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
class AuthTokens < ActiveRecord::Migration
def change
create_table :auth_tokens do |t|
t.string :token
t.datetime :created_at
t.datetime :updated_at
end
end
end
22 changes: 22 additions & 0 deletions db/schema.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.

ActiveRecord::Schema.define(version: 20190305055755) do

create_table "auth_tokens", force: :cascade do |t|
t.string "token"
t.datetime "created_at"
t.datetime "updated_at"
end

end
Empty file removed db/test.sqlite
Empty file.

0 comments on commit 0b21187

Please sign in to comment.