Commit 82b40c7b authored by Markus Scheidgen's avatar Markus Scheidgen
Browse files

Fix for users without pre existing session token. #172

parent 67874303
......@@ -75,7 +75,8 @@ class User(Base): # type: ignore
@staticmethod
def create_user(
email: str, password: str, crypted: bool, user_id: int = None,
affiliation: Dict[str, str] = None, token: str = None, **kwargs):
affiliation: Dict[str, str] = None, token: str = None, generate_token: bool = True,
**kwargs):
repo_db = infrastructure.repository_db
repo_db.begin()
try:
......@@ -88,9 +89,10 @@ class User(Base): # type: ignore
user.set_password(password, crypted)
# TODO this has to change, e.g. trade for JWTs
if token is None:
if token is None and generate_token:
token = ''.join(random.choices(User._token_chars, k=64))
repo_db.add(Session(token=token, user=user))
if token is not None:
repo_db.add(Session(token=token, user=user))
repo_db.commit()
return user
......@@ -126,8 +128,23 @@ class User(Base): # type: ignore
def get_auth_token(self):
repo_db = infrastructure.repository_db
session = repo_db.query(Session).filter_by(user_id=self.user_id).first()
if not session:
raise LoginException('No session, user probably not logged in at NOMAD-coe repository GUI')
# No session, user probably not logged in at NOMAD-coe repository GUI
repo_db.begin()
try:
# TODO this has to change, e.g. trade for JWTs
token = ''.join(random.choices(User._token_chars, k=64))
session = Session(token=token, user=self)
repo_db.add(session)
repo_db.commit()
except Exception as e:
repo_db.rollback()
utils.get_logger('__name__').error(
'could not generate token for user', email=self.email, user_id=self.user_id,
exc_info=e)
raise e
return session.token.encode('utf-8')
......
......@@ -46,6 +46,15 @@ def test_password_authorize(test_user):
assert_user(user, test_user)
def test_generate_token(postgres_infra):
user = User.create_user(
'test@email.com', 'password', False,
first_name='test', last_name='test',
affiliation=dict(name='institut', address='address'),
generate_token=False)
assert user.get_auth_token() is not None
def assert_coe_upload(upload_id: str, upload: datamodel.UploadWithMetadata = None, user_metadata: dict = None):
coe_upload = Upload.from_upload_id(upload_id)
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment