summaryrefslogtreecommitdiff
path: root/app/controllers/api/users_controller.rb
blob: cb7b7bc7839ebab655c9aa46f920abb4b3567329 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
module Api
  class UsersController < ApiController
    include ControllerExtension::FetchUser

    # allow optional access to this controller using API auth tokens:
    before_filter :token_authenticate

    before_filter :fetch_user, :only => [:update, :destroy]
    before_filter :require_monitor, :only => [:index, :show]
    before_filter :require_login, :only => [:index, :update, :destroy]

    respond_to :json

    # used for autocomplete for admins in the web ui
    def index
      if params[:query]
        @users = User.login_starts_with(params[:query])
        respond_with @users.map(&:login).sort
      else
        render :json => {'error' => 'query required', 'status' => :unprocessable_entity}
      end
    end

    def show
      if params[:login]
        @user = User.find_by_login(params[:login])
      elsif params[:id]
        @user = User.find(params[:id])
      end
      if @user
        respond_with user_response
      else
        not_found
      end
    end

    def user_response
      @user.to_hash.tap do |user_hash|
        if @user == current_user
          user_hash['is_admin'] = @user.is_admin?
        end
      end
    end

    def create
      if current_user.is_monitor?
        create_test_account
      elsif APP_CONFIG[:allow_registration]
        create_account
      else
        head :forbidden
      end
    end

    def update
      @user.account.update user_update_params
      respond_with @user
    end

    def destroy
      @user.account.destroy(release_handles)
      if @user == current_user
        logout
      end
      render :json => {'success' => 'user deleted'}
    end

    private

    def user_update_params
      params.require(:user).permit :login,
        :password_verifier,
        :password_salt,
        :recovery_code_verifier,
        :recovery_code_salt,
        :public_key
    end

    def release_handles
      current_user.is_monitor? || params[:identities] == "destroy"
    end

    # tester auth can only create test users.
    def create_test_account
      if User::is_test?(params[:user][:login])
        @user = Account.create(params[:user], :invite_required => false)
        respond_with @user
      else
        head :forbidden
      end
    end

    def create_account
      if APP_CONFIG[:allow_registration]
        @user = Account.create(params[:user])
        respond_with @user # return ID instead?
      else
        head :forbidden
      end
    end

  end
end