Exemple #1
0
    def post(self):
        """Book specific hotels"""
        try:
            params = self.parser.parse_args()

            offerId = params['offerId']
            guests: list = params['guests']
            payments = params['payments']
            booking_responce = amadeus.booking.hotel_bookings.post(offerId, guests, payments)
            booking_dict = booking_responce.data[0]
            booking: BookingModel = BookingModel()
            booking.booking_id = booking_dict['id']
            booking.providerConfirmationId = booking_dict['providerConfirmationId']
            booking.user_id = g.user_id
            booking.hotel_name = params['hotel_name']
            booking.checking_date = params['checking_date']
            booking.checkout_date = params['checkout_date']
            booking.number_of_guest = len(guests)
            booking.number_of_room = params['number_of_room']
            booking.city = params['city']
            booking.address = params['address']
            booking.save()

            return ApiResponse.success(booking_dict, 200)
        except ResponseError as error:
            print(f'Error is ----------{error}')
            return ApiResponse.error(error.response.body, 402)
Exemple #2
0
 def get(self):
     """All offer provided by a specific hotels"""
     try:
         params = self.parser.parse_args()
         params = cleanNullItems(params)
         hotel_offers = amadeus.shopping.hotel_offers_by_hotel.get(**params)
         return ApiResponse.success(hotel_offers.data, 200)
     except ResponseError as error:
         print(f'Error is ----------{error}')
         return ApiResponse.error(error.response.body, 402)
Exemple #3
0
    def get(self):
        """Get User data"""
        user_id = request.args.get('user_id', None, type=int)
        if user_id is None:
            user_id = g.user_id
        user = UserModel.get_by_id(user_id)

        if user is not None:
            return ApiResponse.success(UserSchema().dump(user), 200)
        return ApiResponse.error('User not found.', 402)
Exemple #4
0
 def get(self, booking_id: str = None):
     """Get user booking lisitng and booking with booking_id"""
     if booking_id is not None:
         booking_detail = BookingModel.query.filter(BookingModel.booking_id == booking_id).first()
         return ApiResponse.success(HotelBookingSchema().dump(booking_detail), 200)
     else:
         args = self.booking_parser.parse_args()
         page = args.page
         per_page = args.limit
         records = BookingModel.query.filter(BookingModel.user_id == g.user_id).paginate(page, per_page, False)
         return ApiResponse.success(get_paginated_list(records, HotelBookingSchema(many=True), per_page), 200)
Exemple #5
0
 def post(self):
     """Get Token for Forget password"""
     arg_json = self.parser.parse_args()
     email = arg_json['email']
     user: UserModel = UserModel.query.filter(
         UserModel.email == email).first()
     if user:
         from api.helpers.email import send_password_reset_request_email
         send_password_reset_request_email(user)
         return ApiResponse.success(
             None, 200, message=KMessages.RESET_PASSWORD_TOKEN_SEND)
     return ApiResponse.error(None, 404, message=KMessages.NO_EMAIL_ID)
Exemple #6
0
 def get(self):
     try:
         params = self.parser.parse_args()
         if params['childAges'] is not None:
             params['childAges'] = list_to_csv(params['childAges'])
         if params['ratings'] is not None:
             params['ratings'] = list_to_csv(params['ratings'])
         params = cleanNullItems(params)
         response = amadeus.shopping.hotel_offers.get(**params)
         mf_data = format_muslim_friendly_data(response.data)
         return ApiResponse.success(mf_data, 200)
     except ResponseError as error:
         print(f'Error is ----------{error}')
         return ApiResponse.error(error.response.body, 402)
Exemple #7
0
 def post(self):
     """Update userpasword"""
     arg_json = self.parser.parse_args()
     user: UserModel = UserModel.get_by_id(g.user_id)
     authorized = user.check_password(arg_json['current_password'])
     if not authorized:
         return ApiResponse.error(None,
                                  404,
                                  message=KMessages.CURRENT_PASSWORD_DIFFER)
     new_password = arg_json['new_password']
     password_validation(new_password)
     user.password = generate_password_hash(new_password).decode('utf8')
     user.update()
     return ApiResponse.success(
         None, 200, message=KMessages.PASSWORD_CHANGE_SUCESSFULLY)
Exemple #8
0
def sqlalchemy_error_handler(exc):
    error_type_name = type(exc).__name__
    error_message = str(exc.__dict__['orig'])
    return ApiResponse.error(error=error_message,
                             status_code=422,
                             error_type=error_type_name,
                             message=error_message)
Exemple #9
0
 def delete(self, question_id: int):
     """new questionnaire and options"""
     question = QuestionModel().get_by_id(question_id)
     question.delete()
     return ApiResponse.success(None,
                                200,
                                message=KMessages.QUESTION_DELETED)
