예제 #1
0
def load_roles():

    role = Role()
    role.name = "Client"
    role.save()

    print("Roles loaded")
예제 #2
0
def init_db():
    # import all modules here that might define models so that
    # they will be registered properly on the metadata.  Otherwise
    # you will have to import them first before calling init_db()
    from models import Department, Employee, Role
    for model in [Department, Employee, Role]:
        if model.exists():
            model.delete_table()
        model.create_table(read_capacity_units=1, write_capacity_units=1, wait=True)

    # Create the fixtures
    engineering = Department(id=str(uuid4()), name='Engineering')
    engineering.save()
    hr = Department(id=str(uuid4()), name='Human Resources')
    hr.save()

    manager = Role(id=str(uuid4()), name='manager')
    manager.save()

    engineer = Role(id=str(uuid4()), name='engineer')
    engineer.save()

    peter = Employee(id=str(uuid4()), name='Peter', department=engineering, role=engineer)
    peter.save()

    roy = Employee(id=str(uuid4()), name='Roy', department=engineering, role=engineer)
    roy.save()

    tracy = Employee(id=str(uuid4()), name='Tracy', department=hr, role=manager)
    tracy.save()
예제 #3
0
 def create(self, validated_data):
     slug = validated_data['name'].lower().replace('-','_').strip()
     slug = slug.replace(' ','_')
     new_permission = Role(name=validated_data['name'],slug = slug)
     new_permission.save()
     # add permission
     return new_permission
예제 #4
0
def init_db():
    # Create the fixtures
    engineering = Department(name='Engineering')
    engineering.save()

    hr = Department(name='Human Resources')
    hr.save()

    manager = Role(name='manager')
    manager.save()

    engineer = Role(name='engineer')
    engineer.save()

    peter = Person(first_name='Peter',
                   last_name='Parker',
                   department=engineering,
                   role=engineer)
    peter.save()

    roy = Person(first_name='Roy',
                 last_name='Royce',
                 department=engineering,
                 role=engineer)
    roy.save()

    tracy = Person(first_name='Tracy',
                   last_name='Monita',
                   department=hr,
                   role=manager)
    tracy.save()
예제 #5
0
파일: role.py 프로젝트: Chauhandeep/rbac
    def save(self, data: Dict):
        self.validate(data)

        try:
            role = Role(data)
            role.save()
        except ValueError as err:
            raise ValidationError(message=str(err))
예제 #6
0
def import_roles(role_dict):
    """Add any missing roles to django db"""
    for role in role_dict:
        try:
            update_role(role, role_dict[role])
        except:
            new_role = Role(role_name=role)
            new_role.save()
            update_role(role, role_dict[role])
예제 #7
0
def create_role():
    name = request.json.get("name", None)

    role = Role()
    role.name = request.json.get("name", "")

    role.save()

    return jsonify({"success": "Register Successfully"}), 200
예제 #8
0
def import_roles(role_dict):
    """Add any missing roles to django db"""
    for role in role_dict:
        try:
            update_role(role, role_dict[role])
        except:
            new_role = Role(role_name=role)
            new_role.save()
            update_role(role, role_dict[role])
