Exemplo n.º 1
0
def new_client():
    """ About block edit
    """
    # if errors detected
    errors = []

    # if form incoming
    if request.method == 'POST':
        if not request.form['title']:
            errors += ['Title required!']

        if not errors:
            client = dict()
            client['title'] = unicode(escape(request.form['title']))
            client['description'] = unicode(escape(request.form['description']))
            client['logo'] = unicode(escape(request.form['logo']))
            client['link'] = unicode(escape(request.form['link']))

            client = Client(**client)

            try:
                db_session.add(client)
                db_session.commit()
            except exc.SQLAlchemyError:
                db_session.rollback()
                errors += ['Error creating client #{0}\n'.format(client.id)]

            return redirect(url_for('edit_client', client_id=client.id))

    prop = dict()
    prop.update(default)
    prop['errors'] = errors

    return render_template('admin/new_client.html', **prop)
Exemplo n.º 2
0
def admin_edit_user(user_id):
    user = Journalist.query.get(user_id)

    if request.method == 'POST':
        if request.form['username'] != "":
            user.username = request.form['username']

        if request.form['password'] != "":
            if request.form['password'] != request.form['password_again']:
                flash("Passwords didn't match", "error")
                return redirect(url_for("admin_edit_user", user_id=user_id))
            user.set_password(request.form['password'])

        user.is_admin = bool(request.form.get('is_admin'))

        try:
            db_session.add(user)
            db_session.commit()
        except Exception, e:
            db_session.rollback()
            if "username is not unique" in str(e):
                flash("That username is already in use", "notification")
            else:
                flash(
                    "An unknown error occurred, please inform your administrator",
                    "error")
Exemplo n.º 3
0
def admin_edit_user(user_id):
    user = Journalist.query.get(user_id)

    if request.method == "POST":
        if request.form["username"] != "":
            user.username = request.form["username"]

        if request.form["password"] != "":
            if request.form["password"] != request.form["password_again"]:
                flash("Passwords didn't match", "error")
                return redirect(url_for("admin_edit_user", user_id=user_id))
            try:
                user.set_password(request.form["password"])
            except InvalidPasswordLength:
                flash(
                    "Your password is too long " "(maximum length {} characters)".format(Journalist.MAX_PASSWORD_LEN),
                    "error",
                )
                return redirect(url_for("admin_edit_user", user_id=user_id))

        user.is_admin = bool(request.form.get("is_admin"))

        try:
            db_session.add(user)
            db_session.commit()
        except Exception, e:
            db_session.rollback()
            if "username is not unique" in str(e):
                flash("That username is already in use", "notification")
            else:
                flash("An unknown error occurred, please inform your administrator", "error")
Exemplo n.º 4
0
def edit_about():
    """ About block edit
    """
    # saved?
    saved = False

    if request.method == 'POST':
        about = Info.query.filter(Info.title == 'about').first()
        about.value = unicode(request.form['about'])

        try:
            db_session.add(about)
            db_session.commit()
            saved = True
        except exc.SQLAlchemyError:
            db_session.rollback()
            saved = False

    about = Info.query.filter(Info.title == 'about').first()

    prop = dict()
    prop.update(default)
    prop['about'] = about.value
    prop['saved'] = saved

    return render_template('admin/edit_about.html', **prop)
def send_tweet(data):
    logger.info("send_tweet function")
    try:
        result = send_tweet.clf.hedging_top_n_classes(
            data['media'][0]['media_url_https'], top_n=5)
        logger.info(result)
    except FailToClassify as e:
        logger.exception(e.message)
        return

    classes = u'<ul>' + \
              reduce(lambda x, y: x + y,
                     map(lambda x: '<li>' + x + '</li>',
                         result[0])) + \
              u'</ul>'

    try:
        t = Tweets(text=data['text'],
                   photo_url=data['media'][0]['media_url_https'],
                   date=data['time'],
                   longitude=data['coordinates'][0],
                   latitude=data['coordinates'][1],
                   classes=classes)
        db_session.add(t)
        db_session.commit()

    except IntegrityError as e:
        db_session.rollback()
        logger.exception("IntegrityError: {}".format(e.message))
    except:
        db_session.rollback()
        e = sys.exc_info()[0]
        logger.exception("Error: %s" % e)
