Add basic API functions and working account.auth method
This commit is contained in:
@@ -1,3 +1,54 @@
|
||||
from django.db import models
|
||||
from datetime import datetime
|
||||
|
||||
# Create your models here.
|
||||
from django.db import models
|
||||
from account.models import SiteUser
|
||||
|
||||
from hashlib import sha512
|
||||
from django.contrib.auth.hashers import check_password
|
||||
|
||||
from .api_errors import *
|
||||
|
||||
|
||||
class UserToken(models.Model):
|
||||
user = models.ForeignKey(SiteUser, on_delete=models.CASCADE)
|
||||
access_token = models.CharField(max_length=128, editable=False, unique=True)
|
||||
creation_time = models.DateTimeField(default=datetime.now)
|
||||
|
||||
@staticmethod
|
||||
def create_token(user: SiteUser):
|
||||
source = bytearray(user.email + user.password + str(datetime.now()), 'utf-8')
|
||||
h = sha512(source).hexdigest()
|
||||
|
||||
# чекаем токен в базе
|
||||
if UserToken.objects.filter(access_token=h).count() != 0:
|
||||
# по какой-то причине есть, выкидываем исключение
|
||||
raise Exception(API_ERROR_TOKEN_CREATION)
|
||||
|
||||
token = UserToken(access_token=h, user=user)
|
||||
token.save()
|
||||
|
||||
print(f"created token {token.access_token[:16]}...")
|
||||
|
||||
return token
|
||||
|
||||
@staticmethod
|
||||
def auth(login: str, password: str):
|
||||
user = SiteUser.objects.filter(email=login)
|
||||
|
||||
if len(user) == 0:
|
||||
raise Exception(API_ERROR_INVALID_LOGIN)
|
||||
|
||||
if not check_password(password, user[0].password):
|
||||
raise Exception(API_ERROR_INVALID_PASSWORD)
|
||||
|
||||
return user[0]
|
||||
|
||||
@staticmethod
|
||||
def get_user_by_token(token: str):
|
||||
t = UserToken.objects.get(access_token=token)
|
||||
if t is None:
|
||||
raise Exception(API_ERROR_INVALID_TOKEN)
|
||||
return t.user
|
||||
|
||||
def __str__(self):
|
||||
return self.user.email + ": " + self.access_token[:10] + "..."
|
||||
|
||||
Reference in New Issue
Block a user