예제 #9
0
    async def get_role(self, ctx, *, role_name):
        """
        Gives the user the requested custom role if not locked..
        """

        found_role = Role.where('name', role_name)\
            .where('guild_id', ctx.guild.id).first()
        if found_role:
            if found_role.is_locked:
                await ctx.send("That custom role is currently locked and "
                               "cannot assigned, if you believe this is an "
                               "error then please contact an Admin")
                return
            discord_guild = self.bot.get_guild(found_role.guild_id)
            discord_role = discord_guild.get_role(found_role.role_id)
            if discord_role is None:
                await ctx.send("That custom role appears to be broken, "
                               "please contact an admin")
                return
            await ctx.author.add_roles(discord_role)
            await ctx.send("You have been given the custom role "
                           f"`{role_name}`")
            return

        for role in ctx.guild.roles:
            if lev.distance(role_name.lower(), role.name.lower()) <= 1:
                await ctx.send("That custom role does not exist but cannot be "
                               "created as it's name is too similar to the "
                               f"pre-existing role `{role.name}`")
                return

        result, _ = await ut.get_confirmation(
            ctx.channel, ctx.author, self.bot,
            "It looks like that custom role doesn't exist, "
            "would you like to create it?")

        if result:
            role = Role()

            role.name = role_name

            role.guild_id = ctx.guild.id
            role.created_by = ctx.author.id

            discord_role = await ctx.guild.create_role(
                name=role_name,
                mentionable=True,
                colour=Colour(random.choice(ROLE_COLOURS)),
                reason="Auto-Generated")

            role.role_id = discord_role.id

            role.save()

            await ctx.author.add_roles(discord_role)
            await ctx.send(f"You have been given the role {role_name}")
예제 #10
0
def create_roles():
    print("create_roles")
    now = datetime.datetime.now()
    if not Role.query.get(1):
        role = Role(id=1, name="Admin", created=now, last_update=now)
        role.save()
    if not Role.query.get(2):
        role = Role(id=2, name="User", created=now, last_update=now)
        role.save()
    DBManager.commitSession()
    return
예제 #11
0
def role_add():
    j = request.get_json()
    log('role-add json', type(j), j)
    r = Role(j)
    log('new role: ', r)
    r.save()
    responseData = {
        'role_name': r.name,
        'role_id': r.id,
    }
    return json.dumps(responseData, indent=2)
예제 #12
0
파일: roles.py 프로젝트: helscn/flask-vue
 def post(self):
     roleParse = reqparse.RequestParser()
     roleParse.add_argument('name', type=str)
     args = roleParse.parse_args()
     role_name = args.get('name')
     if not role_name:
         abort(400, error='Need to provide rolename.')
     role = Role.query.filter_by(name=role_name).first()
     if role:
         abort(406, error='The rolename already exists.')
     role = Role(name=role_name)
     role.save()
     return {'success': True}, 201
예제 #13
0
def update_role(role, membership_check):
    """Make sure role membership in db is set to val from csv col 2"""
    role_check = Role.objects.get(role_name=role)
    if role_check.membership != membership_check:
        try:
            new_membership = Role.objects.get(role_name=membership_check)
            role_check.membership = new_membership
            role_check.save()
        except:
            new_role = Role(role_name=membership_check)
            new_role.save()
            new_membership = new_role
            role_check.membership = new_membership
            role_check.save()
예제 #14
0
def update_role(role, membership_check):
    """Make sure role membership in db is set to val from csv col 2"""
    role_check = Role.objects.get(role_name=role)
    if role_check.membership != membership_check:
        try:
            new_membership = Role.objects.get(role_name=membership_check)
            role_check.membership = new_membership
            role_check.save()
        except:
            new_role = Role(role_name=membership_check)
            new_role.save()
            new_membership = new_role
            role_check.membership = new_membership
            role_check.save()
예제 #15
0
파일: app.py 프로젝트: eason-lee/Forum-Gua
def role_add():
    user = current_user()
    is_admin = is_administrator(user)
    log('Is admin?', is_admin)
    if is_admin:
        j = request.json
        log('role-add json', type(j), j)
        r = Role(j)
        log('new role: ', r)
        r.save()
        responseData = {
            'role_name': r.name,
            'role_id': r.id,
        }
        return json.dumps(responseData, indent=2)
    else:
        abort(401)
