tony-auth

RSpec Status Rubocop Status

Middlewares to help login with 3rd party services.

Installation

In a Gemfile

source: 'https://www.jubigems.org/' do
  gem 'tony-auth'
end

Usage

Google

In your config.ru, you can add:

use Tony::Auth::Google, client_id: google_client_id, secret: google_secret

In a view file, you can link to log in like this:

a href=Tony::Auth::Google.url(req, redirect: '/') Sign in with Google

req should be an instance of Rack::Request associated with the current request.

You may pass any other key value pairs you wish (in this case, redirect: '/'), and they will get passed back to you in the state variable.

Finally, in your controller, add a hook for /auth/google. The req.env[:login_info] will be an object with an email and state attribute:

get('/auth/google', ->(req, resp) {
   = req.env[:login_info]
  resp.set_cookie(:email_address, .email)
  resp.redirect(.state[:redirect])
})

Testing Code that Uses tony-auth

Testing tony-auth endpoints can be tricky at first glance. Here's how you could test in RSpec and rack-test (using tony-test) the /auth/google endpoint in the example provided above.

require 'securerandom'

RSpec.describe(Main, type: :rack_test) {
  context('get /auth/google') {
    before(:each) {
      allow(Tony::Auth::Google).to(receive(:url)).and_return(
          SecureRandom.alphanumeric(24))
      @login_info = Tony::Auth::LoginInfo.new(email: '[email protected]',
                                              state: { redirect: '/onward' })
    }

    it('sets the email address') {
      set_cookie(:email, 'nomnomnom')
      get '/auth/google', {}, { 'login_info' => @login_info }
      expect(get_cookie(:email)).to(eq('[email protected]'))
    }

    it('redirects to :r in state') {
      get '/auth/google', {}, { 'login_info' => @login_info }
      expect(last_response.redirect?).to(be(true))
      expect(last_response.location).to(eq('/onward'))
    }
  }
}

More Documentation

License

The gem is available as open source under the terms of the MIT License.