feat(api): create token model

!34 #63
This commit is contained in:
2024-06-28 03:57:09 +09:30
parent 66b8d9362d
commit e655f22fac
4 changed files with 102 additions and 0 deletions

View File

@ -0,0 +1,31 @@
# Generated by Django 5.0.6 on 2024-06-27 18:25
import access.fields
import django.db.models.deletion
import django.utils.timezone
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='AuthToken',
fields=[
('id', models.AutoField(primary_key=True, serialize=False, unique=True)),
('note', models.CharField(blank=True, default=None, max_length=50, null=True)),
('token', models.CharField(db_index=True, max_length=64, unique=True, verbose_name='Auth Token')),
('expires', models.DateTimeField(verbose_name='Expiry Date')),
('created', access.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False)),
('modified', access.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]

View File

View File

71
app/api/models/tokens.py Normal file
View File

@ -0,0 +1,71 @@
import hashlib
import random
import string
from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
from access.fields import *
from access.models import TenancyObject
class AuthToken(models.Model):
id = models.AutoField(
primary_key=True,
unique=True,
blank=False
)
note = models.CharField(
blank = True,
max_length = 50,
default = None,
null= True,
)
token = models.CharField(
verbose_name = 'Auth Token',
db_index=True,
max_length = 64,
null = False,
blank = False,
unique = True,
)
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)
expires = models.DateTimeField(
verbose_name = 'Expiry Date',
null = False,
blank = False
)
created = AutoCreatedField()
modified = AutoLastModifiedField()
def generate(self) -> str:
salt = settings.SECRET_KEY
return str(hashlib.sha256(str(self.randomword() + salt).encode('utf-8')).hexdigest())
def randomword(self) -> str:
return ''.join(random.choice(string.ascii_letters) for i in range(120))
def __str__(self):
return self.token