예제 #16
0
파일: views.py 프로젝트: cash2one/tstpthon
def add_role(request):
    c = {}
    c.update(csrf(request))
    if request.method == 'POST':
        name = request.POST["name"]
        if name == "":
            messages.success(request, "please input role name")
        else:
            try:
                r = Role.objects.get(name=name)
                messages.warning(request, "role name is exist")
            except ObjectDoesNotExist:
                r = Role(name=name)
                r.permission = ",".join(request.POST.getlist("permission"))
                r.save()
                return redirect("role.list")
            c['r'] = r
    return render_to_response("adminuser/add_role.html", c, context_instance=RequestContext(request))
예제 #17
0
def init_db():
    # Create the fixtures
    engineering = Department(name='Engineering')
    engineering.save()

    hr = Department(name='Human Resources')
    hr.save()

    manager = Role(name='manager')
    manager.save()

    engineer = Role(name='engineer')
    engineer.save()

    debug = Task(name='Debug')
    test = Task(name='Test')

    tracy = Employee(
        name='Tracy',
        department=hr,
        roles=[engineer, manager],
        tasks=[]
    )
    tracy.save()

    peter = Employee(
        name='Peter',
        department=engineering,
        leader=tracy,
        roles=[engineer],
        tasks=[debug, test]
    )
    peter.save()

    roy = Employee(
        name='Roy',
        department=engineering,
        leader=tracy,
        roles=[engineer],
        tasks=[debug]
    )
    roy.save()
예제 #18
0
    def exitRolefragment(self, ctx):
        role = Role()
        role.source = self.context[-1]
        role.description = self.stack.pop()
        role.contact = self.stack.pop()
        status = self.stack.pop()
        if status == 'active' :
            role.status = Role.ACTIVE
        elif status == 'disabled' :
            role.status = Role.DISABLED
        else :
            role.status = Role.WORKING
        role.save() 

        # Now that the role exists, we can create the other rows
        # which have FK constraints 
        for row in self.rows :
            row.save()

        self.rows = []
예제 #19
0
    def exitRolefragment(self, ctx):
        role = Role()
        role.source = self.context[-1]
        role.description = self.stack.pop()
        role.contact = self.stack.pop()
        status = self.stack.pop()
        if status == 'active':
            role.status = Role.ACTIVE
        elif status == 'disabled':
            role.status = Role.DISABLED
        else:
            role.status = Role.WORKING
        role.save()

        # Now that the role exists, we can create the other rows
        # which have FK constraints
        for row in self.rows:
            row.save()

        self.rows = []
예제 #20
0
def init_db():
    # Create the fixtures
    engineering = Department(name='Engineering')
    engineering.save()

    hr = Department(name='Human Resources')
    hr.save()

    manager = Role(name='manager')
    manager.save()

    engineer = Role(name='engineer')
    engineer.save()

    peter = Employee(name='Peter', department=engineering, role=engineer)
    peter.save()

    roy = Employee(name='Roy', department=engineering, role=engineer)
    roy.save()

    tracy = Employee(name='Tracy', department=hr, role=manager)
    tracy.save()
예제 #21
0
def init_db():
    # Create the fixtures
    engineering = Department(name="Engineering")
    engineering.save()

    hr = Department(name="Human Resources")
    hr.save()

    manager = Role(name="manager")
    manager.save()

    engineer = Role(name="engineer")
    engineer.save()

    debug = Task(name="Debug")
    test = Task(name="Test")

    tracy = Employee(name="Tracy", department=hr, roles=[engineer, manager], tasks=[])
    tracy.save()

    peter = Employee(
        name="Peter",
        department=engineering,
        leader=tracy,
        roles=[engineer],
        tasks=[debug, test],
    )
    peter.save()

    roy = Employee(
        name="Roy",
        department=engineering,
        leader=tracy,
        roles=[engineer],
        tasks=[debug],
    )
    roy.save()
