|
| 1 | +# Example server with Flask demonstrating use of OAuth 2.0. Server |
| 2 | +# needs to be deployed. Example code is requesting access token from |
| 3 | +# Bitbucket. User has to grant access rights. After authorization the |
| 4 | +# token and the available workspaces are returned. |
| 5 | + |
| 6 | +from requests_oauthlib import OAuth2Session |
| 7 | +from atlassian.bitbucket.cloud import Cloud |
| 8 | +from flask import Flask, request, redirect, session |
| 9 | + |
| 10 | +app = Flask(__name__) |
| 11 | +app.secret_key = "" |
| 12 | + |
| 13 | +# Bitbucket OAuth URLs |
| 14 | +authorization_base_url = "https://bitbucket.org/site/oauth2/authorize" |
| 15 | +token_url = "https://bitbucket.org/site/oauth2/access_token" |
| 16 | + |
| 17 | +# 1. Create OAuth consumer |
| 18 | +# Go to "Your profile and setting" -> "All workspaces" -> "Manage". |
| 19 | +# Go to "Apps and features" -> "OAuth consumers". |
| 20 | +# Click "Add consumer". Fill in Name and Callback URL. Set permissions |
| 21 | +# as needed. Click save and copy client id and secret. |
| 22 | +client_id = "" |
| 23 | +client_secret = "" |
| 24 | + |
| 25 | + |
| 26 | +# 2. Redirect to Bitbucket for authorization |
| 27 | +# The server request to {server_url}/login is redirected to Bitbucket. |
| 28 | +# The user is asked to grant access permissions. |
| 29 | +@app.route("/login") |
| 30 | +def login(): |
| 31 | + bitbucket = OAuth2Session(client_id) |
| 32 | + authorization_url, state = bitbucket.authorization_url(authorization_base_url) |
| 33 | + session["oauth_state"] = state |
| 34 | + return redirect(authorization_url) |
| 35 | + |
| 36 | + |
| 37 | +# 3. Bitbucket sends callback with token |
| 38 | +# Bitbucket is calling the Callback URL specified in the OAuth |
| 39 | +# consumer. This should be set to {server_url}/callback. The callback |
| 40 | +# contains the access token. |
| 41 | +@app.route("/callback") |
| 42 | +def callback(): |
| 43 | + bitbucket = OAuth2Session(client_id, state=session["oauth_state"]) |
| 44 | + token = bitbucket.fetch_token(token_url, client_secret=client_secret, authorization_response=request.url) |
| 45 | + |
| 46 | + return "Token: {}<p />Workspaces: {}".format(token, ", ".join(get_workspaces(token))) |
| 47 | + |
| 48 | + |
| 49 | +# 4. Token used for Bitbucket Python API |
| 50 | +# Bitbucket Cloud API library is called with token information. User is |
| 51 | +# authenticated with OAuth 2.0. |
| 52 | +def get_workspaces(token): |
| 53 | + oauth2 = {"client_id": client_id, "token": token} |
| 54 | + |
| 55 | + bitbucket = Cloud(url="https://api.bitbucket.org/", oauth2=oauth2, cloud=True) |
| 56 | + |
| 57 | + return [ws.name for ws in bitbucket.workspaces.each()] |
0 commit comments