Ejemplo n.º 1
0
def download(filename):
    uploads = os.path.join(app.root_path, app.config['UPLOADS_DIR'])
    logger.info("File with name {} downloaded".format(filename),
                user=current_user.get_id())
    return send_from_directory(directory=uploads,
                               filename=filename,
                               as_attachment=True)
Ejemplo n.º 2
0
def share():
    data = request.get_json()
    user_email = data["email"]
    file_id = data["file"]
    target_user = models.User.query.filter_by(email=user_email).first()
    response = None
    if target_user:
        try:
            target_file = models.File.query.filter_by(id=file_id).first()
            target_file.share_file(target_user)
            db.session.commit()
            flash(
                "You successfully shared your file with {}".format(user_email),
                "positive")
            logger.info("File shared by {} to {}".format(
                current_user.get_id(), target_user.get_id()),
                        user=current_user.get_id())
            return jsonify(dict(success=True, message='File shared!'))
        except Exception as e:
            flash(
                "Error encountered while sharing file, contact an admin or try again",
                "negative")
            logger.error("Exception encountered {}".format(e),
                         user=current_user.get_id())
            response = {"message": "error"}
            pass
    if response is None:
        response = {"status": 200}
    return jsonify(result=response)
Ejemplo n.º 3
0
def delete_file():
    data = request.get_json()
    file_id = data["file"]
    target_file = models.File.query.filter_by(id=file_id).first()
    for item in current_user.files:
        if item.file is target_file:
            db.session.delete(item)
            db.session.commit()
            logger.info("User {} no longer can access file {}".format(
                current_user.get_id(), file_id),
                        user=current_user.get_id())
            return jsonify(dict(success=True, message="File deleted"))
    return jsonify(dict(success=False, message="Unable to delete file"))
Ejemplo n.º 4
0
def check_year(s_id):
    """
    lmutil.exe does not provide a year with license data, this is a work-around to account for that. Checks in
    all licences if there is a difference between current year and the year of any checked out licenses.
    :param s_id: Id of server
    """
    checked_out = History.time_in_none(s_id)
    for r in checked_out:
        if datetime.now().year != r.time_out.year:
            Product.reset(s_id)
            History.reset(s_id)
            logger.info('check_year reset for server id {}'.format(s_id))
            break
Ejemplo n.º 5
0
def reset(token):
    try:
        email = ts.loads(token, salt='password-reset-key', max_age=86400)
    # The token can either expire or be invalid
    except:
        abort(404)
    form = user_forms.Reset()
    if form.validate_on_submit():
        user = models.User.query.filter_by(email=email).first()
        # Check the user exists
        if user is not None:
            # Connect to the LDAP server with the
            c = Connection(s,
                           user=app.config['LDAP_SERVICE_USERNAME'],
                           password=app.config['LDAP_SERVICE_PASSWORD'])
            # Open up the connection between the client and server
            c.open()
            # Raise the security level and start TLS
            c.start_tls()
            # Bind the user to the server now that the connection is secure
            c.bind()

            user_ldap_dn = 'cn=' + user.email.split(
                '@', 1)[0] + ',ou=Users,dc=ldap,dc=com'

            # Modify the user password and the LDAP user password
            user.password = form.password.data
            c.modify(
                user_ldap_dn,
                {'userPassword': [(MODIFY_REPLACE, [form.password.data])]})
            # Modify the LDAP user profile with the new password
            c.unbind()
            # Update the database with the user
            db.session.commit()
            logger.info('User password reset successfully', user=user.get_id())
            # Send to the signin page
            flash('Your password has been reset, you can sign in.', 'positive')
            return redirect(url_for('userbp.signin'))
        else:
            flash('Unknown email address.', 'negative')
            return redirect(url_for('userbp.forgot'))
    return render_template('user/reset.html', form=form, token=token)
Ejemplo n.º 6
0
def forgot():
    form = user_forms.Forgot()
    if form.validate_on_submit():
        user = models.User.query.filter_by(email=form.email.data).first()
        # Check the user exists
        if user is not None:
            # Subject of the confirmation email
            subject = 'Reset your password.'
            # Generate a random token
            token = ts.dumps(user.email, salt='password-reset-key')
            # Build a reset link with token
            resetUrl = url_for('userbp.reset', token=token, _external=True)
            # Render an HTML template to send by email
            html = render_template('email/reset.html', reset_url=resetUrl)
            # Send the email to user
            email.send(user.email, subject, html)
            logger.info('User password reset email sent', user=user.get_id())
            # Send back to the home page
            flash('Check your emails to reset your password.', 'positive')
            return redirect(url_for('index'))
        else:
            flash('Unknown email address.', 'negative')
            return redirect(url_for('userbp.forgot'))
    return render_template('user/forgot.html', form=form)
Ejemplo n.º 7
0
def signin():
    form = user_forms.Login()
    if form.validate_on_submit():
        user = models.User.query.filter_by(email=form.email.data).first()
        # Check the user exists
        if user is not None:
            # Setup a connection between the client and LDAP server
            user_ldap_dn = 'cn=' + user.email.split(
                '@', 1)[0] + ',ou=Users,dc=ldap,dc=com'
            c = Connection(s, user=user_ldap_dn, password=form.password.data)
            # Initialize connection to LDAP server
            c.open()
            # Start TLS to encrypt credentials
            c.start_tls()
            # Check the password is correct
            if user.check_password(form.password.data) and c.bind():
                # unbind user from LDAP server and log them in
                c.unbind()
                login_user(user)
                logger.info('User logged in successfully',
                            user=current_user.get_id())
                # Send back to the home page
                flash('Succesfully signed in.', 'positive')
                return redirect(url_for('index'))
            else:
                print(c)
                logger.info(
                    'User login attempt failed failed for user {}'.format(
                        user.get_id()),
                    user="******")
                flash('The password you have entered is wrong.', 'negative')
                return redirect(url_for('userbp.signin'))
        else:
            flash('Unknown email address.', 'negative')
            return redirect(url_for('userbp.signin'))
    return render_template('user/signin.html', form=form, title='Sign in')