Exemple #10
0
 def post(self):
     """submit new answer"""
     param_dict = self.submit_qanswer_parser.parse_args()
     param_dict['user_id'] = g.user_id
     user_answer = UserQAnswerModel(**param_dict)
     user_answer.save()
     return ApiResponse.success(None, 200, KMessages.DATA_SAVED)
Exemple #11
0
 def post(self):
     """Reset your password with token"""
     arg_json = self.parser.parse_args()
     user: UserModel = verify_reset_password_token(arg_json['token'])
     if not user:
         return ApiResponse.error(None,
                                  404,
                                  message=KMessages.INVALID_TOKEN)
     arg_json = self.parser.parse_args()
     new_password = arg_json['new_password']
     password_validation(new_password)
     user.password = generate_password_hash(new_password).decode('utf8')
     user.update()
     from api.helpers.email import send_password_reset_confirmation_email
     send_password_reset_confirmation_email(user)
     return ApiResponse.success(
         None, 200, message=KMessages.PASSWORD_CHANGE_SUCESSFULLY)
Exemple #12
0
def handle_integrity_error(exc):
    db.session.rollback()
    msg = exc.args[0].split('Key')
    message = re.sub(u'[()\\n]', '', msg[-1])
    message = re.sub(u'[=]', ' ', message)
    return ApiResponse.error(exc.args,
                             409,
                             message,
                             error_type=exc.__class__.__name__)
Exemple #13
0
 def post(self):
     """Registration via Email"""
     user: UserModel = self.validObject(self.parser, UserSchema())
     user.role = UserRole(RoleType.USER)
     user.password = user.create_password()
     user.save()
     loggeding_data = perform_login(user)
     return ApiResponse.success(loggeding_data,
                                200,
                                message=KMessages.REGISTRATION_DONE)
Exemple #14
0
 def post(self):
     """Login via Email"""
     json = self.parser.parse_args()
     userquery = UserModel.query.filter(UserModel.email == json['email'],
                                        UserModel.is_deleted == False)
     user = userquery.first()
     if user is not None:
         authorized = user.check_password(json['password'])
         if authorized:
             loggeding_data = perform_login(user)
             return ApiResponse.success(loggeding_data,
                                        200,
                                        message=KMessages.LOGIN_DONE)
         else:
             return ApiResponse.error(None,
                                      404,
                                      message=KMessages.INVALID_LOGIN_AUTH)
     else:
         return ApiResponse.error(None, 404, message=KMessages.NO_EMAIL_ID)
Exemple #15
0
 def get(self):
     """Fetch user notification"""
     args = self.parser.parse_args()
     page = args.page
     per_page = args.limit
     records = NotificaionModel.query.filter(
         NotificaionModel.user_id == g.user_id).paginate(
             page, per_page, False)
     from api.helpers.pagination import get_paginated_list
     return ApiResponse.success(
         get_paginated_list(records, NotificaionModelSchema(many=True),
                            per_page), 200)
Exemple #16
0
 def post(self, entity_id: str = None):
     """Mark fav any hotel (This will toggel fav/unfav a hotel))"""
     entity_type = 0
     fav_product = FavEntityModel.query.filter_by(user_id=g.user_id, entity_id=entity_id,
                                                  entity_type=entity_type).first()
     is_mark_fav = False
     if fav_product is not None:
         fav_product.delete()
     else:
         FavEntityModel(entity_id=entity_id, user_id=g.user_id, entity_type=entity_type).save()
         is_mark_fav = True
     return ApiResponse.success({'is_mark_fav': is_mark_fav}, 200, KMessages.UPDATED_SUCESSFULLY)
Exemple #17
0
        def wrapper(*args, **kwargs):
            response = False
            if roleTypes is not None:
                for roleType in roleTypes:
                    user_role_type = get_jwt_claims()['user_role']
                    if user_role_type == roleType.value:
                        response = True

            if response is False:
                return ApiResponse.error(
                    f'user is is not authorized to perform this access', 403)
            return fn(*args, **kwargs)
Exemple #18
0
 def put(self):
     """Update user profile data"""
     from api.modules.user.model import UserModel
     json_data = self.update_parser.parse_args()
     profile_image = json_data['profile_image']
     if profile_image:
         from flask import current_app
         directory_path = current_app.config['USER_DP_DIR']
         json_data['profile_image_url'] = AWSManager().updateImage(
             profile_image, directory_path)
     user: UserModel = UserModel.get_by_id(g.user_id)
     user.update(**json_data)
     return ApiResponse.success(UserSchema().dump(user), 200)
