def wrap(*args, **kwargs): token = None if 'Authorization' in request.headers: token = request.headers['Authorization'] if not token: return jsonify({'message': 'Token is missing!'}), 403 is_blacklisted_token = BlacklistToken.check_blacklist(token) if is_blacklisted_token: return jsonify( {'message': 'Token blacklisted. Please log in again.'}), 403 try: # try to decode the token using our SECRET variable payload = jwt.decode(token, app.config['SECRET_KEY']) current_user = payload['sub'] # return current_user except jwt.ExpiredSignatureError: # the token is expired, return an error string return jsonify( {"messge": "Expired token. Please login to get a new token"}), 403 except jwt.InvalidTokenError: # the token is invalid, return an error string return jsonify( {'message': 'Invalid token. Please register or login'}), 403 return function(current_user, *args, **kwargs)
def decode_auth_token(auth_token): """ Decodes the auth token :param auth_token: :return: integer|string """ try: is_blacklisted_token = BlacklistToken.check_blacklist(auth_token) if is_blacklisted_token: return "Token blacklisted. Please log in again." else: payload = jwt.decode(auth_token, os.environ.get("SECRET_KEY"), algorithms=["HS256"]) return payload["sub"] except jwt.ExpiredSignatureError: return "Signature expired. Please log in again." except jwt.InvalidTokenError: return "Invalid token. Please log in again."
def _decode_token(token, user_id, type_: str = 'auth'): """ Decodes the token received :param token: The token to be decoded :param user_id: Unique name of user :return: integer|string """ try: # First check if token has already been blacklisted is_blacklisted_token = BlacklistToken.check_blacklist(token) # If blacklisted, notify user to re-login if is_blacklisted_token: return "Token blacklisted. Please log in again" else: # Decode the valid token payload = jwt.decode(token, app.config.get('JWT_SECRET_KEY'), algorithms=["HS256"]) # Check if token provided really belongs to the currently logged in user whose user_id has been given if user_id != payload['sub']: return 'Incorrect user' # Ensure that the token has correct access level eg type_ = 'refresh' for refreshing if type_ != payload['type']: return 'Incorrect access level' if payload['type'] not in ('refresh', 'auth'): raise JWTDecodeError("Missing or invalid claim: type") # Return user identified by token return payload['sub'], 0 # Token is used after it’s expired (time specified in the payload’s exp field has expired) except jwt.ExpiredSignatureError: return 'Signature expired. Please log in again.' # Token supplied is not correct or malformed except jwt.InvalidTokenError: return 'Invalid token. Please log in again.' except Exception as err: print('DECODE ERROR {}'.format(repr(err))) system_logging(err, exception=True) return 'Error decoding token'
def nd_view(*args, **kwargs): try: auth_t = auth_token(request) if BlacklistToken.check_blacklist(auth_t): responseObject = { 'status': 'fail', 'message': 'Token already used. Please do not perform malpractices.' } if auth_t: resp = User.decode_auth_token(auth_t) if not isinstance(resp, str): u = User.query.filter_by(vid=resp).first() if u is None: responseObject = { 'status': 'fail', 'message': 'Go check your DB' } return jsonify(responseObject) else: responseObject = { 'status': 'fail', 'message': 'Authorization failure:C1' } return jsonify(responseObject) else: responseObject = { 'status': 'fail', 'message': 'Authorization failure:C2' } return jsonify(responseObject) except Exception as e: print(e) # Send mail on the exception # return 401 return func(u, *args, **kwargs)
def post(self): print(request.args) print(request.get_json()) data = request.get_json() token = data.get('idtoken') print(token) try: idinfo = id_token.verify_oauth2_token(token, requests.Request()) print("DEBUGGING = ", idinfo['iss']) if idinfo['iss'] not in [ 'accounts.google.com', 'https://accounts.google.com' ]: raise ValueError('Wrong issuer.') userid = idinfo['sub'] except Exception as e: print(e) # flog = FarerLog(action="Login", point=point, status="error", message="ValueError - wrong issuer") # Send email on the error print("Error encountered - ValueError - Wrong issuer") return "Error encountered - ValueError - Wrong issuer" print(idinfo['email']) u = User.query.filter_by(id=userid).first() print(u) if u is None: try: u = User(id=userid, email=idinfo.get('email'), fname=idinfo.get('given_name'), lname=idinfo.get('family_name'), ppic=idinfo.get('picture')) # flog = FarerLog(vid=u.id, action="Register", point=point, ip=ip) # db.session.add(flog) print("TRYING TO ADD TO DB = ", u) db.session.add(u) db.session.commit() try: farer_welcome_mail(user=u) u.mailsent = True db.session.commit() except Exception as e: print(e) print("Mail error") auth_token = u.encode_auth_token() while BlacklistToken.check_blacklist(auth_token): auth_token = u.encode_auth_token() responseObject = { 'status': 'success', 'message': 'Successfully registered', 'auth_token': auth_token.decode() } print("RESPONOSE = ", responseObject) return jsonify(responseObject) except Exception as e: responseObject = { 'status': 'error', 'message': 'Error1 - Please try again' } print("Error", e) # Send mail on the error return jsonify(responseObject) else: try: auth_token = u.encode_auth_token() responseObject = { 'status': 'success', 'message': 'Successfully logged in', 'auth_token': auth_token.decode() } return jsonify(responseObject) except Exception as e: responseObject = { 'status': 'fail', 'message': 'Error2 - Please try again' } print(e) # Send mail on the error return jsonify(responseObject) return "Other worldly!"