module Sinatra::Fx::Auth

Constants

VERSION

Public Class Methods

registered(app) click to toggle source
# File lib/sinatra/fx-auth.rb, line 131
def self.registered app
  app.helpers Auth::Helpers

  app.enable :logging

  app.set :raise_errors, Proc.new { false }
  app.set :show_exceptions, false


  app.set :auth do |*roles|
    condition do
      unless authenticated? and authorized? *roles
        halt 401 # TODO Return any additional info? Expired session, etc.?
      end
    end
  end


  app.before do
    content_type 'application/json' # TODO Support other representations, XML, etc.
  end


  # Sign Up
  app.post '/profiles/?' do
    halt 422 unless valid_params?

    email, pass_phrase = param_credentials
    profile            = UserProfile.sign_up email, pass_phrase #, request.ip

    if profile.errors.length == 0
      headers "location"     => '/profiles/' + profile.id.to_s,
              "X-AUTH-TOKEN" => profile.pass_key.token
      body profile.to_json :exclude => profile_exclusions
      status 201

    else
      errs = {:errors => profile.errors.to_h}
      body errs.to_json
      status 412
    end
  end


  # Sign On
  app.post '/profiles/:id/key/?' do
    profile = find_user

    raise InvalidUserError unless valid_params?
    raise LockedUserError.new :locked_until => profile.locked_until if profile.status == :locked

    email, pass_phrase = param_credentials
    pass_key           = profile.sign_on email, pass_phrase #, request.ip

    if pass_key
      headers "location"     => '/profiles/' + profile.id.to_s + '/key',
              "X-AUTH-TOKEN" => pass_key.token
      body pass_key.to_json :exclude => pass_key_exclusions
      status 201
    end
  end


  # Sign Off
  app.delete '/profiles/:id/key/?', :auth => [:admin, :user] do
    profile = find_user
    profile.sign_off
  end


  app.get '/profiles/:id', :auth => [:admin, :user] do
    profile = find_user
    profile.to_json :exclude => profile_exclusions
  end


  app.put '/profiles/:id', :auth => [:admin, :user] do
    profile = find_user
    if profile.update params[:profile]
      profile.to_json :exclude => profile_exclusions
    else
      errs = {:errors => profile.errors.to_h}
      body errs.to_json
      status 412
    end
  end


  app.get '/profiles/?', :auth => :admin do
    UserProfile.all.to_json :exclude => profile_exclusions
  end


  app.delete '/profiles/:id', :auth => :admin do
    profile = find_user
    unless profile.destroy
      errs = {:errors => profile.errors.to_h}
      body errs.to_json
      status 412
    end
  end


  app.error InvalidUserError do
    halt 401, error_message
  end


  app.error MissingUserError do
    halt 404, error_message
  end


  app.error DuplicateUserError do
    halt 409, error_message
  end


  app.error LockedUserError do
    halt 423, error_message
  end


  app.error do
    halt 500, error_message
  end

end