Skip to content

Commit

Permalink
Merge pull request #136 from AstreaTSS/improve-auth-scripts
Browse files Browse the repository at this point in the history
Improve authentication scripts
  • Loading branch information
omarryhan authored Jan 21, 2024
2 parents c0b8d69 + 84ff21c commit 1adfda4
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 41 deletions.
43 changes: 23 additions & 20 deletions examples/auth/oauth2.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@
import sys
import webbrowser

from sanic import Sanic, response
from sanic.exceptions import ServerError
from aiohttp.web import RouteTableDef, Application, run_app, Response, json_response, HTTPFound

from aiogoogle import Aiogoogle
from aiogoogle.auth.utils import create_secret
Expand All @@ -13,6 +12,7 @@
import yaml
except: # noqa: E722 bare-except
print('couldn\'t import yaml. Install "pyyaml" first')
sys.exit(-1)

sys.path.append("../..")

Expand All @@ -35,9 +35,9 @@


LOCAL_ADDRESS = "localhost"
LOCAL_PORT = "5000"
LOCAL_PORT = 5000

app = Sanic(__name__)
routes = RouteTableDef()
aiogoogle = Aiogoogle(client_creds=CLIENT_CREDS)

# ----------------------------------------#
Expand All @@ -47,7 +47,7 @@
# ----------------------------------------#


@app.route("/authorize")
@routes.get("/authorize")
def authorize(request):
if aiogoogle.oauth2.is_ready(CLIENT_CREDS):
uri = aiogoogle.oauth2.authorization_url(
Expand All @@ -59,9 +59,9 @@ def authorize(request):
prompt="select_account",
)
# Step A
return response.redirect(uri)
raise HTTPFound(uri)
else:
raise ServerError("Client doesn't have enough info for Oauth2")
return Response(text="Client doesn't have enough info for Oauth2", status=500)


# ----------------------------------------------#
Expand All @@ -83,29 +83,32 @@ def authorize(request):
# Step C
# Google should redirect current_user to
# this endpoint with a grant code
@app.route("/callback/aiogoogle")
@routes.get("/callback/aiogoogle")
async def callback(request):
if request.args.get("error"):
if request.query.get("error"):
error = {
"error": request.args.get("error"),
"error_description": request.args.get("error_description"),
"error": request.query.get("error"),
"error_description": request.query.get("error_description"),
}
return response.json(error)
elif request.args.get("code"):
returned_state = request.args["state"][0]
return json_response(error)
elif request.query.get("code"):
returned_state = request.query["state"]
# Check state
if returned_state != state:
raise ServerError("NO")
return Response(text="NO", status=500)
# Step D & E (D send grant code, E receive token info)
full_user_creds = await aiogoogle.oauth2.build_user_creds(
grant=request.args.get("code"), client_creds=CLIENT_CREDS
grant=request.query.get("code"), client_creds=CLIENT_CREDS
)
return response.json(full_user_creds)
return json_response(full_user_creds)
else:
# Should either receive a code or an error
return response.text("Something's probably wrong with your callback")
return Response(text="Something's probably wrong with your callback", status=400)


if __name__ == "__main__":
webbrowser.open("http://" + LOCAL_ADDRESS + ":" + LOCAL_PORT + "/authorize")
app.run(host=LOCAL_ADDRESS, port=LOCAL_PORT, debug=True)
app = Application()
app.add_routes(routes)

webbrowser.open("http://" + LOCAL_ADDRESS + ":" + str(LOCAL_PORT) + "/authorize")
run_app(app, host=LOCAL_ADDRESS, port=LOCAL_PORT)
45 changes: 24 additions & 21 deletions examples/auth/openid_connect.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@
import webbrowser
import pprint

from sanic import Sanic, response
from sanic.exceptions import ServerError
from aiohttp.web import RouteTableDef, Application, run_app, Response, json_response, HTTPFound

from aiogoogle import Aiogoogle
from aiogoogle.auth.utils import create_secret
Expand All @@ -14,6 +13,7 @@
import yaml
except: # noqa: E722 bare-except
print('couldn\'t import yaml. Install "pyyaml" first')
sys.exit(-1)

sys.path.append("../..")

Expand All @@ -40,9 +40,9 @@


LOCAL_ADDRESS = "localhost"
LOCAL_PORT = "5000"
LOCAL_PORT = 5000

app = Sanic(__name__)
routes = RouteTableDef()
aiogoogle = Aiogoogle(client_creds=CLIENT_CREDS)

# ----------------------------------------#
Expand All @@ -52,7 +52,7 @@
# ----------------------------------------#


@app.route("/authorize")
@routes.get("/authorize")
def authorize(request):
if aiogoogle.openid_connect.is_ready(CLIENT_CREDS):
uri = aiogoogle.openid_connect.authorization_url(
Expand All @@ -65,9 +65,9 @@ def authorize(request):
prompt="select_account",
)
# Step A
return response.redirect(uri)
raise HTTPFound(uri)
else:
raise ServerError("Client doesn't have enough info for Oauth2")
return Response(text="Client doesn't have enough info for Oauth2", status=500)


# ----------------------------------------------#
Expand All @@ -89,35 +89,38 @@ def authorize(request):
# Step C
# Google should redirect current_user to
# this endpoint with a grant code
@app.route("/callback/aiogoogle")
@routes.get("/callback/aiogoogle")
async def callback(request):
if request.args.get("error"):
if request.query.get("error"):
error = {
"error": request.args.get("error"),
"error_description": request.args.get("error_description"),
"error": request.query.get("error"),
"error_description": request.query.get("error_description"),
}
return response.json(error)
elif request.args.get("code"):
returned_state = request.args["state"][0]
return json_response(error)
elif request.query.get("code"):
returned_state = request.query["state"]
# Check state
if returned_state != state:
raise ServerError("NO")
return Response(text="NO", status=500)
# Step D & E (D send grant code, E receive token info)
full_user_creds = await aiogoogle.openid_connect.build_user_creds(
grant=request.args.get("code"),
grant=request.query.get("code"),
client_creds=CLIENT_CREDS,
nonce=nonce,
verify=False,
)
full_user_info = await aiogoogle.openid_connect.get_user_info(full_user_creds)
return response.text(
f"full_user_creds: {pprint.pformat(full_user_creds)}\n\nfull_user_info: {pprint.pformat(full_user_info)}"
return Response(
text=f"full_user_creds: {pprint.pformat(full_user_creds)}\n\nfull_user_info: {pprint.pformat(full_user_info)}"
)
else:
# Should either receive a code or an error
return response.text("Something's probably wrong with your callback")
return Response(text="Something's probably wrong with your callback", status=400)


if __name__ == "__main__":
webbrowser.open("http://" + LOCAL_ADDRESS + ":" + LOCAL_PORT + "/authorize")
app.run(host=LOCAL_ADDRESS, port=LOCAL_PORT, debug=True)
app = Application()
app.add_routes(routes)

webbrowser.open("http://" + LOCAL_ADDRESS + ":" + str(LOCAL_PORT) + "/authorize")
run_app(app, host=LOCAL_ADDRESS, port=LOCAL_PORT)
1 change: 1 addition & 0 deletions examples/auth/openid_connect_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import yaml
except: # noqa: E722 bare-except
print('couldn\'t import yaml. Install "pyyaml" first')
sys.exit(-1)

sys.path.append("../..")

Expand Down

0 comments on commit 1adfda4

Please sign in to comment.