Whats redirect URI in freelancer api OAuth? - freelancer.com-api

I cannot understand how this works:
from flask import Flask, redirect
oauth_uri = 'https://accounts.freelancer.com/oauth/authorise'
client_id = '<CLIENT_ID>'
redirect_uri = '<CLIENT_REDIRECT_URI>'
prompt = 'select_account consent'
advanced_scopes = '1 3'
app = Flask(__name__)
# Users who hit this endpoint will be redirected to the authorisation prompt
#app.route('/authorize')
def handle_authorize():
return redirect(
'{0}?response_type=code'
'&client_id={1}&redirect_uri={2}'
'&scope=basic&prompt={3}'
'&advanced_scopes={4}'.format(
oauth_uri, client_id, redirect_uri, prompt, advanced_scopes
)
)
This code gives me : Invalid redirect URI in browser.
Whats this redirect URI, why can't I give any redirect uri of my choice?
Its documented here: can anyone please explain to me how this works,
https://developers.freelancer.com/docs/authentication/generating-access-tokens#header-receive-authorisation-response

The redirect URL is the URL you set for your application on your apps dashboard. You need to specify a valid URL for Freelancer.com to redirect to after the user has granted access for your app. Think of how Facebook grants access to third party apps using their log in system.

Related

How will I pass parameters such as, user id in hyper link?

I have a HTML page where there is one hyperlink. This html email will be sent to users via outlook (I have written the mail function using flask python) and when users will click on hyperlink on the email body, it will eventually open another page. This page will be same but, the content of the page will be different for different users based on the users' email id.
Right now, my requirement is to pass the user email ID through hyperlink so, I can display different content based on email ID. Can it be done through hyperlink? As, you know that outlook uses Microsoft Word as rendering engine so, will it be difficult to pass parameter through hyperlink ?
Or, can I pass the email ID through my flask function while sending the mails?
My flask function which will send mail to outlook is below
from flask import Flask, render_template
from flask_mail import Mail, Message
app = Flask(__name__)
app.config.update(
DEBUG=True,
MAIL_SERVER='My Company SMTP MAIL SERVER',
MAIL_PORT=My Company SMTP PORT NUMBER,
# MAIL_USE_SSL=True,
MAIL_USERNAME='XXXXX.YYYY#mycompanyname.com',
)
mail = Mail(app)
#app.route('/')
def mailSend():
try:
recipeint_emails = fetch_recipient_emails
msg = Message("Send Mail Tutorial!",
sender="XXXXX.YYYY#mycompanyname.com",
recipients=recipeint_emails)
msg.html = render_template('linkPage.html')
mail.send(msg)
return 'Mail sent!'
except Exception as e:
print(type(e))
print(e)
return 'error'
The linkPage.html will contain the hyperlink which is mentioned below
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hyperlinkdemo</title>
</head>
<body>
Visit Dynamic Page
</body>
</html>
Any suggestion will be very helpful.
Flask has already a builtin function url_for to generate properly a link with extra parameters. Refer to this doc
UPDATE
it's recommended to choose the accurate name for routes
it's recommended to use snake_case when naming views
i recommend you to refer to the official Flask-Mail doc section Bulk Mail
#app.route('/bulk-email')
def bulk_mail():
[..]
# Get all users first
with mail.connect() as conn:
for user in users:
msg = Message(subject="Tutorial",
sender="XXXXX.YYYY#mycompanyname.com",
recipients=[user.email])
# pass dynamically the user to the template
msg.html = render_template('linkPpage.html', user=user)
conn.send(msg)
in linkPage.html template you can do
<p>Dear {{ user.username }},</p>
<p>
Open Link tutorial
</p> //added double quotation
you have to implement the logic of link_tutorial function, when user click on the link it will be redirected to your app to show him a customized page / tutorial:
#app.route('/link-tutorial/<int:user_id>')
def link_tutorial(user_id):
# fetch the user with the given user_id and render the right template for him.
[..]
return render_template('tutorial.html')
finally, i would recommend you using celery an asynchronous task queue to handle the bulk email more efficiently than Flask-Mail, because sending mail is a blocking task and your app will be very slow and not responsive.

Accessing Google API from a web application

