Exemplo n.º 1
0
def do_login():
    """Authenticate users of the web-UI"""
    if not admin_exists():
        return redirect('/create_admin')

    elif flask_login.current_user.is_authenticated:
        flash(gettext(u"Cannot access login page if you're already logged in"),
              "error")
        return redirect(url_for('general_routes.home'))

    form_login = forms_authentication.Login()

    # Check if the user is banned from logging in (too many incorrect attempts)
    if banned_from_login():
        flash(
            gettext(
                u"Too many failed login attempts. Please wait %(min)s "
                u"minutes before attempting to log in again",
                min=(int(LOGIN_BAN_SECONDS - session['ban_time_left']) / 60) +
                1), "info")
    else:
        if request.method == 'POST':
            username = form_login.username.data.lower()
            user_ip = request.environ.get('REMOTE_ADDR', 'unknown address')
            user = User.query.filter(func.lower(User.name) == username).first()

            if not user:
                login_log(username, 'NA', user_ip, 'NOUSER')
                failed_login()
            elif form_login.validate_on_submit():
                if User().check_password(
                        form_login.password.data,
                        user.password_hash) == user.password_hash:

                    login_log(username, user.roles.name, user_ip, 'LOGIN')

                    # flask-login user
                    login_user = User()
                    login_user.id = user.id
                    remember_me = True if form_login.remember.data else False
                    flask_login.login_user(login_user, remember=remember_me)

                    return redirect(url_for('general_routes.home'))
                else:
                    login_log(username, user.roles.name, user_ip, 'FAIL')
                    failed_login()
            else:
                login_log(username, 'NA', user_ip, 'FAIL')
                failed_login()

            return redirect('/login')

    return render_template(
        'login.html',
        form_login=form_login,
    )
Exemplo n.º 2
0
def remote_admin_login():
    """Authenticate Remote Admin login"""
    password_hash = request.form.get('password_hash', None)
    username = request.form.get('username', None)

    if username and password_hash:
        user = User.query.filter(func.lower(User.name) == username).first()
    else:
        user = None

    if user and user.password_hash == password_hash:
        login_user = User()
        login_user.id = user.id
        flask_login.login_user(login_user, remember=False)
        return "Logged in via Remote Admin"
Exemplo n.º 3
0
def newremote():
    """Verify authentication as a client computer to the remote admin."""
    username = request.args.get('user')
    pass_word = request.args.get('passw')

    user = User.query.filter(User.name == username).first()

    if user:
        if User().check_password(pass_word,
                                 user.password_hash) == user.password_hash:
            try:
                with open(
                        '/var/mycodo-root/mycodo/mycodo_flask/ssl_certs/cert.pem',
                        'r') as cert:
                    certificate_data = cert.read()
            except Exception:
                certificate_data = None
            return jsonify(status=0,
                           error_msg=None,
                           hash=str(user.password_hash),
                           certificate=certificate_data)
    return jsonify(status=1,
                   error_msg="Unable to authenticate with user and password.",
                   hash=None,
                   certificate=None)
def create_admin():
    if admin_exists():
        flash(gettext(
            u"Cannot access admin creation form if an admin user "
            u"already exists."), "error")
        return redirect(url_for('general_routes.home'))

    # If login token cookie from previous session exists, delete
    if request.cookies.get('remember_token'):
        response = clear_cookie_auth()
        return response

    form = flaskforms.CreateAdmin()
    if request.method == 'POST':
        if form.validate():
            username = form.username.data.lower()
            error = False
            if form.password.data != form.password_repeat.data:
                flash(gettext(u"Passwords do not match. Please try again."),
                      "error")
                error = True
            if not test_username(username):
                flash(gettext(
                    u"Invalid user name. Must be between 2 and 64 characters "
                    u"and only contain letters and numbers."),
                    "error")
                error = True
            if not test_password(form.password.data):
                flash(gettext(
                    u"Invalid password. Must be between 6 and 64 characters "
                    u"and only contain letters, numbers, and symbols."),
                      "error")
                error = True
            if error:
                return redirect(url_for('general_routes.home'))

            new_user = User()
            new_user.name = username
            new_user.email = form.email.data
            new_user.set_password(form.password.data)
            new_user.role = 1  # Admin
            new_user.theme = 'slate'
            try:
                db.session.add(new_user)
                db.session.commit()
                flash(gettext(u"User '%(user)s' successfully created. Please "
                              u"log in below.", user=username),
                      "success")
                return redirect(url_for('authentication_routes.do_login'))
            except Exception as except_msg:
                flash(gettext(u"Failed to create user '%(user)s': %(err)s",
                              user=username,
                              err=except_msg), "error")
        else:
            flash_form_errors(form)
    return render_template('create_admin.html',
                           form=form)