def create_single_version_file_on_drive(task, parent_drive_id, redmine_type, redmine_id,
                                        file_name, local_path, description, mime_type,
                                        version, modified_date):
    if not parent_drive_id:
        raise Exception("parent_drive_id is required")
    if not redmine_type:
        raise Exception("redmine_type is required")
    if redmine_id is None:
        raise Exception("redmine_id is required")
    if not file_name:
        raise Exception("folder_name is required")
    if not local_path:
        raise Exception("local_path is required")
    if not os.path.isfile(local_path):
        raise Exception("local_path %s is missing" % local_path)

    db_mapping = db_session.query(RedmineToDriveMapping).filter_by(redmine_id=redmine_id).filter_by(
        mapping_type=redmine_type).first()

    if db_mapping and db_mapping.drive_id:
        logger.info("File %s already mapped to %s", file_name, db_mapping.drive_id)
        return

    if not db_mapping:
        try:
            db_mapping = RedmineToDriveMapping(redmine_id=redmine_id, mapping_type=redmine_type,
                                               last_update=datetime.datetime.utcnow())
            db_session.add(db_mapping)
            db_session.commit()
            logger.info("Created mapping for %s %s id:%s", redmine_type, file_name, redmine_id)
        except IntegrityError, e:
            logger.info("Cannot create mapping due to duplicate, will retry: %s", e)
            db_session.rollback()
            task.retry(countdown=min(2 + (2 * current_task.request.retries), 128))
Exemplo n.º 7
0
    def note_create(self, data):
        from apps.notes.models import Note, Note2User
        try:
            note = Note()
            note.name = data['name']
            note.status = data['status']
            db_session.add(note)
            db_session.commit()

            note2user = Note2User()
            note2user.note = note
            note2user.user_id = self.id
            db_session.add(note2user)
            db_session.commit()

            if 'items' in data:
                for item in data['items']:
                    note.item_add(item['name'], item['description'])

            db_session.commit()

            return note
        except Exception as NoteCreatingError:
            log(NoteCreatingError)
            db_session.rollback()
            return 0
Exemplo n.º 8
0
def save_book(book: book.Book) -> Book:
    try:
        db_zipfile = ZipFile(zip_name=book.zip_file.zip_name)
        db_session.merge(db_zipfile)
        db_session.commit()
    except IntegrityError as e:
        db_session.rollback()
        db_zipfile = db_session.query(ZipFile).filter(
            ZipFile.zip_name == book.zip_file.zip_name).first()
        logging.error(e)
    db_book = Book(zip_name=book.zip_file.zip_name,
                   book_name=book.book_name,
                   title=book.title,
                   annotation=book.annotation,
                   authors=book.authors,
                   language=book.lang,
                   genre=book.genre)

    try:
        db_session.add(db_book)
        db_session.commit()
    except IntegrityError as e:
        db_session.rollback()
        db_book = db_session.query(Book).filter(
            Book.zip_name == book.zip_file.zip_name
            and Book.book_name == book.book_name).first()
        logging.error(e)
    for word in book.words:
        save_book_word(db_book, word)
    db_session.commit()
    return db_book
Exemplo n.º 9
0
def create_folder_on_drive(task, parent_drive_id, redmine_type, redmine_id,
                           folder_name):
    if not parent_drive_id:
        raise Exception("parent_drive_id is required")
    if not redmine_type:
        raise Exception("redmine_type is required")
    if redmine_id is None:
        raise Exception("redmine_id is required")
    if not folder_name:
        raise Exception("folder_name is required")

    db_mapping = db_session.query(RedmineToDriveMapping).filter_by(
        redmine_id=redmine_id).filter_by(mapping_type=redmine_type).first()

    if db_mapping and db_mapping.drive_id:
        logger.info("Folder %s already mapped to %s", folder_name,
                    db_mapping.drive_id)
        return

    if not db_mapping:
        try:
            db_mapping = RedmineToDriveMapping(
                redmine_id=redmine_id,
                mapping_type=redmine_type,
                last_update=datetime.datetime.utcnow())
            db_session.add(db_mapping)
            db_session.commit()
            logger.info("Created mapping for %s %s id:%s", redmine_type,
                        folder_name, redmine_id)
        except IntegrityError, e:
            logger.info(
                "Cannot create mapping due to duplicate, will retry: %s", e)
            db_session.rollback()
            task.retry(countdown=min(2 +
                                     (2 * current_task.request.retries), 128))
Exemplo n.º 10
0
def api_get():
    try:
        sayings = Sayings.query.all()
    except:
        db_session.rollback()
        return api_get()
    return {
        'code':
        200,
        'length':
        len(sayings),
        'sayings': [{
            'id':
            s.id,
            'saying':
            s.saying,
            'likes':
            s.likes,
            'info':
            json.loads(s.info if ('{' in s.info and '}' in s.info) else '{}'),
            'time':
            s.datetime,
            'uid':
            s.uid
        } for s in sayings]
    }
