Skip to content

Commit

Permalink
Merge branch 'main' into feature/71/implement-settings
Browse files Browse the repository at this point in the history
  • Loading branch information
jasmineguru authored Dec 15, 2023
2 parents 0a00952 + 49d7a90 commit bec61e1
Show file tree
Hide file tree
Showing 32 changed files with 1,696 additions and 746 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,6 @@
*.DS_Store
node_modules
.venv
/.idea
*.patch
backend/.migrations
6 changes: 4 additions & 2 deletions backend/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,20 @@
from flask import Flask, Response, jsonify
from flask_cors import CORS
from werkzeug.exceptions import HTTPException
import ct_confiq
from utils.customJSONEncoder import CustomJSONProvider

# SERVICES
from routes.ct_firebase_service import ct_firebase_service
# Imports
from routes.users import users
from routes.transportation import transportation_service
from utils.customJSONEncoder import CustomJSONProvider
from routes.food import food_service
from routes.energy import energy_service


app = Flask(__name__)
app.json = CustomJSONProvider(app)
ct_confiq.run_carbon_track_configurations()

# Services
app.register_blueprint(users, url_prefix="/users")
Expand Down
20 changes: 20 additions & 0 deletions backend/ct_confiq.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
"""
File Description
"""
import json
import os


def _load_secrets() -> None:
if os.environ.get('DB_URI') is None:
with open('secrets.json') as secret_json:
secrets = json.load(secret_json)
for key, value in secrets.items():
os.environ[key] = value


def run_carbon_track_configurations() -> None:
_load_secrets()


