Skip to content

Commit

Permalink
fleshed out token auth
Browse files Browse the repository at this point in the history
  • Loading branch information
dantownsend committed Nov 18, 2019
1 parent d61bb6e commit b506fc8
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 4 deletions.
34 changes: 34 additions & 0 deletions piccolo_api/token_auth/endpoints.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from starlette.endpoints import HTTPEndpoint
from starlette.exceptions import HTTPException
from starlette.responses import JSONResponse
from starlette.requests import Request
from piccolo.extensions.user.tables import BaseUser

from .tables import TokenAuth


class TokenAuthLoginEndpoint(HTTPEndpoint):
async def post(self, request: Request) -> JSONResponse:
"""
Return a token if the credentials are correct.
"""
json = await request.json()
username = json.get("username")
password = json.get("password")
if username and password:
user = await BaseUser.login(username=username, password=password)
if user:
token = (
TokenAuth.select(TokenAuth.token)
.first()
.where(TokenAuth.user == user)
)
return JSONResponse({"token": token})
else:
raise HTTPException(
status_code=401, detail="The credentials were incorrect"
)
else:
raise HTTPException(
status_code=401, detail="No credentials were found."
)
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import secrets
import uuid

from asgiref.sync import async_to_sync

from piccolo.columns.column_types import Varchar, ForeignKey
from piccolo.extensions.user.tables import BaseUser
Expand All @@ -12,9 +14,15 @@ class TokenAuth(Table):
Useful for mobile authentication, IOT etc. Session auth is recommended for
web usage.
"""
token = Varchar()

token = Varchar(default=uuid.uuid4)
user = ForeignKey(references=BaseUser)

@classmethod
def create_token(user_id: int):
pass
async def create_token(cls, user_id: int) -> str:
token_auth = await cls(user=user_id).save().run()
return token_auth.token

@classmethod
def create_token_sync(cls, user_id: int) -> str:
return async_to_sync(cls.create_token)(user_id)

0 comments on commit b506fc8

Please sign in to comment.