Exemplo n.º 5
0
def user_add(form):
    action = '{action} {controller} {user}'.format(
        action=gettext("Add"),
        controller=gettext("User"),
        user=form.user_name.data.lower())
    error = []

    if form.validate():
        new_user = User()
        new_user.name = form.user_name.data.lower()
        if not test_username(new_user.name):
            error.append(
                gettext(
                    "Invalid user name. Must be between 2 and 64 characters "
                    "and only contain letters and numbers."))

        new_user.email = form.email.data
        if User.query.filter_by(email=new_user.email).count():
            error.append(
                gettext("Another user already has that email address."))

        if not test_password(form.password_new.data):
            error.append(
                gettext(
                    "Invalid password. Must be between 6 and 64 characters "
                    "and only contain letters, numbers, and symbols."))

        if form.password_new.data != form.password_repeat.data:
            error.append(gettext("Passwords do not match. Please try again."))

        if not error:
            new_user.set_password(form.password_new.data)
            role = Role.query.filter(Role.name == form.addRole.data).first().id
            new_user.role = role
            new_user.theme = form.theme.data
            try:
                new_user.save()
            except sqlalchemy.exc.OperationalError as except_msg:
                error.append(except_msg)
            except sqlalchemy.exc.IntegrityError as except_msg:
                error.append(except_msg)

        flash_success_errors(error, action,
                             url_for('routes_settings.settings_users'))
    else:
        flash_form_errors(form)
Exemplo n.º 6
0
def login_keypad_code(code):
    """Check code from keypad."""
    if not admin_exists():
        return redirect('/create_admin')

    elif flask_login.current_user.is_authenticated:
        flash(gettext("Cannot access login page if you're already logged in"),
              "error")
        return redirect(url_for('routes_general.home'))

    # Check if the user is banned from logging in (too many incorrect attempts)
    if banned_from_login():
        flash(
            gettext(
                "Too many failed login attempts. Please wait %(min)s "
                "minutes before attempting to log in again",
                min=int(
                    (LOGIN_BAN_SECONDS - session['ban_time_left']) / 60) + 1),
            "info")
    else:
        user = User.query.filter(User.code == code).first()
        user_ip = request.environ.get('HTTP_X_FORWARDED_FOR',
                                      'unknown address')

        if not user:
            login_log(code, 'NA', user_ip, 'FAIL')
            failed_login()
            flash("Invalid Code", "error")
            time.sleep(2)
        else:
            role_name = Role.query.filter(Role.id == user.role_id).first().name
            login_log(user.name, role_name, user_ip, 'LOGIN')

            # flask-login user
            login_user = User()
            login_user.id = user.id
            remember_me = True
            flask_login.login_user(login_user, remember=remember_me)

            return redirect(url_for('routes_general.home'))

    return render_template('login_keypad.html',
                           dict_translation=TRANSLATIONS,
                           host=socket.gethostname())
