Exemple #1
0
class SimpleEntries:

    def __init__(self):
        self.testMain = testMain()

        self.userDB = UserDB()
        self.entryDB = EntryDB()
        self.roleDB = RoleDB()

        u = self.userDB.add("criswell", "password", "Sam Hart")
        u1 = self.userDB.add("charles", "password", "Charles Xavier")
        u2 = self.userDB.add("leif", "password", "Lief Ericsson")
        u3 = self.userDB.add("barf", "password", "Barfy Barferson")
        u4 = self.userDB.add("squiddy", "password", "Squidward Tentacles")
        editors = ['charles', 'leif', 'barf', 'squiddy']
        all_groups = ['junkbar', 'dollarbillyall', 'coldnwet']
        for g in all_groups:
            self.userDB.add_group(g)
        role_names = ['tomato', 'spaghetti', 'nuts']
        role_desc = ['Tomato Paste', 'Swirly Cheesy', 'Hardcore Nuts']
        for x in range(len(role_names)):
            self.roleDB.add_role(
                role_names[x],
                role_desc[x])
        parents = []
        for e in entries:
            parent = None
            if randint(0,5) > 3 and len(parents) > 1:
                parent = parents[randint(0,len(parents)-1)]
                print("A parent is {0}".format(parent))
            try:
                entry = self.entryDB.add(e[0], e[1], u, None, e[2], e[3], e[5], parent)
                if e[4]:
                    self.entryDB.add_tag(e[4], entry)

                if randint(0,5) > 2:
                    parents.append(entry)

                if randint(0,5) > 2:
                    for ed in sample(editors, randint(1,len(editors)-1)):
                        self.entryDB.update_editor(ed, entry)
            except:
                print("Dropping an entry due to some entryDB problem (likely duplicate URL")
                print("because of random URL generation- Should be safe to ignore)\n")
                pass # stupid, but for our tests we don't care we just may get duplicate URLs

    def __del__(self):
        del(self.testMain)

    def run(self, debug):
        print("mainApp.jinja_env")
        print("-----------------")
        print("\nmainApp.jinja_loader")
        print("___________________")
        print("\n%s" % mainApp.jinja_loader.searchpath)
        mainApp.run(host="0.0.0.0", debug=debug)
Exemple #2
0
 def test_AssignRole(self):
     user_db = UserDB()
     role_db = RoleDB()
     u = user_db.add("jontest", "pass", "Jon Q. Testuser")
     g = user_db.add_group('test_group')
     user_db.add_to_group(u, g)
     r = role_db.add_role('test_role', 'test role', get_activity_dict(True))
     role_db.assign_role(u, g, r)
     all_roles = set(rm.role for rm in role_db.get_roles(u))
     self.assertTrue(r in all_roles)
Exemple #3
0
def nofilter_getactivities(r):
    """
    Given a role, return the activities that role can do.

    @param r: The role

    @return: A dict containing the activities
    """
    role_db = RoleDB()
    return role_db.get_activities(r)
Exemple #4
0
def static_page():
    """
    Render the administrative static page
    """
    user_db = UserDB()
    role_db = RoleDB()
    event_log = EventLog()
    icebox = Icebox()

    if current_user.is_authenticated() and current_user.is_active():
        is_admin = user_db.in_group(current_user, mainApp.config['ADMIN_GROUP'])
        all_activities = set()
        for m in role_db.get_roles(current_user):
            acts = role_db.get_activities(m.role_id)
            for act in acts:
                if acts[act]:
                    all_activities.add(act)

        can_admin_static = 'make_static' in all_activities
        can_admin_static_now = 'make_static_now' in all_activities

        if is_admin or can_admin_static:
            if request.method == 'POST':
                if 'sched_rebuild' in request.form:
                    event_log.add('rebuild_static', current_user.id)
                    flash(_('Full site rebuild scheduled.'))
                elif 'incr_build' in request.form:
                    icebox.generate_pages()
                    flash(_('New/updated pages generated.'))
                elif 'rebuild_now' in request.form:
                    if can_admin_static_now:
                        icebox.generate_pages(True)
                        flash(_('Full site rebuilt'))
                    else:
                        flash(_('Not authorized for full site rebuild',
                            'error'))
            return render_template('admin_static.html', state=get_state(),
                    can_admin_static=can_admin_static,
                    can_admin_static_now=can_admin_static_now,
                    title=_('Administrate Static Site'),
                    sched_rebuild_text=_('Schedule a full site rebuild'),
                    sched_rebuild_button=_('Schedule'),
                    incr_build_text=_('Perform an incremental build'),
                    incr_build_button=_('Incremental'),
                    rebuild_now_text=_('Perform a full rebuild now'),
                    rebuild_now_button=_('Rebuild'))
        else:
            return _not_auth()
    else:
        return _not_auth()
