Skip to content

Commit

Permalink
saving changes made to app.py, need to generate unique cardIDs for se…
Browse files Browse the repository at this point in the history
…archCards
  • Loading branch information
qianxuege committed Dec 23, 2024
1 parent 0943a0c commit 228fe58
Show file tree
Hide file tree
Showing 4 changed files with 84 additions and 6 deletions.
2 changes: 1 addition & 1 deletion backend/api/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ To use, first create a virtual environment: `python3 -m venv <myenvname>`
Then activate it:

On windows: `.\env\Scripts\activate.bat`
On mac: `source venv/bin/activate`
On mac: `source myvenv/bin/activate`

Then install needed packages: `pip3 install -r requirements.txt`

Expand Down
83 changes: 80 additions & 3 deletions backend/api/app.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,51 @@

import json
from flask import Flask, jsonify, request, url_for, redirect
from flask import Flask, redirect, request, jsonify, session, url_for
from flask_pymongo import PyMongo
from flask_cors import CORS
from google_auth_oauthlib.flow import Flow
from googleapiclient.discovery import build
from dotenv import load_dotenv
import os
import configparser

config = configparser.ConfigParser()
config.read(os.path.abspath(os.path.join("config.ini")))

app = Flask(__name__)
app.config["MONGO_URI"] = config['PROD']['DB_URI']
mongo = PyMongo(app)
app.secret_key = 'YOUR_SECRET_KEY' # Replace with a secure secret key
'''commented out the two lines below so the app won't crash due to missing DB_URI'''
# app.config["MONGO_URI"] = config['PROD']['DB_URI']
# mongo = PyMongo(app)

# CORS(app, supports_credentials=True, resources={r"/*": {"origins": "http://127.0.0.1:5173"}})
CORS(app, supports_credentials=True, resources={r"/*": {"origins": "*"}})


# Load environment variables from .env file
load_dotenv()
# Access Google API credentials from .env
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' # For development only
CLIENT_ID = os.getenv('GOOGLE_CLIENT_ID') # Google client ID
CLIENT_SECRET = os.getenv('GOOGLE_CLIENT_SECRET') # Google client secret
REDIRECT_URI = os.getenv('GOOGLE_REDIRECT_URI') # Google redirect URI
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']

# Initialize OAuth flow
flow = Flow.from_client_config(
{
"web": {
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
"redirect_uris": [REDIRECT_URI],
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
}
},
scopes=SCOPES,
redirect_uri=REDIRECT_URI # Explicitly set the redirect URI
)


# Define the mapping between category and MongoDB collections
category_collections = {
Expand All @@ -31,6 +66,48 @@ def create_text_indexes():
create_text_indexes()
"""

@app.route('/login')
def login():
auth_url, _ = flow.authorization_url(prompt='consent')
return jsonify({"auth_url": auth_url})

@app.route('/callback')
def callback():
flow.fetch_token(authorization_response=request.url)
credentials = flow.credentials
session['credentials'] = {
'token': credentials.token,
'refresh_token': credentials.refresh_token,
'token_uri': credentials.token_uri,
'client_id': credentials.client_id,
'client_secret': credentials.client_secret,
'scopes': credentials.scopes,
}
return redirect("http://127.0.0.1:5173/home") # Redirect to React app

@app.route('/get_user_calendar')
def get_user_calendar():
if 'credentials' not in session:
return jsonify({"error": "User not authenticated"}), 401

credentials = session['credentials']
service = build('calendar', 'v3', credentials=credentials)

try:
events_result = service.events().list(
calendarId='primary',
timeMin='2024-12-01T00:00:00Z', # Replace with your desired time range
maxResults=10,
singleEvents=True,
orderBy='startTime'
).execute()

events = events_result.get('items', [])
return jsonify(events)
except Exception as e:
print(e)
return jsonify({"error": "Failed to fetch events"}), 500

@app.route('/events', methods=['POST'])
def search_events():
data = request.json
Expand Down
2 changes: 0 additions & 2 deletions frontend/src/components/Search.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,6 @@ const Search: React.FC<SearchComponentProps> = ({ page, showSearchBar,
const storedItems = getArrayFromLocalStorage<string>('savedSearches');
// const storedEvents = getArrayFromLocalStorage<string>('savedEvents');
setSavedItems(storedItems);
// clearSavedItems();
console.log(storedItems);
}, [searchInput]);


Expand Down
3 changes: 3 additions & 0 deletions frontend/src/components/SearchCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,9 @@ const SearchCard: React.FC<SearchCardProps> = ({
const handleCardClicked = () => {
setCardClicked(!cardClicked);
}
if (isSelected) {
console.log(cardId, eventName);
}

return (
<div className="bg-white w-full my-3.5 px-6 py-4 rounded-lg flex items-center align-stretch relative">
Expand Down

0 comments on commit 228fe58

Please sign in to comment.