コード例 #1
0
ファイル: views.py プロジェクト: Betty-Kebenei/FlaskAPI
def logout():
    """API can logout a user."""

    #Token retrival
    auth_header = request.headers.get('Authorization', None)

    if not auth_header:
        response = jsonify({'message': 'No token provided!'})
        response.status_code = 500
        return response
    else:
        token = auth_header.split(" ")
        access_token = token[1]
        if access_token:
            user_id = User.decode_auth_token(access_token)
            if not isinstance(user_id, str):
                invalid_token = BlacklistToken(access_token)
                invalid_token.save()
                response = jsonify(
                    {'message': 'You have successfully logged out'})
                response.status_code = 200
                return response

            else:
                response = jsonify({'message': user_id})
                response.status_code = 401
                return response
        else:
            response = jsonify({'message': 'Invalid token'})
            response.status_code = 401
            return response
コード例 #2
0
def logout_user(user):
    """Log out a user
    ---
    tags:
     - "auth"
    parameters:
        - in : "header"
          name: "Authorization"
          description: "Token of logged in user"
          required: true
          type: "string"
    responses:
        200:
            description: "Success"
        401:
            description: "Failed"
    """
    blacklist_token = BlacklistToken(token=user['auth_token'])
    try:
        blacklist_token.save()
        response = {'message': "Successfully logged out", 'status': "Success"}
        return make_response(jsonify(response)), 200
    except Exception as error:
        response = {"message": error, "status": "Failed"}
        return make_response(jsonify(response)), 401
コード例 #3
0
def user_logout():
    """Logout resource."""
    auth_header = request.headers.get("Authorization")
    if auth_header:
        try:
            auth_token = auth_header.split(" ")[1]
        except IndexError:
            response = {"status": "fail", "message": "Bearer token malformed."}
            return make_response(jsonify(response), 401)

    else:
        auth_token = ""
    if auth_token:
        response = User.decode_auth_token(auth_token)
        if not isinstance(response, str):
            # mark the token as blacklisted
            blacklist_token = BlacklistToken(token=auth_token)
            try:
                # insert the token
                blacklist_token.save()
                response = {
                    "status": "success",
                    "message": "Successfully logged out."
                }
                return make_response(jsonify(response), 200)
            except Exception as e:
                response = {"status": "fail", "message": e}
                return make_response(jsonify(response), 200)
        else:
            response = {"status": "fail", "message": response}
            return make_response(jsonify(response), 401)

    else:
        response = {"status": "fail", "message": "Provide a valid auth token."}
        return make_response(jsonify(response), 403)
コード例 #4
0
ファイル: auth.py プロジェクト: Simple2B/mdm-port
 def post(self):
     # get auth token
     args = parser.parse_args()
     auth_header = args["Authorization"]
     if auth_header:
         auth_token = auth_header.split(" ")[1]
     else:
         auth_token = ""
     if auth_token:
         resp = User.decode_auth_token(auth_token)
         if not isinstance(resp, str):
             # mark the token as blacklisted
             blacklist_token = BlacklistToken(token=auth_token)
             try:
                 # insert the token
                 blacklist_token.save()
                 responseObject = {
                     "status": "success",
                     "message": "Successfully logged out.",
                 }
                 return responseObject, 200
             except Exception as e:
                 responseObject = {"status": "fail", "message": e}
                 return responseObject, 200
         else:
             responseObject = {"status": "fail", "message": resp}
             return responseObject, 401
     else:
         responseObject = {
             "status": "fail",
             "message": "Provide a valid auth token.",
         }
         return responseObject, 403
コード例 #5
0
ファイル: views.py プロジェクト: muthash/weConnect-api
 def post(self):
     """Endpoint to logout a user"""
     jti = get_raw_jwt()['jti']
     blacklist = BlacklistToken(token=jti)
     blacklist.save()
     response = {'message': 'Successfully logged out'}
     return jsonify(response), 200
コード例 #6
0
    def test_token_is_successfully_blacklisted(self):
        self.assertTrue(self.user.save())
        user = User.query.filter_by(email=self.user.email).first()
        self.assertIsNotNone(user)
        self.assertEqual(user.email, self.user.email)
        token = user.generate_token(user.id)  # generating the token
        self.assertIsInstance(token, bytes)

        # add the token to the BlacklistToken
        blacklist = BlacklistToken(str(token))
        blacklist.save()
        self.assertTrue(blacklist.is_blacklisted(str(token)))