Exemple #5
0
def admin_new_group():
    """
    Renders the new group page
    """
    user_db = UserDB()
    role_db = RoleDB()

    if current_user.is_authenticated() and current_user.is_active():
        all_activities = set()
        for m in role_db.get_roles(current_user):
            acts = role_db.get_activities(m.role_id)
            for act in acts:
                if acts[act]:
                    all_activities.add(act)

        if 'new_group' in all_activities:
            group = user_db.create_temp_empty_group()
            if 'cancel' in request.form:
                return redirect(url_for('admin_group.admin_group_page'))
            elif 'submit' in request.form:
                gname = request.form.get('group_name', None)
                group.name = gname
                group.description = request.form.get('description', None)
                if gname is not None and gname != '':
                    g = user_db.get_group(gname)
                    if g is None:
                        try:
                            group = user_db.add_group(group.name,
                                   group.description)
                            flash(_('Group "{0}" added.'.format(gname)))
                            return redirect(url_for(
                               'admin_group.admin_group_page'))
                        except DuplicateGroup:
                            flash(_(
                                'Group name "{0}" is already in use!'.format(
                                gname)),
                                'error')
                else:
                    flash(_("Group name cannot be empty!"), 'error')

            return render_template('admin_group.html', group=group,
                    state=get_state(), title=_('Edit Group'),
                    cancel_button=_('Cancel'), submit_button=_('Submit'),
                    can_edit_groups=True)
        else:
            return _not_auth()
    else:
        return _not_auth()
Exemple #6
0
def _role_test(entry, activity):
    """
    Test to determine if an entry can have activity performed against it by
    the current_user

    :param entry: The entry to check against.
    :param activity: The activity to check.

    :returns: True if they can, false if not.
    """
    if current_user.is_authenticated() and current_user.is_active():
        role_db = RoleDB()
        rm = role_db.get_roles(current_user)
        for m in rm:
            if m.group_id == entry.group_id:
                activities = role_db.get_activities(m.role)
                if activities.get(activity, False):
                    return True
    return False
Exemple #7
0
def setup_DB():
    """
    Called when the DB is to be initialized. Should only be called once.
    """
    event_log = EventLog()
    sc = _SiteConfig()
    userDB = UserDB()
    roleDB = RoleDB()
    mainDB.create_all()
    event_log.add('db_setup', -1, True)
    default_group = userDB.add_group(mainApp.config['DEFAULT_GROUP'],
            mainApp.config['DEFAULT_GROUP_DESC'])
    default_acts = get_activity_dict(False)
    default_acts.update(mainApp.config['DEFAULT_ROLE_ACTIVITIES'])

    dummy = roleDB.add_role(
            mainApp.config['DEFAULT_ROLE_NAME'],
            mainApp.config['DEFAULT_ROLE_DESC'],
            default_acts)

    user = userDB.add(mainApp.config['ADMIN_USER'],
        mainApp.config["ADMIN_PASSWD"], mainApp.config['ADMIN_FULLNAME'])
    admin_group = userDB.add_group(mainApp.config['ADMIN_GROUP'],
        mainApp.config['ADMIN_GROUP_DESC'], user.id)
    if not userDB.update_primary(user, admin_group):
        raise SetupError(
            'Could not assign the admin user "{0}" primary group to the ' \
            'admin group "{1}"!'.format(user, admin_group))

    # By default, the admin is part of the top level group as well as default
    dummy = userDB.add_group(mainApp.config['TOP_LEVEL_GROUP'],
        mainApp.config['TOP_LEVEL_GROUP_DESC'], user.id)
    userDB.add_to_group(user, default_group)

    admin_role = get_activity_dict(True)
    role = roleDB.add_role(
            mainApp.config['ADMIN_ROLE_NAME'],
            mainApp.config['ADMIN_ROLE_DESC'],
            admin_role)

    roleDB.assign_role(user, mainApp.config['ADMIN_GROUP'], role)
    roleDB.assign_role(user, mainApp.config['TOP_LEVEL_GROUP'], role)
    roleDB.assign_role(user, mainApp.config['DEFAULT_GROUP'], role)

    sc.add(mainApp.noink_version, mainApp.config['SITE_NAME'],
            mainApp.config['SITE_ADMIN_EMAIL'])

    event_log.add('db_finish', -1, True)