Exemple #19
0
 def wrapper(self, *args, **kwargs):
     verify_jwt_in_request()
     authorization = request.headers.get('Authorization')
     if not authorization:
         return ApiResponse.error('No authorization token provided', 403)
     auth_token = authorization.split(" ")[1]
     resp = UserToken.is_token_valid(auth_token)
     if not resp:
         return ApiResponse.error('Invalid authorization token', 403)
     # validate = JWT.validate_authorization(auth_token)
     #
     from flask_jwt_extended import get_jwt_identity
     user = get_jwt_identity()
     # clam = get_jwt_claims()
     g.user_id = user['user_id']
     #
     # from api.modules.user.role.model import UserRole
     # g.user_role: UserRole = UserRole.query.filter_by(user_id=g.user_id).first()
     #
     # if not validate:
     #     return ApiResponse.error('Unauthorized', 403)
     return fn(self, *args, **kwargs)
Exemple #20
0
 def get(self, keyword: str):
     """Search IATA code of an airport by country/city/airport/iata code"""
     args = self.parser.parse_args()
     page = args.page
     per_page = args.limit
     if keyword is None:
         records = IATACodeModel.query.paginate(page=page, per_page=per_page)
     else:
         query = or_(IATACodeModel.name.ilike('{}%'.format(keyword)),
                     IATACodeModel.city.ilike('{}%'.format(keyword)),
                     IATACodeModel.country.ilike('{}%'.format(keyword)),
                     IATACodeModel.iata.ilike('{}%'.format(keyword)))
         records = IATACodeModel.query.filter(query).paginate(page, per_page, False)
     return ApiResponse.success(get_paginated_list(records, IATACodeModelSchema(many=True), per_page), 200)
Exemple #21
0
    def post(self):
        """add new questionnaire and options"""
        param_dict = self.create_question_parser.parse_args()
        question = QuestionModel(**{'question': param_dict['question']})
        option_icons = list(param_dict['option_icons'])

        for num, option in enumerate(param_dict['option']):
            option: QOptionsModel = QOptionsModel(**{'option': option})
            directory_path = current_app.config['QUESTION_ICONS_DIR']
            option.option_icon = AWSManager().updateImage(
                option_icons[num], directory_path)
            question.options.append(option)
        # TODO: Have to delete saved file if there will any expection while saving question
        question.save()
        return ApiResponse.success(QuestionSchema().dump(question), 200)
Exemple #22
0
    def post(self):
        """Login via Social id/Registration via social id & detail"""
        json = self.login_parser.parse_args()
        social_id = json['social_id']

        user = UserModel.query.filter(UserModel.social_id == social_id,
                                      UserModel.is_deleted == False).first()
        message = KMessages.LOGIN_DONE
        if user is None:
            parser_registration = UserModel.get_parser_user_registration_social(
            )
            new_user: UserModel = self.validObject(parser_registration,
                                                   UserSchema())
            new_user.role = UserRole(RoleType.USER)
            new_user.save()
            user = new_user
            message = KMessages.REGISTRATION_DONE
        loggeding_data = perform_login(user)
        return ApiResponse.success(loggeding_data, 200, message=message)
Exemple #23
0
 def get(self):
     """get all submitted questionnaire by you"""
     questions = UserQAnswerModel.query.filter_by(user_id=g.user_id).all()
     return ApiResponse.success(
         UserQAnswerSchema(many=True).dump(questions), 200)
Exemple #24
0
def schema_validation_error(exc):
    error_type_name = type(exc).__name__
    return ApiResponse.error(error=exc.messages,
                             status_code=422,
                             error_type=error_type_name)
Exemple #25
0
 def validationError(cls, error, status_code):
     print(status_code)
     error, code = ApiResponse.error(error=error,
                                     status_code=status_code,
                                     message='')
     return cls(errors=error, status_code=code)
Exemple #26
0
 def get(self):
     """Get Static data"""
     data = get_static_data()
     return ApiResponse.success(data, 200)
Exemple #27
0
 def get(self):
     """Get all Fav hotels id (Have to call seprterly Hotel Detail api for their details)"""
     page = self.parser.parse_args()['page']
     favorites = FavEntityModel.find_all(**{'pagination': True, 'page': page, 'user_id': g.user_id})
     return ApiResponse.success(get_paginated_list(favorites, FavEntitySchema(many=True), page), 200)
Exemple #28
0
 def post(self):
     """Perform logout"""
     user_token = JWT.get_auth_token()
     perform_logout(user_token.token)
     return ApiResponse.success(None, 200, message=KMessages.LOGOUT_DONE)
Exemple #29
0
 def get(self):
     """Get all questionnaire"""
     questions = QuestionModel().find_all()
     from api.modules.questionnaire.schema import QuestionSchema
     return ApiResponse.success(
         QuestionSchema(many=True).dump(questions), 200)