Commit 4ad91d3c1144c406e50c7b33bae684bd6837faf8

Authored by Nihad Abbasov
1 parent 4aca61e8

add users API

lib/api.rb
1   -class Gitlab::API < Grape::API
  1 +require 'api/entities'
  2 +require 'api/helpers'
  3 +
  4 +module Gitlab
  5 + class API < Grape::API
  6 + format :json
  7 + helpers APIHelpers
  8 +
  9 + resource :users do
  10 + before { authenticate! }
  11 +
  12 + # GET /users
  13 + get do
  14 + @users = User.all
  15 + present @users, :with => Entities::User
  16 + end
  17 +
  18 + # GET /users/:id
  19 + get ":id" do
  20 + @user = User.find(params[:id])
  21 + present @user, :with => Entities::User
  22 + end
  23 + end
  24 +
  25 + # GET /user
  26 + get "/user" do
  27 + authenticate!
  28 + present @current_user, :with => Entities::User
  29 + end
  30 + end
2 31 end
... ...
lib/api/entities.rb 0 → 100644
... ... @@ -0,0 +1,8 @@
  1 +module Gitlab
  2 + module Entities
  3 + class User < Grape::Entity
  4 + expose :id, :email, :name, :bio, :skype, :linkedin, :twitter,
  5 + :dark_scheme, :theme_id, :blocked, :created_at
  6 + end
  7 + end
  8 +end
... ...
lib/api/helpers.rb 0 → 100644
... ... @@ -0,0 +1,11 @@
  1 +module Gitlab
  2 + module APIHelpers
  3 + def current_user
  4 + @current_user ||= User.find_by_authentication_token(params[:private_token])
  5 + end
  6 +
  7 + def authenticate!
  8 + error!('401 Unauthorized', 401) unless current_user
  9 + end
  10 + end
  11 +end
... ...
spec/api/users_spec.rb 0 → 100644
... ... @@ -0,0 +1,38 @@
  1 +require 'spec_helper'
  2 +
  3 +describe Gitlab::API do
  4 + let(:user) { Factory :user }
  5 +
  6 + describe "GET /users" do
  7 + it "should return authentication error" do
  8 + get "/api/users"
  9 + response.status.should == 401
  10 + end
  11 +
  12 + describe "authenticated GET /users" do
  13 + it "should return an array of users" do
  14 + get "/api/users?private_token=#{user.private_token}"
  15 + response.status.should == 200
  16 + json = JSON.parse(response.body)
  17 + json.should be_an Array
  18 + json.first['email'].should == user.email
  19 + end
  20 + end
  21 + end
  22 +
  23 + describe "GET /users/:id" do
  24 + it "should return a user by id" do
  25 + get "/api/users/#{user.id}?private_token=#{user.private_token}"
  26 + response.status.should == 200
  27 + JSON.parse(response.body)['email'].should == user.email
  28 + end
  29 + end
  30 +
  31 + describe "GET /user" do
  32 + it "should return current user" do
  33 + get "/api/user?private_token=#{user.private_token}"
  34 + response.status.should == 200
  35 + JSON.parse(response.body)['email'].should == user.email
  36 + end
  37 + end
  38 +end
... ...
spec/spec_helper.rb
... ... @@ -58,4 +58,8 @@ RSpec.configure do |config|
58 58 config.after do
59 59 DatabaseCleaner.clean
60 60 end
  61 +
  62 + config.include RSpec::Rails::RequestExampleGroup, :type => :request, :example_group => {
  63 + :file_path => /spec\/api/
  64 + }
61 65 end
... ...