Exemple #8
0
 def test_AssignRole(self):
     user_db = UserDB()
     role_db = RoleDB()
     u = user_db.add("jontest", "pass", "Jon Q. Testuser")
     g = user_db.add_group('test_group')
     user_db.add_to_group(u, g)
     r = role_db.add_role('test_role', 'test role', get_activity_dict(True))
     role_db.assign_role(u, g, r)
     all_roles_1st = set(rm.role for rm in role_db.get_roles(u))
     was_in_before = r in all_roles_1st
     role_db.revoke_role(u, g, r)
     all_roles_2nd = set(rm.role for rm in role_db.get_roles(u))
     not_in_after = r not in all_roles_2nd
     self.assertTrue(was_in_before and not_in_after)
Exemple #9
0
    def add(self, username, password, fullname, bio="", group=None,
            active=False):
        '''
        Adds a user to the database.

        @param username: The username to add, must be unique.
        @param password: The password to use.
        @param fullname: The user's full name
        @param bio: The user's bio (optional)
        @param group: The user's primary group (optional)
        @param active: Whether the user is active or not

        @return The user object for the user crated.
        '''
        try:
            exists = self.find_user_by_name(username)
        except:
            exists = False

        if exists:
            raise DuplicateUser("{0} already exists in database with id '{1}'".
                format(username, str(exists)))
        else:
            from noink.role_db import RoleDB
            role_db = RoleDB()
            passHash = mainCrypt.generate_password_hash(password)
            u = User(username, fullname, bio, passHash)
            if group is None:
                group = self.get_group(mainApp.config['DEFAULT_GROUP'])
            u.primary_group = group
            u.active = active
            mainDB.session.add(u)
            mainDB.session.commit()
            self.eventLog.add('add_user', u.id, True, None, username)
            self.add_to_group(u, group)
            role_db.assign_role(u, group, mainApp.config['DEFAULT_ROLE_NAME'])
            return u
Exemple #10
0
def event_viewer():
    """
    Render the event viewer.
    """
    page_num = int(request.args.get('page', 0))
    per_page = int(request.args.get('per_page', 20))
    user_db = UserDB()
    role_db = RoleDB()
    event_log = EventLog()

    if current_user.is_authenticated() and current_user.is_active():
        is_admin = user_db.in_group(current_user, mainApp.config['ADMIN_GROUP'])
        all_activities = set()
        for m in role_db.get_roles(current_user):
            acts = role_db.get_activities(m.role_id)
            for act in acts:
                if acts[act]:
                    all_activities.add(act)

        can_view_logs = 'view_logs' in all_activities

        if is_admin or can_view_logs:
            events = event_log.find_recent_by_num(per_page, page_num * per_page)
            count = event_log.count()

            total_pages = 0
            if count > per_page:
                total_pages = int(ceil(float(count) / float(per_page)))

            return render_template('admin_events.html', events=events,
                state=get_state(), page_num=page_num, per_page=per_page,
                title=_('Event log'), total_pages=total_pages)
        else:
            return _not_auth()
    else:
        return _not_auth()
Exemple #11
0
def admin_new_role():
    """
    Renders the new role page
    """
    role_db = RoleDB()

    if current_user.is_authenticated() and current_user.is_active():
        all_activities = set()
        for m in role_db.get_roles(current_user):
            acts = role_db.get_activities(m.role_id)
            for act in acts:
                if acts[act]:
                    all_activities.add(act)

        if 'new_role' in all_activities:
            role = role_db.create_temp_empty_role()
            if 'cancel' in request.form:
                return redirect(url_for('admin_role.admin_role_page'))
            elif 'submit' in request.form:
                rname = request.form.get('role_name', None)
                role.name = rname
                role.description = request.form.get('description', None)
                updated_acts = request.form.getlist('activities')
                ract = get_activity_dict(False)
                for a in updated_acts:
                    ract[a] = True

                role = role_db.update_temp_role_activities(role, ract)
                if rname is not None and rname != '':
                    r = role_db.get_role(rname)
                    if r is None:
                        try:
                            role = role_db.add_role(role.name,
                                    role.description, ract)
                            flash(_('Role "{0}" added.'.format(rname)))
                            return redirect(url_for(
                                'admin_role.admin_role_page'))
                        except DuplicateRole:
                            flash(_('Role name "{0}" is already in use!'.format(
                                rname)), 'error')

            return render_template('admin_role.html', role=role,
                state=get_state(), title=_('Edit Role'),
                cancel_button=_('Cancel'), submit_button=_('Submit'),
                can_edit_roles=True, activities=activities)
        else:
            return _not_auth()
    else:
        return _not_auth()
