From 810bbe7bbbdefe4b558f8d870656bee2f32add70 Mon Sep 17 00:00:00 2001 From: Frederick Muriuki Muriithi Date: Fri, 20 Jan 2023 11:44:42 +0300 Subject: auth: Save token with update If the token already exists, then update the details rather than trying to insert. --- .../authentication/oauth2/models/oauth2token.py | 30 ++++++++++++++-------- 1 file changed, 19 insertions(+), 11 deletions(-) (limited to 'gn3/auth/authentication/oauth2/models') diff --git a/gn3/auth/authentication/oauth2/models/oauth2token.py b/gn3/auth/authentication/oauth2/models/oauth2token.py index ce7caae..8b73e59 100644 --- a/gn3/auth/authentication/oauth2/models/oauth2token.py +++ b/gn3/auth/authentication/oauth2/models/oauth2token.py @@ -107,14 +107,22 @@ def save_token(conn: db.DbConnection, token: OAuth2Token) -> None: """Save/Update the token.""" with db.cursor(conn) as cursor: cursor.execute( - "INSERT INTO oauth2_tokens VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", - (str(token.token_id), str(token.client.client_id), token.token_type, - token.access_token, token.refresh_token, token.scope, - 1 if token.revoked else 0, int(token.issued_at.timestamp()), - token.expires_in, str(token.user.user_id))) - ## If already exists - # cursor.execute( - # ("UPDATE oauth2_tokens SET refresh_token=?, revoked=?, " - # "expires_in=? WHERE token_id=?"), - # (token.refresh_token, token.scope, 1 if token.revoked else 0, - # token.expires_in, str(token.token_id))) + ("INSERT INTO oauth2_tokens VALUES (:token_id, :client_id, " + ":token_type, :access_token, :refresh_token, :scope, :revoked, " + ":issued_at, :expires_in, :user_id) " + "ON CONFLICT (token_id) DO UPDATE SET " + "refresh_token=:refresh_token, revoked=:revoked, " + "expires_in=:expires_in " + "WHERE token_id=:token_id"), + { + "token_id": str(token.token_id), + "client_id": str(token.client.client_id), + "token_type": token.token_type, + "access_token": token.access_token, + "refresh_token": token.refresh_token, + "scope": token.get_scope(), + "revoked": 1 if token.revoked else 0, + "issued_at": int(token.issued_at.timestamp()), + "expires_in": token.expires_in, + "user_id": str(token.user.user_id) + }) -- cgit v1.2.3