Skip to content

Commit

Permalink
Merge pull request #124 from voynow/123-backend-migration-cleanup
Browse files Browse the repository at this point in the history
123 backend migration cleanup
  • Loading branch information
voynow authored Nov 12, 2024
2 parents ae5431e + 8f91a2d commit 11a8b98
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 18 deletions.
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

0 comments on commit 11a8b98

Please sign in to comment.