summaryrefslogtreecommitdiffstats
path: root/server.lua
blob: 0bd555363b2136e072510222192d3c0f46a0b8be (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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
--[[
Copyright (c) 2012-2013 Kaarle Ritvanen
See LICENSE file for license details
--]]

require 'acf'
local isinstance = acf.object.isinstance

require 'json'
require 'stringy'


math.randomseed(os.time())

-- TODO shared storage for sessions
-- TODO expire stale sessions
local sessions = {}


return function(env)
	  local method = env.REQUEST_METHOD
	  local path = env.REQUEST_URI

	  local function wrap(code, headers, res)
	     if not headers then headers = {} end

	     local ctype
	     if type(res) == 'table' then
		ctype = 'application/json'
		res = json.encode(res)
	     else
		ctype = 'text/plain'
		if not res then res = '' end
	     end
	     headers['Content-Type'] = ctype

	     return code, headers, coroutine.wrap(
		function() coroutine.yield(res) end
	     )
	  end

	  local data
	  if env.CONTENT_LENGTH then
	     local success
	     success, data = pcall(
		json.decode,
		env.input:read(env.CONTENT_LENGTH)
	     )
	     if not success then
		return wrap(400, nil, 'Request not in JSON format')
	     end
	  end

	  local sid = tonumber(env.HTTP_X_ACF_AUTH_TOKEN)
	  local session, user, txn_id
	  if sid then
	     session = sessions[sid]
	     if not session then return wrap(401) end
	     user = session.user
	     txn_id = tonumber(env.HTTP_X_ACF_TRANSACTION_ID)
	  end

	  local parent_txn
	  if txn_id then
	     parent_txn = session.txns[txn_id]
	     if not parent_txn then
		return wrap(400, nil, 'Invalid transaction ID')
	     end
	  end
	  local txn = acf.transaction.start(parent_txn, true)

	  local function fetch_user(name)
	     user = name and txn:search('/auth/users')[name]
	  end
	  if user then
	     fetch_user(user)
	     if not user then return wrap(401) end
	  end

	  if path == '/login' then
	     if method == 'POST' then
		if not data.username or not data.password then
		   return wrap(401)
		end
		fetch_user(data.username)
		if user and user:check_password(data.password) then
		   local sid
		   repeat
		      sid = math.floor(math.random() * 2^32)
		   until not sessions[sid]

		   sessions[sid] = {user=data.username, last_txn_id=0, txns={}}
		   return wrap(204, {['X-ACF-Auth-Token']=sid})
		end
		return wrap(401)
	     end

	     if not user then return wrap(401) end

	     if method == 'DELETE' then
		sessions[sid] = nil
		return wrap(204)
	     end

	     return wrap(405)
	  end

	  if not user then return wrap(401) end

	  local success, code, hdr, res = acf.call(
	     function()
		if stringy.startswith(path, '/config/') then
		   path = string.sub(path, 8, -1)
		   
		   local parent, name
		   if path ~= '/' then
		      parent = txn:search(acf.path.parent(path))
		      name = acf.path.name(path)
		   end
		   
		   if method == 'GET' then
		      local obj = txn:search(path)
		      if obj == nil then return 404 end
		      
		      local res

		      if isinstance(obj, acf.model.node.TreeNode) then
			 local node = {}
			 for _, k in ipairs(acf.model.node.members(obj)) do
			    local v = obj[k]
			    if isinstance(v, acf.model.node.TreeNode) then
			       v = acf.model.node.path(v)
			    end
			    node[k] = v
			 end
			 res = {data=node, meta=acf.model.node.meta(obj)}
		   
		      else
			 res = {
			    data=obj,
			    meta=acf.model.node.mmeta(parent, name)
			 }
		      end

		      return 200, nil, res
		   end

		   -- TODO implement POST for invoking object-specific actions
		   if method == 'DELETE' then parent[name] = nil
		   elseif method == 'PUT' then parent[name] = data
		   else return 405 end
		   
		   txn:commit()
		   return 205
		end

		if path == '/' then
		   if method == 'GET' then
		      return 301, {['Location']='/browser/'}
		   end
	     
		   if ({DELETE=true, PUT=true})[method] then
		      if not txn_id then return 405 end
		      if method == 'PUT' then parent_txn:commit() end
		      session.txns[txn_id] = nil
		      return 204
		   end

		   if method ~= 'POST' then return 405 end

		   session.last_txn_id = session.last_txn_id + 1
		   local txn_id = session.last_txn_id
		   session.txns[txn_id] = acf.transaction.start(parent_txn)
		   return 204, {['X-ACF-Transaction-ID']=txn_id}
		end

		return 404
	     end
	  )

	  if success then return wrap(code, hdr, res) end

	  if code.conflict then return wrap(409, nil, code.conflict) end
	  
	  return wrap(422, nil, code)
       end