- user_content = None
-
- # Try using username/password
- if indata.get("username"):
- user_rows = self.db.get_list("users", {"username": indata.get("username")})
- if user_rows:
- user_content = user_rows[0]
- salt = user_content["_admin"]["salt"]
- shadow_password = sha256(indata.get("password", "").encode('utf-8') + salt.encode('utf-8')).hexdigest()
- if shadow_password != user_content["password"]:
- user_content = None
- if not user_content:
- raise AuthException("Invalid username/password", http_code=HTTPStatus.UNAUTHORIZED)
- elif session:
- user_rows = self.db.get_list("users", {"username": session["username"]})
- if user_rows:
- user_content = user_rows[0]
- else:
- raise AuthException("Invalid token", http_code=HTTPStatus.UNAUTHORIZED)
- else:
- raise AuthException("Provide credentials: username/password or Authorization Bearer token",
- http_code=HTTPStatus.UNAUTHORIZED)
-
- token_id = ''.join(random_choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
- for _ in range(0, 32))
- project_id = indata.get("project_id")
- if project_id:
- if project_id != "admin":
- # To allow project names in project_id
- proj = self.db.get_one("projects", {BaseTopic.id_field("projects", project_id): project_id})
- if proj["_id"] not in user_content["projects"] and proj["name"] not in user_content["projects"]:
- raise AuthException("project {} not allowed for this user"
- .format(project_id), http_code=HTTPStatus.UNAUTHORIZED)
- else:
- project_id = user_content["projects"][0]
- if project_id == "admin":
- session_admin = True
- else:
- # To allow project names in project_id
- project = self.db.get_one("projects", {BaseTopic.id_field("projects", project_id): project_id})
- session_admin = project.get("admin", False)
- new_session = {"issued_at": now, "expires": now + 3600,
- "_id": token_id, "id": token_id, "project_id": project_id, "username": user_content["username"],
- "remote_port": remote.port, "admin": session_admin}
- if remote.name:
- new_session["remote_host"] = remote.name
- elif remote.ip:
- new_session["remote_host"] = remote.ip
-
- self.tokens_cache[token_id] = new_session
- self.db.create("tokens", new_session)
- # check if database must be prune
- self._internal_tokens_prune(now)
- return deepcopy(new_session)
-
- def _internal_get_token_list(self, session):
- now = time()
- token_list = self.db.get_list("tokens", {"username": session["username"], "expires.gt": now})