Exemplo n.º 1
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)
Exemplo n.º 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_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)
Exemplo n.º 3
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
Exemplo n.º 4
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)
Exemplo n.º 5
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()