-
Notifications
You must be signed in to change notification settings - Fork 108
Initial implementation of Pbench user model and associated APIs in server #1937
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
dbutenhof
merged 1 commit into
distributed-system-analysis:main
from
npalaska:pbench_user
Mar 5, 2021
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,121 @@ | ||
import jwt | ||
import os | ||
import datetime | ||
from flask import request, abort | ||
from flask_httpauth import HTTPTokenAuth | ||
from pbench.server.database.models.users import User | ||
from pbench.server.database.models.active_tokens import ActiveTokens | ||
|
||
|
||
class Auth: | ||
token_auth = HTTPTokenAuth("Bearer") | ||
|
||
@staticmethod | ||
def set_logger(logger): | ||
# Logger gets set at the time of auth module initialization | ||
dbutenhof marked this conversation as resolved.
Show resolved
Hide resolved
|
||
Auth.logger = logger | ||
|
||
def encode_auth_token(self, token_expire_duration, user_id): | ||
""" | ||
Generates the Auth Token | ||
:return: jwt token string | ||
""" | ||
current_utc = datetime.datetime.utcnow() | ||
payload = { | ||
"iat": current_utc, | ||
"exp": current_utc + datetime.timedelta(minutes=int(token_expire_duration)), | ||
npalaska marked this conversation as resolved.
Show resolved
Hide resolved
|
||
"sub": user_id, | ||
} | ||
|
||
# Get jwt key | ||
jwt_key = self.get_secret_key() | ||
return jwt.encode(payload, jwt_key, algorithm="HS256") | ||
|
||
def get_secret_key(self): | ||
try: | ||
return os.getenv("SECRET_KEY", "my_precious") | ||
except Exception as e: | ||
Auth.logger.exception(f"{__name__}: ERROR: {e.__traceback__}") | ||
dbutenhof marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
def verify_user(self, username): | ||
""" | ||
Check if the provided username belongs to the current user by | ||
querying the Usermodel with the current user | ||
:param username: | ||
:param logger | ||
:return: User (UserModel instance), verified status (boolean) | ||
""" | ||
user = User.query(id=self.token_auth.current_user().id) | ||
# check if the current username matches with the one provided | ||
verified = user is not None and user.username == username | ||
Auth.logger.warning("verified status of user '{}' is '{}'", username, verified) | ||
webbnh marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
return user, verified | ||
|
||
def get_auth_token(self, logger): | ||
# get auth token | ||
auth_header = request.headers.get("Authorization") | ||
|
||
if not auth_header: | ||
logger.warning("Missing expected Authorization header") | ||
abort( | ||
403, | ||
message="Please add 'Authorization' token as Authorization: Bearer <session_token>", | ||
) | ||
|
||
try: | ||
auth_schema, auth_token = auth_header.split() | ||
except ValueError: | ||
logger.warning("Malformed Auth header") | ||
abort( | ||
401, | ||
message="Malformed Authorization header, please add request header as Authorization: Bearer <session_token>", | ||
) | ||
else: | ||
if auth_schema.lower() != "bearer": | ||
logger.warning( | ||
"Expected authorization schema to be 'bearer', not '{}'", | ||
auth_schema, | ||
) | ||
abort( | ||
401, | ||
message="Malformed Authorization header, request auth needs bearer token: Bearer <session_token>", | ||
) | ||
return auth_token | ||
|
||
@staticmethod | ||
@token_auth.verify_token | ||
def verify_auth(auth_token): | ||
""" | ||
Validates the auth token | ||
:param auth_token: | ||
:return: User object/None | ||
""" | ||
try: | ||
payload = jwt.decode( | ||
auth_token, os.getenv("SECRET_KEY", "my_precious"), algorithms="HS256", | ||
) | ||
user_id = payload["sub"] | ||
if ActiveTokens.valid(auth_token): | ||
user = User.query(id=user_id) | ||
return user | ||
except jwt.ExpiredSignatureError: | ||
try: | ||
ActiveTokens.delete(auth_token) | ||
except Exception: | ||
Auth.logger.error( | ||
"User attempted Pbench expired token but we could not delete the expired auth token from the database. token: '{}'", | ||
auth_token, | ||
) | ||
return None | ||
Auth.logger.warning( | ||
"User attempted Pbench expired token '{}', Token deleted from the database and no longer tracked", | ||
auth_token, | ||
) | ||
except jwt.InvalidTokenError: | ||
Auth.logger.warning("User attempted invalid Pbench token '{}'", auth_token) | ||
except Exception: | ||
Auth.logger.exception( | ||
"Exception occurred while verifying the auth token '{}'", auth_token | ||
) | ||
return None |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.