Exemple #12
0
def admin_group_page(gid):
    """
    Renders the group page
    """
    user_db = UserDB()
    role_db = RoleDB()

    if current_user.is_authenticated() and current_user.is_active():
        is_admin = user_db.in_group(current_user, mainApp.config['ADMIN_GROUP'])
        all_activities = set()
        for m in role_db.get_roles(current_user):
            acts = role_db.get_activities(m.role_id)
            for act in acts:
                if acts[act]:
                    all_activities.add(act)

        can_view_groups = 'view_groups' in all_activities
        can_edit_groups = 'edit_group' in all_activities

        if is_admin or can_view_groups:
            if gid is None:
                if request.method == "POST":
                    if 'delete' in request.form:
                        gids = request.form.getlist('select')
                        for gid in gids:
                            try:
                                user_db.delete_group(int(gid))
                                flash(_('Group with ID "{0}" deleted.'.format(
                                    gid)))
                            except GroupNotFound:
                                flash(_('"{0}" group id not found!'.format(
                                    gid)), 'error')
                    elif 'new' in request.form:
                        return redirect(url_for('admin_group.admin_new_group'))
                groups = user_db.get_all_groups()
                return render_template('list_groups.html', groups=groups,
                        state=get_state(), can_view_groups=can_view_groups,
                        can_edit_groups=can_edit_groups, title=_('All Groups'),
                        delete_button=_('Delete'), new_button=_('New'),
                        cancel_button=_('Cancel'),
                        del_title=_('Delete Group(s)'),
                        del_warn=_('Deleting groups is a permanent action. '\
                                'Are you sure?'))
            else:
                if request.method == "POST":
                    if 'cancel' in request.form:
                        return redirect(url_for('admin_group.admin_group_page'))
                    elif 'submit' in request.form:
                        group = user_db.get_group(gid)
                        if group is not None:
                            group.name = request.form.get('group_name',
                                    group.name)
                            group.description = request.form.get('description',
                                    group.description)
                            user_db.update_group(group)

                group = user_db.get_group(gid)

                if group is not None:
                    return render_template('admin_group.html', group=group,
                            state=get_state(), title=_('Edit Group'),
                            cancel_button=_('Cancel'),
                            submit_button=_('Submit'),
                            can_edit_groups=can_edit_groups)
                else:
                    flash(_('Group "{0}" not found!'.format(gid)), 'error')
                    return redirect(url_for("admin_group.admin_group_page"))
        else:
            return _not_auth()
    else:
        return _not_auth()
Exemple #13
0
def _edit_post(eid=None):
    """
    Edit a post
    """
    # FIXME - This method has kind of gotten monsterous. Refactor.
    user_db = UserDB()
    role_db = RoleDB()
    entry_db = EntryDB()

    if current_user.is_authenticated() and current_user.is_active():
        all_groups = set(user_db.get_users_groups(current_user))
        all_roles = role_db.get_roles(current_user)
        role_groups = set(m.group for m in all_roles)
        role_by_groups = dict(((m.group, role_db.get_activities(m.role))
            for m in all_roles))

        # The available groups are ones which they are both a part of AND which
        # they have a role in!
        avail_groups = all_groups & role_groups

        groups = []
        if current_user.primary_group in avail_groups:
            # Make sure primary group is first in the list, if it's there
            #avail_groups.remove(current_user.primary_group)
            groups.append(current_user.primary_group)
        groups.extend(avail_groups)

        parent_group = None
        parent = None
        if 'parent' in request.values:
            parent = entry_db.find_by_id(request.values['parent'])
            parent_group = parent.group

        # If everything else fails, we default to the top level
        if parent_group is None:
            parent_group = user_db.get_group(mainApp.config['TOP_LEVEL_GROUP'])

        if parent_group in avail_groups and parent_group in role_by_groups:
            if role_by_groups[parent_group].get('new_post', False):
                entry = None
                tags = []
                if eid is None:
                    if request.method == "POST":
                        entry = process_entry_object(parent)
                        if "tags" in request.form:
                            tags = [x.strip() for x in
                                    request.form['tags'].split(',') if x != '']
                        if "submit" in request.form:
                            entry_db.add_entry_object(entry)
                            if len(tags) > 0:
                                entry_db.add_tag(tags, entry)
                            return redirect(url_for('node.show_node',
                                num=entry.id))
                else:
                    entry = entry_db.find_by_id(eid)
                    if entry is None:
                        return render_template('noink_message.html',
                            state=get_state(),
                            title=_('Entry not found!'),
                            message=_(
                                'The entry "{0}" was not found!'.format(eid)))
                    if request.method == "POST":
                        entry = update_entry_object(entry)
                        if "tags" in request.form:
                            tags = [x.strip() for x in
                                    request.form['tags'].split(',') if x != '']
                        if "submit" in request.form:
                            entry_db.update_entry(entry)
                            entry_db.update_editor(current_user, entry)
                            if len(tags) > 0:
                                entry_db.add_tag(tags, entry)
                            return redirect(url_for('node.show_node',
                                num=entry.id))
                    else:
                        for tm in entry.tagmap:
                            tags.append(tm.tag.tag)

                return render_template('new_post.html', state=get_state(),
                    groups=groups, entry=entry, tags=tags, is_edit=True,
                    title=_('New Post'), submit_button=_('Submit'),
                    preview_button=_('Preview'))
            else:
                return not_authorized()
        else:
            return not_authorized()

    return render_template('noink_message.html', state=get_state(),
        title=_('Not authorized'),
        message=_('You must be logged in as a user to access this page!'))