Exemplo n.º 11
0
    def login(cls, email, password):
        try:
            user_model = cls.authorize(email, password)
            if user_model:
                if not user_model.session:
                    secret_key = str(uuid.uuid1())
                    session['token'] = secret_key

                    sess_obj = Session(secret_key)
                    db_session.add(sess_obj)

                    user_model.session = sess_obj
                    user_model.save()

                    db_session.commit()

                    return True
                else:
                    return False
            else:
                return False

        except Exception as Error:
            print 'login error: %s' % Error
            traceback.print_exc(file=sys.stdout)
            db_session.rollback()

            return False
Exemplo n.º 12
0
def categories_list():

    #if errors detected
    errors = []

    #saved?
    saved = False

    if request.method == 'POST':
        categories = []

        saved = True

        for field in request.form:
            if field.startswith('title'):
                not_needed, category_id = field.split('-')
                categories.append(category_id)

        for category_id in categories:
            category = Category.query.get(int(category_id))
            category.title = escape(request.form['title-' + category_id])
            category.description = escape(request.form['description-' + category_id])

            try:
                db_session.add(category)
                db_session.commit()
            except exc.SQLAlchemyError:
                db_session.rollback()
                errors += ['Error saving category #{0}\n'.format(category.id)]
                saved = False

        if request.form['new-title']:
            category = Category(escape(request.form['new-title']), escape(request.form['new-description']))
            try:
                db_session.add(category)
                db_session.commit()
            except exc.SQLAlchemyError:
                db_session.rollback()
                errors += ['Error with new category']
                saved = False

    category_to_delete = request.values.get('delete', False)
    if category_to_delete:
        category = Category.query.get(int(category_to_delete))

        db_session.delete(category)
        db_session.commit()

        return redirect(url_for('categories_list'))

    categories = Category.query.all()

    prop = dict()
    prop.update(default)
    prop['categories'] = categories
    prop['saved'] = saved
    prop['errors'] = errors

    return render_template('admin/categories_list.html', **prop)
Exemplo n.º 13
0
 def logout(self):
     try:
         self._delete_session()
         return True
     except Exception as LogoutError:
         log(LogoutError)
         db_session.rollback()
         return False
Exemplo n.º 14
0
def _add_user(is_admin=False):
    username = _get_username()

    print("Note: Passwords are now autogenerated.")
    password = _make_password()
    print("This user's password is: {}".format(password))

    is_hotp = _get_yubikey_usage()
    otp_secret = None
    if is_hotp:
        while True:
            otp_secret = raw_input(
                "Please configure this user's YubiKey and enter the secret: ")
            if otp_secret:
                tmp_str = otp_secret.replace(" ", "")
                if len(tmp_str) != 40:
                    print("The length of the secret is not correct. "
                          "Expected 40 characters, but received {0}. "
                          "Try again.".format(len(tmp_str)))
                    continue
            if otp_secret:
                break

    try:
        user = Journalist(username=username,
                          password=password,
                          is_admin=is_admin,
                          otp_secret=otp_secret)
        db_session.add(user)
        db_session.commit()
    except Exception as exc:
        db_session.rollback()
        if "UNIQUE constraint failed: journalists.username" in str(exc):
            print('ERROR: That username is already taken!')
        else:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            print(repr(traceback.format_exception(exc_type, exc_value,
                                                  exc_traceback)))
        return 1
    else:
        print('User "{}" successfully added'.format(username))
        if not otp_secret:
            # Print the QR code for FreeOTP
            print('\nScan the QR code below with FreeOTP:\n')
            uri = user.totp.provisioning_uri(username,
                                             issuer_name='SecureDrop')
            qr = qrcode.QRCode()
            qr.add_data(uri)
            sys.stdout = codecs.getwriter("utf-8")(sys.stdout)
            qr.print_ascii(tty=sys.stdout.isatty())
            print('\nIf the barcode does not render correctly, try changing '
                  "your terminal's font (Monospace for Linux, Menlo for OS "
                  'X). If you are using iTerm on Mac OS X, you will need to '
                  'change the "Non-ASCII Font", which is your profile\'s Text '
                  "settings.\n\nCan't scan the barcode? Enter following "
                  'shared secret '
                  'manually:\n{}\n'.format(user.formatted_otp_secret))
        return 0
