forked from gotthardp/lorawan-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlorawan_admin_scopes.erl
More file actions
49 lines (39 loc) · 1.47 KB
/
lorawan_admin_scopes.erl
File metadata and controls
49 lines (39 loc) · 1.47 KB
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
%
% Copyright (c) 2016-2019 Petr Gotthard <[email protected]>
% All rights reserved.
% Distributed under the terms of the MIT License. See the LICENSE file.
%
-module(lorawan_admin_scopes).
-export([init/2]).
-export([allowed_methods/2]).
-export([is_authorized/2]).
-export([forbidden/2]).
-export([content_types_provided/2]).
-export([handle_get/2]).
-include("lorawan_db.hrl").
-record(state, {name, scopes, auth_fields}).
init(Req, Scopes) ->
Name = cowboy_req:binding(name, Req),
{cowboy_rest, Req, #state{name=Name, scopes=Scopes}}.
allowed_methods(Req, State) ->
{[<<"OPTIONS">>, <<"GET">>], Req, State}.
is_authorized(Req, #state{scopes=Scopes}=State) ->
case lorawan_admin:handle_authorization(Req, Scopes) of
{true, AuthFields} ->
{true, Req, State#state{auth_fields=AuthFields}};
Else ->
{Else, Req, State}
end.
forbidden(Req, #state{auth_fields=AuthFields}=State) ->
{lorawan_admin:fields_empty(AuthFields), Req, State}.
content_types_provided(Req, State) ->
{[
{{<<"application">>, <<"json">>, []}, handle_get}
], Req, State}.
handle_get(Req, #state{name=undefined}=State) ->
Scopes = lorawan_http_registry:get(scopes),
Req2 = cowboy_req:set_resp_header(<<"x-total-count">>, integer_to_binary(length(Scopes)), Req),
{jsx:encode([[{id, S}, {name, S}] || S <- Scopes]), Req2, State};
handle_get(Req, #state{name=Name}=State) ->
{jsx:encode([{name, Name}]), Req, State}.
% end of file