Beispiel #1
0
 def test_UpdatePassword(self):
     user_db = UserDB()
     u = user_db.add("jontest", "pass", "Jon Q. Testuser")
     passwd = 'A Test Password'
     self.assertFalse(mainCrypt.check_password_hash(u.passhash, passwd))
     user_db.update_password(u, passwd)
     self.assertTrue(mainCrypt.check_password_hash(u.passhash, passwd))
Beispiel #2
0
    def test_DelUser(self):
        userDB = UserDB()
        uid = userDB.add("jontest", "pass", "Jon Q. Testuser").id

        userDB.delete(uid)
        testUser = userDB.find_user_by_id(uid)
        self.assertTrue(testUser == None)
Beispiel #3
0
def _is_admin():
    is_admin = False
    user_db = UserDB()
    if current_user.is_authenticated() and current_user.is_active():
        admin_group = user_db.get_group(mainApp.config['ADMIN_GROUP'])
        is_admin = user_db.in_group(current_user, admin_group)
    return is_admin
Beispiel #4
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)
Beispiel #5
0
def is_admin():
    """
    Test to determine if the user is an admin or not
    """
    is_a = False
    user_db = UserDB()
    if current_user.is_authenticated() and current_user.is_active():
        admin_group = user_db.get_group(mainApp.config['ADMIN_GROUP'])
        is_a = user_db.in_group(current_user, admin_group)
    return is_a
Beispiel #6
0
def logout_user():
    udb = UserDB()
    if current_user.is_authenticated() and current_user.is_active():
        if udb.logout(current_user):
            flash(_('Logged out.'))
            return redirect(request.args.get("next") or url_for("list_entries.show"))

    return render_template('noink_message.html', state=get_state(),
        title=_('Problem logging out'),
        message=_('There was a problem logging you out (were you logged in?)'))
Beispiel #7
0
    def test_AddEntry(self):
        userDB = UserDB()
        entryDB = EntryDB()
        u = userDB.add("jontest", "pass", "Jon Q. Testuser")
        title = 'Little Buttercup'
        entry = 'There once was a man from Nantucket,' + \
                'who kept his wife in a Bucket.' + \
                "Wait... how'd she fit in that bucket anyway?"

        e = entryDB.add(copy.deepcopy(title), entry, u)
        self.assertTrue(e.title == title)
Beispiel #8
0
def _check_username(username):
    """
    Checks that a username is valid and is not already in use. Returns
    the username if valid, or None if it is not.
    """
    checked_name = None
    if username is not None and username != "":
        user_db = UserDB()
        exists = user_db.find_user_by_name(username)
        if exists == []:
            checked_name = username
    return checked_name
Beispiel #9
0
    def get_rolemapping(self, user, group, role):
        """
        Given a user, group and role, will return the rolemap of the three,
        if it exists. Otherwise will return None.

        FIXME - Docstring
        """
        r = self.get_role(role)
        user_db = UserDB()
        u = user_db.get_user(user)
        g = user_db.get_group(group)

        return RoleMapping.query.filter_by(user=u).filter_by(group=g).filter_by(role=r).first()
Beispiel #10
0
def login_page():
    if request.method == "POST" and "username" in request.form:
        username = request.form["username"]
        password = request.form.get("password", None)
        remember = request.form.get('remember', 'no') == "yes"
        udb = UserDB()
        if udb.authenticate(username, password, remember):
            flash(_('%s logged in.' % username))
            return redirect(request.args.get("next") or \
                url_for("list_entries.show"))
        else:
            flash(_('Problem logging in.'), 'error')
    return render_template('login.html', state=get_state(),
        title=_('Login'), submit_button=_('Login'))
