Skip to content

Instantly share code, notes, and snippets.

@qichunren
Created February 27, 2012 08:16
Show Gist options
  • Save qichunren/1922490 to your computer and use it in GitHub Desktop.
Save qichunren/1922490 to your computer and use it in GitHub Desktop.
ruby china api
module RubyChina
class API < Grape::API
version 'v1', :using => :header, :vendor => 'ruby_china', :format => :json
helpers do
def warden
env['warden']
end
def authenticated
if warden.authenticate(:scope => :user)
return true
else
error!('401 Unauthorized', 401)
end
end
def current_user
warden.user
end
def is_admin?
current_user && current_user.admin?
end
# returns 401 if there's no current user
def authenticated_user
authenticated
error!('401 Unauthorized', 401) unless current_user
end
# returns 401 if not authenticated as admin
def authenticated_admin
authenticated
error!('401 Unauthorized', 401) unless is_admin?
end
end # end helper
resource :users do
# curl -d "user[login]=qichunren&user[password]=qichunren88" http://localhost:3000/api/v1/login
post "/login" do
warden.logout
warden.params[:controller] = "sessions"
if user = warden.authenticate(:scope => :user)
user.ensure_authentication_token!
{:user => {:display_name => user.email, :single_access_token => user.authentication_token, :updated_at => user.updated_at, :id => user.id }}
else
error!('401 Unauthorized', 401)
end
end
# LOGIN curl -d "user[login]=somelogin&user[password]=secartpwd" http://ruby-china.org/account/sign_in.json
# REGISTER curl -d "user[login]=hello_guest&user[password]=justpasserror&user[password_confirmation]=justpasserror&user[email][email protected]" http://localhost:3001/account.json
# GET http://localhost:3000/api/v1/users/actived
get "/actived" do
User.hot.limit(20)
end
# GET http://localhost:3000/api/v1/users/latest" do
get "/latest" do
User.recent.limit(20)
end
get "/:id" do
User.where(:login => /^#{params[:id]}$/i).first
end
get "/me" do
authenticated_user
current_user.as_json
end
end
resource :topics do
# GET http://localhost:3000/api/v1/topics/recent
get "/recent" do
@topics = Topic.recent.includes(:node,:user, :last_reply_user).paginate(:page => params[:page], :per_page => 50)
end
# GET http://localhost:3000/api/v1/topics/last_actived
get "/last_actived" do
@topics = Topic.last_actived.limit(15).includes(:node,:user, :last_reply_user)
end
end
resource :nodes do
get "/" do
@sections = Section.all
@sections.each do |section|
section.nodes
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment