From 11655b31ae6ae442cfe87e56fffa0fa413fc8248 Mon Sep 17 00:00:00 2001 From: tonyrewin Date: Thu, 1 Dec 2022 11:12:48 +0300 Subject: [PATCH] load fixed, auth wip --- auth/authenticate.py | 9 +++---- auth/credentials.py | 4 ++- migration/tables/content_items.py | 43 +++++++++++------------------- migration/tables/replacements.json | 1 + migration/tables/users.py | 5 ++-- orm/user.py | 2 +- resolvers/__init__.py | 6 ++--- resolvers/auth.py | 4 +-- resolvers/create/collab.py | 8 +++--- resolvers/create/editor.py | 2 ++ resolvers/zine/profile.py | 42 ++++++++++++++++------------- schema.graphql | 21 ++------------- 12 files changed, 65 insertions(+), 82 deletions(-) diff --git a/auth/authenticate.py b/auth/authenticate.py index 9821133b..99d0c4d4 100644 --- a/auth/authenticate.py +++ b/auth/authenticate.py @@ -8,11 +8,11 @@ from starlette.requests import HTTPConnection from auth.credentials import AuthCredentials, AuthUser from base.orm import local_session -from orm import User, Role +from orm.user import User, Role, UserRole from settings import SESSION_TOKEN_HEADER from auth.tokenstorage import SessionToken -from base.exceptions import InvalidToken, OperationNotAllowed, Unauthorized +from base.exceptions import InvalidToken, Unauthorized, OperationNotAllowed class JWTAuthenticate(AuthenticationBackend): @@ -41,7 +41,6 @@ class JWTAuthenticate(AuthenticationBackend): user = ( session.query(User).options( joinedload(User.roles), - joinedload(Role.permissions), joinedload(User.ratings) ).filter( User.id == id @@ -78,7 +77,7 @@ def login_required(func): auth: AuthCredentials = info.context["request"].auth # print(auth) if not auth or not auth.logged_in: - raise OperationNotAllowed(auth.error_message or "Please login") + raise Unauthorized(auth.error_message or "Please login") return await func(parent, info, *args, **kwargs) return wrap @@ -90,7 +89,7 @@ def permission_required(resource, operation, func): print('[auth.authenticate] permission_required for %r with info %r' % (func, info)) # debug only auth: AuthCredentials = info.context["request"].auth if not auth.logged_in: - raise Unauthorized(auth.error_message or "Please login") + raise OperationNotAllowed(auth.error_message or "Please login") # TODO: add actual check permission logix here diff --git a/auth/credentials.py b/auth/credentials.py index 15738d16..2096450b 100644 --- a/auth/credentials.py +++ b/auth/credentials.py @@ -23,7 +23,9 @@ class AuthCredentials(BaseModel): async def permissions(self) -> List[Permission]: if self.user_id is None: raise Unauthorized("Please login first") - # TODO: implement permissions logix + else: + # TODO: implement permissions logix + print(self.user_id) return NotImplemented() diff --git a/migration/tables/content_items.py b/migration/tables/content_items.py index e1503994..c85b2cdc 100644 --- a/migration/tables/content_items.py +++ b/migration/tables/content_items.py @@ -110,18 +110,6 @@ def get_userdata(entry, storage): return userdata, user_oid -def get_userdata(entry, storage): - user_oid = entry.get("createdBy", "") - userdata = None - app = entry.get("application") - if app: - userdata = create_author_from_app(app) or {"slug": "anonymous"} - else: - userdata = storage["users"]["by_oid"].get(user_oid) or {"slug": "anonymous"} - userslug = userdata.get("slug") - return userslug, userdata, user_oid - - async def migrate(entry, storage): userdata, user_oid = get_userdata(entry, storage) user = await get_user(userdata, storage, user_oid) @@ -209,21 +197,22 @@ async def add_topics_follower(entry, storage, user): for tpcslug in topics: try: tpc = session.query(Topic).where(Topic.slug == tpcslug).first() - tf = session.query( - TopicFollower - ).where( - TopicFollower.follower == user.id - ).filter( - TopicFollower.topic == tpc.id - ).first() - if not tf: - tf = TopicFollower.create( - topic=tpc.id, - follower=user.id, - auto=True - ) - session.add(tf) - session.commit() + if tpc: + tf = session.query( + TopicFollower + ).where( + TopicFollower.follower == user.id + ).filter( + TopicFollower.topic == tpc.id + ).first() + if not tf: + tf = TopicFollower.create( + topic=tpc.id, + follower=user.id, + auto=True + ) + session.add(tf) + session.commit() except IntegrityError: print('[migration.shout] hidden by topic ' + tpc.slug) # main topic diff --git a/migration/tables/replacements.json b/migration/tables/replacements.json index f9d802e3..8dba6f55 100644 --- a/migration/tables/replacements.json +++ b/migration/tables/replacements.json @@ -283,6 +283,7 @@ "gonzo": "gonzo", "gore-ot-uma": "woe-from-wit", "graffiti": "graffiti", + "graficheskaya-novella": "graphic-novell", "graphics": "graphics", "gravyura": "engraving", "grazhdanskaya-oborona": "grazhdanskaya-oborona", diff --git a/migration/tables/users.py b/migration/tables/users.py index 697e6b4f..b30e82c8 100644 --- a/migration/tables/users.py +++ b/migration/tables/users.py @@ -56,9 +56,10 @@ def migrate(entry): # name fn = entry["profile"].get("firstName", "") ln = entry["profile"].get("lastName", "") - name = user_dict["slug"] if user_dict["slug"] else "anonymous" - name = fn if fn else name + name = fn if fn else "" name = (name + " " + ln) if ln else name + if not name: + name = slug if slug else "anonymous" name = ( entry["profile"]["path"].lower().strip().replace(" ", "-") if len(name) < 2 diff --git a/orm/user.py b/orm/user.py index 7c7128d2..2dc25b61 100644 --- a/orm/user.py +++ b/orm/user.py @@ -107,7 +107,7 @@ class User(Base): if p.resource not in scope: scope[p.resource] = set() scope[p.resource].add(p.operation) - + print(scope) return scope diff --git a/resolvers/__init__.py b/resolvers/__init__.py index 0a1b096f..e35f8ba4 100644 --- a/resolvers/__init__.py +++ b/resolvers/__init__.py @@ -8,7 +8,7 @@ from resolvers.auth import ( get_current_user, ) -from resolvers.create.collab import remove_author, invite_author +from resolvers.create.collab import remove_coauthor, invite_coauthor from resolvers.create.migrate import markdown_body from resolvers.create.editor import create_shout, delete_shout, update_shout @@ -93,8 +93,8 @@ __all__ = [ # create.migrate "markdown_body", # create.collab - "invite_author", - "remove_author", + "invite_coauthor", + "remove_coauthor", # zine.topics "topics_all", "topics_by_community", diff --git a/resolvers/auth.py b/resolvers/auth.py index 1d1ca18c..3cbd5977 100644 --- a/resolvers/auth.py +++ b/resolvers/auth.py @@ -13,7 +13,7 @@ from auth.identity import Identity, Password from auth.jwtcodec import JWTCodec from auth.tokenstorage import TokenStorage from base.exceptions import (BaseHttpException, InvalidPassword, InvalidToken, - ObjectNotExist, OperationNotAllowed, Unauthorized) + ObjectNotExist, Unauthorized) from base.orm import local_session from base.resolvers import mutation, query from orm import Role, User @@ -113,7 +113,7 @@ async def register_by_email(_, _info, email: str, password: str = "", name: str with local_session() as session: user = session.query(User).filter(User.email == email).first() if user: - raise OperationNotAllowed("User already exist") + raise Unauthorized("User already exist") else: slug = generate_unique_slug(name) user = session.query(User).where(User.slug == slug).first() diff --git a/resolvers/create/collab.py b/resolvers/create/collab.py index 1bcbabb3..feff66ba 100644 --- a/resolvers/create/collab.py +++ b/resolvers/create/collab.py @@ -1,7 +1,7 @@ from auth.authenticate import login_required from base.orm import local_session from base.resolvers import query, mutation -from base.exceptions import OperationNotAllowed, ObjectNotExist +from base.exceptions import ObjectNotExist, BaseHttpException from orm.collab import Collab, CollabAuthor from orm.shout import Shout from orm.user import User @@ -27,7 +27,7 @@ async def invite_coauthor(_, info, author: str, shout: int): else: c = session.query(Collab).where(Collab.shout == shout).one() if user.slug not in c.authors: - raise OperationNotAllowed("you are not in authors list") + raise BaseHttpException("you are not in authors list") else: invited_user = session.query(User).where(User.slug == author).one() c.invites.append(invited_user) @@ -47,7 +47,7 @@ async def remove_coauthor(_, info, author: str, shout: int): if not s: raise ObjectNotExist("invalid shout id") if user.slug != s.createdBy.slug: - raise OperationNotAllowed("only onwer can remove coauthors") + raise BaseHttpException("only onwer can remove coauthors") else: c = session.query(Collab).where(Collab.shout == shout).one() ca = session.query(CollabAuthor).where(c.shout == shout, c.author == author).one() @@ -80,4 +80,4 @@ async def accept_coauthor(_, info, shout: int): session.commit() return {} else: - raise OperationNotAllowed("only invited can accept") + raise BaseHttpException("only invited can accept") diff --git a/resolvers/create/editor.py b/resolvers/create/editor.py index e125d2c2..8205369b 100644 --- a/resolvers/create/editor.py +++ b/resolvers/create/editor.py @@ -12,6 +12,8 @@ from orm.user import User from resolvers.zine.reactions import reactions_follow, reactions_unfollow from services.zine.gittask import GitTask from resolvers.inbox.chats import create_chat +from services.inbox import MessagesStorage +from orm.collab import Collab @mutation.field("createShout") diff --git a/resolvers/zine/profile.py b/resolvers/zine/profile.py index 652a602a..fc947d02 100644 --- a/resolvers/zine/profile.py +++ b/resolvers/zine/profile.py @@ -20,7 +20,7 @@ def add_author_stat_columns(q): author_followers = aliased(AuthorFollower) author_following = aliased(AuthorFollower) shout_author_aliased = aliased(ShoutAuthor) - user_rating_aliased = aliased(UserRating) + # user_rating_aliased = aliased(UserRating) q = q.outerjoin(shout_author_aliased).add_columns( func.count(distinct(shout_author_aliased.shout)).label('shouts_stat') @@ -40,11 +40,11 @@ def add_author_stat_columns(q): # func.sum(user_rating_aliased.value).label('rating_stat') # ) - q = q.add_columns(literal(0).label('commented_stat')) - # FIXME - # q = q.outerjoin(Reaction, and_(Reaction.createdBy == User.id, Reaction.body.is_not(None))).add_columns( - # func.count(distinct(Reaction.id)).label('commented_stat') - # ) + # q = q.add_columns(literal(0).label('commented_stat')) + + q = q.outerjoin(Reaction, and_(Reaction.createdBy == User.id, Reaction.body.is_not(None))).add_columns( + func.count(distinct(Reaction.id)).label('commented_stat') + ) q = q.group_by(User.id) @@ -117,12 +117,18 @@ async def get_followed_authors(_, _info, slug) -> List[User]: return await followed_authors(slug) -async def followed_authors(slug) -> List[User]: - q = select(User) - q = add_author_stat_columns(q) - q = q.join(AuthorFollower).join(User, User.id == AuthorFollower.follower).where(User.slug == slug) - - return get_authors_from_query(q) +async def followed_authors(slug): + with local_session() as session: + user = session.query(User).where(User.slug == slug).first() + q = select(User) + q = add_author_stat_columns(q) + aliased_user = aliased(User) + q = q.join(AuthorFollower, AuthorFollower.author == user.id).join( + aliased_user, aliased_user.id == AuthorFollower.follower + ).where( + aliased_user.slug == slug + ) + return get_authors_from_query(q) @query.field("userFollowers") @@ -145,10 +151,10 @@ async def get_user_roles(slug): user = session.query(User).where(User.slug == slug).first() roles = ( session.query(Role) - .options(joinedload(Role.permissions)) - .join(UserRole) - .where(UserRole.user == user.id) - .all() + .options(joinedload(Role.permissions)) + .join(UserRole) + .where(UserRole.user == user.id) + .all() ) return roles @@ -175,8 +181,8 @@ async def rate_user(_, info, rated_userslug, value): with local_session() as session: rating = ( session.query(UserRating) - .filter(and_(UserRating.rater == user.slug, UserRating.user == rated_userslug)) - .first() + .filter(and_(UserRating.rater == user.slug, UserRating.user == rated_userslug)) + .first() ) if rating: rating.value = value diff --git a/schema.graphql b/schema.graphql index 17ae65dc..e0d9d5f5 100644 --- a/schema.graphql +++ b/schema.graphql @@ -186,8 +186,8 @@ type Mutation { deleteReaction(id: Int!): Result! # collab - inviteCoauthor(author: String!, shout: int!): Result! - removeCouthor(author: String!, shout: Int!): Result! + inviteCoauthor(author: String!, shout: Int!): Result! + removeCoauthor(author: String!, shout: Int!): Result! acceptCoauthor(shout: Int!): Result! # following @@ -373,23 +373,6 @@ type User { oid: String } -<<<<<<< HEAD -======= -type Draft { - title: String - body: String - createdBy: Int -} - -type Collab { - authors: [String]! - invites: [String] - createdAt: DateTime! - title: String - body: String -} - ->>>>>>> migation-fix2 enum ReactionKind { LIKE DISLIKE