Exemplo n.º 7
0
def add_user(admin=False):
    new_user = User()

    print('\nAdd user to database')

    while True:
        user_name = raw_input('User (a-z, A-Z, 2-64 chars): ').lower()
        if test_username(user_name):
            new_user.name = user_name
            break

    while True:
        user_password = getpass.getpass('Password: '******'Password (again): ')
        if user_password != user_password_again:
            print("Passwords don't match")
        else:
            if test_password(user_password):
                new_user.set_password(user_password)
                break

    while True:
        email = raw_input('Email: ')
        if is_email(email):
            new_user.email = email
            break

    if admin:
        new_user.role = 1
    else:
        new_user.role = 4

    new_user.theme = 'slate'
    try:
        with session_scope(MYCODO_DB_PATH) as db_session:
            db_session.add(new_user)
        sys.exit(0)
    except sqlalchemy.exc.OperationalError:
        print("Failed to create user.  You most likely need to "
              "create the DB before trying to create users.")
        sys.exit(1)
    except sqlalchemy.exc.IntegrityError:
        print("Username already exists.")
        sys.exit(1)
Exemplo n.º 8
0
def user_roles(form):
    action = None
    if form.add_role.data:
        action = gettext("Add")
    elif form.save_role.data:
        action = gettext("Modify")
    elif form.delete_role.data:
        action = gettext("Delete")

    action = '{action} {controller}'.format(
        action=action,
        controller=gettext("User Role"))
    error = []

    if not error:
        if form.add_role.data:
            new_role = Role()
            new_role.name = form.name.data
            new_role.view_logs = form.view_logs.data
            new_role.view_camera = form.view_camera.data
            new_role.view_stats = form.view_stats.data
            new_role.view_settings = form.view_settings.data
            new_role.edit_users = form.edit_users.data
            new_role.edit_settings = form.edit_settings.data
            new_role.edit_controllers = form.edit_controllers.data
            try:
                new_role.save()
            except sqlalchemy.exc.OperationalError as except_msg:
                error.append(except_msg)
            except sqlalchemy.exc.IntegrityError as except_msg:
                error.append(except_msg)
        elif form.save_role.data:
            mod_role = Role.query.filter(Role.unique_id == form.role_id.data).first()
            mod_role.view_logs = form.view_logs.data
            mod_role.view_camera = form.view_camera.data
            mod_role.view_stats = form.view_stats.data
            mod_role.view_settings = form.view_settings.data
            mod_role.edit_users = form.edit_users.data
            mod_role.edit_settings = form.edit_settings.data
            mod_role.edit_controllers = form.edit_controllers.data
            db.session.commit()
        elif form.delete_role.data:
            if User().query.filter(User.role_id == form.role_id.data).count():
                error.append(
                    "Cannot delete role if it is assigned to a user. "
                    "Change the user to another role and try again.")
            else:
                delete_entry_with_id(Role,
                                     form.role_id.data)
    flash_success_errors(error, action, url_for('routes_settings.settings_users'))
Exemplo n.º 9
0
def newremote():
    """Verify authentication as a client computer to the remote admin"""
    username = request.args.get('user')
    pass_word = request.args.get('passw')

    user = User.query.filter(User.name == username).first()

    # TODO: Change sleep() to max requests per duration of time
    time.sleep(1)  # Slow down requests (hackish, prevent brute force attack)
    if user:
        if User().check_password(pass_word,
                                 user.password_hash) == user.password_hash:
            return jsonify(status=0,
                           message="{hash}".format(hash=user.password_hash))
    return jsonify(status=1,
                   message="Unable to authenticate with user and password.")
Exemplo n.º 10
0
        user_valid = True

email = input("Email Address: ")

while not passwords_match and not password_valid:
    password = getpass("Password: "******"Repeat Password: "******"Password don't math. Try again.")
    else:
        passwords_match = True

try:
    with session_scope(MYCODO_DB_PATH) as db_session:
        new_user = User()
        new_user.unique_id = set_uuid()
        new_user.name = user_name.lower()
        new_user.password_hash = set_password(password)
        new_user.email = email
        new_user.role_id = 1
        new_user.theme = 'slate'
        new_user.landing_page = 'live'
        new_user.language = 'en'
        db_session.add(new_user)

    print("Admin user '{}' successfully created.".format(user_name.lower()))
except Exception:
    print(
        "Error creating admin user. Refer the the traceback, below, for the error."
    )
Exemplo n.º 11
0
        user_valid = True

email = input("Email Address: ")

while not passwords_match and not password_valid:
    password = getpass("Password: "******"Repeat Password: "******"Password don't math. Try again.")
    else:
        passwords_match = True

try:
    with session_scope(MYCODO_DB_PATH) as db_session:
        new_user = User()
        new_user.unique_id = set_uuid()
        new_user.name = user_name.lower()
        new_user.password_hash = set_password(password)
        new_user.email = email
        new_user.role_id = 1
        new_user.theme = 'slate'
        new_user.landing_page = 'live'
        new_user.language = 'en'
        db_session.add(new_user)

    print("Admin user '{}' successfully created.".format(user_name.lower()))
except Exception:
    print("Error creating admin user. Refer the the traceback, below, for the error.")
    traceback.print_exc()
Exemplo n.º 12
0
def create_admin():
    if admin_exists():
        flash(
            gettext("Cannot access admin creation form if an admin user "
                    "already exists."), "error")
        return redirect(url_for('routes_general.home'))

    # If login token cookie from previous session exists, delete
    if request.cookies.get('remember_token'):
        response = clear_cookie_auth()
        return response

    form_create_admin = forms_authentication.CreateAdmin()
    form_notice = forms_authentication.InstallNotice()

    if request.method == 'POST':
        form_name = request.form['form-name']
        if form_name == 'acknowledge':
            mod_misc = Misc.query.first()
            mod_misc.dismiss_notification = 1
            db.session.commit()
        elif form_create_admin.validate():
            username = form_create_admin.username.data.lower()
            error = False
            if form_create_admin.password.data != form_create_admin.password_repeat.data:
                flash(gettext("Passwords do not match. Please try again."),
                      "error")
                error = True
            if not test_username(username):
                flash(
                    gettext(
                        "Invalid user name. Must be between 2 and 64 characters "
                        "and only contain letters and numbers."), "error")
                error = True
            if not test_password(form_create_admin.password.data):
                flash(
                    gettext(
                        "Invalid password. Must be between 6 and 64 characters "
                        "and only contain letters, numbers, and symbols."),
                    "error")
                error = True
            if error:
                return redirect(url_for('routes_general.home'))

            new_user = User()
            new_user.name = username
            new_user.email = form_create_admin.email.data
            new_user.set_password(form_create_admin.password.data)
            new_user.role_id = 1  # Admin
            new_user.theme = 'spacelab'
            try:
                db.session.add(new_user)
                db.session.commit()
                flash(
                    gettext(
                        "User '%(user)s' successfully created. Please "
                        "log in below.",
                        user=username), "success")
                return redirect(url_for('routes_authentication.login_check'))
            except Exception as except_msg:
                flash(
                    gettext("Failed to create user '%(user)s': %(err)s",
                            user=username,
                            err=except_msg), "error")
        else:
            utils_general.flash_form_errors(form_create_admin)

    dismiss_notification = Misc.query.first().dismiss_notification

    return render_template('create_admin.html',
                           dict_translation=TRANSLATIONS,
                           dismiss_notification=dismiss_notification,
                           form_create_admin=form_create_admin,
                           form_notice=form_notice)
Exemplo n.º 13
0
def login_password():
    """Authenticate users of the web-UI."""
    if not admin_exists():
        return redirect('/create_admin')
    elif flask_login.current_user.is_authenticated:
        flash(gettext("Cannot access login page if you're already logged in"),
              "error")
        return redirect(url_for('routes_general.home'))

    form_login = forms_authentication.Login()

    # Check if the user is banned from logging in (too many incorrect attempts)
    if banned_from_login():
        flash(
            gettext(
                "Too many failed login attempts. Please wait %(min)s "
                "minutes before attempting to log in again",
                min=int(
                    (LOGIN_BAN_SECONDS - session['ban_time_left']) / 60) + 1),
            "info")
    else:
        if request.method == 'POST':
            username = form_login.username.data.lower()
            user_ip = request.environ.get('HTTP_X_FORWARDED_FOR',
                                          'unknown address')
            user = User.query.filter(func.lower(User.name) == username).first()

            if not user:
                login_log(username, 'NA', user_ip, 'NOUSER')
                failed_login()
            elif form_login.validate_on_submit():
                matched_hash = User().check_password(form_login.password.data,
                                                     user.password_hash)

                # Encode stored password hash if it's a str
                password_hash = user.password_hash
                if isinstance(user.password_hash, str):
                    password_hash = user.password_hash.encode('utf-8')

                if matched_hash == password_hash:
                    user = User.query.filter(User.name == username).first()
                    role_name = Role.query.filter(
                        Role.id == user.role_id).first().name
                    login_log(username, role_name, user_ip, 'LOGIN')

                    # flask-login user
                    login_user = User()
                    login_user.id = user.id
                    remember_me = True if form_login.remember.data else False
                    flask_login.login_user(login_user, remember=remember_me)

                    return redirect(url_for('routes_general.home'))
                else:
                    user = User.query.filter(User.name == username).first()
                    role_name = Role.query.filter(
                        Role.id == user.role_id).first().name
                    login_log(username, role_name, user_ip, 'FAIL')
                    failed_login()
            else:
                login_log(username, 'NA', user_ip, 'FAIL')
                failed_login()

            return redirect('/login')

    return render_template('login_password.html',
                           dict_translation=TRANSLATIONS,
                           form_login=form_login,
                           host=socket.gethostname())
def do_login():
    """Authenticate users of the web-UI"""
    if not admin_exists():
        return redirect('/create_admin')

    elif flask_login.current_user.is_authenticated:
        flash(gettext(u"Cannot access login page if you're already logged in"),
              "error")
        return redirect(url_for('general_routes.home'))

    form = flaskforms.Login()
    form_notice = flaskforms.InstallNotice()

    misc = Misc.query.first()
    dismiss_notification = misc.dismiss_notification
    stats_opt_out = misc.stats_opt_out

    # Check if the user is banned from logging in (too many incorrect attempts)
    if banned_from_login():
        flash(gettext(
            u"Too many failed login attempts. Please wait %(min)s "
            u"minutes before attempting to log in again",
            min=(int(LOGIN_BAN_SECONDS - session['ban_time_left']) / 60) + 1),
                "info")
    else:
        if request.method == 'POST':
            username = form.username.data.lower()
            user_ip = request.environ.get('REMOTE_ADDR', 'unknown address')
            form_name = request.form['form-name']
            if form_name == 'acknowledge':
                try:
                    mod_misc = Misc.query.first()
                    mod_misc.dismiss_notification = 1
                    db.session.commit()
                except Exception as except_msg:
                    flash(gettext(u"Acknowledgement unable to be saved: "
                                  u"%(err)s", err=except_msg), "error")
            elif form_name == 'login' and form.validate_on_submit():
                user = User.query.filter(
                    User.name == username).first()
                if not user:
                    login_log(username, 'NA', user_ip, 'NOUSER')
                    failed_login()
                elif User().check_password(
                        form.password.data,
                        user.password_hash) == user.password_hash:

                    login_log(username, user.roles.name, user_ip, 'LOGIN')

                    # flask-login user
                    login_user = User()
                    login_user.id = user.id
                    remember_me = True if form.remember.data else False
                    flask_login.login_user(login_user, remember=remember_me)

                    return redirect(url_for('general_routes.home'))
                else:
                    login_log(username, user.roles.name, user_ip, 'FAIL')
                    failed_login()
            else:
                login_log(username, 'NA', user_ip, 'FAIL')
                failed_login()

            return redirect('/login')

    return render_template('login.html',
                           form=form,
                           formNotice=form_notice,
                           dismiss_notification=dismiss_notification,
                           stats_opt_out=stats_opt_out)