Skip to content

Instantly share code, notes, and snippets.

@istro
Last active August 29, 2015 14:00
Show Gist options
  • Save istro/11234209 to your computer and use it in GitHub Desktop.
Save istro/11234209 to your computer and use it in GitHub Desktop.
Code for rails post
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
...
before_filter :authenticate_user_from_token!
private
def authenticate_user_from_token!
auth_header = request.headers['AUTHORIZATION']
return if auth_header.blank?
type, email, token = auth_header.split(' ')
return unless type == 'Bearer'
user = User.find_by_email(email)
# use `secure_compare` to mitigate timing attacks.
if user && Devise.secure_compare(user.authorization_token, token)
sign_in user, store: false
end
end
end
# config/database.yml
development:
adapter: postgresql
database: purelighst-dev
host: localhost
...
# Gemfile
source 'https://rubygems.org'
ruby "2.0.0"
gem 'rails', '~> 4.0.0'
...
group :development do
gem 'better_errors'
end
# app/controllers/locations_controller.rb
class LocationsController < ApplicationController
before_action :authenticate_user!
respond_to :json
def index
@locations = current_user.locations
render json: @locations
end
...
end
class AddAuthorizationTokenToUser < ActiveRecord::Migration
def change
add_column :users, :authorization_token, :string
end
end
# app/controllers/rooms_controller.rb
class RoomsController < ApplicationController
...
respond_to :json
# route that leads to this action is 'rooms#index'
def index
@rooms = user_rooms
if ids = params[:ids]
@rooms = @rooms.where(id: ids)
end
render json: @rooms
end
...
def create
@room = @location.rooms.new(room_params)
if @room.save
render json: @room
else
render json: { errors: @room.errors }, status: :unprocessable_entity
end
end
...
end
# config/routes.rb
Purelights::Application.routes.draw do
root 'landing#home'
...
scope '/api' do
# Our Resources
resources :locations
resources :rooms
resources :fixtures
end
...
end
class LocationSerializer < ActiveModel::Serializer
attributes :id, :name, :postal, :home_type, :rate_id
has_many :rooms, embed: :ids
def rate_id
object.rate_identifier
end
end
# app/models/user.rb
class User < ActiveRecord::Base
...
has_many :locations
validates :postal_code, presence: true
...
def generate_authorization_token!
loop do
token = Devise.friendly_token
break token unless User.where(authorization_token: token).first
end
end
end
# app/controllers/users_controller.rb
...
def add_authorization_token_to_response!
response.headers['Access-Token'] = @user.authorization_token
end
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment