Beispiel #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()
Beispiel #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)
Beispiel #3
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)
Beispiel #4
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)
Beispiel #5
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)
Beispiel #6
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)
Beispiel #7
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)
Beispiel #8
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)
Beispiel #9
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
Beispiel #10
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)
Beispiel #11
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)
Beispiel #12
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)