Exemple #14
0
 def test_AddRole(self):
     role_db = RoleDB()
     r1 = role_db.add_role("test_role", "A test role", get_activity_dict(True))
     r2 = role_db.get_role("test_role")
     self.assertEqual(r1.id, r2.id)
Exemple #15
0
def list_users():
    """
    Renders the list users page
    """
    page_num = int(request.args.get("page", 0))
    per_page = mainApp.config["NUM_ENTRIES_PER_PAGE"][0]
    user_db = UserDB()
    role_db = RoleDB()

    if current_user.is_authenticated() and current_user.is_active():
        is_admin = user_db.in_group(current_user, mainApp.config["ADMIN_GROUP"])
        all_activities = set()
        for m in role_db.get_roles(current_user):
            acts = role_db.get_activities(m.role_id)
            for act in acts:
                if acts[act]:
                    all_activities.add(act)

        can_edit_users = "edit_user" in all_activities

        if is_admin or "view_users" in all_activities:
            if request.method == "POST":
                if "new" in request.form:
                    return redirect(url_for("admin_user.new_user"))
                elif "delete" in request.form:
                    uids = request.form.getlist("select")
                    for uid in uids:
                        try:
                            user_db.delete(int(uid))
                            flash(_('User with ID "{0}" deleted.'.format(uid)))
                        except UserNotFound:
                            flash(_('"{0}" user id not found!'.format(uid)), "error")
                elif "update" in request.form:
                    uids = {int(i): True for i in request.form.getlist("active")}
                    if len(uids) > 0:
                        users = user_db.get_all_users()
                        for u in users:
                            if u.id in uids:
                                u.active = True
                            else:
                                u.active = False
                            user_db.update_user(u)
                # import ipdb; ipdb.set_trace()
            users = user_db.get_all_users()
            total_pages = 0
            if len(users) > per_page:
                total_pages = int(ceil(float(len(users)) / float(per_page)))

            return render_template(
                "list_users.html",
                users=users,
                state=get_state(),
                page_num=page_num,
                total_pages=total_pages,
                can_edit_users=can_edit_users,
                is_admin=is_admin,
                title=_("Users"),
                delete_button=_("Delete"),
                update_button=_("Update"),
                new_button=_("New User"),
                del_title=_("Delete User(s)"),
                cancel_button=_("Cancel"),
                del_warn=_("Deleting users is a permanent action. " "Are you sure?"),
            )
        else:
            return _not_auth()
    else:
        return _not_auth()
Exemple #16
0
def new_user():
    """
    Dialog for new user.
    """
    user_db = UserDB()
    role_db = RoleDB()

    if current_user.is_authenticated() and current_user.is_active():

        is_admin = user_db.in_group(current_user, mainApp.config["ADMIN_GROUP"])

        all_activities = set()
        for m in role_db.get_roles(current_user):
            acts = role_db.get_activities(m.role_id)
            for act in acts:
                if acts[act]:
                    all_activities.add(act)

        if "new_user" in all_activities:
            user = user_db.create_temp_empty_user()
            groups = user_db.get_all_groups()

            if "cancel" in request.form:
                return redirect(request.args.get("next") or url_for("admin.admin_page"))
            elif "update" in request.form:
                password = _check_password(request.form.get("password", None), request.form.get("pcheck", None))
                user.name = _check_username(request.form.get("name", None))
                user.fullname = request.form.get("fullname", None)
                user.bio = request.form.get("bio", None)
                g = user_db.get_group(request.form.get("primary_group", None))
                user.primary_group_id = g.id
                user.active = request.form.get("active", None) == "on"
                # Validation
                if user.name is not None:
                    if password is not None:
                        if g is not None:
                            u = user_db.add(user.name, password, user.fullname, user.bio, g, user.active)
                            flash(_('User "{0}" added.'.format(u.name)))
                            return redirect(url_for("admin_user.admin_user_page", uid=u.id))
                        else:
                            flash(_("Invalid group"))
                    else:
                        flash(_("Passwords do not match!"))
                else:
                    flash(_("Username invalid"))

            return render_template(
                "admin_new_user.html",
                state=get_state(),
                user=user,
                groups=groups,
                title=_("Add new user"),
                can_edit_users=True,
                is_admin=is_admin,
                submit_button=_("Add"),
                cancel_button=_("Cancel"),
            )
        else:
            return _not_auth()

    return _not_auth()