コード例 #7
0
ファイル: Users.py プロジェクト: lakehub/ote-api
def blacklist_auth_token(current_user):
    """blacklist token"""
    auth_header = None

    if 'Authorization' in request.headers:
        auth_header = request.headers.get('Authorization')

    if auth_header:
        auth_token = list(filter(None, auth_header.split(" ")))[1]
    else:
        auth_token = ''

    if not auth_token:
        response = jsonify({'error': True, 'message': 'token is missing!'})
        response.status_code = 401
        return response

    is_token_blacklisted = BlacklistToken.blacklisted(auth_token)

    if is_token_blacklisted:
        response = jsonify({
            'error': True,
            'message': 'Token already blacklisted'
        })
        response.status_code = 401
        return response

    try:
        data = jwt.decode(auth_token,
                          current_app.config['SECRET'],
                          algorithms=['HS256'])
        _current_user = User.get_by_public_id(data['public_id'])

        if not _current_user:
            response = jsonify({'error': True, 'message': 'token is invalid'})
            response.status_code = 401
            return response

        blacklist_token = BlacklistToken(auth_token)
        blacklist_token.save()

        return jsonify({"error": False, "message": "logout successful"})

    except jwt.ExpiredSignatureError:
        response = jsonify({'error': True, 'message': 'token has expired'})
        response.status_code = 401
        return response

    except jwt.InvalidTokenError:
        response = jsonify({'error': True, 'message': 'token is invalid'})
        response.status_code = 401
        return response
コード例 #8
0
def logout(current_user, user_id):
    access_token = request.headers.get('Authorization')
    if user_id != User.decode_token(access_token):
        response = {'message': 'An error occured.'}
        return make_response(jsonify(response)), 403
    try:
        # insert the token
        blacklist_token = BlacklistToken(token=access_token)
        blacklist_token.save()
        response = {'message': 'Successfully logged out.'}
        return make_response(jsonify(response)), 200
    except Exception as e:
        response = {'message': e}
        return make_response(jsonify(response)), 400
コード例 #9
0
    def post(self, user_type):
        args = parser.parse_args(strict=True)

        # Check aruments are valid or not
        error_mssgs = check_valid_request(args, endpoint='logout')
        # log_info(error_mssgs)

        # Error for invalid arguments
        if error_mssgs:
            return {'status': 'fail', 'msg': error_mssgs}, 400

        auth_header = args.get('Authorization')

        if auth_header:
            try:
                # 'auth_header' format "Authorization: Bearer JWT_TOKEN"
                auth_token = auth_header.split(' ')[1]
            except IndexError:
                return {'status': 'fail', 'msg': 'Bearer token malformed'}, 400
        else:
            return {
                'status': 'fail',
                'msg': "Provide valid 'Authorization' header"
            }, 403

        if user_type == 'buyer':
            User = Buyer
        elif user_type == 'seller':
            User = Seller
        else:
            return {'status': 'fail', 'msg': 'Invalid endpoint'}, 404

        decode = User.decode_auth_token(auth_token)

        if not isinstance(decode, str):
            # mark the token as blacklisted
            blacklist_token = BlacklistToken(token=auth_token)
            try:
                blacklist_token.save()

                response = {
                    'status': 'success',
                    'msg': 'Successfully logged out'
                }
                return response, 200

            except Exception as e:
                return {'status': 'fail', 'msg': e}, 202
        else:
            return {'status': 'fail', 'msg': decode}, 401
コード例 #10
0
ファイル: views.py プロジェクト: muthash/weConnect-api
    def delete(self):
        """Endpoint to delete a user account"""
        data = request.get_json()
        password = data.get('password')
        user_id = get_jwt_identity()
        jti = get_raw_jwt()['jti']

        user_data = dict(password=password)
        if check_missing_field(**user_data):
            return jsonify(check_missing_field(**user_data)), 422

        user = User.query.filter_by(id=user_id).first()
        if not user.password_is_valid(password):
            return self.generate_response(messages['valid_pass'], 401)
        user.delete()
        blacklist = BlacklistToken(token=jti)
        blacklist.save()
        return self.generate_response(messages['delete'], 200)