예제 #22
0
def create_roles():
    if not Role.query.get(Role.ADMIN_ROLE_ID):
        role = Role(id=Role.ADMIN_ROLE_ID, name="Admin")
        role.save()
    if not Role.query.get(Role.MANAGER_ROLE_ID):
        role = Role(id=Role.MANAGER_ROLE_ID, name="Manager")
        role.save()
    if not Role.query.get(Role.HELPER_ROLE_ID):
        role = Role(id=Role.HELPER_ROLE_ID, name="Helper")
        role.save()
    DBManager.commitSession()
    return
예제 #23
0
from models import Role, database

r = Role()
r.name = 'conversationee'
r.description = 'day-to-day system user'

with database.transaction():
	r.save()
예제 #24
0
def _save_role(cd):
    role = Role()
    role.id = cd['id'] or None
    role.name = cd['name']
    role.save()
    return role
예제 #25
0
파일: views.py 프로젝트: ricree/Mafiastats
def edit(request, game_id):
    game = get_object_or_404(Game, pk=game_id)
    if request.method == "POST":
        form = AddGameForm(request.POST)
        teamForm = TeamFormSetEdit(request.POST, prefix="teamForm")
        roleForm = RoleFormSet(request.POST, prefix="roleForm")
        if form.is_valid() and teamForm.is_valid() and roleForm.is_valid():
            game = Game.objects.get(pk=form.cleaned_data["game_id"])
            game.title = form.cleaned_data["title"]
            game.url = form.cleaned_data["url"]
            game.gameType = form.cleaned_data["type"]
            moderator, created = Player.objects.get_or_create(
                name=form.cleaned_data["moderator"],
                site=game.site,
                defaults={"firstGame": game, "lastGame": game, "score": 0, "played": 0},
            )
            if created:
                moderator.save()
            game.moderator = moderator
            game.start_date = form.cleaned_data["start_date"]
            game.end_date = form.cleaned_data["end_date"]
            game.save()
            game.livedToEnd.clear()
            for pName in form.cleaned_data["livedToEnd"]:
                player, created = Player.objects.get_or_create(
                    name=pName, site=game.site, defaults={"firstGame": game, "lastGame": game}
                )
                if created:
                    player.save()
                game.livedToEnd.add(player)
            for t in Team.objects.filter(game=game):
                t.delete()
            for tForm in teamForm.forms:
                if ("title" in tForm.cleaned_data) and (tForm.cleaned_data["title"] != ""):
                    title = tForm.cleaned_data["title"]
                else:
                    title = tForm.cleaned_data["type"].title()
                team = Team(
                    game=game,
                    title=title,
                    category=Category.objects.get(title=tForm.cleaned_data["type"]),
                    site=game.site,
                    won=tForm.cleaned_data["won"],
                )
                team.save()
                for pName in tForm.cleaned_data["players"]:
                    p, created = Player.objects.get_or_create(
                        name=pName,
                        site=game.site,
                        defaults={"firstGame": game, "lastGame": game, "score": 0, "played": 0},
                    )
                    p.updateDates(game)
                    p.save()
                    team.players.add(p)
                team.save()
            for role in Role.objects.filter(game=game):
                role.delete()
            for rForm in roleForm.forms:
                if rForm.has_changed():
                    p, created = Player.objects.get_or_create(
                        name=rForm.cleaned_data["player"],
                        site=game.site,
                        defaults={"firstGame": game, "lastGame": game, "score": 0, "played": 0},
                    )
                    role = Role(game=game, player=p, text=rForm.cleaned_data["text"], title=rForm.cleaned_data["title"])
                    role.save()
            game.save()
            return HttpResponseRedirect(reverse("mafiastats_game", args=[game.id]))
    else:
        game = get_object_or_404(Game, pk=game_id)
        teams = Team.objects.filter(game=game)
        dateFormat = "%m/%d/%Y"
        gameData = {
            "title": game.title,
            "url": game.url,
            "livedToEnd": [p.name for p in game.livedToEnd.all()],
            "moderator": game.moderator.name,
            "start_date": game.start_date.strftime(dateFormat),
            "end_date": game.end_date.strftime(dateFormat),
            "type": game.gameType,
            "game_id": game.id,
        }
        teamData = [
            {
                "title": team.title,
                "won": team.won,
                "type": team.category.title,
                "team_id": team.id,
                "players": [p.name for p in team.players.all()],
            }
            for team in teams
        ]
        roleData = [
            {"title": role.title, "player": role.player.name, "text": role.text}
            for role in Role.objects.filter(game=game)
        ]
        form = AddGameForm(gameData)
        teamForm = TeamFormSetEdit(initial=teamData, prefix="teamForm")
        roleForm = RoleFormSet(initial=roleData, prefix="roleForm")
    left_attrs = [("Team Name:", "title"), ("Team Type:", "type"), ("Won:", "won")]
    for tform in teamForm.forms:
        tform.left_attrs = [(label, tform[property], property) for label, property in left_attrs]
    sheets = (form.media + teamForm.media + roleForm.media).render_css()
    bodyscripts = (form.media + teamForm.media + roleForm.media).render_js()
    return render_to_response(
        "addGame.html",
        {
            "game_form": form,
            "teamFormset": teamForm,
            "roleFormset": roleForm,
            "site": game.site,
            "sheets": sheets,
            "id": game.site.id,
            "bodyscripts": bodyscripts,
            "submit_link": reverse("mafiastats_edit", args=[int(game_id)]),
        },
        context_instance=RequestContext(request),
    )