run_carbon_track_configurations()
30 changes: 20 additions & 10 deletions backend/models/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ class User(DB_MODEL):
email: str
badges: list[str]
friends: list[str]
score: int
monthly_score: int
yearly_score: int
overall_score: int
province: str
household: int
fuel_efficiency: float
Expand All @@ -27,7 +29,9 @@ def __init__(
uid: str,
badges: list[str],
friends: list[str],
score: int,
monthly_score:int,
yearly_score:int,
overall_score:int,
province: str,
household: int,
fuel_efficiency: float,
Expand All @@ -38,7 +42,9 @@ def __init__(
self.uid = uid
self.badges = badges
self.friends = friends
self.score = score
self.monthly_score = monthly_score
self.yearly_score = yearly_score
self.overall_score = overall_score
self.province = province
self.household = household
self.fuel_efficiency = fuel_efficiency
Expand All @@ -49,12 +55,14 @@ def to_json(self) -> json:
"full_name": self.full_name,
"email": self.email,
"uid": self.uid,
"badges": self.badges,
"friends": self.friends,
"score": self.score,
"province": self.province,
"household": self.household,
"fuel_efficiency": self.fuel_efficiency,
'badges': self.badges,
'friends': self.friends,
'monthly_score': self.monthly_score,
'yearly_score': self.yearly_score,
'overall_score': self.overall_score,
'province': self.province,
'household': self.household,
'fuel_efficiency': self.fuel_efficiency
}

@staticmethod
Expand All @@ -66,7 +74,9 @@ def from_json(doc: json) -> User:
uid=doc["uid"],
badges=doc["badges"],
friends=doc["friends"],
score=doc["score"],
monthly_score=doc["monthly_score"],
yearly_score=doc["yearly_score"],
overall_score=doc["overall_score"],
province=doc["province"],
household=doc["household"],
fuel_efficiency=doc["fuel_efficiency"],
Expand Down
8 changes: 4 additions & 4 deletions backend/mongodb_api/carbon_track_db.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
# Python Imports
import os
from pymongo import MongoClient
from pymongo.collection import Collection
from pymongo.database import Database

# Imports
from mongodb_api.secrets import get_db


# Get DB From Cluster
carbonTrackDB: Database = get_db("CarbonTrack")
_cluster: MongoClient = MongoClient(os.environ.get("DB_URI"))
carbonTrackDB: Database = _cluster["CarbonTrack"]


class CarbonTrackDB:
Expand Down
23 changes: 0 additions & 23 deletions backend/mongodb_api/secrets.py

This file was deleted.

2 changes: 2 additions & 0 deletions backend/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,5 @@ Flask_Cors==4.0.0
Flask_HTTPAuth==4.8.0
pymongo==4.6.0
ruff==0.1.4
typing~=3.7.4.3
werkzeug~=3.0.1
61 changes: 60 additions & 1 deletion backend/routes/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,67 @@ def get_user(user_id: str) -> Response:
except CarbonTrackError as e:
abort(code=400, description=f"{e}")

@users.route("/get_top_users", methods=['POST'])
@carbon_auth.auth.login_required
def get_top_users() -> Response:
try:
count = request.get_json()["count"]

# Monthly
_top_monthly_users = CarbonTrackDB.users_coll.find().sort("monthly_score", -1).limit(count)
top_monthly_users = []
rank = 1
for user in _top_monthly_users:
obj = User.from_json(user)
user = {
'rank': rank,
'name': obj.full_name,
'footprint': 0,
'score': obj.overall_score,
}
rank += 1
top_monthly_users.append(user)

# Yearly
_top_yearly_users = CarbonTrackDB.users_coll.find().sort("yearly_score", -1).limit(count)
top_yearly_users = []
rank = 1
for user in _top_yearly_users:
obj = User.from_json(user)
user = {
'rank': rank,
'name': obj.full_name,
'footprint': 0,
'score': obj.overall_score,
}
rank += 1
top_yearly_users.append(user)

# Overall
_top_overall_users = CarbonTrackDB.users_coll.find().sort("overall_score", -1).limit(count)
top_overall_users = []
rank = 1
for user in _top_overall_users:
obj = User.from_json(user)
user = {
'rank': rank,
'name': obj.full_name,
'footprint': 0,
'score': obj.overall_score,
}
rank += 1
top_overall_users.append(user)

return jsonify({
'top_monthly_users': top_monthly_users,
'top_yearly_users': top_yearly_users,
'top_overall_users': top_overall_users,
})
except CarbonTrackError as e:
abort(code=400, description=f"{e}")


@users.route("/user_email/<user_email>", methods=["GET"])
@users.route("/user_email/<user_email>", methods=['GET'])
@carbon_auth.auth.login_required
def get_user_by_email(user_email: str) -> Response:
try:
Expand Down
42 changes: 38 additions & 4 deletions backend/templates/google_login.html
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
<script type="module">
// Import the necessary Firebase modules
import { initializeApp } from "https://www.gstatic.com/firebasejs/10.5.0/firebase-app.js";
import { getAuth, GoogleAuthProvider, signInWithPopup } from "https://www.gstatic.com/firebasejs/10.5.0/firebase-auth.js";
import { getAuth, GoogleAuthProvider, signInWithPopup, signInWithEmailAndPassword } from "https://www.gstatic.com/firebasejs/10.5.0/firebase-auth.js";

// Your web app's Firebase configuration
const firebaseConfig = {
Expand Down Expand Up @@ -72,6 +72,21 @@
});
};

window.signInWithEmailAndPasswordCT = function () {
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;

signInWithEmailAndPassword(auth, email, password)
.then((result) => {
// User signed in with email/password
displayUserInfo(result.user);
})
.catch((error) => {
// Handle sign-in errors
console.error(error);
});
};