コード例 #11
0
ファイル: views.py プロジェクト: muthash/weConnect-api
    def put(self):
        """Endpoint to change a user password"""
        data = request.get_json()
        old_password = data.get('old_password')
        new_password = data.get('new_password')
        user_id = get_jwt_identity()
        jti = get_raw_jwt()['jti']

        user_data = dict(old_password=old_password, new_password=new_password)
        if check_missing_field(**user_data):
            return jsonify(check_missing_field(**user_data)), 422
        if check_password(new_password):
            return check_password(new_password)
        user = User.query.filter_by(id=user_id).first()
        if user and user.password_is_valid(old_password):
            password = Bcrypt().generate_password_hash(new_password).decode()
            user.update(user, password=password)
            blacklist = BlacklistToken(token=jti)
            blacklist.save()
            return self.generate_response(messages['password'], 201)
        return self.generate_response(messages['valid_pass'], 401)
コード例 #12
0
    def post():
        """ User can only logout if and only if a user is
        logged in and has an authentication token. """
        user_id, msg, status, status_code, token = parse_auth_header(request)
        if user_id is None:
            return jsonify({"status": status, "message": msg}), status_code

        user = User.query.filter_by(id=user_id).first()
        blacklist = BlacklistToken(token)
        if blacklist.save():  # blacklist token
            return jsonify({
                "status": "success",
                "message": f"Successfully logged out '{user.email}'"
            }), 200
コード例 #13
0
    def post(self, user_in_session):
        """Method to logout the user

         User logout
        ---
        tags:
          - Authentication
        responses:
          200:
            description: User logged out successfully
          400:
            description: Invalid access token
          409:
            description: The user is already logged out!
        """
        access_token = request.headers.get('x-access-token')
        if access_token:
            user_details = Users.query.filter_by(id=user_in_session).first()
            save_tokens = BlacklistToken(token=access_token)
            save_tokens.save()

            return make_response(jsonify({'message': 'User '+str(user_details.username) +
                                                     ' logged out successfully'})), 200
        return make_response(jsonify({'message': 'Invalid access token'})), 400
コード例 #14
0
ファイル: __init__.py プロジェクト: stirlingcarter/HNGR
def logout():
    auth_header = request.headers.get('Authorization')
    if auth_header:
        auth_token = auth_header.split(" ")[1]
    else:
        auth_token = ''
    if auth_token:
        response = User.decode_auth_token(auth_token)
        if not isinstance(response, str):
            #Mark token as blacklisted
            blacklist_token = BlacklistToken(token=auth_token)
            try:
                blacklist_token.save()
                response_object = {
                    'status': 'success',
                    'message': 'Successfully logged out.'
                }
                return jsonify(response_object), 200
            except Exception as e:
                response_object = {
                    'status': 'fail',
                    'message': e
                }
                return jsonify(response_object), 500
        else:
            response_object = {
                'status': 'fail',
                'message': resp
            }
            return jsonify(response_object), 401
    else:
        response_object = {
            'status': 'fail', 
            'message': 'Please return a valid auth token.'
        }
        return jsonify(response_object), 403
コード例 #15
0
ファイル: views.py プロジェクト: graycadeau/Bright-Events
    def post():
        """Makes a post request of the user valid token and black lists it if still valid"""

        # get auth token
        auth_header = request.headers.get('Authorization')
        access_token = auth_header.split(" ")[1]

        if access_token:
            resp = User.decode_token(access_token)
            if isinstance(resp, int):
                # mark the token as blacklisted
                blacklist_token = BlacklistToken(token=access_token)
                try:
                    blacklist_token.save()
                    response_object = jsonify({
                        'status':
                        'success',
                        'message':
                        'Successfully logged out.'
                    })
                    return make_response(response_object), 200
                except Exception as error:
                    response_object = jsonify({
                        'status': 'fail',
                        'message': error
                    })
                    return make_response(response_object), 200

            response_object = {'status': 'fail', 'message': resp}
            return make_response(jsonify(response_object)), 401

        response_object = {
            'status': 'fail',
            'message': 'Provide a valid auth token.'
        }
        return make_response(jsonify(response_object)), 403