How can I access a raw private paste from pastebin? - lua

I know how to generate a user key using the pastebin API, but how can I use this userkey to access a raw private paste?
I am using Lua for this.

Obtaining the raw paste bin output is not part of of the Pastebin API:
This option is actually not part of our API, but you might still want to use it. To get the RAW output of a paste you can use our RAW data output URL:
http://pastebin.com/raw.php?i=
Simply add the paste_key at the end of that URL and you will get the RAW output.
Since private pastes can only be seen by the user who created them, my guess is that they use the logincookie for authentication. In that case, you'll need to send it with the HTTP request.
In respect to implementing this in Lua, (since you haven't said which library you're using) I'm gonna go forth and recommend the HTTP module in LuaSocket or the wonderful Luvit (http://luvit.io).

Here is a ready example of the code for you:
local https = require('ssl.https')
https.TIMEOUT= 15
local private_raw_url="https://pastebin.com/raw/YOURPAGE" -- Change raw link
local user_name, user_password = "USER", "PASS" -- and user with password
local request_body = "submit_hidden=submit_hidden&user_name=".. user_name .. "&user_password=" .. user_password .. "&submit=Login"
local resp = {}
local res, code, headers, status = https.request ( {
method = 'POST',
url = "https://pastebin.com/login",
headers = {
Host = "pastebin.com",
["Content-Type"] = "application/x-www-form-urlencoded",
["Content-Length"] = string.len(request_body),
Connection = "keep-alive",
},
source = ltn12.source.string(request_body),
sink = ltn12.sink.table(resp),
protocol = "tlsv1",
verify = "none",
verifyext = {"lsec_continue", "lsec_ignore_purpose"},
options = { "all", "no_sslv2", "no_sslv3" }
} )
if not headers['set-cookie']:find('pastebin_user') then
print('bad login')
return
end
resp={}
local cookie = headers['set-cookie'] or ''
local cookie1, cookie2, cookie3 = cookie:match("(__cfduid=%w+; ).*(PHPSESSID=%w+; ).*(pastebin_user=%w+; )" )
if cookie1 and cookie2 and cookie3 then
cookie = cookie1 .. cookie2 .. cookie3
body, code, headers= https.request{
url = private_raw_url ,
headers = {
--Host = "pastebin.com",
['Cookie'] = cookie,
['Connection'] = 'keep-alive'
},
sink = ltn12.sink.table(resp)
}
if code~=200 then return end
print( table.concat(resp) )
else
print("error match cookies!" )
end

I know that this is a little late to answer the question but I hope this will help someone later on.
If you want to access raw private pastes, you will first need to list the pastes that the user has created. This is a part of the API. This requires the user to be logged in.
With this API you can list all the pastes created by a certain user.
You will need send a valid POST request to the URL below to access the
data:
http://pastebin.com/api/api_post.php
The response that you will get will be an XML response, as follows:
<paste>
<paste_key>0b42rwhf</paste_key>
<paste_date>1297953260</paste_date>
<paste_title>javascript test</paste_title>
<paste_size>15</paste_size>
<paste_expire_date>1297956860</paste_expire_date>
<paste_private>0</paste_private>
<paste_format_long>JavaScript</paste_format_long>
<paste_format_short>javascript</paste_format_short>
<paste_url>http://pastebin.com/0b42rwhf</paste_url>
<paste_hits>15</paste_hits>
</paste>
Once you have that, parse the XML to get the paste_key and the paste_private. You need to check the value of paste_private because you want private pastes only. The documentation says:
We have 3 valid values available which you can use with the
'api_paste_private' parameter:
0 = Public
1 = Unlisted
2 = Private (only allowed in combination with api_user_key, as you have to be logged into your account to access the paste)
So, if your paste has paste_private set to 2, get the paste_key for it.
Once you have the paste_key, use the API call to get the RAW paste. No username or password required once you have the paste key for the private paste.
Have fun!

Related

How to retrieve Slack messages via API identified by permalink?