예제 #26
0
def add_edit_role(request, *args, **kwargs):
    """Takes in the project id and allows you to add a new role."""

    project_name = kwargs['project_name']
    project = get_object_or_404(CollabProject, slug=project_name)
    id = project.id

    # If the user is not the project admin, just return him to the project page.
    if not project.admin.filter(
            id=request.user.id) and not request.user.is_superuser:
        request.user.message_set.create(
            message="You do not have privileges to edit roles!")
        return HttpResponseRedirect(project.get_absolute_url())

    if 'role_id' in kwargs:
        role_id = kwargs['role_id']
        role = get_object_or_404(Role, id=role_id)
        # Check if the role exists in that project!
        if role.project.id != project.id:
            request.user.message_set.create(
                message="The role does not exist in that project!")
            return HttpResponseRedirect(project.get_absolute_url())
        edit, instance, initial = True, role, None
    else:
        edit, instance, initial = False, None, {}

    if request.method == 'POST':
        form = RoleForm(project.id,
                        request.POST,
                        instance=instance,
                        clean=(not edit),
                        initial=initial)
        if form.is_valid():
            if not edit:
                new_role = Role()
                message = "The role was added."
            else:
                message = "The role was modified."
            new_role = form.save(commit=False)
            new_role.project = project
            new_role.save()
            # Need this as I have a many to many field and did commit=False.
            form.save_m2m()

            # It's possible that a user gave some Editable privileges without the corresponding Viewable. The
            # following code automatically adds those Viewable privileges.
            for privilege in form.cleaned_data["privileges"]:
                if privilege.permission_type == 'Editable':
                    new_privilege = get_object_or_404(
                        Privilege,
                        project=project,
                        related_model=privilege.related_model,
                        permission_type='Viewable')
                    new_role.privileges.add(new_privilege)
            new_role.save()

            if form.cleaned_data["make_default"] == True:
                if project.default_role != new_role:
                    project.default_role = new_role
                    project.save()

            request.user.message_set.create(message=message)
            return HttpResponseRedirect(
                reverse('roles_overview',
                        kwargs={'project_name': project.slug}))
    else:
        form = RoleForm(project.id, instance=instance, initial=initial)
    return render_to_response('project/addrole.html', {
        'form': form,
        'project': project,
        'edit': edit,
        'role': instance
    },
                              context_instance=RequestContext(request))
예제 #27
0
def save_role(role):
    print("SALVANDO ROLE")
    role = Role(name=role.name)
    role.save()
    return role