Exemple #1
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()
Exemple #2
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)
Exemple #3
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)
Exemple #4
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)
Exemple #5
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()

    bg_color = '#' + str(bg_color)
    img = Image.new('RGB', (744, 838), bg_color)

    buff = BytesIO()
    img.save(buff, format="JPEG")
    image_data = base64.b64encode(buff.getvalue())

    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)
Exemple #6
0
def changeName():
    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(username=data['username'])
        if user:
            if not verifyPassword(user, data['password']):
                return ErrorResponse(PasswordNotFound().message, 422, {
                    'Content-Type': 'application/json'
                }).respond()

            user.name = data['name']
            try:
                user.save_to_db()
            except Exception:
                return ErrorResponse(OperationNotFound().message, 422, {
                    'Content-Type': 'application/json'
                }).respond()

            return jsonify(
                Response(200).generateMessage('Name Updated successfully'))
    else:
        return ErrorResponse(JsonNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()
Exemple #7
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)
Exemple #8
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)
Exemple #9
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') + ".png"
    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)
Exemple #10
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)
Exemple #11
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)
Exemple #12
0
def export_data():
    input_data = request.args
    file = File().query.filter_by(filename=input_data.get('filename')).first()

    if file is None:
        return ErrorResponse(
            FileNotFound(input_data.get('filename')).message, 422, {
                'Content-Type': 'application/json'
            }).respond()

    export_obj = {
        'filename': file.filename,
        'filetype': file.filetype,
        'id': str(uuid.uuid4()),
        'file_data': None
    }

    with open(
            os.path.join(app.config.get('BASE_DIR'), 'static', 'uploads',
                         'csv', export_obj['filename']), "r") as f:
        export_obj['file_data'] = f.read()

    export_obj['file_data'] = base64.b64encode(
        export_obj['file_data'].encode())

    return jsonify(ExportFileSchema().dump(export_obj).data)
Exemple #13
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')))
Exemple #14
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(username=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()
Exemple #15
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)
Exemple #16
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)
Exemple #17
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)
Exemple #18
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)
Exemple #19
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
Exemple #20
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()
Exemple #21
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)
Exemple #22
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)
Exemple #23
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'))
    try:
        resetObj = ResetPasswordToken.query.get(user.id)
        resetObj.token = token
    except ProgrammingError:
        resetObj = ResetPasswordToken(user.id, token.decode('UTF-8'))

    resetObj.save_to_db()
    return jsonify(TokenSchema().dump(resetObj).data)
Exemple #24
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')
    csv_type = data.get('csv_type') or ''
    badge_name = data.get('badge_name') or 'My Badge'
    image_names = data.get('image').split(',')
    logo_image = data.get('logo_image')
    logo_text = data.get('logo_text') or ''
    logo_color = data.get('logo_color') or '#000000'
    font_color_1 = data.get('font_color_1') or '#ffffff'
    font_color_2 = data.get('font_color_2') or '#ffffff'
    font_color_3 = data.get('font_color_3') or '#ffffff'
    font_color_4 = data.get('font_color_4') or '#ffffff'
    font_color_5 = data.get('font_color_5') 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'
    ticket_types = data.get('ticket_types').split(',')

    svg2png = SVG2PNG()

    if config.ENV == 'PROD':
        svg2png.do_text_fill(
            os.getcwd() + '/api/static/badges/8BadgesOnA3.svg', font_color_1,
            font_color_2, font_color_3, font_color_4, font_color_5, logo_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', logo_color,
                             font_color_1, font_color_2, font_color_3,
                             font_color_4, font_color_5, 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_names, logo_text, logo_image, csv_name,
                               csv_type, paper_size, badge_size, ticket_types)

    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(csv=csv_name,
                           font_color_1=font_color_1,
                           font_color_2=font_color_2,
                           font_color_3=font_color_3,
                           font_color_4=font_color_4,
                           font_color_5=font_color_5,
                           font_size_1=font_size_1,
                           font_size_2=font_size_2,
                           font_size_3=font_size_3,
                           font_size_4=font_size_4,
                           font_size_5=font_size_5,
                           font_type_1=font_type_1,
                           font_type_2=font_type_2,
                           font_type_3=font_type_3,
                           font_type_4=font_type_4,
                           font_type_5=font_type_5,
                           paper_size=paper_size,
                           logo_text=logo_text,
                           logo_color=logo_color,
                           logo_image=logo_image,
                           image=",".join(image_names),
                           badge_size=badge_size,
                           badge_name=badge_name,
                           creator=user_creator,
                           csv_type=csv_type,
                           ticket_types=",".join(ticket_types))

    badge_created.save_to_db()

    badgeFolder = image_names[0].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):
        image_links = []
        for image in image_names:
            imageDirectory = os.path.join(badgePath, '../../uploads/image',
                                          image)
            link = fileUploader(imageDirectory, 'images/' + image)
            image_links.append(link)
        badge_created.image_link = ",".join(image_links)
        if logo_image != '':
            logoImageDirectory = os.path.join(badgePath, '../../uploads/image',
                                              logo_image)
            link = fileUploader(logoImageDirectory, 'images/' + logo_image)
            badge_created.logo_image_link = link
        else:
            badge_created.logo_image_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)