I'm trying to retrieve a list of Slack reminders, which works fine using Slack API's reminders.list method. However, reminders that are set using SlackBot (i.e. by asking Slackbot to remind me of a message) return the respective permalink of that message as text:
{
"ok": true,
"reminders": [
{
"id": "Rm012C299C1E",
"creator": "UV09YANLX",
"text": "https:\/\/team.slack.com\/archives\/DUNB811AM\/p1583441290000300",
"user": "UV09YANLX",
"recurring": false,
"time": 1586789303,
"complete_ts": 0
},
Instead of showing the permalink, I'd naturally like to show the message I wanted to be reminded of. However, I couldn't find any hints in the Slack API docs on how to retrieve a message identified by a permalink. The link is presumably generated by chat.getPermalink, but there seems to be no obvious chat.getMessageByPermalink or so.
I tried to interpet the path elements as channel and timestamp, but the timestamp (transformed from the example above: 1583441290.000300) doesn't seem to really match. At least I don't end up with the message I expected to retrieve when passing this as latest to conversations.history and limiting to 1.
After fiddling a while longer, here's how I finally managed in JS:
async function downloadSlackMsgByPermalink(permalink) {
const pathElements = permalink.substring(8).split('/');
const channel = pathElements[2];
var url;
if (permalink.includes('thread_ts')) {
// Threaded message, use conversations.replies endpoint
var ts = pathElements[3].substring(0, pathElements[3].indexOf('?'));
ts = ts.substring(0, ts.length-6) + '.' + ts.substring(ts.length-6);
var latest = pathElements[3].substring(pathElements[3].indexOf('thread_ts=')+10);
if (latest.indexOf('&') != -1) latest = latest.substring(0, latest.indexOf('&'));
url = `https://slack.com/api/conversations.replies?token=${encodeURIComponent(slackAccessToken)}&channel=${channel}&ts=${ts}&latest=${latest}&inclusive=true&limit=1`;
} else {
// Non-threaded message, use conversations.history endpoint
var latest = pathElements[3].substring(1);
if (latest.indexOf('?') != -1) latest = latest.substring(0, latest.indexOf('?'));
latest = latest.substring(0, latest.length-6) + '.' + latest.substring(latest.length-6);
url = `https://slack.com/api/conversations.history?token=${encodeURIComponent(slackAccessToken)}&channel=${channel}&latest=${latest}&inclusive=true&limit=1`;
}
const response = await fetch(url);
const result = await response.json();
if (result.ok === true) {
return result.messages[0];
}
}
It's not been tested to the latest extend, but first results look alright:
The trick with the conversations.history endpoint was to include the inclusive=true parameter
Messages might be threaded - the separate endpoint conversations.replies is required to fetch those
As the Slack API docs state: ts and thread_ts look like timestamps, but they aren't. Using them a bit like timestamps (i.e. cutting off some characters at the back and inserting a dot) seems to work, gladly, however.
Naturally, the slackAccessToken variable needs to be set beforehand
I'm aware the way to extract & transform the URL components in the code above might not the most elegant solution, but it proves the concept :-)

upload doc on dropbox how to get url

How to get URL uploaded doc on drop box and how to store this URL our data base.
This is the code :
def passport_upload
app_key = ENV['APP_DROPBOX_APP_KEY_DEVELOPMENT']
app_secret = ENV['APP_DROPBOX_APP_SECRET_DEVELOPMENT']
flow = DropboxOAuth2FlowNoRedirect.new(app_key, app_secret)
authorize_url = flow.start()
client=DropboxClient.new(ENV['APP_DROPBOX_ACCESS_TOKEN_DEVELOPMENT'])
file = open(params[:doc])
file_name = params[:doc].original_filename
response = client.put_file(file_name, file)
end
If you want the URL to retrieve it using authorized access, you should appending the path returned in the metadata response to https://content.dropboxapi.com/1/files/auto/ (per https://www.dropbox.com/developers-v1/core/docs#files-GET).
If you want to publicly share it and get a public URL you will have to
make a call to share it (per https://www.dropbox.com/developers-v1/core/docs#shares)
client.shares(response.path)

How can I integrate ASP pages and queries into an iOS app?

I have a rather puzzling scenario right now, of figuring out how to integrate several large queries (many different items for each) into an iOS app that communicates with a C#-based REST API. I am trying to pull up several reports in the app, and if I recreate all these queries within the API along with recreating the interface in iOS, it could be quite time-consuming. The page that accesses the reports is a classic ASP page and includes a security header to ensure that the user session has been validated through the login page. Is there a way to set this up as a UIWebView and somehow validate a session upon loading of the UIWebView? Otherwise it will be quite a long, arduous process.
Could a cookie possibly be transferred over after the user has logged in using NSURLRequest to the UIWebView?
Each page has code to check if the session is authenticated
<%
if Session("portallogin") <> "good" then
response.redirect("example.com")
end if
%>
Here is some of the relevant login code that is responsible for initial authentication
'Get the username and password sent as well as user ip
On Error resume next
Session("login") = "bad" 'init to bad
sent_username = Request("username")
sent_password = Request("password")
source = Request.form("source")
remember_me = Request("remember_me")
userip = Request.ServerVariables("REMOTE_ADDR")
sent_username = replace(sent_username,"'","'")
sent_username = protectval(sent_username)
sent_password = protectval(sent_password)
if rs.BOF and rs.EOF then
Session("login") = "bad"
response.cookies("user")("name") = ""
response.Cookies("user")("pword") = ""
else
arr = rs.GetRows()
password = arr(0,0)
memberid = arr(1,0)
expired = arr(2,0)
if sent_password = password then
Session("login") = "good"
if expired = "True" Then
%>
'''''''''''''''''''
if session is good
'''''''''''''''''''
Session("username") = sent_username
Session("maintuser") = sent_username
Session("b2buser") = sent_username
Session("password") = sent_password
Session("memberid") = memberid
Session("customernumber") = customernumber
Session("cno") = cno
Session("login") = "good"
if remember_me = "on" Then
response.cookies("entry")("doorway") = cook(sent_username)
response.Cookies("entry")("michael") = cook(sent_password)
response.Cookies("entry")("remember_me") = cook("CHECKED")
Response.Cookies("entry").Expires = Now() + 365
else
response.cookies("entry")("doorway") = ""
response.Cookies("entry")("michael") = ""
response.Cookies("entry")("remember_me") = ""
Response.Cookies("entry").Expires = Now() + 5
end if
As most of the parameters reference the Request collection you could put the parameters in the querystring and thus make them part of the base url for UIWebView. So your URL request would look like
file.asp?username=xxx&password=yyy&source=zzz&remember_me=on
you would need to change line 7 in your sample file to be
source = Request("source")
but it would still work for existing requests.
The obvious problem with this code is that you have a username and password stored in your app which could be intercepted and abused. So be aware of that. I would not recommend this approach.
A better solution would be to consider rewriting the login function to store a temporary GUID and a timestamp in the database which could then be passed in the request as part of the querystring. Your authentication code could then be modified to check if that GUID is valid and update the timestamp associated with the GUID (or check for the session if they are using the old access method for that page).

using python to send POST request

I'm trying to send a POST request to a site (https://get.cbord.com/dartmouth/full/login.php) to log in. I think I'm running into issues with the format of the data I'm passing in, but truthfully I'm just getting started so I don't understand this very well. I tried deciphering the POST request using Chrome dev tools and this is what I came up with.
#!/usr/bin/env python
import requests
import sys
EMAIL = 'xxx'
PASSWORD = 'xxx'
LOGIN_URL = 'https://get.cbord.com/dartmouth/full/login.php'
FULL_URL = 'https://get.cbord.com/dartmouth/full/funds_home.php'
def main():
# Start a session so we can have persistant cookies
#session = requests.session(config={'verbose': sys.stderr})
session = requests.session()
# This is the form data that the page sends when logging in
login_data = {
'username': EMAIL,
'password': PASSWORD,
'submit': 'Login',
}
# Authenticate
r = session.post(LOGIN_URL, data=login_data)
# Try accessing a page that requires you to be logged in
r = session.get(FULL_URL)
if __name__ == '__main__':
main()
The majority of the code is directly copy pasted from a response to a similar question. I guess I just don't understand how to figure out what the login_data dictionary should be.
Thanks for the help!
Pat
I examined this page and found that there is one more parameter: formToken.
You can get its value from webpage source. It looks like these
So first you need to get https://get.cbord.com/dartmouth/full/login.php page
login_page = session.get(LOGIN_URL)
login_page_text = login_page.text
then parse the page to retrieve formToken value from it and finally authenticate
login_data = {
'username': EMAIL,
'password': PASSWORD,
'submit': 'Login',
'formToken': formToken_value
}
# Authenticate
r = session.post(LOGIN_URL, data=login_data)

Google Docs: Cannot export/download user's document using administrative access/impersonation (forbidden 403) in python

I have read this thoroughly: https://developers.google.com/google-apps/documents-list/#using_google_apps_administrative_access_to_impersonate_other_domain_users
I have googled this to death.
So far I have been able to:
Authorise with:
clientLogin
OAuth tokens (using my domain key)
retrieve document feeds for all users in the domain (authorised either way in #1)
I am using the "entry" from the feed to Export/Download documents and always get forbidden for other users for documents not shared with admin. The feed query I am using is like:
https://docs.google.com/feeds/userid#mydomain.com/private/full/?v=3
(I have tried with and without the ?v=3)
I have also tried adding the xoauth_requestor_id (which I have also seen in posts as xoauth_requestor), both on the uri, and as a client property: client.xoauth_requestor_id = ...
Code fragments:
Client Login (using administrator credentials):
client.http_client.debug = cfg.get('HTTPDEBUG')
client.ClientLogin( cfg.get('ADMINUSER'), cfg.get('ADMINPASS'), 'HOSTED' )
OAuth:
client.http_client.debug = cfg.get('HTTPDEBUG')
client.SetOAuthInputParameters( gdata.auth.OAuthSignatureMethod.HMAC_SHA1, cfg.get('DOMAIN'), cfg.get('APPS.SECRET') )
oatip = gdata.auth.OAuthInputParams( gdata.auth.OAuthSignatureMethod.HMAC_SHA1, cfg.get('DOMAIN'), cfg.get('APPS.SECRET') )
oat = gdata.auth.OAuthToken( scopes = cfg.get('APPS.%s.SCOPES' % section), oauth_input_params = oatip )
oat.set_token_string( cfg.get('APPS.%s.TOKEN' % section) )
client.current_token = oat
Once the feed is retrieved:
# pathname eg whatever.doc
client.Export(entry, pathname)
# have also tried
client.Export(entry, pathname, extra_params = { 'v': 3 } )
# and tried
client.Export(entry, pathname, extra_params = { 'v': 3, 'xoauth_requestor_id': 'admin#mydomain.com' } )
Any suggestions, or pointers as to what I am missing here?
Thanks
You were very close to having a correct implementation. In your example above, you had:
client.Export(entry, pathname, extra_params = { 'v': 3, 'xoauth_requestor_id': 'admin#mydomain.com' } )
xoauth_requestor_id must be set to the user you're impersonating. Also what you need is to use 2-Legged OAuth 1.0a with the xoauth_requestor_id set either in the token or in the client.
import gdata.docs.client
import gdata.gauth
import tempfile
# Replace with values from your Google Apps domain admin console
CONSUMER_KEY = ''
CONSUMER_SECRET = ''
# Set this to the user you're impersonating, NOT the admin user
username = 'userid#mydomain.com'
destination = tempfile.mkstemp()
token = gdata.gauth.TwoLeggedOAuthHmacToken(
consumer_key, consumer_secret, username)
# Setting xoauth_requestor_id in the DocsClient constructor is not required
# because we set it in the token above, but I'm showing it here in case your
# token is constructed via some other mechanism and you need another way to
# set xoauth_requestor_id.
client = gdata.docs.client.DocsClient(
auth_token=token, xoauth_requestor_id=username)
# Replace this with the resource your application needs
resource = client.GetAllResources()[0]
client.DownloadResource(resource, path)
print 'Downloaded %s to %s' % (resource.title.text, destination)
Here is the reference in the source code to the TwoLeggedOAuthHmacToken class:
http://code.google.com/p/gdata-python-client/source/browse/src/gdata/gauth.py#1062
And here are the references in the source code that provide the xoauth_requestor_id constructor parameter (read these in order):
http://code.google.com/p/gdata-python-client/source/browse/src/atom/client.py#42
http://code.google.com/p/gdata-python-client/source/browse/src/atom/client.py#179
http://code.google.com/p/gdata-python-client/source/browse/src/gdata/client.py#136

Resources