register user, sign in and sign out working

This commit is contained in:
knst-kotov 2021-06-29 13:26:46 +03:00
parent 2dac73b412
commit c9b3d3a833
14 changed files with 81 additions and 30 deletions

View File

@ -56,9 +56,8 @@ class JWTAuthenticate(AuthenticationBackend):
if JWT_AUTH_HEADER not in request.headers: if JWT_AUTH_HEADER not in request.headers:
return AuthCredentials(scopes=[]), AuthUser(user_id=None) return AuthCredentials(scopes=[]), AuthUser(user_id=None)
auth = request.headers[JWT_AUTH_HEADER] token = request.headers[JWT_AUTH_HEADER]
try: try:
scheme, token = auth.split()
payload = await _Authenticate.verify(token) payload = await _Authenticate.verify(token)
except Exception as exc: except Exception as exc:
return AuthCredentials(scopes=[], error_message=str(exc)), AuthUser(user_id=None) return AuthCredentials(scopes=[], error_message=str(exc)), AuthUser(user_id=None)

View File

@ -3,7 +3,7 @@ from datetime import datetime, timedelta
from auth.token import Token from auth.token import Token
from redis import redis from redis import redis
from settings import JWT_LIFE_SPAN from settings import JWT_LIFE_SPAN
from validations import User from auth.validations import User
class Authorize: class Authorize:
@ -30,7 +30,7 @@ class Authorize:
except: # noqa except: # noqa
pass pass
else: else:
await redis.execute("DEL", f"{payload.id}-{token}") await redis.execute("DEL", f"{payload.user_id}-{token}")
return True return True
@staticmethod @staticmethod

View File

@ -2,7 +2,7 @@ from auth.password import Password
from exceptions import InvalidPassword, ObjectNotExist from exceptions import InvalidPassword, ObjectNotExist
from orm import User as OrmUser from orm import User as OrmUser
from orm.base import global_session from orm.base import global_session
from validations import User from auth.validations import User
class Identity: class Identity:

View File

@ -3,7 +3,7 @@ from datetime import datetime
import jwt import jwt
from settings import JWT_ALGORITHM, JWT_SECRET_KEY from settings import JWT_ALGORITHM, JWT_SECRET_KEY
from validations import PayLoad, User from auth.validations import PayLoad, User
class Token: class Token:

View File

@ -20,9 +20,10 @@ class PayLoad(BaseModel):
class CreateUser(BaseModel): class CreateUser(BaseModel):
email: Text
username: Text username: Text
# age: Optional[int] # age: Optional[int]
# phone: Optional[Text] # phone: Optional[Text]
password: Optional[Text] password: Optional[Text]
# TODO: update validations # TODO: update validations

View File

@ -6,12 +6,12 @@ from starlette.applications import Starlette
from starlette.middleware import Middleware from starlette.middleware import Middleware
from starlette.middleware.authentication import AuthenticationMiddleware from starlette.middleware.authentication import AuthenticationMiddleware
from authority.authenticate import JWTAuthenticate from auth.authenticate import JWTAuthenticate
from redis import redis from redis import redis
from resolvers.base import resolvers from resolvers.base import resolvers
import_module('resolvers') import_module('resolvers')
schema = make_executable_schema(load_schema_from_path("schema.graphql"), resolvers) schema = make_executable_schema(load_schema_from_path("schema/"), resolvers)
middleware = [Middleware(AuthenticationMiddleware, backend=JWTAuthenticate())] middleware = [Middleware(AuthenticationMiddleware, backend=JWTAuthenticate())]

View File

@ -1,4 +1,7 @@
from orm.rbac import Operation, Permission, Role from orm.rbac import Operation, Permission, Role
from orm.user import User from orm.user import User
from orm.base import Base, engine
__all__ = ["User", "Role", "Operation", "Permission"] __all__ = ["User", "Role", "Operation", "Permission"]
Base.metadata.create_all(engine)

View File

@ -9,11 +9,11 @@ from orm.base import Base
class User(Base): class User(Base):
__tablename__ = 'user' __tablename__ = 'user'
name: str = Column(String, nullable=False, comment="Name") email: str = Column(String, nullable=False)
username: str = Column(String, nullable=False, comment="Name")
password: str = Column(String, nullable=False, comment="Password") password: str = Column(String, nullable=False, comment="Password")
# phone: str = Column(String, comment="Phone")
# age: int = Column(Integer, comment="Age") role_id: int = Column(ForeignKey("role.id"), nullable=True, comment="Role")
role_id: int = Column(ForeignKey("role.id"), nullable=False, comment="Role")
@classmethod @classmethod
def get_permission(cls, user_id): def get_permission(cls, user_id):