Exemplo n.º 15
0
    def save(self):
        try:
            db_session.add(self)
            db_session.commit()

            return self
        except:
            db_session.rollback()
            return False
Exemplo n.º 16
0
def save_zip_file(zipfile: zip_file.ZipFile) -> ZipFile:
    z = ZipFile(zip_name=zipfile.zip_name)
    try:
        db_session.add(z)
        db_session.commit()
    except IntegrityError as e:
        db_session.rollback()
        logging.error(e)
    return z
Exemplo n.º 17
0
def delete_me(user):
    try:
        if user.delete():
            return json_response(200, 'User deleted')
        return json_response(200, 'Could not delete this user')
    except Exception as DeleteWhileDeleting:
        db_session.rollback()
        log(DeleteWhileDeleting)
        return json_response(400, 'Could not delete this user')
Exemplo n.º 18
0
    def delete(self):
        try:
            db_session.delete(self)
            db_session.commit()

            return True
        except:
            db_session.rollback()
            return False
Exemplo n.º 19
0
def main():
    while True:
        try:
            run_phones_normalization_cycle()
        except OperationalError:
            db_session.rollback()
            time.sleep(TIMEOUT_WHEN_ERROR)
            continue
        time.sleep(TIMEOUT_BETWEEN_PHONES_NORMALIZATION_CYCLES)
Exemplo n.º 20
0
 def delete(self):
     try:
         self._delete_session()
         db_session.query(User).filter(User.id == self.id).delete()
         db_session.commit()
         return 1
     except Exception as UserDeletingError:
         log(UserDeletingError)
         db_session.rollback()
         return 0
Exemplo n.º 21
0
def _add_user(is_admin=False):
    username = _get_username()

    print("Note: Journalist passwords are now autogenerated.")
    password = _make_password()
    print("This journalist's password is: {}".format(password))

    is_hotp = _get_yubikey_usage()
    otp_secret = None
    if is_hotp:
        while True:
            otp_secret = raw_input(
                'Please configure your YubiKey and enter the secret: ')
            if otp_secret:
                break

    try:
        user = Journalist(username=username,
                          password=password,
                          is_admin=is_admin,
                          otp_secret=otp_secret)
        db_session.add(user)
        db_session.commit()
    except Exception as exc:
        db_session.rollback()
        if "UNIQUE constraint failed: journalists.username" in str(exc):
            print('ERROR: That username is already taken!')
        else:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            print(
                repr(
                    traceback.format_exception(exc_type, exc_value,
                                               exc_traceback)))
        return 1
    else:
        print('User "{}" successfully added'.format(username))
        if not otp_secret:
            # Print the QR code for FreeOTP/ Google Authenticator
            print(
                '\nScan the QR code below with FreeOTP or Google '
                'Authenticator:\n')
            uri = user.totp.provisioning_uri(username,
                                             issuer_name='SecureDrop')
            qr = qrcode.QRCode()
            qr.add_data(uri)
            qr.print_ascii(tty=sys.stdout.isatty())
            print(
                '\nIf the barcode does not render correctly, try changing '
                "your terminal's font (Monospace for Linux, Menlo for OS "
                'X). If you are using iTerm on Mac OS X, you will need to '
                'change the "Non-ASCII Font", which is your profile\'s Text '
                "settings.\n\nCan't scan the barcode? Enter following "
                'shared secret '
                'manually:\n{}\n'.format(user.formatted_otp_secret))
        return 0
Exemplo n.º 22
0
def create_project_employee(row, project):
    project_employee = ProjectEmployee(employee_id=row['employee_id'],
                                       project_id=project.id,
                                       date_start=row['date_start'],
                                       date_end=row['date_end'])
    db_session.add(project_employee)
    try:
        db_session.commit()
    except SQLAlchemyError:
        db_session.rollback()
        raise
Exemplo n.º 23
0
def get_or_create_project(project_name, company_id):
    project = Project.query.filter(Project.name == project_name,
                                   Project.company_id == company_id).first()
    if not project:
        project = Project(name=project_name, company_id=company_id)
        db_session.add(project)
        try:
            db_session.commit()
        except SQLAlchemyError:
            db_session.rollback()
            raise
    return project
