def get_or_new_token(self, user_id: int, icu_id: int, admin_id: int = None, update=False) -> str: """Returns the token for a user-icu. May insert it in the database. If the token is stale, set a new one in the database. Args: user_id: the user id associated with the token. icu_id: the icu id associated with the token. admin_id: if set the user id of the admin requesting this token. update: if True, may update the token if it is stale in the db. """ token_obj = self.db.get_token_from_ids(user_id, icu_id) # This token does not exist, create one. if token_obj is None: return self.db.add_token( admin_id, store.UserICUToken(user_id=user_id, icu_id=icu_id)) # We do not wish to update stale tokens, return the current one. if self.validity is None or not update: return token_obj.token delta = self.validity + 1 if token_obj.last_modified is not None: time_delta = datetime.datetime.utcnow() - token_obj.last_modified delta = time_delta.total_seconds() / 86400 # The token has expired. Renew it. if delta > self.validity: return self.db.renew_token(admin_id, user_id, icu_id) return token_obj.token
def test_user_not_in_icu(self): other_icu_id = self.db.add_icu(self.admin_id, store.ICU(name='other')) token = self.db.add_token( self.admin_id, store.UserICUToken(user_id=self.user_id, icu_id=other_icu_id)) self.assertIsNotNone(self.authenticator.decode(token)) self.assertIsNone(self.authenticator.authenticate(token))
def test_icu_is_off(self): self.db.update_icu(self.admin_id, self.icu_id, dict(is_active=False)) token = self.db.add_token( self.admin_id, store.UserICUToken(user_id=self.user_id, icu_id=self.icu_id)) self.assertIsNotNone(self.authenticator.decode(token)) self.assertIsNone(self.authenticator.authenticate(token))
def test_from_db(self): token = self.db.add_token( self.admin_id, store.UserICUToken(user_id=self.user_id, icu_id=self.icu_id)) user_icu = self.authenticator.authenticate(token) self.assertIsNotNone(user_icu) user, icu = user_icu self.assertEqual(user.user_id, self.user.user_id) self.assertEqual(icu.icu_id, self.icu.icu_id)
def test_user_icu_token(self): icu_id = self.add_icu('icu') user_id = self.admin_user_id self.assertFalse(self.store.has_token(user_id, icu_id)) self.assertIsNone(self.store.get_token_from_ids(user_id, icu_id)) token_obj = db_store.UserICUToken(user_id=user_id, icu_id=icu_id) token_str = self.store.add_token(self.admin_user_id, token_obj) self.assertEqual(len(token_str), db_store.UserICUToken.TOKEN_SIZE) self.assertTrue(self.store.has_token(user_id, icu_id)) with self.assertRaises(ValueError): self.store.add_token(self.admin_user_id, token_obj) token_obj = self.store.get_token_from_ids(user_id, icu_id) self.assertIsNotNone(token_obj) self.assertEqual(token_obj.token, token_str) # Now renew the token. renewed_token_str = self.store.renew_token(None, user_id, icu_id) renewed_token = self.store.get_token(renewed_token_str) self.assertNotEqual(token_str, renewed_token)