This repository has been archived by the owner on Aug 13, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
EvernoteOAuth.lua
372 lines (318 loc) · 9.76 KB
/
EvernoteOAuth.lua
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
local random = math.random
local socket = require('socket')
local url = require('socket.url')
local http = require('socket.http')
local https = require('ssl.https')
local ltn12 = require('ltn12')
--local inspect = require('inspect')
--[[
-- Cookie helper functions from: https://github.com/diegonehab/luasocket/
--]]
local token_class = '[^%c%s%(%)%<%>%@%,%;%:%\\%"%/%[%]%?%=%{%}]'
local function unquote(t, quoted)
local n = string.match(t, "%$(%d+)$")
if n then n = tonumber(n) end
if quoted[n] then return quoted[n]
else return t end
end
local function parse_set_cookie(c, quoted, cookie_table)
c = c .. ";$last=last;"
local _, __, n, v, i = string.find(c, "(" .. token_class ..
"+)%s*=%s*(.-)%s*;%s*()")
local cookie = {
name = n,
value = unquote(v, quoted),
attributes = {}
}
while 1 do
_, __, n, v, i = string.find(c, "(" .. token_class ..
"+)%s*=?%s*(.-)%s*;%s*()", i)
if not n or n == "$last" then break end
cookie.attributes[#cookie.attributes+1] = {
name = n,
value = unquote(v, quoted)
}
end
cookie_table[#cookie_table+1] = cookie
end
local function split_set_cookie(s, cookie_table)
cookie_table = cookie_table or {}
-- remove quoted strings from cookie list
local quoted = {}
s = string.gsub(s, '"(.-)"', function(q)
quoted[#quoted+1] = q
return "$" .. #quoted
end)
-- add sentinel
s = s .. ",$last="
-- split into individual cookies
i = 1
while 1 do
local _, __, cookie, next_token
_, __, cookie, i, next_token = string.find(s, "(.-)%s*%,%s*()(" ..
token_class .. "+)%s*=", i)
if not next_token then break end
parse_set_cookie(cookie, quoted, cookie_table)
if next_token == "$last" then break end
end
return cookie_table
end
local function quote(s)
if string.find(s, "[ %,%;]") then return '"' .. s .. '"'
else return s end
end
local _empty = {}
local function build_cookies(cookies)
s = ""
for i,v in ipairs(cookies or _empty) do
if v.name and v.name ~= "$last" then
s = s .. v.name
if v.value and v.value ~= "" then
s = s .. '=' .. quote(v.value)
end
s = s .. "; "
end
end
return s
end
--[[
-- Gist source: https://gist.github.com/jrus/3197011
--]]
local function uuid4()
math.randomseed(os.time())
local template ='xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'
return string.gsub(template, '[xy]', function (c)
local v = (c == 'x') and random(0, 0xf) or random(8, 0xb)
return string.format('%x', v)
end)
end
local OAuth = {
domain,
username,
password,
code,
logger = print,
urlPath = {
oauth = "/OAuth.action?oauth_token=",
access = "/OAuth.action",
token = "/oauth",
login = "/OAuth.action",
tfa = "/OTCAuth.action",
},
postData = {
login = {
login = 'Sign+in',
username = '',
password = '',
targetUrl = nil,
},
access = {
authorize = 'Authorize',
oauth_token = nil,
oauth_callback = nil,
embed = 'false',
},
tfa = {
code = '',
login = 'Sign+in',
},
},
cookies = {},
tmpOAuthToken,
verifierToken,
OAuthToken,
incorrectLogin = 0,
incorrectCode = 0,
}
function OAuth:new(o)
o = o or {}
setmetatable(o, self)
self.__index = self
if o.init then o:init() end
return o
end
function OAuth:init()
local config = require('EvernoteConfig')
if self.domain then
self.baseUrl = config["BASE_URL_"..self.domain:upper()]
self.consumer_key = config["CONSUMER_KEY_"..self.domain:upper()]
self.signature = config["CONSUMER_SECRET_"..self.domain:upper()]
else
self.baseUrl = config.BASE_URL
self.consumer_key = config.CONSUMER_KEY
self.signature = config.CONSUMER_SECRET
end
end
function OAuth:getTokenQueryData(args)
local data = {
oauth_consumer_key = self.consumer_key,
oauth_signature = self.signature,
oauth_signature_method = 'PLAINTEXT',
oauth_timestamp = tostring(os.time()),
oauth_nonce = uuid4()
}
for k,v in pairs(args or {}) do
data[k] = v
end
return data
end
function OAuth:loadPage(method, path, params, data)
local request, headers, sink = {}, {}, {}
-- Build query string
local query = ""
for k,v in pairs(data) do
query = query .. k .. '=' .. v .. '&'
end
-- Write URL
local parsed = url.parse(self.baseUrl)
parsed.path = path
parsed.params = params
parsed.query = method == "GET" and query or nil
parsed.protocol = "sslv23"
-- Write headers
headers['cookie'] = build_cookies(self.cookies)
if method == "POST" then
headers["content-type"] = "application/x-www-form-urlencoded"
headers["content-length"] = string.len(query)
end
-- HTTP request
request['url'] = url.build(parsed)
request['method'] = method
request['source'] = method == "POST" and ltn12.source.string(query) or nil
request['sink'] = ltn12.sink.table(sink)
request['headers'] = headers
self.logger(request)
http.TIMEOUT, https.TIMEOUT = 10, 10
local httpRequest = parsed.scheme == 'http' and http.request or https.request
local code, headers, status = socket.skip(1, httpRequest(request))
self.logger("Evernote received response: ")
self.logger("Response code: ", code)
self.logger("Response headers: ", headers)
-- raise error message when page cannot be loaded
if headers == nil and code then
error(code)
end
-- Update cookies
local cookies = split_set_cookie(headers['set-cookie'] or "")
for lk,lv in pairs(cookies) do
for sk,sv in pairs(self.cookies) do
if lv.name == sv.name then
self.cookies[sk] = lv
cookies[lk] = nil
end
end
table.insert(self.cookies, cookies[lk])
end
return code, headers['location'], table.concat(sink)
end
function OAuth:parseResponse(content)
local response = {}
for item in (content.."&"):gmatch("(.-)&") do
local _, _, key, val = item:find("(.+)%s*=%s*(.+)")
if key then response[key] = url.unescape(val or "") end
end
return response
end
function OAuth:getTmpOAuthToken()
self.logger("Evernote - getTempOAuthToken request:")
local code, _, content = self:loadPage(
"GET", self.urlPath['token'], nil,
self:getTokenQueryData({ oauth_callback = self.baseUrl }))
if code ~= 200 then
error("Unexpected response status to get temp oauth token", code)
end
local response = self:parseResponse(content)
if not response.oauth_token then
error("Temporary OAuth token not found")
end
self.tmpOAuthToken = response.oauth_token
return self.tmpOAuthToken
end
function OAuth:getCookie(name)
for _,v in ipairs(self.cookies) do
if v.name == name then return v.value end
end
end
function OAuth:login()
local code, _, response = self:loadPage("GET", self.urlPath['login'], nil,
{ oauth_token = self.tmpOAuthToken })
if code ~= 200 then
error("Unexpected response code to login", code)
end
self.jsessionid = self:getCookie('JSESSIONID')
if not self.jsessionid then
error("No JSESSIONID value in the response cookies")
end
local target_url = url.escape(self.urlPath['oauth'])..self.tmpOAuthToken
self.postData['login']['username'] = self.username
self.postData['login']['password'] = self.password
self.postData['login']['targetUrl'] = target_url
self.postData['login']['hpts'] = response:match('%("hpts"%)%.value.-"(.-)"')
self.postData['login']['hptsh'] = response:match('%("hptsh"%)%.value.-"(.-)"')
self.logger("Evernote - login request:")
local code, loc, content = self:loadPage("POST",
self.urlPath['login'], "jsessionid="..self.jsessionid,
self.postData['login'])
if not loc and code == 200 then
if self.incorrectLogin < 3 then
print("Sorry, incorrect username or password")
self.incorrectLogin = self.incorrectLogin + 1
return self:login()
else
error("Incorrect username or password")
end
end
if not loc then
error("Target URL was not found in the response on login")
end
return true
end
function OAuth:_getCsrfToken()
self.logger("Evernote - _getCsrfToken request:")
local code, _, content = self:loadPage("GET",
self.urlPath['access'], nil, {oauth_token = self.tmpOAuthToken})
return content
end
function OAuth:allowAccess()
local content = self:_getCsrfToken()
self.postData.access.oauth_token = self.tmpOAuthToken
self.postData.access.oauth_callback = self.baseUrl
self.postData.access.csrfBusterToken = content:match('"csrfBusterToken" value="(.-)"')
self.logger("Evernote - allowAccess request:")
local code, loc, content = self:loadPage(
"POST", self.urlPath['access'], nil, self.postData.access)
if code ~= 302 then
error("Unexpected response status on allowing access", code)
end
local location = self:parseResponse(loc)
if not location['oauth_verifier'] then
error("OAuth verifier not found")
end
self.verifierToken = location['oauth_verifier']
return self.verifierToken
end
function OAuth:getOAuthToken()
self.logger("Evernote - getOAuthToken request:")
local code, _, content = self:loadPage("GET", self.urlPath['token'], nil,
self:getTokenQueryData({
oauth_token = self.tmpOAuthToken,
oauth_verifier = self.verifierToken
}))
if code ~= 200 then
error("Unexpected response status on getting oauth token", code)
end
local response = self:parseResponse(content)
if not response['oauth_token'] then
error("OAuth token not found")
end
self.OAuthToken = response['oauth_token']
return self.OAuthToken
end
function OAuth:getToken()
if self.OAuthToken then return self.OAuthToken end
self:getTmpOAuthToken()
self:login()
self:allowAccess()
return self:getOAuthToken()
end
return OAuth