function displayUserInfo(user) {
// Create a container for user details
const container = document.createElement("div");
Expand Down Expand Up @@ -100,8 +115,9 @@
copyButton.textContent = "Copy Token";
copyButton.onclick = function () {
// Copy the token to the clipboard
navigator.clipboard.writeText(user.accessToken);
alert("Token copied to clipboard!");
navigator.clipboard.writeText(user.accessToken).then(() => {
alert("Token copied to clipboard!");
});
};

// Append the token and copy button to the container
Expand All @@ -115,8 +131,26 @@

<body>
<h1>Login with Firebase</h1>
<!-- Add a button to trigger the sign-in -->
<!-- Add input fields for email and password -->
<label for="email"></label>
<input type="email" id="email" placeholder="Email">

<br/>

<label for="password"></label>
<input type="password" id="password" placeholder="Password">

<br/>

<!-- Add a button to trigger the email/password sign-in -->
<button onclick="signInWithEmailAndPasswordCT()">Sign in with Email/Password</button>

<br/><br/><br/><br/>
<!-- Add a button to trigger the sign-in with Google -->
<button onclick="signInWithGoogle()">Sign in with Google</button>
<br/>
<br/>

</body>

</html>
4 changes: 2 additions & 2 deletions backend/utils/FirebaseAPI.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
# from typing import Optional
import os
from typing import Optional
import firebase_admin
from firebase_admin import credentials, auth

from models.user import User
from mongodb_api.carbon_track_db import CarbonTrackDB

cred = credentials.Certificate("firebase.json")
cred = credentials.Certificate(dict(os.environ))
APP = firebase_admin.initialize_app(cred)


class FirebaseAPI:
@staticmethod
def verify_google_token(id_token: str) -> Optional[dict]:
print(id_token)
return auth.verify_id_token(
id_token=id_token, check_revoked=True
)
Expand Down
Binary file added frontend/assets/butterfly.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
7 changes: 5 additions & 2 deletions frontend/assets/colorConstants.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ const Colors = {
DARKGREEN: '#10302b',
DARKGREEN2: '#224A3E',
DARKGREEN3: '#2E5C4E',
WHITE: '#fff',
LIGHTGREENBUTTON: '#a5ba8f',
LIGHTGREENBACK: '#C7E0A6',
WHITE: '#ffffff',
BLACK: '#000000',
DARKLIMEGREEN: '#4B8552',
GREY: '#ccc',
Expand All @@ -17,6 +19,7 @@ const Colors = {
TRANSLIGHTGREEN2: '#b3c99d',
TRANSGREENBACK: '#07332b',
DARKDARKGREEN: '#031c19',
GREYGREEN: '#B4C792',
};

export default Colors;
export default Colors;
4 changes: 3 additions & 1 deletion frontend/assets/foodQuestions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ const foodSlidersData: SliderData[] = [
{ id: 1, label: 'Beef', minValue: 0, maxValue: 8, initialValue: 0 },
{ id: 2, label: 'Lamb', minValue: 0, maxValue: 8, initialValue: 0 },
{ id: 3, label: 'Pork', minValue: 0, maxValue: 8, initialValue: 0 },
{ id: 4, label: 'Chicken/Fish', minValue: 0, maxValue: 8, initialValue: 0 },
{ id: 4, label: 'Chicken', minValue: 0, maxValue: 8, initialValue: 0 },
{ id: 5, label: 'Fish', minValue: 0, maxValue: 8, initialValue: 0 },
{ id: 6, label: 'Cheese', minValue: 0, maxValue: 8, initialValue: 0 },
];

export default foodSlidersData;
2 changes: 2 additions & 0 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,9 @@
"react-native-circular-progress-indicator": "^4.4.2",
"react-native-elements": "^3.4.3",
"react-native-gesture-handler": "^2.13.3",
"react-native-modal-dropdown": "^1.0.2",
"react-native-paper": "^5.11.3",
"react-native-picker-select": "^9.0.0",
"react-native-reanimated": "~3.3.0",
"react-native-safe-area-context": "^4.6.3",
"react-native-screens": "~3.22.0",
Expand Down
6 changes: 3 additions & 3 deletions frontend/src/APIs/FLASK_API.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import axios from 'axios';
import firebaseService from '../utilities/firebase';
const FLASK_LOCAL_ADDRESS: string = 'http://192.168.68.104:6050';
import axios from "axios";
import firebaseService from "../utilities/firebase";
const FLASK_LOCAL_ADDRESS: string = "http://10.0.0.72:6050";

// Function to get the Firebase authentication token
const getFirebaseAuthToken = async (): Promise<string | null> => {
Expand Down
Loading

0 comments on commit bec61e1

Please sign in to comment.