Skip to content

Instantly share code, notes, and snippets.

@pikajude
Created June 11, 2011 23:30
Show Gist options
  • Select an option

  • Save pikajude/1021083 to your computer and use it in GitHub Desktop.

Select an option

Save pikajude/1021083 to your computer and use it in GitHub Desktop.
module(..., package.seeall)
require("luarocks.require")
local socket = require("socket")
local https = require("ssl.https")
local oauth = {}
function oauth.spawn_server()
oauth.serv = socket.bind("127.0.0.1", 12345)
end
function oauth.cleanup ()
oauth.serv:close()
oauth.serv = nil
end
function oauth.getcode ()
oauth.spawn_server()
print("Please log in on deviantART to the account that this bot will use.")
print("Once you have done that, please authorize orange at http://bit.ly/lwXFS6.")
local client = oauth.serv:accept()
local line = ""
local code = nil
repeat
line = client:receive("*l")
code = line:match("code=(%d+)")
until code ~= nil
local fh = assert(io.open("lib/oauth_greet.html", "r"))
local html = fh:read("*a")
fh:close()
local resp = {
"HTTP/1.0 200 OK",
"Date: " .. os.date("%a, %d %b %Y %H:%M:%S GMT"),
"Content-Type: text/html",
"Content-Length: " .. html:len(),
"",
html,
""
}
client:send(table.concat(resp, "\r\n"))
client:close()
oauth.cleanup()
return code
end
function oauth.getaccesstoken (code)
local body, respcode, headers = https.request("https://www.deviantart.com/oauth2/draft15/token", "client_id=29&client_secret=cd0df3d5ce2bea758e73d927474462e8&code=" .. code .. "&grant_type=authorization_code")
return body:match('"access_token":"(%x+)"')
end
function oauth.token_is_valid (token)
local body = https.request("https://www.deviantart.com/api/draft15/placebo?access_token=" .. token)
return body == '{"status":"success"}'
end
function oauth.gettoken (token)
if not oauth.token_is_valid(token) then
error("invalid oauth token")
end
local body = https.request("https://www.deviantart.com/api/draft15/user/damntoken", "access_token=" .. token)
return (body:gsub("\"", ""))
end
function oauth.getuname (token)
local body = https.request("https://www.deviantart.com/api/draft15/user/whoami", "access_token=" .. token)
return (body:gsub("\"", ""))
end
function oauth.fromscratch ()
return oauth.gettoken(oauth.getaccess(oauth.getcode()))
end
return oauth
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment