Esempio n. 1
0
def manage_users():
    cd = create_delete('user')
    if cd == 'c':
        username = enter_user()
        users.create(username)
        return f'Created user {username}'
    elif cd == 'd':
        username = choose_user()
        remove_files = True if input(
            f'Remove ALL files of user "{username}"? [YES], [n]o'
        ) == 'YES' else False
        users.delete(username, remove_files)
        return f'Deleted user {username}'
Esempio n. 2
0
def users_api():
    if request.method == "GET":
        return users.get()
    elif request.method == "POST":
        return users.post()
    elif request.method == "PATCH":
        return users.update()
    elif request.method == "DELETE":
        return users.delete()
Esempio n. 3
0
def deleteaccount(id):
    users.delete(id)

    return redirect("/")
Esempio n. 4
0
def remove(email):
  List.getOrCreate('list', namespace='alphas').run('remove', email)
  
  import users
  users.delete(email)
Esempio n. 5
0
def settings():
    if request.method == "POST":
        if request.form.get('action') in ["update", "other_update"]:
            # Update user information. other_update specifies updating another users info and requires admin rights.
            if request.form.get('action') == "other_update":
                if not session['admin']:
                    # Non-admin tried to update another users' info. Log and deny access.
                    session['logger'].write("Non-admin tried: " + request.form.get('action'))
                    return jsonify({
                        'return': False,
                        'details': "Unauthorized Access"
                    })
                # Other user is being updated by admin - Remember subject user id.
                user_id = request.form.get('user_id')
            else:
                # User is updating their own info.
                # If a new password is provided, ensure current password was entered and is correct. Duel password entry is ensured on client side.
                if request.form.get('npassword'):
                    selection = users.getUser("user_id", session["user_id"])
                    if not selection['return'] or not pwd_context.verify(request.form.get("password"), selection['user'][2]):
                        return jsonify({
                            'return': False,
                            'details': "Incorrect current password entered."
                        })

                # Proceed with update request, remember subject (current) user id.
                user_id = session['user_id']

            # Store new password as a hash if provided, otherwise it hash will be stored as an empty string.
            if request.form.get('npassword'):
                newHash = pwd_context.hash(request.form.get('npassword'))
            else:
                newHash = ""

            # This holds the user id to update and everything that can be updated. Empty strings indicate fields that should remain unchanced.
            update_bundle = [
                user_id,
                newHash,
                request.form.get('first'),
                request.form.get('last'),
                request.form.get('email'),
                request.form.get('phone')
            ]

            # Attempt to update though users' update handler.
            result = users.updateUser(update_bundle)

            if result['return'] == True:
                # Update was successful - Log and return.
                update_return = update_session_vars()
                # Check if session vars updated successfully.
                if not update_return['success']:
                    return jsonify({
                        'return': False,
                        'details': "User information updated, but there was an issue reading the updated info."
                    })
                session['logger'].write("Update with info: " + str(update_bundle))
                return jsonify({
                    'return': True,
                    'details': "User information updated."
                })
            else:
                # Update was unsuccessful - Log and return edetails.
                session['logger'].write("Failed to update with info: " + str(update_bundle))
                return jsonify(result)

        # Settings actions below this point require admin rights. Ensure privilege before moving forward.
        if not session['admin']:
            session['logger'].write("Non-admin tried: " + request.form.get('action'))
            return jsonify({
                'return': False,
                'details': "Session by admin required"
            })

        # Returns a table of users or requested users.
        if request.form.get('action') == "get_table":
            # Validate requested table.
            if not request.form.get("table") in ["users", "requests"]:
                return jsonify({
                    'reported': False,
                    'details': "Invalide table"
                })
            # Get and return data.
            return jsonify({
                'reported': True,
                'lines': users.getUsers(group=request.form.get("table"))
            })

        # Returns the current log settings.
        if request.form.get('action') == "get_config":
            return jsonify(get_config('whm.cfg'))

        # Sets log settings
        if request.form.get('action') == "set_config":
            if request.form.get('section') == "log":
                # Load defaults from backup config if defaults are requested, or load settings from the form.
                if int(request.form.get('logs_default_flag')) == 1:
                    settings = get_config('whm.cfg.bak')
                    # Ensure backup config was loaded.
                    if not settings['return']:
                        session['logger'].write(settings['details'])
                        return jsonify(settings)
                else:
                    settings = {
                        'max_log_size': request.form.get('max_size'),
                        'max_log_age_unit': request.form.get('max_age_unit'),
                        'max_log_age_n': request.form.get('max_age_n'),
                        'user_str_len': request.form.get('usr_len'),
                        'source_str_len': request.form.get('src_len')
                    }

                # Ensure max_log_size is within range. Errors may occur outside of this range.
                if settings['max_log_size']:
                    try:
                        x = int(settings['max_log_size'])
                        if not 5000 <= x <= 1000000000:
                            raise Exception()
                    except:
                        return jsonify({
                            'return': False,
                            'details': "Invalid Maximum Log File Size"
                        })

                # Ensure valid age unit.
                if not settings['max_log_age_unit'] in ['minutes', 'hours', 'days', 'weeks']:
                    return jsonify({
                        'return': False,
                        'details': "Invalid Maximum Archive Age Unit"
                    })

                # Ensure age is a non-neg whole number.
                if settings['max_log_age_n']:
                    try:
                        x = int(settings['max_log_age_n'])
                        if not 0 <= x:
                            raise Exception()
                    except:
                        return jsonify({
                            'return': False,
                            'details': "Invalid Maximum Archive Age"
                        })

                # Ensure user_str_len is in acceptable range.
                if settings['user_str_len']:
                    try:
                        x = int(settings['user_str_len'])
                        if not 0 <= x <= 50:
                            raise Exception()
                    except:
                        return jsonify({
                            'return': False,
                            'details': "Invalid User Length"
                        })

                # Ensure source_str_len is in acceptable range.
                if settings['source_str_len']:
                    try:
                        x = int(settings['source_str_len'])
                        if not 0 <= x <= 50:
                            raise Exception()
                    except:
                        return jsonify({
                            'return': False,
                            'details': "Invalid Source Length"
                        })

                # Attempt to write each setting to config.
                try:
                    config = configparser.RawConfigParser()
                    config.read('whm.cfg')
                    for var in ['max_log_size', 'max_log_age_unit', 'max_log_age_n', 'user_str_len', 'source_str_len']:
                        if settings[var]:
                            config.set('logger', var, settings[var])
                    with open('whm.cfg', 'w') as configfile:
                        config.write(configfile)
                except:
                    return jsonify({
                        'return': False,
                        'details': "Failed to write config."
                    })

                # Log and return success.
                session["logger"].write("Log config changed")
                return jsonify({
                    'return': True,
                    'details': "Function ran with no errors."
                })

		    # Sets record settings
            if request.form.get('section') == "record":
                # Load defaults from backup config if defaults are requested, or load settings from the form.
                if int(request.form.get('record_default_flag')) == 1:
                    settings = get_config('whm.cfg.bak')
                    if not settings['return']:
                        # Ensure backup config was loaded.
                        session['logger'].write(settings['details'])
                        return jsonify(settings)
                else:
                    settings = {
                        'hours_age_max': request.form.get('record_hours'),
                        'days_age_max': request.form.get('record_days'),
                        'weeks_age_max': request.form.get('record_weeks')
                    }

                # Ensure all fields are whole numbers between 0 and 500.
                for field in ['hours_age_max', 'days_age_max', 'weeks_age_max']:
                    if settings[field]:
                        try:
                            x = int(settings[field])
                            if not 0 <= x <= 500:
                                raise Exception()
                        except:
                            return jsonify({
                                'return': False,
                                'details': "Values must be whole numbers between 0 and 500."
                            })

                # Attempt to write each setting to config.
                try:
                    config = configparser.RawConfigParser()
                    config.read('whm.cfg')
                    for var in ['hours_age_max', 'days_age_max', 'weeks_age_max']:
                        if settings[var]:
                            config.set('record', var, settings[var])
                    with open('whm.cfg', 'w') as configfile:
                        config.write(configfile)
                    # Load new config settings
                    load_record_conf()
                except:
                    return jsonify({
                        'return': False,
                        'details': "Failed to write config."
                    })

                # Log and return success.
                session["logger"].write("Log config changed")
                return jsonify({
                    'return': True,
                    'details': "Function ran with no errors."
                })

            if request.form.get('section') == "port":
                # Load default from backup config if defaults are requested, or load settings from the form.
                if int(request.form.get('port_default_flag')) == 1:
                    settings = get_config('whm.cfg.bak')
                    if not settings['return']:
                        # Ensure backup config was loaded.
                        session['logger'].write(settings['details'])
                        return jsonify(settings)
                else:
                    settings = {
                        'port_n': request.form.get('port_n')
                    }

                # Ensure port is a positive whole number.
                try:
                    x = int(settings['port_n'])
                    if not 1 <= x:
                        raise Exception()
                except:
                    return jsonify({
                        'return': False,
                        'details': "Port number must be a positive whole number."
                    })

                # Attempt to write port number.
                try:
                    config = configparser.RawConfigParser()
                    config.read('whm.cfg')
                    config.set('general', 'port_n', settings['port_n'])
                    with open('whm.cfg', 'w') as configfile:
                        config.write(configfile)
                except:
                    return jsonify({
                        'return': False,
                        'details': "Failed to write config."
                    })

                # Log and return success.
                session["logger"].write("Log config changed")
                return jsonify({
                    'return': True,
                    'details': "Function ran with no errors."
                })

        # User table actions - Requests can be accepted or declined, and current users can be deleted or have admin rights toggled.
        # Requests are handled by users.py and actions are logged.
        if request.form.get('action') == "accept":
            if not users.accept(request.form.get('request_id')):
                session['logger'].write("Failed to accept user with id: " + request.form.get('request_id'))
                return jsonify({
                    'return': False,
                    'details': "Failed to accept user."
                })

        # User action handling.
        if request.form.get('action') == "decline":
            users.delReq(request.form.get('request_id'))
            session['logger'].write("Deleted request with id: " + request.form.get('request_id'))
        if request.form.get('action') == "delete":
            users.delete(request.form.get('request_id'))
            session['logger'].write("Deleted user with id: " + request.form.get('request_id'))
        if request.form.get('action') == "toggle":
            users.toggleAdmin(request.form.get('request_id'))
            session['logger'].write("Toggles admin rights for user id: " + request.form.get('request_id'))

        # Return with no errors.
        return jsonify({
            'return': True,
            'details': "Success"
        })
    else:
        # GET request, return template.
        return render_template("settings.html")
Esempio n. 6
0
import trucks
import truck_locs
import users

users.delete()
truck_locs.delete()
trucks.delete()
Esempio n. 7
0
async def delete_user(sid, id_str):
    users.delete(id_str)