Exemplo n.º 1
0
def uploadImage():
    try:
        data = request.get_json()['imgFile']
        image = data['imgFile']
    except Exception:
        return ErrorResponse(PayloadNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    extension = data['extension']
    try:
        imageName = saveToImage(imageFile=image, extension=extension)
    except Exception:
        return ErrorResponse(ImageNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    uid = data['uid']
    fetch_user = User.getUser(user_id=uid)
    if fetch_user is None:
        return ErrorResponse(
            UserNotFound(uid).message, 422, {
                'Content-Type': 'application/json'
            }).respond()

    file_upload = File(filename=imageName,
                       filetype='image',
                       uploader=fetch_user)
    file_upload.save_to_db()
    return jsonify(ImageFileSchema().dump(file_upload).data)
Exemplo n.º 2
0
def upload_default():
    try:
        data = request.get_json()['data']['attributes']
    except Exception:
        return ErrorResponse(PayloadNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    uid = data.get('uid')
    image_name = data.get('defaultImage')
    image_data = None
    with open(
            os.path.join(app.config.get('BASE_DIR'), 'badge_backgrounds',
                         image_name), "rb") as image_file:
        image_data = base64.b64encode(image_file.read())

    try:
        imageName = saveToImage(imageFile=image_data.decode('utf-8'),
                                extension=".png")
    except Exception as e:
        print(e)
        return ErrorResponse(ImageNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    fetch_user = User.getUser(user_id=uid)
    file_upload = File(filename=imageName,
                       filetype='image',
                       uploader=fetch_user)
    file_upload.save_to_db()
    return jsonify(DefImageSchem().dump(file_upload).data)
Exemplo n.º 3
0
def login():
    args = request.args
    ip_addr = request.environ['REMOTE_ADDR']
    if 'id' in args.keys():
        user = User.getUser(user_id=args['id'])
        uid = user.id
        if not user:
            return ErrorResponse(
                UserNotFound(uid).message, 422, {
                    'Content-Type': 'application/json'
                }).respond()

        tokenObj = {'user': user.username}
        perm = Permissions.get_by_uid(user.id)
        if perm:
            if perm.isAdmin:
                tokenObj = {'adminStatus': True}
        # Token that is not expiring and validated for the whole session
        token = jwt.encode(tokenObj, app.config.get('SECRET_KEY'))

        # Saving the IP of the logged in user
        user.last_login_ip = ip_addr
        user.last_login_date = datetime.utcnow()
        user.save_to_db()

        resp = {'id': user.id, 'token': token.decode('UTF-8')}

        return jsonify(LoginTokenSchema().dump(resp).data)

    return ErrorResponse(OperationNotFound().message, 422, {
        'Content-Type': 'application/json'
    }).respond()
Exemplo n.º 4
0
def changePwd():
    try:
        data = request.get_json()['data']['attributes']
    except Exception as e:
        print(e)
        return ErrorResponse(PayloadNotFound().message, 422, {'Content-Type': 'application/json'}).respond()

    token = data['token']
    try:
        decoded_res = jwt.decode(token, app.config['SECRET_KEY'])
    except Exception as e:
        print(e)
        return ErrorResponse(SignatureExpired().message, 422, {'Content-Type': 'application/json'}).respond()

    user = User.getUser(user_id=decoded_res['id'])

    if 'pwd' not in data.keys():
        return ErrorResponse(PasswordNotFound().message, 422, {'Content-Type': 'application/json'}).respond()

    pwd = data['pwd']
    oldPwd = user.password
    user.password = generate_password_hash(pwd)
    user.save_to_db()

    resp = {'id': token}
    if update_firebase_password(user.id, pwd):
        resp['status'] = 'Changed'
        return jsonify(ResetPasswordOperation().dump(resp).data)
    else:
        print('Firebase not uploaded')
        user.password = oldPwd
        user.save_to_db()
        resp['status'] = 'Not Changed'
        return jsonify(ResetPasswordOperation().dump(resp).data)
Exemplo n.º 5
0
def stripe_payment():
    try:
        data = request.get_json()
    except Exception:
        return ErrorResponse(PayloadNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    try:
        token = data['stripe_refresh_token']
    except Exception:
        return ErrorResponse(PayloadNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    try:
        charge = stripe.Charge.create(amount=data['amount'],
                                      currency=data['currency'],
                                      customer=data['stripe_user_id'],
                                      source=token)
        user = User.getUser(user_id=data['uid'])
        resp = {'id': user.id, 'charge': charge}
        resp['status'] = 'Charge Created'
    except Exception:
        return ErrorResponse(OperationNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    return jsonify(StripePaymentSchema().dump(resp).data)
Exemplo n.º 6
0
def add_as_admin():
    schema = ModifyPermissionsIncoming()
    input_data = request.get_json()
    data, err = schema.load(input_data)
    if err:
        return jsonify(err)

    if not data['isAdmin']:
        return ErrorResponse(FieldNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    user_permissions = Permissions.get_by_uid(uid=data['uid'])

    if user_permissions is None:
        return ErrorResponse(UserNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    user_permissions.isUser = False
    user_permissions.isAdmin = True
    user_permissions.isSales = False

    db.session.commit()

    return jsonify(ModifyPermissionsDone().dump(user_permissions).data)
Exemplo n.º 7
0
def update_profile_image():
    try:
        data = request.get_json()['data']['attributes']
    except Exception:
        return ErrorResponse(PayloadNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    if not data['image']:
        return ErrorResponse(ImageNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    if not data['extension']:
        return ErrorResponse(ExtensionNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    uid = data['uid']
    image = data['image']
    extension = data['extension']

    try:
        imageName = saveToImage(imageFile=image, extension=extension)
    except Exception:
        return ErrorResponse(ImageNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    fetch_user, imageLink = update_database(uid, imageName)
    return jsonify(UpdateUserSchema().dump(fetch_user).data)
Exemplo n.º 8
0
def upload_manual_data():
    try:
        data = request.get_json()['data']['attributes']
    except Exception:
        return ErrorResponse(PayloadNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    if not data.get('manual_data'):
        return ErrorResponse(ManualDataNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    uid = data.get('uid')
    manual_data = data.get('manual_data')
    fetch_user = User.getUser(user_id=uid)
    if fetch_user is None:
        return ErrorResponse(
            UserNotFound(uid).message, 422, {
                'Content-Type': 'application/json'
            }).respond()

    try:
        csvName = saveAsCSV(csvData=manual_data)
    except Exception:
        return ErrorResponse(OperationNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    file_upload = File(filename=csvName, filetype='csv', uploader=fetch_user)
    file_upload.save_to_db()
    return jsonify(ManualFileSchema().dump(file_upload).data)
Exemplo n.º 9
0
 def decorated(*args, **kwargs):
     token = request.headers.get('x-access-token')
     if not token:
         return ErrorResponse(PayloadNotFound().message, 422, {'Content-Type': 'application/json'}).respond()
     try:
         data = jwt.decode(token, app.config['SECRET_KEY'])
         if 'adminStatus' in data.keys():
             return func(*args, **kwargs)
         return ErrorResponse(AdminNotFound().message, 422, {'Content-Type': 'application/json'}).respond()
     except Exception as e:
         print(e)
Exemplo n.º 10
0
def update_user(userid):
    user = User.getUser(user_id=userid)
    permissions = Permissions.get_by_uid(userid)
    if not user:
        return ErrorResponse(UserNotFound().message, 422, {'Content-Type': 'application/json'}).respond()
    data = request.get_json()['data']['attributes']
    if not data:
        return ErrorResponse(JsonNotFound().message, 422, {'Content-Type': 'application/json'}).respond()
    for key in data:
        if key in User.__table__.columns.keys():
            setattr(user, key, data[key])
        if key in Permissions.__table__.columns.keys():
            setattr(permissions, key, data[key])
    user.save_to_db()
    schema = AllUsersSchema()
    result = schema.dump(user)
    return jsonify(result.data)
Exemplo n.º 11
0
def delete_user(userid):
    user = User.getUser(user_id=userid)
    if not user:
        return ErrorResponse(UserNotFound().message, 422, {'Content-Type': 'application/json'}).respond()
    user.deleted_at = datetime.datetime.utcnow()
    user.save_to_db()
    schema = AllUsersSchema()
    result = schema.dump(user)
    return jsonify(result.data)
Exemplo n.º 12
0
def oauth_token():
    try:
        data = request.get_json()
    except Exception:
        return ErrorResponse(PayloadNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    try:
        token = jwt.encode({'user': data.get('username')},
                           app.config.get('SECRET_KEY'))

    except Exception:
        return ErrorResponse(OperationNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    return jsonify(Response(200).generateToken(token.decode('UTF-8')))
Exemplo n.º 13
0
def reset_password():
    try:
        data = request.get_json()
    except Exception:
        return ErrorResponse(PayloadNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    if data and data['username']:
        user = User.getUser(data['username'])
        expire = datetime.datetime.utcnow() + datetime.timedelta(hours=24)
        token = jwt.encode({
            'id': user.username,
            'exp': expire
        }, app.config.get('SECRET_KEY'))
        return jsonify(Response(200).generateResetURL(token.decode('UTF-8')))
    else:
        return ErrorResponse(JsonNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()
Exemplo n.º 14
0
def delete_sales():
    args = request.args
    if 'email' in args.keys():
        user = User.getUser(email=args['email'])
        if not user:
            return ErrorResponse(UserNotFound().message, 422, {'Content-Type': 'application/json'}).respond()
        user.siteAdmin = False
        permissions = Permissions.get_by_uid(user.id)
        permissions.isSales = False
        permissions.save_to_db()
        user.save_to_db()
        return jsonify(DeleteSales().dump(user).data)
Exemplo n.º 15
0
def register_sales():
    schema = SalesSchema()
    input_data = request.get_json()['data']['attributes']
    if 'email' in input_data.keys():
        user = User.getUser(email=input_data['email'])
        if 'salesStat' in input_data.keys():
            permission = Permissions.get_by_uid(user.id)
            permission.isSales = input_data['salesStat']
            permission.save_to_db()
        user.save_to_db()
        return jsonify(schema.dump(user).data)
    else:
        return ErrorResponse(JsonNotFound().message, 422, {'Content-Type': 'application/json'}).respond()
Exemplo n.º 16
0
def background_color():
    try:
        data = request.get_json()['data']['attributes']
        bg_color = data['bg_color']
    except Exception:
        return ErrorResponse(PayloadNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    svg2png = SVG2PNG()

    bg_color = '#' + str(bg_color)
    user_defined_path = svg2png.do_svg2png(1, bg_color)
    with open(user_defined_path, "rb") as image_file:
        image_data = base64.b64encode(image_file.read())
        os.remove(user_defined_path)

    try:
        imageName = saveToImage(imageFile=image_data.decode('utf-8'),
                                extension=".png")
    except Exception:
        return ErrorResponse(ImageNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    uid = data['uid']
    fetch_user = User.getUser(user_id=uid)
    if fetch_user is None:
        return ErrorResponse(
            UserNotFound(uid).message, 422, {
                'Content-Type': 'application/json'
            }).respond()

    file_upload = File(filename=imageName,
                       filetype='image',
                       uploader=fetch_user)
    file_upload.save_to_db()
    return jsonify(ColorImageSchema().dump(file_upload).data)
Exemplo n.º 17
0
def admin_add_usage():
    try:
        data = request.get_json()['data']
        print(data)
    except Exception:
        return ErrorResponse(JsonNotFound().message, 422, {'Content-Type': 'application/json'}).respond()

    uid = data['uid']
    allowed_usage = data['allowed_usage']
    user = User.getUser(user_id=uid)
    user.allowed_usage = user.allowed_usage + allowed_usage
    db.session.commit()

    return jsonify(UserAllowedUsage().dump(user).data)
Exemplo n.º 18
0
def fileUpload():
    try:
        data = request.json['csvFile']
        csv = data['csvFile']
    except Exception:
        return ErrorResponse(PayloadNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    if 'extension' not in data.keys():
        return ErrorResponse(ExtensionNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    extension = data['extension']
    if extension != 'csv':
        return ErrorResponse(CSVNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()
    try:
        csvName = saveToCSV(csvFile=csv, extension='.csv')
    except Exception:
        return ErrorResponse(OperationNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    uid = data.get('uid')
    fetch_user = User.getUser(user_id=uid)
    if fetch_user is None:
        return ErrorResponse(
            UserNotFound(uid).message, 422, {
                'Content-Type': 'application/json'
            }).respond()

    file_upload = File(filename=csvName, filetype='csv', uploader=fetch_user)
    file_upload.save_to_db()
    return jsonify(CSVUploadSchema().dump(file_upload).data)
Exemplo n.º 19
0
def validate_email():
    args = request.args
    if 'id' in args.keys():
        encryptID = args['id']
        email = _decrypt(encryptID, "", password)
        user = User.getUser(email=email)
        if not user:
            return ErrorResponse(UserNotFound().message, 422, {
                'Content-Type': 'application/json'
            }).respond()
        resp = {'id': user.id}
        if not update_firebase_emailVerified(user.id):
            print('Email not verified')
            resp['status'] = 'Not verified'
        else:
            resp['status'] = 'Verified'
        return jsonify(EmailVerificationOperation().dump(resp).data)
Exemplo n.º 20
0
def pwd_reset_token():
    data = request.get_json()['data']['attributes']
    if 'email' not in data.keys():
        print('Email not found')
    email = data['email']
    user = User.getUser(email=email)
    if not user:
        return ErrorResponse(UserNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()
    expire = datetime.datetime.utcnow() + datetime.timedelta(hours=24)
    token = jwt.encode({
        'id': user.id,
        'exp': expire
    }, app.config.get('SECRET_KEY'))
    resetObj = ResetPasswordToken(user.id, token.decode('UTF-8'))
    resetObj.save_to_db()
    return jsonify(TokenSchema().dump(resetObj).data)
Exemplo n.º 21
0
def update_database(uid, imageName):
    fetch_user = User.getUser(user_id=uid)
    if fetch_user is None:
        return ErrorResponse(
            UserNotFound(uid).message, 422, {
                'Content-Type': 'application/json'
            }).respond()
    imagePath = os.path.join(app.config.get('BASE_DIR'), 'static', 'uploads',
                             'image') + '/' + imageName
    imageLink = fileUploader(imagePath, 'profile/images/' + imageName)
    fetch_user.photoURL = imageLink
    fetch_user.save_to_db()

    try:
        os.unlink(imagePath)
    except Exception:
        print('Unable to delete the temporary file')

    return fetch_user, imageLink
Exemplo n.º 22
0
def generateBadges():
    try:
        data = request.get_json()['badge']
    except Exception:
        return ErrorResponse(JsonNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    if not data['csv']:
        return ErrorResponse(CSVNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    if not data['image']:
        return ErrorResponse(ImageNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    csv_name = data.get('csv')
    badge_name = data.get('badge_name') or 'My Badge'
    image_name = data.get('image')
    text_color = data.get('font_color') or '#ffffff'
    paper_size = data.get('paper_size') or 'A3'
    badge_size = data.get('badge_size') or '4x3'
    font_size_1 = data.get('font_size_1') or None
    font_size_2 = data.get('font_size_2') or None
    font_size_3 = data.get('font_size_3') or None
    font_size_4 = data.get('font_size_4') or None
    font_size_5 = data.get('font_size_5') or None
    font_type_1 = data.get('font_type_1') or 'helvetica'
    font_type_2 = data.get('font_type_2') or 'helvetica'
    font_type_3 = data.get('font_type_3') or 'helvetica'
    font_type_4 = data.get('font_type_4') or 'helvetica'
    font_type_5 = data.get('font_type_5') or 'helvetica'

    svg2png = SVG2PNG()

    if config.ENV == 'PROD':
        svg2png.do_text_fill(
            os.getcwd() + '/api/static/badges/8BadgesOnA3.svg', text_color,
            badge_size, paper_size)

        svg2png.change_font_size(
            os.getcwd() + '/api/static/badges/8BadgesOnA3.svg', badge_size,
            paper_size, font_size_1, font_size_2, font_size_3, font_size_4,
            font_size_5)

        svg2png.change_font_family(
            os.getcwd() + '/api/static/badges/8BadgesOnA3.svg', badge_size,
            paper_size, font_type_1, font_type_2, font_type_3, font_type_4,
            font_type_5)
    else:
        svg2png.do_text_fill('static/badges/8BadgesOnA3.svg', text_color,
                             badge_size, paper_size)

        svg2png.change_font_size('static/badges/8BadgesOnA3.svg', badge_size,
                                 paper_size, font_size_1, font_size_2,
                                 font_size_3, font_size_4, font_size_5)

        svg2png.change_font_family(
            os.getcwd() + '/api/static/badges/8BadgesOnA3.svg', badge_size,
            paper_size, font_type_1, font_type_2, font_type_3, font_type_4,
            font_type_5)

    merge_badges = MergeBadges(image_name, csv_name, paper_size, badge_size)

    merge_badges.merge_pdfs()

    uid = data.get('uid')
    user_creator = User.getUser(user_id=uid)

    if user_creator.allowed_usage == 0:
        return ErrorResponse(UsageNotAllowed().message, 403, {
            'Content-Type': 'application/json'
        }).respond()

    user_creator.allowed_usage = user_creator.allowed_usage - 1

    badge_created = Badges(image=image_name,
                           csv=csv_name,
                           text_color=text_color,
                           badge_size=badge_size,
                           badge_name=badge_name,
                           creator=user_creator)

    badge_created.save_to_db()

    badgeFolder = badge_created.image.split('.')[0]
    badgePath = ''
    if config.ENV == 'LOCAL':
        badgePath = os.getcwd() + '/static/temporary/' + badgeFolder
    else:
        badgePath = os.getcwd() + '/api/static/temporary/' + badgeFolder
    if os.path.isdir(badgePath):
        imageDirectory = os.path.join(badgePath, '../../uploads/image',
                                      image_name)
        link = fileUploader(imageDirectory, 'images/' + image_name)
        badge_created.image_link = link
        link = fileUploader(badgePath + '/all-badges.pdf',
                            'badges/' + badge_created.id + '.pdf')
        send_badge_mail(badge_created.id, user_creator.id, link)
        badge_created.download_link = link
        rmtree(badgePath, ignore_errors=True)

    db.session.commit()

    return jsonify(BadgeSchema().dump(badge_created).data)
Exemplo n.º 23
0
def register_user():
    schema = UserSchema()
    input_data = request.get_json()
    if 'uid' not in input_data['data']['attributes'].keys():
        data, err = schema.load(input_data)
        if err:
            return jsonify(err)
        try:
            user = auth.create_user(
                email=data['email'],
                email_verified=False,
                password=data['password'],
                display_name=data['username'],
            )
        except auth.AuthError as e:
            if e.code == 'USER_CREATE_ERROR':
                errmsg = 'User with email already exists'
            return ErrorResponse(
                FirebaseError(errmsg).message, 422, {
                    'Content-Type': 'application/json'
                }).respond()

        newUser = User(id_=user.uid,
                       username=data['username'],
                       email=user.email,
                       password=data['password'])

        if user.email in admins:
            newUser.siteAdmin = True

        newUser.save_to_db()

        if newUser.email in admins:
            perm = Permissions(isUser=True,
                               isAdmin=True,
                               user_permissions=newUser)
            perm.save_to_db()
        else:
            perm = Permissions(isUser=True, user_permissions=newUser)
            perm.save_to_db()

        return jsonify(schema.dump(newUser).data)
    else:
        schema = OAuthUserSchema()
        data, err = schema.load(input_data)
        if err:
            return jsonify(err)

        uid = input_data['data']['attributes']['uid']
        user_ = User.getUser(user_id=uid)
        if not user_:
            newUser = User(id_=uid,
                           username=data['username'],
                           email=data['email'],
                           password=data['password'],
                           photoURL=data['photoURL'])
            if data['email'] in admins:
                newUser.siteAdmin = True
            newUser.save_to_db()

            if newUser.email in admins:
                perm = Permissions(isUser=True,
                                   isAdmin=True,
                                   user_permissions=newUser)
                perm.save_to_db()
            else:
                perm = Permissions(isUser=True, user_permissions=newUser)
                perm.save_to_db()
        else:
            newUser = user_
        return jsonify(schema.dump(newUser).data)