-
Notifications
You must be signed in to change notification settings - Fork 0
Added auth to backend #71
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
Open
claiireyu
wants to merge
4
commits into
master
Choose a base branch
from
claire/auth
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
d421cc6
Implement user authentication with Firebase and JWT, add user model a…
claiireyu 477e534
Add user disabled error handling and token revocation check in authen…
claiireyu 054a166
Update error message for adding favorite game mutation
claiireyu fa5380f
fix(game existence check): add game check in remove favorite game mut…
claiireyu File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,8 @@ | ||
| YOUTUBE_API_KEY= | ||
| MONGO_URI= | ||
| MONGO_DB= | ||
| JWT_SECRET_KEY= | ||
| STAGE= | ||
| DAILY_SUN_URL= | ||
| DAILY_SUN_URL= | ||
| GOOGLE_APPLICATION_CREDENTIALS= | ||
| FIREBASE_CREDENTIALS_HOST_PATH=./firebase-service-account-key.json |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -11,3 +11,4 @@ Flask-APScheduler | |
| python-dotenv | ||
| pytz | ||
| gunicorn | ||
| firebase-admin==7.3.0 | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,5 @@ | ||
| from .game import Game | ||
| from .team import Team | ||
| from .youtube_video import YoutubeVideo | ||
| from .article import Article | ||
| from .article import Article | ||
| from .user import User |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| from dataclasses import dataclass, field | ||
| from datetime import datetime, timezone | ||
| from typing import Optional | ||
|
|
||
|
|
||
| def utc_now(): | ||
| now = datetime.now(timezone.utc) | ||
| return now.replace(microsecond=(now.microsecond // 1000) * 1000) | ||
|
|
||
|
|
||
| @dataclass | ||
| class User: | ||
| """Application user linked to an identity managed by Firebase.""" | ||
|
|
||
| firebase_uid: Optional[str] | ||
| email: Optional[str] = None | ||
| name: Optional[str] = None | ||
| favorite_game_ids: list = field(default_factory=list) | ||
| created_at: datetime = field(default_factory=utc_now) | ||
| updated_at: datetime = field(default_factory=utc_now) | ||
| id: object = None | ||
|
|
||
| def to_dict(self): | ||
| document = { | ||
| "firebase_uid": self.firebase_uid, | ||
| "email": self.email, | ||
| "name": self.name, | ||
| "favorite_game_ids": list(self.favorite_game_ids), | ||
| "created_at": self.created_at, | ||
| "updated_at": self.updated_at, | ||
| } | ||
| if self.id is not None: | ||
| document["_id"] = self.id | ||
| return document | ||
|
|
||
| @classmethod | ||
| def from_dict(cls, data): | ||
| if data is None: | ||
| return None | ||
| return cls( | ||
| id=data.get("_id"), | ||
| firebase_uid=data.get("firebase_uid"), | ||
| email=data.get("email"), | ||
| name=data.get("name"), | ||
| favorite_game_ids=list(data.get("favorite_game_ids") or []), | ||
| created_at=data.get("created_at") or utc_now(), | ||
| updated_at=data.get("updated_at") or utc_now(), | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| from graphql import GraphQLError | ||
| from graphene import Boolean, Mutation, String | ||
|
|
||
| from flask_jwt_extended import get_jwt_identity | ||
| from src.services.game_service import GameService | ||
| from src.services.user_service import UserService | ||
| from src.utils.graphql_errors import graphql_jwt_required | ||
|
|
||
|
|
||
| class AddFavoriteGame(Mutation): | ||
| class Arguments: | ||
| game_id = String(required=True, description="ID of the game to add to favorites.") | ||
|
|
||
| success = Boolean() | ||
|
|
||
| @graphql_jwt_required() | ||
| def mutate(self, info, game_id): | ||
| user_id = get_jwt_identity() | ||
| if not UserService.require_user(user_id): | ||
| raise GraphQLError("User not found.") | ||
| if not GameService.get_game_by_id(game_id): | ||
| raise GraphQLError("Game not found.") | ||
| if not UserService.add_favorite_game(user_id, game_id): | ||
| raise GraphQLError("Could not add game to favorites.") | ||
| return AddFavoriteGame(success=True) | ||
|
|
||
|
|
||
| class RemoveFavoriteGame(Mutation): | ||
| class Arguments: | ||
| game_id = String(required=True, description="ID of the game to remove from favorites.") | ||
|
|
||
| success = Boolean() | ||
|
|
||
| @graphql_jwt_required() | ||
| def mutate(self, info, game_id): | ||
| user_id = get_jwt_identity() | ||
| if not UserService.require_user(user_id): | ||
| raise GraphQLError("User not found.") | ||
| if not GameService.get_game_by_id(game_id): | ||
| raise GraphQLError("Game not found.") | ||
| UserService.remove_favorite_game(user_id, game_id) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Just as in the previous mutation, should this line by preceded by a check on whether the game exists? |
||
| return RemoveFavoriteGame(success=True) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,23 +1,46 @@ | ||
| from graphql import GraphQLError | ||
| from graphene import Mutation, String, Field | ||
| from graphene import Field, Mutation, String | ||
|
|
||
| from firebase_admin import auth as firebase_auth | ||
| from flask_jwt_extended import create_access_token, create_refresh_token | ||
| from src.database import db | ||
| from src.services.user_service import UserService | ||
| from src.types import UserType | ||
|
|
||
| _TOKEN_ERRORS = ( | ||
| firebase_auth.InvalidIdTokenError, | ||
| firebase_auth.ExpiredIdTokenError, | ||
| firebase_auth.RevokedIdTokenError, | ||
| firebase_auth.UserDisabledError, | ||
| ) | ||
|
|
||
|
|
||
| class LoginUser(Mutation): | ||
| class Arguments: | ||
| net_id = String(required=True, description="User's net ID (e.g. Cornell netid).") | ||
| id_token = String(required=True, description="Google Firebase ID token from the client.") | ||
|
|
||
| access_token = String() | ||
| refresh_token = String() | ||
| user = Field(UserType, required=True) | ||
|
|
||
| def mutate(self, info, id_token): | ||
| try: | ||
| decoded = firebase_auth.verify_id_token(id_token, check_revoked=True) | ||
| except _TOKEN_ERRORS as err: | ||
| raise GraphQLError("Invalid or expired token.") from err | ||
| except ValueError as err: | ||
| raise GraphQLError("Invalid or expired token.") from err | ||
|
|
||
| firebase_uid = decoded.get("uid") | ||
| provider = decoded.get("firebase", {}).get("sign_in_provider") | ||
| if not firebase_uid or provider != "google.com": | ||
| raise GraphQLError("Google authentication required.") | ||
|
|
||
| def mutate(self, info, net_id): | ||
| user = db["users"].find_one({"net_id": net_id}) | ||
| user = UserService.get_user_by_firebase_uid(firebase_uid) | ||
| if not user: | ||
| raise GraphQLError("User not found.") | ||
| identity = str(user["_id"]) | ||
| identity = str(user.id) | ||
| return LoginUser( | ||
| access_token=create_access_token(identity=identity), | ||
| refresh_token=create_refresh_token(identity=identity), | ||
| user=user, | ||
| ) |
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,33 +1,53 @@ | ||
| from graphql import GraphQLError | ||
| from graphene import Mutation, String | ||
| from graphene import Field, Mutation, String | ||
|
|
||
| from firebase_admin import auth as firebase_auth | ||
| from flask_jwt_extended import create_access_token, create_refresh_token | ||
| from src.database import db | ||
| from pymongo.errors import DuplicateKeyError | ||
| from src.services.user_service import UserService | ||
| from src.types import UserType | ||
|
|
||
| _TOKEN_ERRORS = ( | ||
| firebase_auth.InvalidIdTokenError, | ||
| firebase_auth.ExpiredIdTokenError, | ||
| firebase_auth.RevokedIdTokenError, | ||
| firebase_auth.UserDisabledError, | ||
| ) | ||
|
|
||
|
|
||
| class SignupUser(Mutation): | ||
| class Arguments: | ||
| net_id = String(required=True, description="User's net ID (e.g. Cornell netid).") | ||
| name = String(required=False, description="Display name.") | ||
| email = String(required=False, description="Email address.") | ||
| id_token = String(required=True, description="Google Firebase ID token from the client.") | ||
|
|
||
| access_token = String() | ||
| refresh_token = String() | ||
| user = Field(UserType, required=True) | ||
|
|
||
| def mutate(self, info, id_token): | ||
| try: | ||
| decoded = firebase_auth.verify_id_token(id_token, check_revoked=True) | ||
| except _TOKEN_ERRORS as err: | ||
| raise GraphQLError("Invalid or expired token.") from err | ||
| except ValueError as err: | ||
| raise GraphQLError("Invalid or expired token.") from err | ||
|
|
||
| firebase_uid = decoded.get("uid") | ||
| provider = decoded.get("firebase", {}).get("sign_in_provider") | ||
| if not firebase_uid or provider != "google.com": | ||
| raise GraphQLError("Google authentication required.") | ||
|
|
||
| try: | ||
| user = UserService.create_user( | ||
| firebase_uid, | ||
| decoded.get("email"), | ||
| decoded.get("name"), | ||
| ) | ||
| except DuplicateKeyError as err: | ||
| raise GraphQLError("User already exists.") from err | ||
|
|
||
| def mutate(self, info, net_id, name=None, email=None): | ||
| if db["users"].find_one({"net_id": net_id}): | ||
| raise GraphQLError("Net ID already exists.") | ||
| user_doc = { | ||
| "net_id": net_id, | ||
| "favorite_game_ids": [], | ||
| } | ||
| if name is not None: | ||
| user_doc["name"] = name | ||
| if email is not None: | ||
| user_doc["email"] = email | ||
| result = db["users"].insert_one(user_doc) | ||
| identity = str(result.inserted_id) | ||
| identity = str(user.id) | ||
| return SignupUser( | ||
| access_token=create_access_token(identity=identity), | ||
| refresh_token=create_refresh_token(identity=identity), | ||
| user=user, | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,5 @@ | ||
| from .game_query import GameQuery | ||
| from .team_query import TeamQuery | ||
| from .youtube_video_query import YoutubeVideoQuery | ||
| from .article_query import ArticleQuery | ||
| from .article_query import ArticleQuery | ||
| from .user_query import UserQuery |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This looks good, love the consolidation! Especially noticed that you abstracted the read/writes using
UserService, which looks much cleaner