-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #5 from osmus/dev
Update login workflow
- Loading branch information
Showing
13 changed files
with
162 additions
and
221 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,106 @@ | ||
import os | ||
from fastapi import APIRouter, Depends, HTTPException, Query, Request, Form | ||
from fastapi.staticfiles import StaticFiles | ||
from fastapi.templating import Jinja2Templates | ||
from sqlalchemy.orm import Session | ||
from fastapi.responses import JSONResponse, RedirectResponse | ||
from requests_oauthlib import OAuth2Session | ||
import uuid | ||
|
||
# Import database utils | ||
from database import get_db | ||
|
||
# Import utils | ||
from utils.osm_credentials import get_osm_credentials | ||
from utils.sandbox_sessions import save_update_stack_session, update_user_session | ||
from utils.sandbox_database import save_user_sandbox_db | ||
|
||
( | ||
client_id, | ||
client_secret, | ||
redirect_uri, | ||
osm_instance_url, | ||
osm_instance_scopes, | ||
) = get_osm_credentials() | ||
|
||
router = APIRouter() | ||
|
||
domain = os.getenv("SANDBOX_DOMAIN") | ||
|
||
oauth = OAuth2Session( | ||
client_id=client_id, redirect_uri=redirect_uri, scope=osm_instance_scopes | ||
) | ||
|
||
# Custom static files to set cache control | ||
class CustomStaticFiles(StaticFiles): | ||
async def get_response(self, path: str, scope): | ||
response = await super().get_response(path, scope) | ||
response.headers["Cache-Control"] = "public, max-age=86400" | ||
return response | ||
|
||
|
||
static_path = os.path.join(os.path.dirname(__file__), "./../static") | ||
router.mount("/static", CustomStaticFiles(directory=static_path), name="static") | ||
|
||
templates_path = os.path.join(os.path.dirname(__file__), "./../templates") | ||
templates = Jinja2Templates(directory=templates_path) | ||
|
||
|
||
@router.get("/login_sandbox", tags=["OSM Sandbox"]) | ||
def test_page(request: Request, stack: str = Query(None), db: Session = Depends(get_db)): | ||
"""Page for login test""" | ||
return templates.TemplateResponse("index.html", {"request": request}) | ||
|
||
@router.get("/osm_authorization", tags=["OSM Sandbox"]) | ||
def osm_authorization(request: Request, stack: str = Query(...), db: Session = Depends(get_db)): | ||
"""Enable OSM authorization""" | ||
|
||
cookie_id = request.cookies.get("cookie_id") | ||
|
||
if cookie_id is None: | ||
# Generate a new cookie_id | ||
cookie_id = str(uuid.uuid4()) | ||
response = RedirectResponse(url=request.url) | ||
response.set_cookie(key="cookie_id", value=cookie_id) | ||
return response | ||
|
||
if cookie_id and stack: | ||
save_update_stack_session(db, cookie_id, stack) | ||
auth_url = f"{osm_instance_url}/oauth2/authorize?response_type=code&client_id={client_id}&redirect_uri={redirect_uri}&scope={osm_instance_scopes}" | ||
return RedirectResponse(url=auth_url, status_code=303) | ||
else: | ||
raise HTTPException(status_code=404, detail="stack or cookie_id not found") | ||
|
||
|
||
@router.get("/redirect_sandbox", tags=["OSM Sandbox"]) | ||
async def redirect_sandbox(request: Request, code: str, db: Session = Depends(get_db)): | ||
"""Redirect and login in sandbox""" | ||
|
||
try: | ||
## Get user data | ||
token = oauth.fetch_token( | ||
f"{osm_instance_url}/oauth2/token", code=code, client_secret=client_secret | ||
) | ||
oauth.token = token | ||
user_details_response = oauth.get( | ||
f"{osm_instance_url}/api/0.6/user/details.json" | ||
) | ||
user_details = user_details_response.json() | ||
display_name = user_details.get("user").get("display_name") | ||
# languages = user_details.get("user").get("languages") | ||
|
||
cookie_id = request.cookies.get("cookie_id") | ||
if cookie_id: | ||
session_obj = update_user_session(db, cookie_id, display_name) | ||
save_user_sandbox_db(session_obj.get("stack"), session_obj.get("user")) | ||
# Construct the subdomain URL | ||
stack = session_obj.get("stack") | ||
user = session_obj.get("user") | ||
sub_domain_url = f"https://{stack}.{domain}/login?user={user}" # noqa: E231 | ||
return RedirectResponse(url=sub_domain_url) | ||
else: | ||
raise HTTPException(status_code=404, detail="Check if instance exist") | ||
|
||
except Exception as e: | ||
print(f"Error: {e}") | ||
return JSONResponse(content={"error": str(e)}, status_code=400) |
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,2 @@ | ||
#!/usr/bin/env bash | ||
aws eks update-kubeconfig --region ${AWS_REGION} --name ${EKS_CLUSTER} | ||
uvicorn main:app --host 0.0.0.0 --port 8000 --reload |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,69 +1,44 @@ | ||
<!DOCTYPE html> | ||
<html lang="en"> | ||
<head> | ||
<meta charset="UTF-8" /> | ||
<title>OpenStreetMap Sandbox</title> | ||
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> | ||
<style> | ||
body { | ||
margin: 0; | ||
height: 100vh; | ||
width: 100vw; | ||
} | ||
.modal { | ||
position: absolute; | ||
top: 0; | ||
left: 0; | ||
width: 100%; | ||
height: 100%; | ||
display: flex; | ||
align-items: center; | ||
justify-content: center; | ||
background-color: rgba(0, 0, 0, 0.3); | ||
visibility: visible; | ||
} | ||
button { | ||
padding: 10px 20px; | ||
font-size: 16px; | ||
cursor: pointer; | ||
color: white; | ||
background-color: #007bff; | ||
border: none; | ||
border-radius: 5px; | ||
} | ||
</style> | ||
<meta charset="UTF-8"> | ||
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | ||
<title>Login Sandbox</title> | ||
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"> | ||
</head> | ||
<body> | ||
<div class="modal"> | ||
<button onclick="startAuth()">Login with OpenStreetMap</button> | ||
</div> | ||
|
||
<script> | ||
const client_id = "{{client_id}}"; | ||
const redirect_uri = "{{redirect_uri}}"; | ||
const osm_instance_scopes = "{{osm_instance_scopes}}"; | ||
const osm_instance_url = "{{osm_instance_url}}"; | ||
|
||
function startAuth() { | ||
saveStack() | ||
const authUrl = `${osm_instance_url}/oauth2/authorize?response_type=code&client_id=${client_id}&redirect_uri=${redirect_uri}&scope=${osm_instance_scopes}`; | ||
console.log(`Redirecting to: ${authUrl}`); | ||
window.location.href = authUrl; | ||
} | ||
|
||
function saveStack() { | ||
const stack = "{{stack}}"; | ||
localStorage.setItem('stack', stack); | ||
} | ||
|
||
function loadStack() { | ||
const stack = localStorage.getItem('stack'); | ||
if (stack) { | ||
document.querySelector('.modal div').innerHTML = stack; | ||
} | ||
} | ||
|
||
document.addEventListener('DOMContentLoaded', loadStack); | ||
</script> | ||
<div class="container mt-5"> | ||
<div class="row justify-content-center"> | ||
<div class="col-md-6"> | ||
<div class="card"> | ||
<div class="card-header"> | ||
<h3 class="card-title">Login OSM Sandbox</h3> | ||
</div> | ||
<div class="card-body"> | ||
<form id="loginForm"> | ||
<div class="form-group"> | ||
<label for="stack">Stack:</label> | ||
<input type="text" class="form-control" id="stack" name="stack" value="osm" required> | ||
</div> | ||
<button type="submit" class="btn btn-primary btn-block">Login with OpenStreetMap</button> | ||
</form> | ||
</div> | ||
</div> | ||
</div> | ||
</div> | ||
</div> | ||
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script> | ||
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.4/dist/umd/popper.min.js"></script> | ||
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> | ||
<script> | ||
document.getElementById('loginForm').addEventListener('submit', function(event) { | ||
event.preventDefault(); | ||
const stack = document.getElementById('stack').value; | ||
localStorage.setItem('stack', stack); | ||
const queryString = new URLSearchParams({ stack }).toString(); | ||
const url = `/osm_authorization?${queryString}`; | ||
window.location.href = url; | ||
}); | ||
</script> | ||
</body> | ||
</html> | ||
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.