Exemple #17
0
def admin_user_page(uid):
    """
    Renders the user admin page
    """
    user_db = UserDB()
    role_db = RoleDB()

    if current_user.is_authenticated() and current_user.is_active():
        # Gather permissions for currently logged in user
        # cur_all_groups = set(user_db.get_users_groups(current_user))
        cur_rolemap = role_db.get_roles(current_user)
        admin_group = user_db.get_group(mainApp.config["ADMIN_GROUP"])
        is_admin = user_db.in_group(current_user, admin_group)
        gs = set(user_db.get_all_groups())

        avail_roles = role_db.get_all_roles()
        avail_roles_by_group = dict()
        for g in gs:
            avail_roles_by_group[g.id] = list(avail_roles)

        cur_roles_by_group = _get_roles_by_group(cur_rolemap, avail_roles_by_group)

        user = None
        group = []
        if uid is None:
            uid = current_user.id
            # We do this because ptherwise we get a proxy to the object
            user = user_db.get_user(current_user.id)
        else:
            user = user_db.get_user(uid)

        if user is None:
            return render_template(
                "noink_message.html",
                state=get_state(),
                title=_("User not found!"),
                message=_('User with ID "{0}" was not found!'.format(uid)),
            )
        else:
            group = user_db.get_users_groups(user)

        all_groups = set(user_db.get_users_groups(user))
        rolemap = role_db.get_roles(user)

        avail_groups = list(gs - all_groups)

        user_roles = set()
        for m in rolemap:
            user_roles.add(m.role)

        roles_by_group = _get_roles_by_group(rolemap, avail_roles_by_group)

        #
        # DETERMINE PERMISSIONS MORE SPECIFICALLY
        #
        can_edit_users = False
        if admin_group.id in cur_roles_by_group:
            for rm in cur_roles_by_group[admin_group.id]:
                acts = role_db.get_activities(rm.role)
                can_edit_users = acts.get("edit_user")

        if is_admin or uid == current_user.id:
            if request.method == "POST":
                if "form_id" in request.form:
                    if request.form["form_id"] == "general":
                        #
                        # PASSWORD UPDATE
                        #
                        if request.form.get("password", "") != "":
                            password = _check_password(
                                request.form.get("password", None), request.form.get("pcheck", None)
                            )
                            if password != "" and password is not None:
                                user_db.update_password(user, password)
                                flash(_("Updated password"))
                            else:
                                flash(_("Passwords do not match!"))
                        #
                        # NAME UPDATE
                        #
                        if request.form.get("name", user.name) != user.name:
                            new_name = _check_username(request.form.get("name", user.name))
                            if new_name != user.name and new_name is not None:
                                user.name = new_name
                                flash(_("User name updated"))
                            else:
                                flash(_('"{0}" user already exists!'.format(new_name)), "error")
                        #
                        # FULLNAME & BIO UPDATE
                        #
                        user.fullname = request.form.get("fullname", user.fullname)
                        user.bio = request.form.get("bio", user.bio)
                        #
                        # PRIMARY GROUP
                        #
                        primary_group = request.form.get("primary_group", None)
                        if primary_group is not None and primary_group != user.primary_group.name:
                            if user_db.update_primary(user, primary_group):
                                flash(_("Updated primary group"))
                            else:
                                flash(_("Failed to update primary group"), "error")
                        #
                        # ACTIVE
                        #
                        active = request.form.get("active", None) == "on"
                        if isinstance(active, bool):
                            if active != user.active:
                                user.active = active
                                flash(_("User active setting changed"))
                        #
                        # UPDATE DATABASE
                        #
                        user_db.update_user(user)
                    elif request.form["form_id"] == "groups":
                        #
                        # UPDATE GROUP MEMBERSHIPS
                        #
                        if "delete" in request.form:
                            rm_g = user_db.get_group(int(request.form["delete"]))
                            if isinstance(rm_g, Group):
                                if user_db.remove_from_group(user, rm_g):
                                    flash(_('User removed from group "{0}".'.format(rm_g.name)))
                                    group = user_db.get_users_groups(user)
                                    all_groups = set(group)
                                    avail_groups = list(gs - all_groups)
                                else:
                                    print("HERE")
                                    flash(
                                        _(
                                            'Unable to remove user "{0}" from'
                                            ' group "{1}".'.format(user.name, rm_g.name)
                                        )
                                    )
                            else:
                                flash(
                                    _(
                                        'Unable to remove user "{0}" from'
                                        'group "{1}".'.format(user.name, request.form["delete"])
                                    )
                                )
                        elif "add" in request.form:
                            add_g = user_db.get_group(request.form.get("add_group", None))
                            if isinstance(add_g, Group):
                                user_db.add_to_group(user, add_g)
                                group = user_db.get_users_groups(user)
                                all_groups = set(group)
                                avail_groups = list(gs - all_groups)
                                if add_g in group:
                                    flash(_('Added user to group "{0}".'.format(add_g.name)))
                                else:
                                    flash(
                                        _('Problem adding user "{0} to ' 'group "{1}"!'.format(user.name, add_g.name)),
                                        "error",
                                    )
                            else:
                                flash(_('Unable to find group "{0}"!'.format(request.form["add"])), "error")
                    elif request.form["form_id"] == "roles":
                        #
                        # UPDATE ROLE MEMBERSHIP
                        #
                        if "delete" in request.form:
                            rm_r = role_db.get_role(int(request.form["delete"]))
                            g = user_db.get_group(int(request.form.get("group", -1)))
                            if isinstance(rm_r, Role) and isinstance(g, Group):
                                rolemap = role_db.get_rolemapping(user, g, rm_r)
                                if rolemap is not None:
                                    role_db.revoke_role(user, g, rm_r)
                                    roles_by_group[g.id].remove(rolemap)
                                    avail_roles_by_group[g.id].append(rm_r)
                                    flash(_('Role "{0}" revoked.'.format(rm_r.name)))
                                else:
                                    flash(_("Role not assigned to user."), "error")
                            else:
                                flash(_("Problem finding role or group.", "error"))
                        elif "add" in request.form:
                            g = user_db.get_group(int(request.form.get("group", -1)))
                            r = role_db.get_role(request.form.get("add_role", None))
                            if isinstance(r, Role) and isinstance(g, Group):
                                role_db.assign_role(user, g, r)
                                rolemap = role_db.get_rolemapping(user, g, r)
                                if r in avail_roles_by_group[g.id]:
                                    avail_roles_by_group[g.id].remove(r)
                                if g.id not in roles_by_group:
                                    roles_by_group[g.id] = []
                                if rolemap not in roles_by_group[g.id]:
                                    roles_by_group[g.id].append(rolemap)
                                flash(
                                    _(
                                        'Role "{0}" assigned for user "{1}"'
                                        ' with group "{2}".'.format(r.name, user.name, g.name)
                                    )
                                )
                            else:
                                flash(_("Problem finding role or group.", "error"))
                    else:
                        return render_template(
                            "noink_message.html",
                            state=get_state(),
                            title=_("Form error"),
                            message=_(
                                "There was a problem identifying form "
                                "elements. If this problem persists, contact"
                                " your site administrator"
                            ),
                        )
            # render the admin user page for uid user
            return render_template(
                "admin_user.html",
                state=get_state(),
                user=user,
                groups=group,
                avail_groups=avail_groups,
                is_admin=is_admin,
                role_map=rolemap,
                avail_roles=avail_roles,
                roles_by_group=roles_by_group,
                title=_("User Account"),
                avail_roles_by_group=avail_roles_by_group,
                can_edit_users=can_edit_users,
                submit_button=_("Update"),
            )

    return _not_auth()
