Skip to content

Commit 28108eb

Browse files
committed
Add Rodauth integration, forcing users to authenticate before using Ginatra
1 parent 191cdac commit 28108eb

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

README.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,10 @@
1+
# Ginatra/Rodauth Integration
2+
3+
This branch shows how to integrate Ginatra with the Rodauth authentication framework.
4+
Ginatra by default does not support authentication, which means it can only be used
5+
in trusted environments. This allows you to use Ginatra in untrusted environments,
6+
by forcing users to login via Rodauth.
7+
18
# Ginatra
29

310
[![Build Status](https://img.shields.io/travis/NARKOZ/ginatra/master.svg)](https://travis-ci.org/NARKOZ/ginatra)

lib/ginatra.rb

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@
88
require 'ginatra/repo'
99
require 'ginatra/repo_list'
1010
require 'ginatra/repo_stats'
11+
require 'roda'
12+
require 'sequel/core'
13+
require 'bcrypt'
1114

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

42+
# Add a cookie-based session handler, to store the login id of the user
43+
use Rack::Session::Cookie, :secret=>File.file?('ginatra.secret') ? File.read('ginatra.secret') : (ENV['GINATRA_SECRET'] || SecureRandom.hex(20))
44+
45+
class RodauthApp < Roda
46+
# Include these modules, as Ginatra's layout calls methods in them
47+
include Ginatra::Helpers
48+
include Sinatra::Partials
49+
50+
# Setup the database unless it already exists
51+
db = Sequel.sqlite('users.sqlite3')
52+
unless db.table_exists?(:accounts)
53+
db.create_table(:accounts) do
54+
primary_key :id
55+
String :email, :unique=>true, :null=>false
56+
String :password_hash, :null=>false
57+
end
58+
59+
# Add a demo account for testing, since we aren't allowing users to create their own
60+
# accounts.
61+
db[:accounts].insert(:email=>'demo', :password_hash=>BCrypt::Password.create('demo'))
62+
end
63+
64+
plugin :middleware
65+
plugin :rodauth do
66+
enable :login
67+
68+
# Since we are using SQLite as the database and not PostgreSQL, just store the
69+
# password hash in a column in the main table
70+
account_password_hash_column :password_hash
71+
end
72+
73+
# Alias render to erb, since the layout calls the erb method to render
74+
alias erb render
75+
76+
route do |r|
77+
r.rodauth
78+
79+
# Force all users to login before accessing Ginatra
80+
rodauth.require_authentication
81+
end
82+
end
83+
84+
use RodauthApp
85+
3986
def cache(obj)
4087
etag obj if settings.production?
4188
end

0 commit comments

Comments
 (0)