Skip to content

Commit

Permalink
Merge pull request #5 from osmus/dev
Browse files Browse the repository at this point in the history
Update login workflow
  • Loading branch information
Rub21 authored Jun 12, 2024
2 parents c577392 + 9de194c commit 0692b6a
Show file tree
Hide file tree
Showing 13 changed files with 162 additions and 221 deletions.
5 changes: 1 addition & 4 deletions dashboard-charts/templates/dashboard/configMap.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,9 @@ data:
SANDBOX_PG_DB_USER: {{ .Values.dashboard.env.SANDBOX_PG_DB_USER | quote }}
SANDBOX_PG_DB_PASSWORD: {{ .Values.dashboard.env.SANDBOX_PG_DB_PASSWORD | quote }}
SANDBOX_PG_DB_NAME: {{ .Values.dashboard.env.SANDBOX_PG_DB_NAME | quote }}
OSM_SANDBOX_CHART: {{ .Values.dashboard.env.OSM_SANDBOX_CHART | quote }}

# Domian
SANDBOX_DOMAIN: {{ .Values.dashboard.env.SANDBOX_DOMAIN | quote }}

# EKS
AWS_REGION: {{ .Values.dashboard.env.AWS_REGION | quote }}
EKS_CLUSTER: {{ .Values.dashboard.env.EKS_CLUSTER | quote }}

{{- end }}
17 changes: 2 additions & 15 deletions images/dashboard/src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@

# Import routes
from routes.stacks_route import router as stacks_route
from routes.oauth_route import router as oauth_route
from routes.main_route import router as main_route
from routes.login_route import router as login_route

app = FastAPI()
app.title = "OSM-Sandbox API User"
Expand All @@ -21,18 +20,6 @@
stacks_models.Base.metadata.create_all(bind=engine)
sessions_models.Base.metadata.create_all(bind=engine)


# Middleware to add unique ID cookie
@app.middleware("http")
async def add_unique_id_cookie(request: Request, call_next):
response = await call_next(request)
if "unique_id" not in request.cookies:
unique_id = str(uuid.uuid4())
response.set_cookie(key="unique_id", value=unique_id)
return response


# Include routes
app.include_router(main_route)
app.include_router(login_route)
app.include_router(stacks_route)
app.include_router(oauth_route)
106 changes: 106 additions & 0 deletions images/dashboard/src/routes/login_route.py
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)
61 changes: 0 additions & 61 deletions images/dashboard/src/routes/main_route.py

This file was deleted.

55 changes: 0 additions & 55 deletions images/dashboard/src/routes/oauth_route.py

This file was deleted.

1 change: 0 additions & 1 deletion images/dashboard/src/start.sh
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
101 changes: 38 additions & 63 deletions images/dashboard/src/templates/index.html
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>
5 changes: 1 addition & 4 deletions images/dashboard/src/utils/helm_deploy.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,4 @@ async def list_releases():
releases = await client.list_releases(all=True, all_namespaces=True)
for release in releases:
revision = await release.current_revision()
print(release.name, release.namespace, revision.revision, str(revision.status))

# if __name__ == "__main__":
# asyncio.run(list_releases())
print(release.name, release.namespace, revision.revision, str(revision.status))
1 change: 0 additions & 1 deletion images/dashboard/src/utils/osm_credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
osm_instance_url = os.getenv("OSM_INSTANCE_URL")
osm_instance_scopes = os.getenv("OSM_INSTANCE_SCOPES")


def get_osm_credentials():
"""Returns the OSM credentials"""
return client_id, client_secret, redirect_uri, osm_instance_url, osm_instance_scopes
Loading

0 comments on commit 0692b6a

Please sign in to comment.