Exemple #18
0
def admin_role_page(rid):
    """
    Renders the role admin page
    """
    user_db = UserDB()
    role_db = RoleDB()

    if current_user.is_authenticated() and current_user.is_active():
        is_admin = user_db.in_group(current_user, mainApp.config['ADMIN_GROUP'])
        all_activities = set()
        for m in role_db.get_roles(current_user):
            acts = role_db.get_activities(m.role_id)
            for act in acts:
                if acts[act]:
                    all_activities.add(act)

        can_view_roles = 'view_roles' in all_activities
        can_edit_roles = 'edit_roles' in all_activities

        if is_admin or can_view_roles:
            if rid is None:
                if request.method == 'POST':
                    if 'delete' in request.form:
                        rids = request.form.getlist('select')
                        for rid in rids:
                            try:
                                role_db.delete_role(int(rid))
                                flash(_('Role with ID "{0}" deleted'.format(
                                    rid)))
                            except RoleNotFound:
                                flash(_('"{0}" role id not found!'.format(
                                    rid)), 'error')
                    elif 'new' in request.form:
                        return redirect(url_for('admin_role.admin_new_role'))
                roles = role_db.get_all_roles()
                return render_template('list_roles.html', roles=roles,
                        state=get_state(), can_view_roles=can_view_roles,
                        can_edit_roles=can_edit_roles, title=_('All Roles'),
                        delete_button=_('Delete'), new_button=_('New'),
                        cancel_button=_('Cancel'), activities=activities,
                        del_title=_('Delete Roles(s)'),
                        del_warn=_('Deleting roles is a permanent action. '\
                                'Are you sure?'))
            else:
                if request.method == "POST":
                    if 'cancel' in request.form:
                        return redirect(url_for('admin_role.admin_role_page'))
                    elif 'submit' in request.form:
                        role = role_db.get_role(rid)
                        if role is not None:
                            role.name = request.form.get('role_name',
                                    role.name)
                            role.description = request.form.get('description',
                                    role.description)
                            updated_acts = request.form.getlist('activities')
                            ract = get_activity_dict(False)
                            for a in updated_acts:
                                ract[a] = True
                            role = role_db.update_temp_role_activities(
                                    role, ract)
                            role_db.update_role(role)
                            return redirect(url_for(
                                'admin_role.admin_role_page'))

                role = role_db.get_role(rid)
                if role is not None:
                    return render_template('admin_role.html', role=role,
                        state=get_state(), title=_('Edit Role'),
                        cancel_button=_('Cancel'), submit_button=_('Submit'),
                        can_edit_roles=True, activities=activities)
        else:
            return _not_auth()
    else:
        return _not_auth()
