示例#1
0
 def post(self):
     _user_schema = UserSchema(only=(
         "email",
         "password",
     ))
     data = request.get_json()
     args = _user_schema.load(data)
     user = User.query.filter_by(email=args['email']).first()
     if user and user.password and user.check_pass(args['password']):
         if user.confirmation.activated:
             access_token = create_access_token(identity=user.id,
                                                fresh=True)
             refresh_token = create_refresh_token(identity=user.id)
             # encode jti token to store database redis
             access_jti = get_jti(encoded_token=access_token)
             refresh_jti = get_jti(encoded_token=refresh_token)
             # store to database redis
             conn_redis.set(access_jti, 'false', _ACCESS_EXPIRES)
             conn_redis.set(refresh_jti, 'false', _REFRESH_EXPIRES)
             return {
                 "access_token": access_token,
                 "refresh_token": refresh_token,
                 "username": user.username
             }, 200
         return {"message": "Check your email to activated user."}, 400
     return {"message": "Invalid credential"}, 422
    def get_token(cls, user_id: int) -> Dict[str, str]:
        # create access_token & refresh_token
        access_token = create_access_token(identity=user_id, fresh=True)
        refresh_token = create_refresh_token(identity=user_id)
        # encode jti token to store database redis
        access_jti = get_jti(encoded_token=access_token)
        refresh_jti = get_jti(encoded_token=refresh_token)
        # store to database redis
        conn_redis.set(access_jti, 'false', cls._ACCESS_EXPIRES)
        conn_redis.set(refresh_jti, 'false', cls._REFRESH_EXPIRES)

        return {"access_token": access_token, "refresh_token": refresh_token}
    def post(self):
        _image_schema = AddImageNewsletterSchema()
        file = _image_schema.load(request.files)
        data = _newsletter_schema.load(request.form)
        if Newsletter.query.filter_by(title=data['title']).first():
            raise ValidationError({'title':['The title has already been taken.']})

        slug = slugify(data['title'],lowercase=False)
        image = MagicImage(file=file['image'],width=3003,height=1287,path_upload='newsletters/',
            dir_name=slug,square=False)
        image.save_image()

        thumbnail = MagicImage(file=file['image'],width=1024,height=686,path_upload='newsletters/',
            dir_name=slug,square=False)
        thumbnail.save_image()

        newsletter = Newsletter(slug=slug,image=image.FILE_NAME,thumbnail=thumbnail.FILE_NAME,**data)
        newsletter.save_to_db()
        # send email notification to subscriber
        access_token = create_access_token(identity=get_jwt_identity())
        title_email = newsletter.title[:25] + '...' if len(newsletter.title) > 25 else newsletter.title
        with current_app.test_client() as client:
            client.post(
                '/send-email/subscriber',
                headers={'Authorization':f"Bearer {access_token}"},
                json={
                    'subscribe_type':'newsletter',
                    'subject': f"Newsletter: {title_email}",
                    'html':'email/EmailNewsletter.html',
                    'content': {
                        'image': f"{os.getenv('BACKEND_URL')}/static/newsletters/{newsletter.slug}/{newsletter.thumbnail}",
                        'link': f"{os.getenv('APP_URL')}/news/{newsletter.slug}",
                        'title': newsletter.title,
                        'description': newsletter.description,
                        'created_at': newsletter.created_at.strftime("%d %B %Y"),
                        'unsubscribe': f"{os.getenv('APP_URL')}?unsubscribe=email"
                    }
                }
            )
        # revoke token after send notification email
        ACCESS_EXPIRES = int(os.getenv("ACCESS_TOKEN_EXPIRES"))
        access_jti = get_jti(encoded_token=access_token)
        conn_redis.set(access_jti, 'true', ACCESS_EXPIRES)

        return {"message":"Success add newsletter."}, 201