Exemplo n.º 24
0
def get_rating(uid):
    fields_available = [
        "uid", "user_id_source", "user_id_destination", "rating", "message",
        "creation_date", "transaction_id"
    ]
    rating_type = "received"
    size = 5
    fields = ["rating"]

    for arg in request.args:
        print arg
    if "rating" in request.args:
        if request.args.get("rating") not in ["received", "given", "all"]:
            return build_error_response(
                "Invalid rating parameter", 400,
                "Rating argument should be received, given or all")
        rating_type = request.args.get("rating")

    if "size" in request.args:
        print request.args.get("size")
        if not request.args.get(
                "size").isdigit() and request.args.get("size") != "all":
            return build_error_response(
                "Invalid size parameter", 400,
                "Size argument should be a number or all")
        try:
            size = int(request.args.get("size"))
        except:
            size = request.args.get("size")

    if "fields" in request.args:
        print request.args.get("fields")
        fields_requested = request.args.get("fields").split(",")
        if False if [x in fields_available
                     for x in fields_requested] else True:
            return build_error_response(
                "Invalid fields parameter", 400,
                "Fields argument contains an invalid field")
        fields = fields_requested

    try:
        data = UsersRating.query.filter_by(uid=uid).first().serialize(
            fields=fields, size=size, rating_type=rating_type)
    except:
        user_dest = UsersRating(uid=uid)
        db_session.add(user_dest)
        try:
            db_session.commit()
        except:
            db_session.rollback()
        data = UsersRating.query.filter_by(uid=uid).first().serialize(
            fields=fields, size=size, rating_type=rating_type)
    return build_response(data, 200, "Rating successfully retrieved.")
Exemplo n.º 25
0
    def logout(cls, token):
        try:
            db_session.query(User).filter(Session.token == token).delete()
            db_session.commit()

            del session['token']

            return True
        except Exception as Error:
            print 'logout error: %s' % Error
            traceback.print_exc(file=sys.stdout)
            db_session.rollback()
            return False
Exemplo n.º 26
0
def commit_account_changes(user):
    if db_session.is_modified(user):
        try:
            db_session.add(user)
            db_session.commit()
        except Exception as e:
            flash("An unexpected error occurred! Please check the application "
                  "logs or inform your adminstrator.", "error")
            app.logger.error("Account changes for '{}' failed: {}".format(user,
                                                                          e))
            db_session.rollback()
        else:
            flash("Account successfully updated!", "success")
Exemplo n.º 27
0
def admin_add_user():
    if request.method == 'POST':
        form_valid = True

        username = request.form['username']
        if len(username) == 0:
            form_valid = False
            flash("Missing username", "error")

        password = request.form['password']
        password_again = request.form['password_again']
        if password != password_again:
            form_valid = False
            flash("Passwords didn't match", "error")

        is_admin = bool(request.form.get('is_admin'))

        if form_valid:
            try:
                otp_secret = None
                if request.form.get('is_hotp', False):
                    otp_secret = request.form.get('otp_secret', '')
                new_user = Journalist(username=username,
                                      password=password,
                                      is_admin=is_admin,
                                      otp_secret=otp_secret)
                db_session.add(new_user)
                db_session.commit()
            except InvalidPasswordLength:
                form_valid = False
                flash(
                    "Your password must be between {} and {} characters.".
                    format(Journalist.MIN_PASSWORD_LEN,
                           Journalist.MAX_PASSWORD_LEN), "error")
            except IntegrityError as e:
                db_session.rollback()
                form_valid = False
                if "UNIQUE constraint failed: journalists.username" in str(e):
                    flash("That username is already in use", "error")
                else:
                    flash(
                        "An error occurred saving this user to the database."
                        " Please check the application logs.", "error")
                    app.logger.error("Adding user '{}' failed: {}".format(
                        username, e))

        if form_valid:
            return redirect(
                url_for('admin_new_user_two_factor', uid=new_user.id))

    return render_template("admin_add_user.html")
Exemplo n.º 28
0
def commit_account_changes(user):
    if db_session.is_modified(user):
        try:
            db_session.add(user)
            db_session.commit()
        except Exception as e:
            flash(
                gettext("An unexpected error occurred! Please "
                        "inform your administrator."), "error")
            current_app.logger.error(
                "Account changes for '{}' failed: {}".format(user, e))
            db_session.rollback()
        else:
            flash(gettext("Account updated."), "success")