Beispiel #11
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()
Beispiel #12
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)
Beispiel #13
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()
Beispiel #14
0
    def test_RmFromGroup(self):
        userDB = UserDB()
        u = userDB.add("jontest", "pass", "Jon Q. Testuser")
        g_foo = userDB.add_group('foo')
        g_bar = userDB.add_group('bar')

        self.assertTrue(userDB.update_primary(u, g_foo))
        userDB.add_to_group(u, g_bar)

        self.assertTrue(userDB.in_group(u, g_bar))

        self.assertTrue(userDB.remove_from_group(u, g_bar))

        self.assertFalse(userDB.in_group(u, g_bar))
Beispiel #15
0
    def get_roles(self, user, group=None):
        """
        Get the roles a given user has. Optionally, limit by group.

        @param user: The user. Can be user object, uid, or string name.
        @param group: Group to limit by. Can be group object, gid, or string
                      name.

        @return A list of role mappings.
        """
        userDB = UserDB()
        u = userDB.get_user(user)
        rm = RoleMapping.query.filter_by(user=u)
        if group is not None:
            g = userDB.get_group(group)
            rm = rm.filter_by(group=g)

        return rm.all()
Beispiel #16
0
    def revoke_role(self, user, group, role):
        """
        Given a user, group and role, revoke the user's rights to that role
        when part of the group.

        @param user: The user. Can be a user object, uid, or string name of
                     the user.
        @param group: The group. Can be a group object, gid, or string name.
        @param role: The role. Can be role object, rid, or string name.
        """
        user_db = UserDB()
        u = user_db.get_user(user)
        g = user_db.get_group(group)
        r = self.get_role(role)
        rmaps = RoleMapping.query.filter_by(user=u).filter_by(group=g).filter_by(role=r).all()

        for rm in rmaps:
            mainDB.session.delete(rm)

        mainDB.session.commit()
Beispiel #17
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)
Beispiel #18
0
    def assign_role(self, user, group, role):
        """
        Given a user, group and role, assign the user as the role when part of
        the group.

        @param user: The user. Can be user object, uid, or string name of the
                     user.
        @param group: The group. Can be group object, gid, or string name.
        @param role: The role. Can be role object, rid, or string name.
        """
        userDB = UserDB()
        u = userDB.get_user(user)
        g = userDB.get_group(group)
        r = self.get_role(role)

        exist = RoleMapping.query.filter_by(user=u).filter_by(group=g).filter_by(role=r).all()

        if exist == []:
            rm = RoleMapping(r, u, g)
            mainDB.session.add(rm)

        mainDB.session.commit()
Beispiel #19
0
 def test_AddToGroup(self):
     user_db = UserDB()
     u = user_db.add("jontest", "pass", "Jon Q. Testuser")
     g = user_db.add_group('test_group')
     gid = g.id
     user_db.add_to_group(u, g)
     groups = set(user_db.get_users_groups(u))
     self.assertTrue(g in groups)
Beispiel #20
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)
Beispiel #21
0
def process_entry_object(parent):
    '''
    Return an entry object. Does not add to db
    '''
    user_db = UserDB()
    entry_db = EntryDB()
    group_used = user_db.get_group(request.form.get('group', None))
    purl = request.form.get('url', None)
    if purl is not None:
        t = entry_db.find_by_URL(purl)
        if len(t) > 0:
            flash(_("'{0}' URL is already in use!".format(purl)))
            purl = None
    return entry_db.create_temp_entry(
        request.form.get('title', ''),
        request.form.get('entry', ''),
        current_user,
        group_used,
        int(request.form.get('weight', 0)),
        purl,
        bool(request.form.get('html', False)),
        parent,
        bool(request.form.get('static', False)))
Beispiel #22
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()
Beispiel #23
0
 def test_AddGroup(self):
     user_db = UserDB()
     g = user_db.add_group('test_group')
     self.assertTrue(g.id > 0)
Beispiel #24
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()
Beispiel #25
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()
Beispiel #26
0
 def test_AddUser(self):
     userDB = UserDB()
     u = userDB.add("jontest", "pass", "Jon Q. Testuser")
     uid = u.id
     self.assertTrue(uid > 0)
Beispiel #27
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()
Beispiel #28
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!'))
Beispiel #29
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()
Beispiel #30
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()