Skip to content

feat: adds user authentication #218

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 21 commits into from
Jun 3, 2025
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .flake8
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,7 @@
exclude =
.git,
__pycache__,
build
build,
venv,
.venv
max-complexity = 10
3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@ server = [
'wtforms',
'requests==2.25.0',
'openpyxl',
'python-logging-loki'
'python-logging-loki',
'authlib'
]

[tool.setuptools.packages.find]
Expand Down
84 changes: 73 additions & 11 deletions src/aind_data_transfer_service/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@
from pydantic import SecretStr, ValidationError
from starlette.applications import Starlette
from starlette.routing import Route
from starlette.middleware.sessions import SessionMiddleware
from starlette.config import Config
from starlette.responses import RedirectResponse
from authlib.integrations.starlette_client import OAuth, OAuthError

from aind_data_transfer_service import OPEN_DATA_BUCKET_NAME
from aind_data_transfer_service.configs.csv_handler import map_csv_row_to_job
Expand Down Expand Up @@ -77,6 +81,7 @@

logger = get_logger(log_configs=LoggingConfigs())
project_names_url = os.getenv("AIND_METADATA_SERVICE_PROJECT_NAMES_URL")
AIND_SSO_SECRET_NAME = os.getenv('AIND_SSO_SECRET_NAME')


def get_project_names() -> List[str]:
Expand All @@ -88,6 +93,32 @@ def get_project_names() -> List[str]:
return project_names


def set_oauth() -> OAuth:
"""Set up OAuth for the service"""
secrets_client = boto3.client('secretsmanager')
try:
secret_response = secrets_client.get_secret_value(
SecretId=AIND_SSO_SECRET_NAME
)
secret_value = json.loads(secret_response["SecretString"])
except ClientError as e:
return {"error": f"{e.__class__.__name__}{e.args}"}
for secrets in secret_value:
os.environ[secrets] = secret_value[secrets]
config = Config()
oauth = OAuth(config)
oauth.register(
name='azure',
client_id=config("CLIENT_ID"),
client_secret=config("CLIENT_SECRET"),
server_metadata_url=config("AUTHORITY"),
client_kwargs={
'scope': 'openid email profile'
}
)
return oauth


async def validate_csv(request: Request):
"""Validate a csv or xlsx file. Return parsed contents as json."""
logger.info("Received request to validate csv")
Expand Down Expand Up @@ -796,17 +827,20 @@ async def jobs(request: Request):

async def job_params(request: Request):
"""Get Job Parameters page"""
return templates.TemplateResponse(
name="job_params.html",
context=(
{
"request": request,
"project_names_url": os.getenv(
"AIND_METADATA_SERVICE_PROJECT_NAMES_URL"
),
}
),
)
user = request.session.get('user')
if user:
return templates.TemplateResponse(
name="job_params.html",
context=(
{
"request": request,
"project_names_url": os.getenv(
"AIND_METADATA_SERVICE_PROJECT_NAMES_URL"
),
}
),
)
return RedirectResponse(url='/login')


async def download_job_template(_: Request):
Expand Down Expand Up @@ -904,6 +938,31 @@ def get_parameter(request: Request):
)


async def login(request: Request):
"""Redirect to Azure login page"""
oauth = set_oauth()
redirect_uri = request.url_for('auth')
return await oauth.azure.authorize_redirect(request, redirect_uri)


async def auth(request: Request):
"""Authenticate user and store user info in session"""
oauth = set_oauth()
try:
token = await oauth.azure.authorize_access_token(request)
except OAuthError as error:
return JSONResponse(
content={
"message": "Error Logging In",
"data": {"error": f"{error.__class__.__name__}{error.args}"},
},
status_code=500,
)
user = token.get('userinfo')
if user:
request.session['user'] = dict(user)
return RedirectResponse(url='/')

routes = [
Route("/", endpoint=index, methods=["GET", "POST"]),
Route("/api/validate_csv", endpoint=validate_csv_legacy, methods=["POST"]),
Expand Down Expand Up @@ -937,6 +996,9 @@ def get_parameter(request: Request):
endpoint=download_job_template,
methods=["GET"],
),
Route("/login", login, methods=["GET"]),
Route("/auth", auth, methods=["GET"])
]

app = Starlette(routes=routes)
app.add_middleware(SessionMiddleware, secret_key=None)
3 changes: 2 additions & 1 deletion src/aind_data_transfer_service/templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@
<a href="/job_params">Job Parameters</a> |
<a title="Download job template as .xslx" href= "/api/job_upload_template" download>Job Submit Template</a> |
<a title="List of project names" href= "{{ project_names_url }}" target="_blank" >Project Names</a> |
<a title="For more information click here" href="https://aind-data-transfer-service.readthedocs.io" target="_blank" >Help</a>
<a title="For more information click here" href="https://aind-data-transfer-service.readthedocs.io" target="_blank" >Help</a> |
<a href="/login">Sign-In</a>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add the Sign-In button to the navbar in the other pages? Namely, the Job Status and Job Params pages.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not entirely sure if the Sign-In button is necessary, as it's kind of doesn't add anything. I am actually thinking to remove it. @jtyoung84?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Replaced with button for Admin page instead

</nav>
<br>
<div>
Expand Down
Loading