예제 #1
0
    def delete(self, username):
        """
        This endpoint deletes a user by its username
        ---
        tags:
          - Users
        parameters:
          - in: path
            name: username
            required: true
            description: The username of the User!
            type: string
        responses:
          responses:
            200:
              description: User deleted
            401:
              description: Authorization required
            403:
              description: Admin privilege required
        """
        # Checking claims for actually execute or not the request as expected
        claims = get_jwt_claims()
        if not claims['is_admin']:
            return {'message': 'Admin privilege required'}, 403

        user = UserModel.find_by_username(username)
        if user:
            user.delete_from_db()
        return {'message': 'User deleted'}
예제 #2
0
 def _get_or_404(self, username):
     store = UserModel.find_by_username(username)
     if store is None:
         abort(
             404,
             message='User with username {} not found'.format(username))
     else:
         return store
예제 #3
0
    def post(self):
        data = UserRegister.parser.parse_args()

        if not data.get('phone', None) is None:
            parsed_phone = parse_phone(data['phone'])
            if parsed_phone is None:
                return {"message": "Invalid phone format for the user"}, 400

            data['phone'] = "-".join(parsed_phone).strip('-')

        if UserModel.find_by_username(data['username']):
            return {"message": "A user with that username already exists"}, 400

        user = UserModel(**data)
        try:
            user.save_to_db()
        except:
            return {"message": "An error occurred creating the user."}, 500

        return {"message": "User created successfully."}, 201
예제 #4
0
    def post(self):
        """This endpoint allows a user to login with the right credentials
        Standard login endpoint. Will return ONLY a fresh access token
        All following lines until the hyphens is added to description
        the format of the first lines until 3 hyphens will be not yaml compliant
        but everything below the 3 hyphens should be.
        ---
        tags:
          - Auth
        parameters:
          - in: body
            name: body
            schema:
              type: object
              properties:
                username:
                  type: string
                  required: true
                  description: The username of the user
                password:
                  type: string
                  required: true
                  description: The password of the user
        responses:
          201:
            description: User logged in successfully
            schema:
              type: object
              properties:
                message:
                  type: string
                  default: User logged in successfully
          401:
            id: message
            description: User not logged in
            schema:
              type: object
              properties:
                message:
                  type: string
                  default: Wrong credentials
          422:
            id: message
            description: Data sent not possible to understand
            schema:
              type: object
              properties:
                message:
                  type: string
                  default: Missing JSON in request
        """
        if not request.is_json:
            response = jsonify({"message": "Missing JSON in request"})
            response.status_code = 400  # Or 422, need to double check
            return response

        data = UserLogin.parser.parse_args()

        try:
            UserModel.login_valid(data['username'], data['password'])
        except (IncorrectPasswordError, UserNotFoundError) as loginEx:
            response = jsonify({'message': loginEx.message})
            response.status_code = 401
            return response

        current_user = UserModel.find_by_username(data['username'])

        # create_access_token supports an optional 'fresh' argument,
        # which marks the token as fresh or non-fresh accordingly.
        # As we just verified their username and password, we are
        # going to mark the token as fresh here.
        access_token = create_access_token(
            identity=current_user, fresh=True)

        # Store the token in our database with a status non-revoked.
        add_token_to_database(access_token,
                              current_app.config['JWT_IDENTITY_CLAIM'])

        raw_response = {
            'message': 'Logged in as {}'.format(current_user.username),
            'access_token': access_token,
            'user_id': current_user.id,
        }

        # Creating the response
        response = jsonify(raw_response)
        response.status_code = 200

        # This header is used for Swagger-UI, it uses this header to authenticate the following requests.
        # This header is used for Swagger-UI, it uses this header to authenticate the following requests.
        response.headers.extend({'jwt-token': access_token})
        response.headers.extend({'access_csrf': get_csrf_token(access_token)})

        # By default, the CSRF double submit values are sent back as additional cookies to the caller.
        # If you prefer, you can disable that, and send them back directly to the caller,
        # returning the double submit values in the resulting JSON, instead of in additional cookies:
        if not current_app.config['JWT_CSRF_IN_COOKIES']:
            # Return the double submit values in the resulting JSON
            # instead of in additional cookies
            raw_response.update({
                'access_csrf':
                    get_csrf_token(access_token)
            })

        # Set the JWT cookies in the response
        # We need to call these functions to set the JWTs in the httpOnly cookies, sent through our response object
        set_access_cookies(response, access_token)
        return response