Drop-Dead Simple Authentication for Microapps
For Inspectinator (a sinatra microapp), I needed a database-less authentication solution that was as lightweight as possible, but with a reasonable amount of security and maintainability. I came up with something that suits this purpose well, and I’m sharing it in case anyone is looking for something similar. I call it EasyAuth.
To use EasyAuth to authenticate your sinatra app, you first need to generate hashed passwords for each user you want to allow into your system. You can do this easily in IRB:
$ irb -r lib/easy_auth/easy_auth.rb
irb(main):001:0> EasyAuth.encrypt_password(“foobar”)
=> ["$2a$10$bNh/qPqZt2sgLqetuOkpWuqIt6ANFzoZrtrEevQYjrlUP2Ka/JLNS", “d84/Q”]This should be stored in your easy_auth.rb, in the AUTHORIZED_USERS hash.
Next, you mix-in EasyAuth, and in your password-protected route you do something like:
include
EasyAuth
get
'
/admin
’
do
if_auth
do
erb :
'
admin/index
’
end
end
post
'
/admin
’
do
if_auth(params[
:login], params[
:password])
do
redirect
'
/admin
’
end
end
EasyAuth yields to the block if authentication is successful (either based on the passed-in credentials, or cookies). It defaults to rendering /admin/login if not already authenticated, so throw a username/password form on that page and you should be good to go.