Exemplo n.º 29
0
def edit_project(project_id):
    """ Edit project
    """
    # if errors detected
    errors = []

    # saved?
    saved = False

    # if form incoming
    if request.method == 'POST':
        if not request.form['title']:
            errors += ['Title required!']

        if not errors:
            project = Project.query.get(project_id)
            project.title = unicode(escape(request.form['title']))
            project.description = unicode(escape(request.form['description']))
            project.logo = unicode(escape(request.form['logo']))
            project.link = unicode(escape(request.form['link']))
            project.category_id = int(escape(request.form['category']))
            project.client_id = int(escape(request.form['client']))

            try:
                db_session.add(project)
                db_session.commit()
                saved = True

            except exc.SQLAlchemyError:
                db_session.rollback()
                errors += ["Error saving project!"]
                saved = False

        else:
            project = Project.query.get(project_id)
    else:
        project = Project.query.get(project_id)

    categories = Category.query.all()
    clients = Client.query.all()

    prop = dict()
    prop.update(default)
    prop['project'] = project
    prop['categories'] = categories
    prop['clients'] = clients
    prop['errors'] = errors
    prop['saved'] = saved

    return render_template('admin/edit_project.html', **prop)
Exemplo n.º 30
0
def commit_account_changes(user):
    if db_session.is_modified(user):
        try:
            db_session.add(user)
            db_session.commit()
        except Exception as e:
            flash(gettext(
                "An unexpected error occurred! Please "
                  "inform your administrator."), "error")
            current_app.logger.error("Account changes for '{}' failed: {}"
                                     .format(user, e))
            db_session.rollback()
        else:
            flash(gettext("Account updated."), "success")
Exemplo n.º 31
0
    def add_user():
        form = NewUserForm()
        if form.validate_on_submit():
            form_valid = True
            username = request.form['username']
            password = request.form['password']
            is_admin = bool(request.form.get('is_admin'))

            try:
                otp_secret = None
                if request.form.get('is_hotp', False):
                    otp_secret = request.form.get('otp_secret', '')
                new_user = Journalist(username=username,
                                      password=password,
                                      is_admin=is_admin,
                                      otp_secret=otp_secret)
                db_session.add(new_user)
                db_session.commit()
            except PasswordError:
                flash(gettext(
                      'There was an error with the autogenerated password. '
                      'User not created. Please try again.'), 'error')
                form_valid = False
            except InvalidUsernameException as e:
                form_valid = False
                flash('Invalid username: '******'{}' failed: {}".format(
                                                 username, e))

            if form_valid:
                return redirect(url_for('admin.new_user_two_factor',
                                        uid=new_user.id))

        return render_template("admin_add_user.html",
                               password=make_password(config),
                               form=form)
Exemplo n.º 32
0
def save_book_word(book: Book, word: str):
    db_word = Word(word=word, cnt=1)
    try:
        db_session.add(db_word)
        db_session.commit()
    except IntegrityError as e:
        db_session.rollback()
        db_session.query(Word).filter(Word.word == word).update(
            {Word.cnt: Word.cnt + 1})
        db_word = db_session.query(Word).filter(Word.word == word).first()
    db_book_word = BookWord(book_id=book.id, word_id=db_word.id)
    try:
        db_session.add(db_book_word)
        db_session.commit()
    except IntegrityError as e:
        db_session.rollback()
Exemplo n.º 33
0
    def login(cls, email, password):
        try:
            user_model = cls.authorize(email, password)
            if user_model:
                if not user_model.session or ('token' not in session) or (session['token'] is None):
                    user_model._create_session()
                    return user_model
                else:
                    return 1
            else:
                return 2
        except Exception as LoginUserError:
            log(LoginUserError)
            db_session.rollback()

            return 0
Exemplo n.º 34
0
    def _create_session(self):
        try:
            self._delete_session()

            sess = Session()
            sess.user = self
            session['token'] = sess.token
            db_session.add(sess)
            db_session.commit()

            # self.session = sess
            # db_session.commit()
        except Exception as newSessionError:
            db_session.rollback()
            log(newSessionError)
            session['token'] = None
Exemplo n.º 35
0
def edit_client(client_id):
    """ About block edit
    """
    # if errors detected
    errors = []

    #saved?
    saved = False

    # if form incoming
    if request.method == 'POST':
        if not request.form['title']:
            errors += ['Title required!']

        if not errors:
            client = Client.query.get(client_id)

            client.title = unicode(escape(request.form['title']))
            client.description = unicode(escape(request.form['description']))
            client.logo = unicode(escape(request.form['logo']))
            client.link = unicode(escape(request.form['link']))

            try:
                db_session.add(client)
                db_session.commit()
                saved = True
            except exc.SQLAlchemyError:
                db_session.rollback()
                saved = False
                errors += ['Error saving client #{0}\n'.format(client.id)]

        else:
            client = Client.query.get(client_id)

    else:
        client = Client.query.get(client_id)

    prop = dict()
    prop.update(default)
    prop['client'] = client
    prop['errors'] = errors
    prop['saved'] = saved

    return render_template('admin/edit_client.html', **prop)
