Skip to content
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

123 backend migration cleanup #124

Merged
merged 2 commits into from
Nov 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
17 changes: 17 additions & 0 deletions api/src/main.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import logging
from typing import Optional

from fastapi import Body, Depends, FastAPI, HTTPException
from src import activities, auth_manager, supabase_client
Expand Down Expand Up @@ -118,3 +119,19 @@ async def get_weekly_summaries(
except Exception as e:
logger.error(f"Failed to get weekly summaries: {e}", exc_info=True)
raise HTTPException(status_code=400, detail=str(e))


@app.post("/authenticate/")
async def authenticate(code: str, email: Optional[str] = None) -> dict:
"""
Authenticate with Strava code and sign up new users

:param code: Strava authorization code
:param email: User's email (optional)
:return: Dictionary with success status, JWT token and new user flag
"""
try:
return auth_manager.authenticate_on_signin(code=code, email=email)
except Exception as e:
logger.error(f"Authentication failed: {e}", exc_info=True)
raise HTTPException(status_code=400, detail=str(e))
7 changes: 1 addition & 6 deletions lambda/src/lambda_function.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,7 @@ def strategy_router(event: dict) -> dict:
only present if success is False
"""

if event.get("code"):
return auth_manager.authenticate_on_signin(
code=event["code"], email=event.get("email")
)

elif event.get("jwt_token") and event.get("method"):
if event.get("jwt_token") and event.get("method"):
return frontend_router.handle_request(
jwt_token=event["jwt_token"],
method=event["method"],
Expand Down
4 changes: 2 additions & 2 deletions mobile/mobile/APIManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ class APIManager {
session = URLSession(configuration: config)
}

private let session: URLSession
internal let session: URLSession
private let baseURL = "https://lwg77yq7dd.execute-api.us-east-1.amazonaws.com/prod/signup"
private let apiURL = "http://trackflow-alb-499532887.us-east-1.elb.amazonaws.com"
internal let apiURL = "http://trackflow-alb-499532887.us-east-1.elb.amazonaws.com"

// new request functions

Expand Down
39 changes: 29 additions & 10 deletions mobile/mobile/StravaAuthManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -41,35 +41,54 @@ class StravaAuthManager: ObservableObject {

Task {
do {
let url = URL(string: "https://lwg77yq7dd.execute-api.us-east-1.amazonaws.com/prod/signup")!
guard let url = URL(string: "\(APIManager.shared.apiURL)/authenticate/") else {
throw NSError(
domain: "AuthError", code: 0, userInfo: [NSLocalizedDescriptionKey: "Invalid URL"])
}

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let payload = ["code": code]
request.httpBody = try JSONSerialization.data(withJSONObject: payload)

let (data, _) = try await URLSession.shared.data(for: request)
let response = try JSONDecoder().decode(SignupResponse.self, from: data)
let (data, response) = try await APIManager.shared.session.data(for: request)

if response.success {
UserDefaults.standard.set(response.jwt_token, forKey: "jwt_token")
if let httpResponse = response as? HTTPURLResponse,
!(200..<300).contains(httpResponse.statusCode)
{
throw NSError(
domain: "AuthError",
code: httpResponse.statusCode,
userInfo: [NSLocalizedDescriptionKey: "Authentication failed"]
)
}

let authResponse = try JSONDecoder().decode(SignupResponse.self, from: data)

if authResponse.success {
UserDefaults.standard.set(authResponse.jwt_token, forKey: "jwt_token")
DispatchQueue.main.async {
self.appState.jwtToken = response.jwt_token
if let isNewUser = response.is_new_user, isNewUser {
self.appState.jwtToken = authResponse.jwt_token
if let isNewUser = authResponse.is_new_user, isNewUser {
self.appState.status = .newUser
} else {
self.appState.status = .loggedIn
}
}
} else {
throw NSError(
domain: "AuthError", code: 0,
userInfo: [NSLocalizedDescriptionKey: "Verification failed"]
domain: "AuthError",
code: 0,
userInfo: [NSLocalizedDescriptionKey: "Authentication failed"]
)
}
} catch {
print("Error during verification: \(error.localizedDescription)")
print("Error during authentication: \(error.localizedDescription)")
DispatchQueue.main.async {
self.appState.status = .loggedOut
}
}
}
}
Expand Down
Loading