I've been trying for a couple of days now to crack this but have not had any success.
I have a web application that I want to use with Google Drives API.
I want the web application to check if there is an access token it can use and if not redirect to Google so the user can log in and grant access.
Seemingly a simple task but it's driving me mad! I've checked the Google documentation but it all seems to be geared around console applications
Google provides an interface UserService which stores details of the users using the application. If the users is not logged in redirect the user to login page using:
response.sendRedirect(userService.createLoginURL(request.getRequestURI()))
Later or if the user is logged in, redirect him to "Request for Permission" page using:
List<String> scopes = Arrays.asList(PlusScopes.PLUS_LOGIN,PlusScopes.PLUS_ME,PlusScopes.USERINFO_EMAIL,PlusScopes.USERINFO_PROFILE......); // Add/remove scopes as per your requirement
List<String> responseTypes = Arrays.asList("code");
GoogleAuthorizationCodeRequestUrl gAuthCode = new GoogleAuthorizationCodeRequestUrl(Google project client id, redirect url, scopes);
gAuthCode.setAccessType("offline");
gAuthCode.setClientId(Google project client id);
gAuthCode.setResponseTypes(responseTypes);
gAuthCode.setApprovalPrompt("force");
authURl = gAuthCode.toURL().toString();
response.sendRedirect(authURl);
Make sure you add all required scopes of the API methods you will be using. After the user has accepted, you will have to create a servlet with "/oauth2callback" mapping to get the authorization code.
request.getParameter("code")
In the same servlet using the code obtained, get refresh and access token making a rest call.
URL url = new URL("https://www.googleapis.com/oauth2/v3/token");
HttpURLConnection connection= (HttpURLConnection)url.openConnection();
connection.setRequestMethod("post");
connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream dw= new DataOutputStream(connection.getOutputStream());
dw.writeBytes("code="+authorizationCode+"&client_id="+CLIENT_ID+"&client_secret="+CLIENT_SECRET+"&redirect_uri="+REDIRECT_URL+"&grant_type=authorization_code");
dw.flush();
dw.close();
InputStream inputStream= connection.getInputStream();
Parse the input stream to get your refresh token and access token and redirect the user to your landing page.
Now you have access token to query your api whose scopes were provided in authorization flow. Also you have a refresh token which can be used to regenerate new access token if the previously issued access token has expired.
You should be able to implement the OAuthHandshake using HTTP requests and a redirect URL to your web application. You can play around with the requests here to see what the headers and responses look like: https://developers.google.com/oauthplayground/
You can store the authorization code and tokens any way you like. You would have your web application refer to these tokens to see if they are expired. For example:
def getTokenFromFile(self):
creds = self.readCredsFromDisk()
# check if token is expired
expiration_time = datetime.datetime.strptime(creds['token_expiry'], '"%Y-%m-%dT%H:%M:%S.%f"')
if expiration_time < datetime.datetime.now():
self.refreshToken()
# reload creds
creds = self.readCredsFromDisk()
return creds['access_token']
I'm writing just a python script that does the handshake and saves the token to a plain text file. Any time the script runs a function to the Google API it will use this function.
The refresh function:
def refreshToken(self):
with open('client_secret.json') as s:
secret = json.load(s)
secret = secret['installed']
creds = self.readCredsFromDisk()
refresh_url = secret['token_uri']
post_data = {'client_id':secret['client_id'],
'client_secret':secret['client_secret'],
'refresh_token':creds['refresh_token'],
'grant_type':'refresh_token'}
headers = {'Content-type':'application/x-www-form-urlencoded'}
(resp, content) = self.http.request(refresh_url,
method='POST',
body=urlencode(post_data),
headers=headers)
content = json.loads(content)
creds['access_token'] = content['access_token']
date = datetime.datetime.now() + datetime.timedelta(seconds=content['expires_in'])
creds['token_expiry'] = json.dumps(date.isoformat())
self.writeCredsToDisk(json.dumps(creds))
You would write a function similar to this to trade the original authorization code and access code following the logic the OAuth Playground shows you.

Cannot access the Box Application using API Key

