summaryrefslogtreecommitdiff
path: root/src/services/api/graphql/libs/token_auth.py
diff options
context:
space:
mode:
authorJohn Estabrook <jestabro@vyos.io>2022-10-23 11:08:06 -0500
committerJohn Estabrook <jestabro@vyos.io>2022-10-25 10:35:48 -0500
commit28676844e3f4317786e457fcd8651939a05c88ff (patch)
tree1031b5079f076584a9c9a40833d4452bf33106d4 /src/services/api/graphql/libs/token_auth.py
parentaf56ddf4615974c6b5f5886520d6abb0781cea80 (diff)
downloadvyos-1x-28676844e3f4317786e457fcd8651939a05c88ff.tar.gz
vyos-1x-28676844e3f4317786e457fcd8651939a05c88ff.zip
graphql: T4574: add context to read token in queries/mutations
Diffstat (limited to 'src/services/api/graphql/libs/token_auth.py')
-rw-r--r--src/services/api/graphql/libs/token_auth.py29
1 files changed, 29 insertions, 0 deletions
diff --git a/src/services/api/graphql/libs/token_auth.py b/src/services/api/graphql/libs/token_auth.py
index c53e354b1..2d63a1cc7 100644
--- a/src/services/api/graphql/libs/token_auth.py
+++ b/src/services/api/graphql/libs/token_auth.py
@@ -36,3 +36,32 @@ def generate_token(user: str, passwd: str, secret: str) -> dict:
users |= {user_id: user}
return {'token': token}
+
+def get_user_context(request):
+ context = {}
+ context['request'] = request
+ context['user'] = None
+ if 'Authorization' in request.headers:
+ auth = request.headers['Authorization']
+ scheme, token = auth.split()
+ if scheme.lower() != 'bearer':
+ return context
+
+ try:
+ secret = state.settings.get('secret')
+ payload = jwt.decode(token, secret, algorithms=["HS256"])
+ user_id: str = payload.get('sub')
+ if user_id is None:
+ return context
+ except jwt.PyJWTError:
+ return context
+ try:
+ users = state.settings['app'].state.vyos_token_users
+ except AttributeError:
+ return context
+
+ user = users.get(user_id)
+ if user is not None:
+ context['user'] = user
+
+ return context