Exemplo n.º 36
0
    def register(cls, email, passwd):
        try:
            user = db_session.query(User).filter(User.email == email).first()

            if user:
                return 0

            password = str(md5(passwd).hexdigest())
            user = User(email=email, password=password)
            user._create_session()

            db_session.add(user)
            db_session.commit()

            return user
        except Exception as RegisterUserError:
            log(ReferenceError)
            db_session.rollback()
            return 0
Exemplo n.º 37
0
def new_project():
    """ New project
    """

    # if errors detected
    errors = []

    # if form incoming
    if request.method == 'POST':
        if not request.form['title']:
            errors += ['Title required!']
        if not errors:
            project = dict()
            project['title'] = unicode(escape(request.form['title']))
            project['description'] = unicode(escape(request.form['description']))
            project['logo'] = unicode(escape(request.form['logo']))
            project['link'] = unicode(escape(request.form['link']))
            project['category_id'] = int(escape(request.form['category']))
            project['client_id'] = int(escape(request.form['client']))

            project = Project(**project)

            try:
                db_session.add(project)
                db_session.commit()
            except exc.SQLAlchemyError:
                db_session.rollback()
                errors += ['Error creating project #{0}\n'.format(project.id)]

            return redirect(url_for('edit_project', project_id=project.id))

    categories = Category.query.all()
    clients = Client.query.all()

    prop = dict()
    prop.update(default)
    prop['categories'] = categories
    prop['clients'] = clients
    prop['errors'] = errors

    return render_template('admin/new_project.html', **prop)
Exemplo n.º 38
0
    def create():
        filesystem_id = crypto_util.hash_codename(session['codename'])

        source = Source(filesystem_id, crypto_util.display_id())
        db_session.add(source)
        try:
            db_session.commit()
        except IntegrityError as e:
            db_session.rollback()
            current_app.logger.error(
                "Attempt to create a source with duplicate codename: %s" %
                (e, ))

            # Issue 2386: don't log in on duplicates
            del session['codename']
            abort(500)
        else:
            os.mkdir(store.path(filesystem_id))

        session['logged_in'] = True
        return redirect(url_for('.lookup'))
Exemplo n.º 39
0
def admin_edit_user(user_id):
    user = Journalist.query.get(user_id)

    if request.method == 'POST':
        if request.form['username'] != "":
            user.username = request.form['username']

        if request.form['password'] != "":
            if request.form['password'] != request.form['password_again']:
                flash("Passwords didn't match", "error")
                return redirect(url_for("admin_edit_user", user_id=user_id))
            user.set_password(request.form['password'])

        user.is_admin = bool(request.form.get('is_admin'))

        try:
            db_session.add(user)
            db_session.commit()
        except Exception, e:
            db_session.rollback()
            if "username is not unique" in str(e):
                flash("That username is already in use", "notification")
            else:
                flash("An unknown error occurred, please inform your administrator", "error")
Exemplo n.º 40
0
def _add_user(is_admin=False):  # pragma: no cover
    while True:
        username = raw_input('Username: '******'Password: '******'Confirm Password: '******'Your password is too long (maximum length {} characters). '
                  'Please pick a shorter '
                  'password.'.format(Journalist.MAX_PASSWORD_LEN))
            continue

        if len(password) < Journalist.MIN_PASSWORD_LEN:
            print('Error: Password needs to be at least {} characters.'.format(
                Journalist.MIN_PASSWORD_LEN
            ))
            continue

        if password == password_again:
            break
        print("Passwords didn't match!")

    hotp_input = raw_input('Will this user be using a YubiKey [HOTP]? (y/N): ')
    otp_secret = None
    if hotp_input.lower() in ('y', 'yes'):
        while True:
            otp_secret = raw_input(
                'Please configure your YubiKey and enter the secret: ')
            if otp_secret:
                break

    try:
        user = Journalist(username=username,
                          password=password,
                          is_admin=is_admin,
                          otp_secret=otp_secret)
        db_session.add(user)
        db_session.commit()
    except Exception as exc:
        db_session.rollback()
        if "UNIQUE constraint failed: journalists.username" in str(exc):
            print('ERROR: That username is already taken!')
        else:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            print(repr(traceback.format_exception(exc_type, exc_value,
                                                  exc_traceback)))
        return 1
    else:
        print('User "{}" successfully added'.format(username))
        if not otp_secret:
            # Print the QR code for FreeOTP/ Google Authenticator
            print('\nScan the QR code below with FreeOTP or Google '
                  'Authenticator:\n')
            uri = user.totp.provisioning_uri(username,
                                             issuer_name='SecureDrop')
            qr = qrcode.QRCode()
            qr.add_data(uri)
            qr.print_ascii(tty=sys.stdout.isatty())
            print('\nIf the barcode does not render correctly, try changing '
                  "your terminal's font (Monospace for Linux, Menlo for OS "
                  'X). If you are using iTerm on Mac OS X, you will need to '
                  'change the "Non-ASCII Font", which is your profile\'s Text '
                  "settings.\n\nCan't scan the barcode? Enter following "
                  'shared secret '
                  'manually:\n{}\n'.format(user.formatted_otp_secret))
        return 0