I have created an application in Box and got an API Key, and then edited the redirect URL. But when I accessed through URL https://www.box.net/api/1.0/rest?action=get_ticket&api_key=APIKEY, I'm not getting a positive response, instead of I'm getting a response like:
<response>
<status>application_restricted</status>
</response>
Please provide me a solution to get access to the application.
Thanks in advance.
The V1 API has been deprecated and will no longer provide authentication or file access. You need to migrate your application to the V2 API, which is documented here.
For accessing access_token using java sdk , You need to have following key values
1) clienId > Use Application console
2) client_secret > Use application console
3) code > Code value you will get using below link
https://account.box.com/api/oauth2/authorize?response_type=code&client_id={your_client_id}&state=security_token%3DKnhMJatFipTAnM0nHlZA
Replace your client id with original value. client id you will get from your apps.
And Follow steps and authorize you application using your credential.
after that it will redirect to https://localhost/?state=security_token%3DKnhMJatFipTAnM0nHlZA&code=sdsdsd3sdsdC0oGqOS2WgaFipZBdj
Copy code value
String clienId = "your client id ";
String client_secret = "your secret id";
String code = "sdsdsd3sdsdC0oGqOS2WgaFipZBdj"; // use above extracted code value
BoxAPIConnection con = new BoxAPIConnection(clienId,client_secret,code);
String accessToken = con.getAccessToken();
System.out.println("Accss_Token : " +accessToken);

Invalid Redirect URL in Google Drive

When i am entering http://mydomain.com in Google Drive Redirect URL then getting:
Invalid Redirect URL
Please let me know what is the issue ?
I am referring to the console, where you create and get your keys for your projects:
https://cloud.google.com/console
Your URL to localhost is the box "Redirect URIs"
In your code, then you have:
$redirectURI = 'http://localhost';
$client = new Google_Client();
// Get your credentials from the console
$client->setClientId($clientID);
$client->setClientSecret($clientSecret);
$client->setRedirectUri($redirectURI);
$client->setScopes(array('https://www.googleapis.com/auth/drive.file'));
These must match, or you'll get this error every time.

How to programmatically get access_token with authorization_code from BOX?

after reading the oauth documentation on box's website, I understand the steps to get access_token and refresh_token, which requires authorization_code.
step1: send Get request to https://www.box.com/api/oauth2/authorize?response_type=code&client_id=CLIENT_ID&state=authenticated&redirect_uri=https://www.appfoo.com
step2: after entering credentials of box in browser and then click the "Allow" button, redirect to the specified redirect_uri with state=authenticated&code=AUTHORIZATION_CODE
step3: now with the AUTHORIZATION_CODE in the redirect url from step2, getting access_token can be done programmatically, by sending POST request to https://www.box.com/api/oauth2/token with AUTHORIZATION_CODE, client_id, client_secret in body and then parsing the returned json response.
My question is: is it possible to programmatically do step1 and step2 instead of via browser?
thank you very much!
The current OAuth 2 flow requires the user to go through the browser and can't be done programmatically.
It is possible, just imitate every form with cURL and on second step post cookies.
First time you will need 3 requests, next time only one (if refresh_token isn't expired, otherwise 3 again)
The point about imitating the browser transactions is a good one but instead of using cURL you would want to use a higher level tool like mechanize (available for ruby, perl and python). It will handle the cookies for you and can programatically traverse forms and links. Good for page scraping and writing scripts to order hot concert tickets from TicketMaster too!
If you have the authorization code, you then should be able to get the OAuth Token(access_token, refresh_token) via SDK, correct?
In response to aIKid, this is what I first do to get a BoxClient
BoxClient client = new BoxClient(clientId, clientSecret);
Map<String,Object> authToken = new HashMap<String,Object>();
authToken.put("exprires_in","3600");
authToken.put( "token_type","bearer");
authToken.put("refresh_token", clientRefreshToken);
authToken.put("access_token",clientAccessToken);
BoxOAuthToken oauthToken = new BoxOAuthToken(authToken);
client.authenticate(oauthToken);
return client;
Then, I have this to create a new user,
BoxUser createdUser = new BoxUser();
BoxUserRequestObject createUserRequest = BoxUserRequestObject.createEnterpriseUserRequestObject("someEmail.domain.com", "test user");
createdUser = client.getUsersManager().createEnterpriseUser(createUserRequest);
Now I'm trying to figure out how to do the RUD part of my CRUD operations on users and groups.