Exemple #19
0
def admin_page():
    """
    Renders the admin page
    """
    user_db = UserDB()
    role_db = RoleDB()

    if current_user.is_authenticated() and current_user.is_active():
        links = OrderedDict()

        is_admin = user_db.in_group(current_user, mainApp.config['ADMIN_GROUP'])

        roles_by_group = {}
        all_roles = set()
        all_activities = set()
        for m in role_db.get_roles(current_user):
            if m.group_id not in roles_by_group:
                roles_by_group[m.group_id] = set()
            roles_by_group[m.group_id].add(m.role_id)
            all_roles.add(m.role_id)
            acts = role_db.get_activities(m.role_id)
            for act in acts:
                if acts[act]:
                    all_activities.add(act)

        personal_and_group = _('Personal and Group Settings')
        links[personal_and_group] = []
        #
        # Personal User and Group items
        #
        if 'edit_self' in all_activities:
            links[personal_and_group].append({
                    'url' : url_for("admin_user.admin_user_page"),
                    'text' : _('My User Settings'),
                    'desc' : _('Adjust your personal user settings.')
                })
        if 'new_user' in all_activities:
            links[personal_and_group].append({
                    'url' : url_for("admin_user.new_user"),
                    'text' : _('Create New User'),
                    'desc' : _('Create a new user.')
                })
        if 'view_users' in all_activities:
            links[personal_and_group].append({
                    'url' : url_for("admin_user.list_users"),
                    'text' : _('List All Users'),
                    'desc' : _('View all users and administrate them')
                })
        if 'view_groups' in all_activities:
            links[personal_and_group].append({
                    'url' : url_for("admin_group.admin_group_page"),
                    'text' : _('Edit Groups'),
                    'desc' : _('View and edit all groups')
                })
        if 'view_roles' in all_activities:
            links[personal_and_group].append({
                    'url' : url_for("admin_role.admin_role_page"),
                    'text' : _('Edit roles'),
                    'desc' : _('View and edit all roles')
                })

        entries = _('Entries')
        links[entries] = []
        #
        # Entries
        #
        if 'new_post' in all_activities:
            links[entries].append({
                    'url' : url_for("post.new_post"),
                    'text' : _('New entry'),
                    'desc' : _('Create a new entry')
                })

        sysadmin = _('System Administrative')
        links[sysadmin] = []
        #
        # System
        #
        if 'view_log' in all_activities:
            links[sysadmin].append({
                    'url' : url_for("admin_events.event_viewer"),
                    'text' : _('View log'),
                    'desc' : _('View the events log')
                })
        if 'make_static' in all_activities:
            links[sysadmin].append({
                    'url' : url_for("admin_static.static_page"),
                    'text' : _('Generate static site'),
                    'desc' : _('Generate the static site')
                })

        return render_template('admin.html', state=get_state(), links=links,
                is_admin=is_admin, title=_('Admin'))

    return render_template('noink_message.html', state=get_state(),
        title=_('Not authorized'),
        message=_('You must be logged in as a user to access this page!'))