Use UTC for tokens_valid_from in user config

This commit is contained in:
Andrew 2024-05-29 13:21:50 -10:00
parent 2a6c0ca751
commit 9ec0044458
5 changed files with 22 additions and 5 deletions

View File

@ -38,7 +38,7 @@ class Users(BaseModel):
superuser = BooleanField(default=False) superuser = BooleanField(default=False)
lang = CharField(default="en_EN") lang = CharField(default="en_EN")
support_logs = CharField(default="") support_logs = CharField(default="")
valid_tokens_from = DateTimeField(default=datetime.datetime.now) valid_tokens_from = DateTimeField(default=Helpers.get_utc_now)
server_order = CharField(default="") server_order = CharField(default="")
preparing = BooleanField(default=False) preparing = BooleanField(default=False)
hints = BooleanField(default=True) hints = BooleanField(default=True)
@ -261,6 +261,8 @@ class HelperUsers:
@staticmethod @staticmethod
def update_user(user_id, up_data=None): def update_user(user_id, up_data=None):
for item in up_data:
print(item, type(item))
if up_data is None: if up_data is None:
up_data = {} up_data = {}
if up_data: if up_data:

View File

@ -1,5 +1,6 @@
import logging import logging
import time import time
from datetime import datetime
from typing import Optional, Dict, Any, Tuple from typing import Optional, Dict, Any, Tuple
import jwt import jwt
from jwt import PyJWTError from jwt import PyJWTError
@ -62,7 +63,14 @@ class Authentication:
user = HelperUsers.get_user(user_id) user = HelperUsers.get_user(user_id)
# TODO: Have a cache or something so we don't constantly # TODO: Have a cache or something so we don't constantly
# have to query the database # have to query the database
if int(user.get("valid_tokens_from").timestamp()) < iat:
valid_tokens_from_str = user.get("valid_tokens_from")
# Convert the string to a datetime object
valid_tokens_from_dt = datetime.strptime(
valid_tokens_from_str, "%Y-%m-%d %H:%M:%S.%f%z"
)
if int(valid_tokens_from_dt.timestamp()) < iat:
# Success! # Success!
return key, data, user return key, data, user
return None return None

View File

@ -19,7 +19,8 @@ import shutil
import shlex import shlex
import subprocess import subprocess
import itertools import itertools
from datetime import datetime from datetime import datetime, timezone
import time
from socket import gethostname from socket import gethostname
from contextlib import redirect_stderr, suppress from contextlib import redirect_stderr, suppress
import libgravatar import libgravatar
@ -640,6 +641,10 @@ class Helpers:
version = f"{major}.{minor}.{sub}" version = f"{major}.{minor}.{sub}"
return str(version) return str(version)
@staticmethod
def get_utc_now() -> datetime:
return datetime.fromtimestamp(time.time(), tz=timezone.utc)
def encode_pass(self, password): def encode_pass(self, password):
return self.passhasher.hash(password) return self.passhasher.hash(password)

View File

@ -1,6 +1,7 @@
import datetime import datetime
import logging import logging
from app.classes.web.base_api_handler import BaseApiHandler from app.classes.web.base_api_handler import BaseApiHandler
from app.classes.shared.helpers import Helpers
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -13,7 +14,7 @@ class ApiAuthInvalidateTokensHandler(BaseApiHandler):
logger.debug(f"Invalidate tokens for user {auth_data[4]['user_id']}") logger.debug(f"Invalidate tokens for user {auth_data[4]['user_id']}")
self.controller.users.raw_update_user( self.controller.users.raw_update_user(
auth_data[4]["user_id"], {"valid_tokens_from": datetime.datetime.now()} auth_data[4]["user_id"], {"valid_tokens_from": Helpers.get_utc_now()}
) )
self.finish_json(200, {"status": "ok"}) self.finish_json(200, {"status": "ok"})

View File

@ -1,10 +1,11 @@
import peewee import peewee
import datetime import datetime
from app.classes.shared.helpers import Helpers
def migrate(migrator, database, **kwargs): def migrate(migrator, database, **kwargs):
migrator.add_columns( migrator.add_columns(
"users", valid_tokens_from=peewee.DateTimeField(default=datetime.datetime.now) "users", valid_tokens_from=peewee.DateTimeField(default=Helpers.get_utc_now)
) )
migrator.drop_columns("users", ["api_token"]) migrator.drop_columns("users", ["api_token"])