Skip to content

Commit

Permalink
Merge pull request #43 from utmgdsc/main
Browse files Browse the repository at this point in the history
Deploy Changes
  • Loading branch information
Yazan10x authored Dec 15, 2023
2 parents a6436e8 + 1d34bbf commit 6598764
Show file tree
Hide file tree
Showing 34 changed files with 2,023 additions and 613 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()
19 changes: 14 additions & 5 deletions backend/models/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,23 @@ 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

def __init__(self, oid: ObjectId, full_name: str, email: str, badges: list[str], friends: list[str], score:int, province:str, household:int, fuel_efficiency: float) -> None:
def __init__(self, oid: ObjectId, full_name: str, email: str, badges: list[str], friends: list[str], monthly_score:int,
yearly_score:int, overall_score:int, province:str, household:int, fuel_efficiency: float) -> None:
super().__init__(oid)
self.full_name = str(full_name)
self.email = str(email)
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 @@ -37,7 +42,9 @@ def to_json(self) -> json:
'email': self.email,
'badges': self.badges,
'friends': self.friends,
'score': self.score,
'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
Expand All @@ -51,7 +58,9 @@ def from_json(doc: json) -> User:
email=doc["email"],
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
62 changes: 60 additions & 2 deletions backend/routes/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,66 @@ def get_user(user_id: str) -> Response:
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'])
@carbon_auth.auth.login_required
def get_user_by_email(user_email: str) -> Response:
Expand Down Expand Up @@ -81,5 +141,3 @@ def update_user(user_id: str) -> Response:
return jsonify({'user': item})
except CarbonTrackError as e:
abort(code=400, description=f"{e}")


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.
17 changes: 11 additions & 6 deletions frontend/assets/colorConstants.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
const Colors = {
LIGHTFGREEN: '#E0EEC6',
DARKGREEN: '#243E36',
LIGHTFGREEN: '#d8edc2',
DARKGREEN: '#012b26',
DARKTRANS: '#07332f',
DARKGREEN2: '#224A3E',
DARKGREEN3: '#2E5C4E',
WHITE: '#fff',
BLACK: '000',
LIGHTGREENBUTTON: '#a5ba8f',
LIGHTGREENBACK: '#C7E0A6',
WHITE: '#ffffff',
BLACK: '#000000',
DARKLIMEGREEN: '#4B8552',
GREY: '#ccc',
GREY: '#cccccc',
FILLGREEN: '#7CA982',
ERROR: 'red',
TRANSGREEN: '#366959',
BLACKTRANS: '#000000aa',
BLUE: 'blue',
GREYGREEN: '#B4C792',
TEAL: '#6bcfca'
};

export default Colors;
export default Colors;
8 changes: 5 additions & 3 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
"@react-native-community/slider": "^4.4.2",
"@react-native-firebase/auth": "^18.6.0",
"@react-native-firebase/firestore": "^18.6.0",
"@react-native-picker/picker": "^2.5.1",
"@react-native-picker/picker": "2.4.10",
"@react-navigation/bottom-tabs": "^6.5.11",
"@react-navigation/native": "^6.1.9",
"@react-navigation/native-stack": "^6.9.15",
Expand All @@ -38,8 +38,10 @@
"react-native-circular-progress-indicator": "^4.4.2",
"react-native-elements": "^3.4.3",
"react-native-gesture-handler": "^2.13.3",
"react-native-paper": "^5.11.1",
"react-native-reanimated": "^3.5.4",
"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",
"react-native-svg": "13.9.0",
Expand Down
2 changes: 1 addition & 1 deletion 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://100.112.45.130:6050";
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 6598764

Please sign in to comment.