load fixed, auth wip

This commit is contained in:
tonyrewin 2022-12-01 11:12:48 +03:00
parent 86401f5cb7
commit 11655b31ae
12 changed files with 65 additions and 82 deletions

View File

@ -8,11 +8,11 @@ from starlette.requests import HTTPConnection
from auth.credentials import AuthCredentials, AuthUser from auth.credentials import AuthCredentials, AuthUser
from base.orm import local_session 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 settings import SESSION_TOKEN_HEADER
from auth.tokenstorage import SessionToken from auth.tokenstorage import SessionToken
from base.exceptions import InvalidToken, OperationNotAllowed, Unauthorized from base.exceptions import InvalidToken, Unauthorized, OperationNotAllowed
class JWTAuthenticate(AuthenticationBackend): class JWTAuthenticate(AuthenticationBackend):
@ -41,7 +41,6 @@ class JWTAuthenticate(AuthenticationBackend):
user = ( user = (
session.query(User).options( session.query(User).options(
joinedload(User.roles), joinedload(User.roles),
joinedload(Role.permissions),
joinedload(User.ratings) joinedload(User.ratings)
).filter( ).filter(
User.id == id User.id == id
@ -78,7 +77,7 @@ def login_required(func):
auth: AuthCredentials = info.context["request"].auth auth: AuthCredentials = info.context["request"].auth
# print(auth) # print(auth)
if not auth or not auth.logged_in: 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 await func(parent, info, *args, **kwargs)
return wrap 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 print('[auth.authenticate] permission_required for %r with info %r' % (func, info)) # debug only
auth: AuthCredentials = info.context["request"].auth auth: AuthCredentials = info.context["request"].auth
if not auth.logged_in: 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 # TODO: add actual check permission logix here

View File

@ -23,7 +23,9 @@ class AuthCredentials(BaseModel):
async def permissions(self) -> List[Permission]: async def permissions(self) -> List[Permission]:
if self.user_id is None: if self.user_id is None:
raise Unauthorized("Please login first") raise Unauthorized("Please login first")
else:
# TODO: implement permissions logix # TODO: implement permissions logix
print(self.user_id)
return NotImplemented() return NotImplemented()

View File

@ -110,18 +110,6 @@ def get_userdata(entry, storage):
return userdata, user_oid 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): async def migrate(entry, storage):
userdata, user_oid = get_userdata(entry, storage) userdata, user_oid = get_userdata(entry, storage)
user = await get_user(userdata, storage, user_oid) user = await get_user(userdata, storage, user_oid)
@ -209,6 +197,7 @@ async def add_topics_follower(entry, storage, user):
for tpcslug in topics: for tpcslug in topics:
try: try:
tpc = session.query(Topic).where(Topic.slug == tpcslug).first() tpc = session.query(Topic).where(Topic.slug == tpcslug).first()
if tpc:
tf = session.query( tf = session.query(
TopicFollower TopicFollower
).where( ).where(

View File

@ -283,6 +283,7 @@
"gonzo": "gonzo", "gonzo": "gonzo",
"gore-ot-uma": "woe-from-wit", "gore-ot-uma": "woe-from-wit",
"graffiti": "graffiti", "graffiti": "graffiti",
"graficheskaya-novella": "graphic-novell",
"graphics": "graphics", "graphics": "graphics",
"gravyura": "engraving", "gravyura": "engraving",
"grazhdanskaya-oborona": "grazhdanskaya-oborona", "grazhdanskaya-oborona": "grazhdanskaya-oborona",

View File

@ -56,9 +56,10 @@ def migrate(entry):
# name # name
fn = entry["profile"].get("firstName", "") fn = entry["profile"].get("firstName", "")
ln = entry["profile"].get("lastName", "") ln = entry["profile"].get("lastName", "")
name = user_dict["slug"] if user_dict["slug"] else "anonymous" name = fn if fn else ""
name = fn if fn else name
name = (name + " " + ln) if ln else name name = (name + " " + ln) if ln else name
if not name:
name = slug if slug else "anonymous"
name = ( name = (
entry["profile"]["path"].lower().strip().replace(" ", "-") entry["profile"]["path"].lower().strip().replace(" ", "-")
if len(name) < 2 if len(name) < 2

View File

@ -107,7 +107,7 @@ class User(Base):
if p.resource not in scope: if p.resource not in scope:
scope[p.resource] = set() scope[p.resource] = set()
scope[p.resource].add(p.operation) scope[p.resource].add(p.operation)
print(scope)
return scope return scope

View File

@ -8,7 +8,7 @@ from resolvers.auth import (
get_current_user, 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.migrate import markdown_body
from resolvers.create.editor import create_shout, delete_shout, update_shout from resolvers.create.editor import create_shout, delete_shout, update_shout
@ -93,8 +93,8 @@ __all__ = [
# create.migrate # create.migrate
"markdown_body", "markdown_body",
# create.collab # create.collab
"invite_author", "invite_coauthor",
"remove_author", "remove_coauthor",
# zine.topics # zine.topics
"topics_all", "topics_all",
"topics_by_community", "topics_by_community",

View File

@ -13,7 +13,7 @@ from auth.identity import Identity, Password
from auth.jwtcodec import JWTCodec from auth.jwtcodec import JWTCodec
from auth.tokenstorage import TokenStorage from auth.tokenstorage import TokenStorage
from base.exceptions import (BaseHttpException, InvalidPassword, InvalidToken, from base.exceptions import (BaseHttpException, InvalidPassword, InvalidToken,
ObjectNotExist, OperationNotAllowed, Unauthorized) ObjectNotExist, Unauthorized)
from base.orm import local_session from base.orm import local_session
from base.resolvers import mutation, query from base.resolvers import mutation, query
from orm import Role, User 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: with local_session() as session:
user = session.query(User).filter(User.email == email).first() user = session.query(User).filter(User.email == email).first()
if user: if user:
raise OperationNotAllowed("User already exist") raise Unauthorized("User already exist")
else: else:
slug = generate_unique_slug(name) slug = generate_unique_slug(name)
user = session.query(User).where(User.slug == slug).first() user = session.query(User).where(User.slug == slug).first()

View File

@ -1,7 +1,7 @@
from auth.authenticate import login_required from auth.authenticate import login_required
from base.orm import local_session from base.orm import local_session
from base.resolvers import query, mutation 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.collab import Collab, CollabAuthor
from orm.shout import Shout from orm.shout import Shout
from orm.user import User from orm.user import User
@ -27,7 +27,7 @@ async def invite_coauthor(_, info, author: str, shout: int):
else: else:
c = session.query(Collab).where(Collab.shout == shout).one() c = session.query(Collab).where(Collab.shout == shout).one()
if user.slug not in c.authors: if user.slug not in c.authors:
raise OperationNotAllowed("you are not in authors list") raise BaseHttpException("you are not in authors list")
else: else:
invited_user = session.query(User).where(User.slug == author).one() invited_user = session.query(User).where(User.slug == author).one()
c.invites.append(invited_user) c.invites.append(invited_user)
@ -47,7 +47,7 @@ async def remove_coauthor(_, info, author: str, shout: int):
if not s: if not s:
raise ObjectNotExist("invalid shout id") raise ObjectNotExist("invalid shout id")
if user.slug != s.createdBy.slug: if user.slug != s.createdBy.slug:
raise OperationNotAllowed("only onwer can remove coauthors") raise BaseHttpException("only onwer can remove coauthors")
else: else:
c = session.query(Collab).where(Collab.shout == shout).one() c = session.query(Collab).where(Collab.shout == shout).one()
ca = session.query(CollabAuthor).where(c.shout == shout, c.author == author).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() session.commit()
return {} return {}
else: else:
raise OperationNotAllowed("only invited can accept") raise BaseHttpException("only invited can accept")

View File

@ -12,6 +12,8 @@ from orm.user import User
from resolvers.zine.reactions import reactions_follow, reactions_unfollow from resolvers.zine.reactions import reactions_follow, reactions_unfollow
from services.zine.gittask import GitTask from services.zine.gittask import GitTask
from resolvers.inbox.chats import create_chat from resolvers.inbox.chats import create_chat
from services.inbox import MessagesStorage
from orm.collab import Collab
@mutation.field("createShout") @mutation.field("createShout")

View File

@ -20,7 +20,7 @@ def add_author_stat_columns(q):
author_followers = aliased(AuthorFollower) author_followers = aliased(AuthorFollower)
author_following = aliased(AuthorFollower) author_following = aliased(AuthorFollower)
shout_author_aliased = aliased(ShoutAuthor) shout_author_aliased = aliased(ShoutAuthor)
user_rating_aliased = aliased(UserRating) # user_rating_aliased = aliased(UserRating)
q = q.outerjoin(shout_author_aliased).add_columns( q = q.outerjoin(shout_author_aliased).add_columns(
func.count(distinct(shout_author_aliased.shout)).label('shouts_stat') 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') # func.sum(user_rating_aliased.value).label('rating_stat')
# ) # )
q = q.add_columns(literal(0).label('commented_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( q = q.outerjoin(Reaction, and_(Reaction.createdBy == User.id, Reaction.body.is_not(None))).add_columns(
# func.count(distinct(Reaction.id)).label('commented_stat') func.count(distinct(Reaction.id)).label('commented_stat')
# ) )
q = q.group_by(User.id) q = q.group_by(User.id)
@ -117,11 +117,17 @@ async def get_followed_authors(_, _info, slug) -> List[User]:
return await followed_authors(slug) return await followed_authors(slug)
async def followed_authors(slug) -> List[User]: async def followed_authors(slug):
with local_session() as session:
user = session.query(User).where(User.slug == slug).first()
q = select(User) q = select(User)
q = add_author_stat_columns(q) q = add_author_stat_columns(q)
q = q.join(AuthorFollower).join(User, User.id == AuthorFollower.follower).where(User.slug == slug) 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) return get_authors_from_query(q)

View File

@ -186,8 +186,8 @@ type Mutation {
deleteReaction(id: Int!): Result! deleteReaction(id: Int!): Result!
# collab # collab
inviteCoauthor(author: String!, shout: int!): Result! inviteCoauthor(author: String!, shout: Int!): Result!
removeCouthor(author: String!, shout: Int!): Result! removeCoauthor(author: String!, shout: Int!): Result!
acceptCoauthor(shout: Int!): Result! acceptCoauthor(shout: Int!): Result!
# following # following
@ -373,23 +373,6 @@ type User {
oid: String 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 { enum ReactionKind {
LIKE LIKE
DISLIKE DISLIKE