Skip to content

Commit

Permalink
Add Rodauth integration, forcing users to authenticate before using G…
Browse files Browse the repository at this point in the history
…inatra
  • Loading branch information
jeremyevans committed Apr 5, 2016
1 parent 191cdac commit 28108eb
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
# Ginatra/Rodauth Integration

This branch shows how to integrate Ginatra with the Rodauth authentication framework.
Ginatra by default does not support authentication, which means it can only be used
in trusted environments. This allows you to use Ginatra in untrusted environments,
by forcing users to login via Rodauth.

# Ginatra

[![Build Status](https://img.shields.io/travis/NARKOZ/ginatra/master.svg)](https://travis-ci.org/NARKOZ/ginatra)
Expand Down
47 changes: 47 additions & 0 deletions lib/ginatra.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@
require 'ginatra/repo'
require 'ginatra/repo_list'
require 'ginatra/repo_stats'
require 'roda'
require 'sequel/core'
require 'bcrypt'

module Ginatra
# The main application class.
Expand Down Expand Up @@ -36,6 +39,50 @@ class App < Sinatra::Base
Dir["#{settings.root}/ginatra/*.rb"].each { |file| also_reload file }
end

# Add a cookie-based session handler, to store the login id of the user
use Rack::Session::Cookie, :secret=>File.file?('ginatra.secret') ? File.read('ginatra.secret') : (ENV['GINATRA_SECRET'] || SecureRandom.hex(20))

class RodauthApp < Roda
# Include these modules, as Ginatra's layout calls methods in them
include Ginatra::Helpers
include Sinatra::Partials

# Setup the database unless it already exists
db = Sequel.sqlite('users.sqlite3')
unless db.table_exists?(:accounts)
db.create_table(:accounts) do
primary_key :id
String :email, :unique=>true, :null=>false
String :password_hash, :null=>false
end

# Add a demo account for testing, since we aren't allowing users to create their own
# accounts.
db[:accounts].insert(:email=>'demo', :password_hash=>BCrypt::Password.create('demo'))
end

plugin :middleware
plugin :rodauth do
enable :login

# Since we are using SQLite as the database and not PostgreSQL, just store the
# password hash in a column in the main table
account_password_hash_column :password_hash
end

# Alias render to erb, since the layout calls the erb method to render
alias erb render

route do |r|
r.rodauth

# Force all users to login before accessing Ginatra
rodauth.require_authentication
end
end

use RodauthApp

def cache(obj)
etag obj if settings.production?
end
Expand Down

0 comments on commit 28108eb

Please sign in to comment.