Exemplo n.º 41
0
def create():
    if request.form["dest_id"] is None or request.form[
            "source_id"] is None or request.form[
                "rating"] is None or request.form["transaction_id"] is None:
        return build_error_response(
            "Invalid Parameters", 400,
            "Destination ID, Source ID, Rating or Transaction ID not present in the request"
        )

    if int(request.form["rating"]) < 1 or int(request.form["rating"]) > 5:
        return build_error_response("Invalid Rating Values", 400,
                                    "Rating value should be between 1 and 5")

    dest_id = request.form["dest_id"]
    source_id = request.form["source_id"]
    rate_value = int(request.form["rating"])
    transaction_id = request.form["transaction_id"]
    rate_id = uuid.uuid4()

    if UsersRating.query.filter_by(uid=source_id).first() is None:
        user_dest = UsersRating(uid=source_id)
        db_session.add(user_dest)
        try:
            db_session.commit()
        except:
            db_session.rollback()

    if UsersRating.query.filter_by(uid=dest_id).first() is None:
        user_dest = UsersRating(uid=dest_id)
        db_session.add(user_dest)
        try:
            db_session.commit()
        except:
            db_session.rollback()

    if Ratings.query.filter_by(
            transaction_id=transaction_id).first() is not None:
        return build_error_response("Invalid transaction ID", 400,
                                    "Transaction ID is already in use.")

    if request.form["message"] is not None:
        message = request.form["message"]
        rate = Ratings(uid=rate_id,
                       user_id_source=source_id,
                       user_id_destination=dest_id,
                       rating=rate_value,
                       transaction_id=transaction_id,
                       message=message)
    else:
        rate = Ratings(uid=rate_id,
                       user_id_source=source_id,
                       user_id_destination=dest_id,
                       rating=rate_value,
                       transaction_id=transaction_id)

    db_session.add(rate)
    db_session.commit()

    if UsersRating.query.filter_by(uid=dest_id).count() < 1:
        rating_received = (rate_value * 100) / 5
        rating_received_count = 1
        user_dest = UsersRating(uid=dest_id,
                                rating_received=rating_received,
                                rating_received_count=rating_received_count,
                                rating_total=rating_received)
        db_session.add(user_dest)
        db_session.commit()
    else:
        user = UsersRating.query.filter_by(uid=dest_id).first()
        rating_received = (rate_value * 100) / 5
        user.rating_received = ((user.rating_received*user.rating_received_count) + rating_received) / \
                               (user.rating_received_count + 1)

        user.rating_total = (((user.rating_received*user.rating_received_count) + rating_received) +
                             (user.rating_given*user.rating_given_count)) / \
                            (user.rating_given_count + user.rating_received_count + 1)

        user.rating_received_count += 1
        db_session.commit()

    if UsersRating.query.filter_by(uid=source_id).count() < 1:
        rating_given = (rate_value * 100) / 5
        rating_given_count = 1
        user_source = UsersRating(uid=source_id,
                                  rating_given=rating_given,
                                  rating_given_count=rating_given_count,
                                  rating_total=rating_received)
        db_session.add(user_source)
        db_session.commit()
    else:
        user = UsersRating.query.filter_by(uid=source_id).first()
        rating_given = (rate_value * 100) / 5
        user.rating_given = ((user.rating_given * user.rating_given_count) + rating_given) / \
                            (user.rating_given_count + 1)

        user.rating_total = (((user.rating_given * user.rating_given_count) + rating_given) +
                             (user.rating_received * user.rating_received_count)) / \
                            (user.rating_given_count + user.rating_received_count + 1)

        user.rating_given_count += 1
        db_session.commit()

    return build_response("Rate Done", 200, "Rate has been done successfully")