Ejemplo n.º 8
0
def signup():
    form = user_forms.SignUp()
    if form.validate_on_submit():
        # Create a user who hasn't validated his email address
        user = models.User(
            first_name=form.first_name.data,
            last_name=form.last_name.data,
            #            phone=form.phone.data,
            email=form.email.data,
            confirmation=False,
            password=form.password.data)

        # Create a ldap_user
        ldap_user = {
            'objectClass': ['inetOrgPerson', 'posixAccount', 'top'],
            'givenName': user.first_name,
            'sn': user.last_name,
            'gidNumber': 500,
            'uidNumber': random.randint(1000, 1000000),
            'uid': user.email.split('@', 1)[0],
            'homeDirectory': '/home/users/' + user.email.split('@', 1)[0],
            'userPassword': form.password.data
        }

        user_ldap_dn = 'cn=' + ldap_user['uid'] + ',ou=Users,dc=ldap,dc=com'
        # Insert the user in the database
        db.session.add(user)
        # Add user in LDAP
        try:
            c = Connection(s,
                           user=app.config['LDAP_SERVICE_USERNAME'],
                           password=app.config['LDAP_SERVICE_PASSWORD'])
            c.open()
            c.start_tls()
            c.bind()
            c.add(user_ldap_dn, attributes=ldap_user)
        except Exception as e:
            # remove the user from the db session
            print(e)
            db.session.rollback()
            db.session.commit()
            logger.error('User account creation failed', user=user.get_id())
            flash(
                'There was an error in creating your account, if the issue persists, '
                'please contact and administrator.', 'negative')
            return redirect(url_for('index'))
        logger.info('User account created successfully', user=user.get_id())
        # If there was no error in adding user via LDAP we will commit the session to the database
        c.unbind()
        db.session.commit()
        # Subject of the confirmation email
        subject = 'Please confirm your email address.'
        # Generate a random token
        token = ts.dumps(user.email, salt='email-confirm-key')
        # Build a confirm link with token
        confirmUrl = url_for('userbp.confirm', token=token, _external=True)
        # Render an HTML template to send by email
        html = render_template('email/confirm.html', confirm_url=confirmUrl)
        # Send the email to user
        email.send(user.email, subject, html)
        # Send back to the home page
        flash('Check your emails to confirm your email address.', 'positive')
        return redirect(url_for('index'))
    return render_template('user/signup.html', form=form, title='Sign up')
Ejemplo n.º 9
0
def signout():
    logger.info('User logged out', user=current_user.get_id())
    logout_user()
    flash('Succesfully signed out.', 'positive')
    return redirect(url_for('index'))
Ejemplo n.º 10
0
def read(license_file=None):
    """
    entry point for reading license data from a FlexLM license server.
    :param license_file: manually pass in a license file in the same format the lmutil.exe displays data.
    :return:
    """
    for s in license_servers:
        try:
            info = ''
            server_id = Server.upsert(s['hostname'], s['port'])
            update_id = Updates.start(server_id)
            check_year(server_id)
            checked_out_history_ids = []
            if license_file:
                with open(license_file) as process:
                    lines = process.read()
            else:
                process = subprocess.Popen([
                    lm_util, "lmstat", "-f", "-c", "{}@{}".format(
                        s['port'], s['hostname'])
                ],
                                           stdout=subprocess.PIPE,
                                           stderr=subprocess.PIPE,
                                           bufsize=1,
                                           universal_newlines=True)
                lines = process.stdout.read()
            has_error = parse_error_info(lines)
            if has_error:
                reset(update_id, server_id,
                      '{}@{}: {}'.format(s['port'], s['hostname'], has_error))
                raise Exception(has_error)
            license_data = split_license_data(lines)
            updates = {'update_id': update_id, 'status': None}
            server_information = parse_server_info(lines)
            if server_information:
                updates['status'] = server_information[2]
            else:
                updates['status'] = "DOWN"
                reset(update_id, server_id,
                      '{}@{} is DOWN'.format(s['port'], s['hostname']))
                raise Exception(has_error)
            for lic in license_data:
                split_line = lic.split('FLOATING LICENSE')
                product_id = add_product(split_line[0], server_id=server_id)
                users_and_workstations = add_users_and_workstations(
                    split_line[-1])
                if product_id and len(users_and_workstations):
                    data = map_product_id(product_id, users_and_workstations)
                    for kwargs in data:
                        history_id = History.add(update_id=update_id,
                                                 server_id=server_id,
                                                 **kwargs)
                        checked_out_history_ids.append(history_id)
            dt = datetime.now().replace(second=0, microsecond=0)
            checked_out = History.time_in_none(server_id)
            for c in checked_out:
                if c.id not in checked_out_history_ids:
                    History.update(c.id, dt, server_id)
        except Exception as e:
            info = "{} error: {}".format(s['hostname'], str(e))
            logger.error(str(e))
            pass
        finally:
            logger.info('Finished reading data from \'{}\'. '
                        'Update details | id:{} | status:{} | info:{}.'.format(
                            s['hostname'], update_id, updates['status'], info))
            Updates.end(update_id, updates['status'], info)