View File

@ -1,3 +1,3 @@
from resolvers.login import get_user, login, logout, register from resolvers.auth import sign_in, sign_out, register
__all__ = ["get_user", "login", "logout", "register"] __all__ = ["sign_in", "sign_out", "register"]

View File

@ -11,35 +11,35 @@ from resolvers.base import mutation, query
from settings import JWT_AUTH_HEADER from settings import JWT_AUTH_HEADER
@mutation.field("SignUp") @mutation.field("registerUser")
async def register(*_, create: dict = None) -> User: async def register(*_, input: dict = None) -> User:
create_user = CreateUser(**create) create_user = CreateUser(**input)
create_user.password = Password.encode(create_user.password) create_user.password = Password.encode(create_user.password)
return User.create(**create_user.dict()) return User.create(**create_user.dict())
@query.field("SignIn") @query.field("signIn")
async def login(_, info: GraphQLResolveInfo, id: int, password: str) -> str: async def sign_in(_, info: GraphQLResolveInfo, id: int, password: str):
try: try:
device = info.context["request"].headers['device'] device = info.context["request"].headers['device']
except KeyError: except KeyError:
device = "pc" device = "pc"
auto_delete = False if device == "mobile" else True auto_delete = False if device == "mobile" else True
user = Identity.identity(user_id=id, password=password) user = Identity.identity(user_id=id, password=password)
return await Authorize.authorize(user, device=device, auto_delete=auto_delete) token = await Authorize.authorize(user, device=device, auto_delete=auto_delete)
return {"status" : True, "token" : token}
# TODO: implement some queries, ex. @query.field("isUsernameFree") @query.field("signOut")
@query.field("logout")
@login_required @login_required
async def logout(_, info: GraphQLResolveInfo, id: int) -> bool: async def sign_out(_, info: GraphQLResolveInfo):
token = info.context["request"].headers[JWT_AUTH_HEADER] token = info.context["request"].headers[JWT_AUTH_HEADER]
return await Authorize.revoke(token) status = await Authorize.revoke(token)
return {"status" : status}
@query.field("getUser") #@query.field("getUser")
@login_required #@login_required
async def get_user(*_, id: int): async def get_user(*_, id: int):
return global_session.query(User).filter(User.id == id).first() return global_session.query(User).filter(User.id == id).first()

View File

@ -60,7 +60,7 @@ type Mutation {
# proposal # proposal
createProposal(shout: Int!, range: String!): Boolean! createProposal(shout: Int!, range: String!): Boolean!
updateProposal(proposal: Int!, body: String!): Boolean! updateProposal(proposal: Int!, body: String!): Boolean!
removeProposal(proposal: Int!) removeProposal(proposal: Int!): Boolean!
approveProposal(proposal: Int!): Boolean! approveProposal(proposal: Int!): Boolean!
} }

View File

@ -0,0 +1,46 @@
type Role {
id: Int!
name: String!
}
type User {
createdAt: DateTime!
email: String
emailConfirmed: Boolean
id: Int!
muted: Boolean
rating: Int
roles: [Role!]!
updatedAt: DateTime!
username: String
userpic: String
userpicId: String
wasOnlineAt: DateTime
}
input registerUserInput {
email: String!
username: String!
password: String!
}
type signInPayload {
status: Boolean!
error: String
token: String
}
type signOutPayload {
status: Boolean!
error: String
}
type Query{
signIn(id: Int!, password: String!): signInPayload!
signOut: signOutPayload!
}
type Mutation{
registerUser(input: registerUserInput!): User!
}

View File

@ -0,0 +1,2 @@
scalar DateTime

View File

@ -5,4 +5,4 @@ JWT_ALGORITHM = "HS256"
JWT_SECRET_KEY = "8f1bd7696ffb482d8486dfbc6e7d16dd-secret-key" JWT_SECRET_KEY = "8f1bd7696ffb482d8486dfbc6e7d16dd-secret-key"
JWT_LIFE_SPAN = 24 * 60 * 60 # seconds JWT_LIFE_SPAN = 24 * 60 * 60 # seconds
JWT_AUTH_HEADER = "Auth" JWT_AUTH_HEADER = "Auth"
REDIS_URL = "redis://redis" REDIS_URL = "redis://127.0.0.1"