示例#4
0
    def put(self, token: str):
        confirmation = Confirmation.query.filter_by(id=token).first_or_404(
            description='Token not found')
        if confirmation.activated:
            return {"message": "Your account already activated."}, 200

        confirmation.activated = True
        confirmation.save_to_db()
        # create access_token & refresh token
        access_token = create_access_token(identity=confirmation.user.id,
                                           fresh=True)
        refresh_token = create_refresh_token(identity=confirmation.user.id)
        # encode jti token to store database redis
        access_jti = get_jti(encoded_token=access_token)
        refresh_jti = get_jti(encoded_token=refresh_token)
        # store to database redis
        conn_redis.set(access_jti, 'false', _ACCESS_EXPIRES)
        conn_redis.set(refresh_jti, 'false', _REFRESH_EXPIRES)
        # subscribe newsletter & property
        with current_app.test_client() as client:
            client.post('/subscribe',
                        json={
                            'email': confirmation.user.email,
                            'subscribe_type': 'newsletter',
                            'subscribe_from': 'login'
                        })
            client.post('/subscribe',
                        json={
                            'email': confirmation.user.email,
                            'subscribe_type': 'property',
                            'subscribe_from': 'login'
                        })
        return {
            "access_token": access_token,
            "refresh_token": refresh_token,
            "username": confirmation.user.username
        }, 200
示例#5
0
 def delete(self):
     jti = get_raw_jwt()['jti']
     conn_redis.set(jti, 'true', _REFRESH_EXPIRES)
     return {"message": "Refresh token revoked."}, 200
示例#6
0
 def delete(self):
     jti = get_raw_jwt()['jti']
     conn_redis.set(jti, 'true', _ACCESS_EXPIRES)
     return {"message": "Access token revoked."}, 200
示例#7
0
 def post(self):
     user_id = get_jwt_identity()
     new_token = create_access_token(identity=user_id, fresh=False)
     access_jti = get_jti(encoded_token=new_token)
     conn_redis.set(access_jti, 'false', _ACCESS_EXPIRES)
     return {"access_token": new_token}, 200
    def post(self):
        _image_schema = AddImagePropertySchema()
        files = _image_schema.load(request.files)
        data = _property_schema.load(request.form)
        # delete data unnecessarily before validate
        ValidateProperty.delete_data_unnecessarily(data)

        if len(files['images']) < 5:
            raise ValidationError(
                {'images': ['Minimum 5 images to be upload']})
        # check name exists in db
        if Property.query.filter_by(name=data['name']).first():
            raise ValidationError(
                {'name': ['The name has already been taken.']})

        if 'facility' in data:
            ValidateProperty.check_facility(data['facility'])
        # save images
        slug = slugify(data['name'], lowercase=False)
        magic_image = MagicImage(file=files['images'],
                                 width=1200,
                                 height=800,
                                 path_upload='properties/',
                                 square=False,
                                 dir_name=slug,
                                 watermark='center')
        magic_image.save_image()
        images = ','.join(magic_image.FILE_NAME.values())
        # save data to db
        property_db = Property(**data, slug=slug, images=images)
        property_db.save_to_db()
        # save price to db
        property_price = PropertyPrice(**data, property_id=property_db.id)
        property_price.save_to_db()
        if 'facility' in data:
            # many to many between property and facility
            [
                property_db.facilities.append(Facility.query.get(
                    int(facility))) for facility in data['facility'].split(',')
            ]
            property_db.save_to_db()

        # send email notification to subscriber
        access_token = create_access_token(identity=get_jwt_identity())
        first_image = property_db.images.split(',')[0]
        title_email = property_db.name[:25] + '...' if len(
            property_db.name) > 25 else property_db.name
        with current_app.test_client() as client:
            client.post(
                '/send-email/subscriber',
                headers={'Authorization': f"Bearer {access_token}"},
                json={
                    'subscribe_type': 'property',
                    'subject': f"Property: {title_email}",
                    'html': 'email/EmailProperty.html',
                    'content': {
                        'image':
                        f"{os.getenv('BACKEND_URL')}/static/properties/{property_db.slug}/{first_image}",
                        'link':
                        f"{os.getenv('APP_URL')}/property/{property_db.slug}",
                        'name': property_db.name,
                        'description': property_db.description,
                        'created_at':
                        property_db.created_at.strftime("%d %B %Y"),
                        'unsubscribe':
                        f"{os.getenv('APP_URL')}?unsubscribe=email"
                    }
                })
        # revoke token after send notification email
        ACCESS_EXPIRES = int(os.getenv("ACCESS_TOKEN_EXPIRES"))
        access_jti = get_jti(encoded_token=access_token)
        conn_redis.set(access_jti, 'true', ACCESS_EXPIRES)

        return {"message": "Success add property."}, 201