Exemple #25
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)

        if User.getUser(username=data['username']):
            errmsg = 'User with username already exists'
            return ErrorResponse(
                FirebaseError(errmsg).message, 422, {
                    'Content-Type': 'application/json'
                }).respond()

        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)
Exemple #26
0
def editBadges(badgeId):
    try:
        data = request.get_json()['badge']
    except Exception:
        return ErrorResponse(JsonNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    try:
        badge = Badges.getBadge(badgeId)
    except Exception:
        return ErrorResponse(JsonNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

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

    badge.update(data)

    svg2png = SVG2PNG()
    _badge = badge.first()

    badgeFolder = _badge.image.split(',')[0].split('.')[0]
    badgePath = ''
    if config.ENV == 'LOCAL':
        badgePath = os.getcwd() + '/static/temporary/' + badgeFolder
    else:
        badgePath = os.getcwd() + '/api/static/temporary/' + badgeFolder
    rmtree(badgePath, ignore_errors=True)

    if config.ENV == 'PROD':
        svg2png.do_text_fill(
            os.getcwd() + '/api/static/badges/8BadgesOnA3.svg',
            _badge.font_color_1, _badge.font_color_2, _badge.font_color_3,
            _badge.font_color_4, _badge.font_color_5, _badge.logo_color,
            _badge.badge_size, _badge.paper_size)

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

        svg2png.change_font_family(
            os.getcwd() + '/api/static/badges/8BadgesOnA3.svg',
            _badge.badge_size, _badge.paper_size, _badge.font_type_1,
            _badge.font_type_2, _badge.font_type_3, _badge.font_type_4,
            _badge.font_type_5)
    else:
        svg2png.do_text_fill('static/badges/8BadgesOnA3.svg',
                             _badge.logo_color, _badge.font_color_1,
                             _badge.font_color_2, _badge.font_color_3,
                             _badge.font_color_4, _badge.font_color_5,
                             _badge.badge_size, _badge.paper_size)

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

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

    merge_badges = MergeBadges(_badge.image.split(','), _badge.logo_text,
                               _badge.logo_image, _badge.csv, _badge.csv_type,
                               _badge.paper_size, _badge.badge_size,
                               _badge.ticket_types.split(','))

    merge_badges.merge_pdfs()

    if os.path.isdir(badgePath):
        image_links = []
        for image in _badge.image.split(','):
            imageDirectory = os.path.join(badgePath, '../../uploads/image',
                                          image)
            link = fileUploader(imageDirectory, 'images/' + image)
            image_links.append(link)
        _badge.image_link = ",".join(image_links)
        if _badge.logo_image != '':
            logoImageDirectory = os.path.join(badgePath, '../../uploads/image',
                                              _badge.logo_image)
            link = fileUploader(logoImageDirectory,
                                'images/' + _badge.logo_image)
            _badge.logo_image_link = link
        else:
            _badge.logo_image_link = ''
        link = fileUploader(badgePath + '/all-badges.pdf',
                            'badges/' + str(uuid.uuid4()) + '.pdf')
        send_badge_mail(_badge.id, user_creator.id, link)
        _badge.download_link = link
        rmtree(badgePath, ignore_errors=True)

    db.session.commit()
    return jsonify(BadgeSchema().dump(_badge).data)