Skip to content

Commit 9d2860d

Browse files
authored
Merge pull request #244 from CodeForPhilly/198-refresh
Adds server side of JWT refresh
2 parents af696f7 + e46eb46 commit 9d2860d

File tree

2 files changed

+41
-3
lines changed

2 files changed

+41
-3
lines changed

src/server/api/jwt_ops.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,12 @@ def create_token(username, accesslevel):
3434
return jsonify(access_token=new_token)
3535

3636

37-
def get_jwt_user():
38-
""" Read the JWT and return the associated username """
39-
return get_jwt_identity()
37+
def validate_decode_jwt():
38+
""" If valid, return jwt fields as a dictionary, else None """
39+
jwtdict = None
40+
try:
41+
jwtdict = verify_jwt_in_request()[1]
42+
except:
43+
pass # Wasn't valid - either expired or failed validation
44+
45+
return jwtdict

src/server/api/user_api.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,38 @@ def user_logout():
143143
return jsonify("Logged out " + username)
144144

145145

146+
# Generate a new access token
147+
148+
@user_api.route("/api/user/refresh", methods=["GET"])
149+
@jwt_ops.jwt_required()
150+
def user_refresh():
151+
""" If user still active, send back an access_token with a new expiration stamp """
152+
old_jwt = jwt_ops.validate_decode_jwt()
153+
154+
# If token bad, should be handled & error message sent by jwt_required() and we won't get here
155+
if old_jwt:
156+
user_name = old_jwt['sub']
157+
with engine.connect() as connection:
158+
159+
s = text( """select active from pdp_users where username=:u """ )
160+
s = s.bindparams(u=user_name)
161+
result = connection.execute(s)
162+
163+
if result.rowcount: # Did we get a match on username?
164+
is_active = result.fetchone()
165+
else:
166+
log_user_action(user_name, "Failure", "Valid JWT presented for refesh attempt on unknown username")
167+
return jsonify("Bad credentials"), 401
168+
169+
if is_active[0].lower() == 'y': # In the user DB and still Active?
170+
token = jwt_ops.create_token(user_name,old_jwt['role'])
171+
return token
172+
173+
else:
174+
return jsonify("Bad credentials"), 401
175+
176+
177+
146178
### Unexpired *Admin* JWT required ############################
147179

148180

0 commit comments

Comments
 (0)