예제 #1
0
def add_membership(request, group):
    current_user = LyfeUser.objects.get(pk=request.user.username)
    
    newMembership = Membership(user_id=current_user, group_id_id=group, accepted=False)
    newMembership.save()
    
    return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
예제 #2
0
    def add_member(asso, form):
        if not form.is_valid():
            return

        member = form.cleaned_data['membre']
        membership = Membership(asso=asso,
                                member=member,
                                role=MemberRole.SIMPLE._value_)
        membership.save()

        Dashboard.msg = member.username + " a bien été ajouté à l'association."
예제 #3
0
def add_group(request):
    current_user = LyfeUser.objects.get(pk=request.user.username)
    
    GroupForm = modelform_factory(Group, fields=('name', 'description', 'logo'))
    
    newGroup = GroupForm(request.POST, request.FILES)
    if newGroup.is_valid():
        group = newGroup.save(commit=False)
        group.creator_id = current_user
        group.save()
        
        defaultMembership = Membership(group_id=group, user_id=current_user)
        defaultMembership.save()
        
    return HttpResponseRedirect(reverse('core.views.dashboard'))
예제 #4
0
def list(request, validated={}, *args, **kwargs):
    if request.method == 'GET':
        roles = Role.objects.filter(name__icontains=validated['match']).values(
            'id', 'name', 'server')

        limit = validated['limit']
        offset = validated['offset']
        roles = roles[offset:] if limit < 0 else roles[offset:limit]

        return [g for g in roles]
    else:
        users = []
        for user in validated['members']:
            for u in User.objects.filter(id=user):
                users.append(u)

        role = Role(name=validated['name'])

        if validated['flags'] is not None:
            flags = validated['flags']
            permission = ServerPermission().convert(conv=flags)
        else:
            permission = ServerPermission()
        permission.save()

        role.flags = permission
        role.immunity = validated['immunity']

        if validated['server'] is not None:
            role.server = Server.objects.get(id=validated['server'])

        if validated['usetime'] is not None:
            role.usetime = datetime.timedelta(seconds=validated['usetime'])

        role.save()

        for u in users:
            m = Membership(user=u, role=role)
            m.save()
        # role.user_set.set(users)
        # role.save()

        return 'passed'
예제 #5
0
    def boompanel(self):
        self.conn.query("""SELECT * FROM bp_players""")
        r = self.conn.store_result()
        result = r.fetch_row(maxrows=0, how=1)

        users = {}
        for raw in result:
            query = User.objects.filter(username=raw['steamid'])
            if not query:
                user = User.objects.create_user(username=raw['steamid'])
                user.is_active = False
                user.is_steam = True

                populate(user)
            else:
                user = query[0]
            user.save()

            users[raw["id"]] = user

        self.conn.query("""SELECT * FROM bp_servers""")
        r = self.conn.store_result()
        result = r.fetch_row(maxrows=0, how=1)

        servers = {}
        for raw in result:
            server, _ = Server.objects.get_or_create(ip=raw['ip'],
                                                     port=raw['port'])
            server.password = raw['rcon_pw']
            server.name = raw['name']

            servers[raw['id']] = server
            try:
                conn = RCONBase(server, timeout=3)
                conn.connect()
                conn.authenticate(timeout=3)
                conn.close()
            except (valve.rcon.RCONTimeoutError,
                    valve.rcon.RCONAuthenticationError, ConnectionError,
                    TimeoutError, socket.timeout) as e:

                print("Warning: Could not connect to server {}:{} ({})".format(
                    raw['ip'], raw['port'], e))
                continue

            server.save()

        self.conn.query("""SELECT * FROM bp_admin_groups""")
        r = self.conn.store_result()
        result = r.fetch_row(maxrows=0, how=1)

        roles = {}
        for raw in result:
            role, _ = Role.objects.get_or_create(name=raw['name'])
            role.immunity = raw['immunity']
            role.flags = ServerPermission().convert(raw['flags'])
            role.usetime = None if raw['usetime'] == 0 else raw['usetime']
            role.save()

            roles[raw['id']] = role

        self.conn.query("""SELECT * FROM bp_admins""")
        r = self.conn.store_result()
        result = r.fetch_row(maxrows=0, how=1)

        admins = {}
        for raw in result:
            m = Membership()
            m.role = roles[raw['sid']]
            m.user = roles[raw['pid']]
            m.save()

            admins[raw['aid']] = m

        self.conn.query("""SELECT * FROM bp_mutegag""")
        r = self.conn.store_result()
        result = r.fetch_row(maxrows=0, how=1)

        for raw in result:
            if raw['aid'] not in users or raw['pid'] not in users or raw[
                    'sid'] not in servers:
                continue

            m = Punishment()
            m.user = users[raw["pid"]]
            m.server = servers[raw[
                'sid']] if raw['sid'] != 0 and raw['sid'] in servers else None
            m.created_by = users[raw['aid']]
            m.created_at = timezone.make_aware(
                datetime.datetime.fromtimestamp(raw['time']))
            m.reason = raw['reason'][:255]
            m.length = datetime.timedelta(seconds=raw['length'] *
                                          60) if raw['length'] > 0 else None
            m.is_muted = True if raw['type'] == 1 else False
            m.is_gagged = True if raw['type'] == 2 else False

            m.resolved = False
            if raw['time'] + raw['length'] < self.now.timestamp(
            ) and raw['length'] > 0:
                m.resolved = True

            if raw['unbanned'] == 1:
                m.resolved = True
            m.save()

        self.conn.query("""SELECT * FROM bp_bans""")
        r = self.conn.store_result()
        result = r.fetch_row(maxrows=0, how=1)

        for raw in result:
            if raw['aid'] not in users or raw['pid'] not in users or raw[
                    'sid'] not in servers:
                continue

            b = Punishment()
            b.is_banned = True
            b.user = users[raw["pid"]]
            b.server = servers[raw[
                'sid']] if raw['sid'] != 0 and raw['sid'] in servers else None
            b.created_by = users[raw['aid']]
            m.created_at = timezone.make_aware(
                datetime.datetime.fromtimestamp(raw['time']))
            b.reason = raw['reason'][:255]
            b.length = datetime.timedelta(
                seconds=raw['length']) if raw['length'] > 0 else None
            b.resolved = False
            if raw['time'] + raw['length'] < self.now.timestamp(
            ) and raw['length'] > 0:
                b.resolved = True

            if raw['unbanned'] == 1:
                b.resolved = True
            b.save()

        return True
예제 #6
0
    def sourcemod(self):
        self.conn.query("""SELECT * FROM sm_groups""")
        r = self.conn.store_result()
        result = r.fetch_row(maxrows=0, how=1)

        roles = {}
        for raw in result:
            flags = ServerPermission().convert(raw['flags'])
            flags.save()

            role = Role.objects.get_or_create(name=raw['name'],
                                              default={
                                                  'flags': flags,
                                                  'immunity':
                                                  raw['immunity_level']
                                              })
            role.name = raw['name']
            role.flags = flags
            role.immunity = raw['immunity_level']
            role.save()

            roles[raw['id']] = role

        self.conn.query("""SELECT * FROM sm_admins""")
        r = self.conn.store_result()
        result = r.fetch_row(maxrows=0, how=1)

        generated = {}
        for raw in result:
            try:
                steamid = SteamID.from_text(raw['identity']).as_64()
            except:
                print("Could not add admin {}".format(raw['name']))
                continue

            query = User.objects.filter(username=steamid)

            if not query:
                user = User.objects.create_user(username=steamid)
                user.is_active = False
                user.is_steam = True

                populate(user)
            else:
                user = query[0]
                user.namespace = raw['user']
            user.save()

            self.conn.query("""SELECT *
                         FROM sm_admins_groups
                         WHERE admin_id = {}""".format(raw['id']))
            r = self.conn.store_result()
            groups = r.fetch_row(maxrows=0, how=1)

            if not groups and raw['flags']:
                if raw['flags'] in generated:
                    role = generated[raw['flags']]
                else:
                    role = Role()
                    role.name = raw['flags']
                    role.flags = ServerPermission().convert(raw['flags'])
                    role.flags.save()
                    role.immunity = 0
                    role.save()

                    generated[raw['flags']] = role

                m = Membership()
                m.user = user
                m.role = role
                m.save()

            elif groups:
                for group in groups:
                    role = roles[group["group_id"]]

                    m = Membership()
                    m.user = user
                    m.role = role
                    m.save()

        return True
예제 #7
0
    def sourceban(self):
        superuser = User.objects.filter(is_superuser=True)
        superuser = superuser[0] if superuser else None

        # get servers
        self.conn.query("""SELECT * FROM sb_servers""")
        r = self.conn.store_result()
        result = r.fetch_row(maxrows=0, how=1)

        servers = {}
        for raw in result:
            if raw['enabled'] != 1:
                continue

            server, _ = Server.objects.get_or_create(ip=raw['ip'],
                                                     port=raw['port'])
            server.password = raw['rcon']
            server.name = "{}:{}".format(raw['ip'], raw['port'])
            server.save()

            try:
                conn = RCONBase(server, timeout=3)
                conn.connect()
                conn.authenticate(timeout=3)
                conn.close()

                servers[raw['sid']] = server
            except (valve.rcon.RCONTimeoutError,
                    valve.rcon.RCONAuthenticationError, ConnectionError,
                    TimeoutError, socket.timeout) as e:

                server.delete()
                print("Warning: Could not connect to server {}:{} ({})".format(
                    raw['ip'], raw['port'], e))
                continue

        # get groups
        self.conn.query("""SELECT * FROM sb_srvgroups""")
        r = self.conn.store_result()
        result = r.fetch_row(maxrows=0, how=1)

        for raw in result:
            flags = ServerPermission().convert(raw['flags'])
            flags.save()
            role, _ = Role.objects.get_or_create(name=raw['name'],
                                                 defaults={
                                                     'flags': flags,
                                                     'immunity':
                                                     raw['immunity']
                                                 })
            role.immunity = raw['immunity']
            role.flags = flags
            role.save()

        # get admins
        self.conn.query("""SELECT * FROM sb_admins""")
        r = self.conn.store_result()
        result = r.fetch_row(maxrows=0, how=1)

        users = {0: User.objects.filter(is_superuser=True)[0]}
        generated = {}
        for raw in result:
            try:
                steamid = SteamID.from_text(raw['authid']).as_64()
            except:
                print("Could not add admin {}".format(raw['user']))
                continue

            query = User.objects.filter(username=steamid)

            if not query:
                user = User.objects.create_user(username=steamid)
                user.is_active = False
                user.is_steam = True

                populate(user)
            else:
                user = query[0]

            user.namespace = raw['user']
            user.save()

            if not raw['srv_group'] and raw['srv_flags']:
                m = Membership()
                m.user = user
                if raw['srv_flags'] in generated:
                    m.role = generated[raw['srv_flags']]
                else:
                    m.role = Role()
                    m.role.immunity = 0
                    m.role.name = raw['srv_flags']
                    m.role.flags = ServerPermission().convert(raw['srv_flags'])
                    m.role.flags.save()
                    m.role.save()
                    m.save()

                    generated[raw['srv_flags']] = m.role

            elif raw['srv_group']:
                m = Membership()
                m.role = Role.objects.get(name=raw['srv_group'])
                m.user = user
                m.save()

            users[raw['aid']] = user

        # get bans
        self.conn.query("""SELECT * FROM sb_bans""")
        r = self.conn.store_result()
        result = r.fetch_row(maxrows=0, how=1)

        for raw in result:
            try:
                steamid = SteamID.from_text(raw['authid']).as_64()
            except:
                print("Could not add ban of user {}".format(raw['name']))
                continue

            query = User.objects.filter(username=steamid)

            if not query:
                user = User.objects.create_user(username=steamid)
                user.is_active = False
                user.is_steam = True

                populate(user)
            else:
                user = query[0]

            b = Punishment()
            b.is_banned = True
            b.user = user

            if raw['sid'] in servers:
                b.server = servers[raw['sid']] if raw['sid'] != 0 else None
            else:
                b.server = None

            if raw['aid'] in users:
                b.created_by = users[raw['aid']]
            elif superuser:
                b.created_by = superuser
            else:
                continue

            m.created_at = timezone.make_aware(
                datetime.datetime.fromtimestamp(raw['created']))
            b.reason = raw['reason'][:255]
            b.length = datetime.timedelta(
                seconds=raw['length']
            ) if raw['length'] > 0 and raw['length'] < 31540000 else None
            b.resolved = False
            if raw['created'] + raw['length'] < self.now.timestamp(
            ) and raw['length'] > 0:
                b.resolved = True

            if raw['RemovedOn']:
                b.resolved = True
            b.save()

        # get comms
        self.conn.query("""SELECT * FROM sb_comms""")
        r = self.conn.store_result()
        result = r.fetch_row(maxrows=0, how=1)

        for raw in result:
            try:
                steamid = SteamID.from_text(raw['authid']).as_64()
            except:
                print("Could not add mutegag of user {}".format(raw['name']))
                continue

            query = User.objects.filter(username=steamid)

            if not query:
                user = User.objects.create_user(username=steamid)
                user.is_active = False
                user.is_steam = True

                populate(user)
            else:
                user = query[0]

            m = Punishment()
            m.user = user

            if raw['sid'] in servers:
                m.server = servers[raw['sid']] if raw['sid'] != 0 else None
            else:
                m.server = None

            if raw['aid'] in users:
                m.created_by = users[raw['aid']]
            elif superuser:
                m.created_by = superuser
            else:
                continue

            m.created_at = timezone.make_aware(
                datetime.datetime.fromtimestamp(raw['created']))
            m.reason = raw['reason'][:255]
            m.length = datetime.timedelta(
                seconds=raw['length']
            ) if raw['length'] > 0 and raw['length'] < 31540000 else None
            m.is_muted = True if raw['type'] == 1 else False
            m.is_gagged = True if raw['type'] == 2 else False

            m.resolved = False
            if raw['created'] + raw['length'] < self.now.timestamp(
            ) and raw['length'] > 0:
                m.resolved = True

            if raw['RemovedOn']:
                m.resolved = True

            m.save()

        return True
예제 #8
0
파일: user.py 프로젝트: indietyp/hawthorne
def detailed(request, u=None, s=None, validated={}, *args, **kwargs):
  if request.method == 'GET':
    if u is not None:
      try:
        user = User.objects.get(id=u)
      except Exception as e:
        return 'not existent user queried - {}'.format(e), 403

    if s is not None:
      user = User.objects.get(username=s)
      try:
        pass
      except Exception as e:
        return 'not existent steamid provided - {}'.format(e), 403

    output = {'id': user.id,
              'ip': user.ip,
              'username': user.namespace if user.is_steam else user.username,
              'steamid': int(user.username) if user.is_steam else None,
              'avatar': user.avatar,
              'profile': user.profile,
              'permissions': [a.content_type.app_label + '.' + a.codename for a in user.user_permissions.all()],
              'groups': [str(a) for a in user.groups.all()],
              'roles': [],
              'is_internal': user.is_active,
              'country': None if user.country is None else user.country.code
              }

    memberships = user.membership_set.filter(user=user)
    if validated['server'] is not None:
      server = Server.objects.get(id=validated['server'])
      memberships.filter(Q(role__server=server) | Q(role__server=None))

    memberships = memberships.order_by('-role__immunity')

    if user.is_superuser:
      # fake root role
      output['roles'].append({'name': settings.ROOT,
                              'server': None,
                              'flags': 'ABCDEFGHIJKLNMNOPQRSTUVXYZ'.lower(),
                              'immunity': 100,
                              'usetime': None,
                              'timeleft': None
                              })

    for mem in memberships:
      usetime = None if mem.role.usetime is None else mem.role.usetime
      timeleft = None

      if usetime is not None:
        timeleft = (mem.created_at + usetime) - timezone.now()
        usetime = usetime.total_seconds()

        if timeleft < 0:
          mem.delete()
          continue

      output['roles'].append({'name': mem.role.name,
                              'server': None if not mem.role.server else mem.role.server.id,
                              'flags': mem.role.flags.convert().lower(),
                              'immunity': mem.role.immunity,
                              'usetime': usetime,
                              'timeleft': timeleft
                              })

    return output

  elif request.method == 'POST':
    if u is not None:
      try:
        user = User.objects.get(id=u)
      except Exception as e:
        return 'not existent user queried - {}'.format(e), 403

    if s is not None:
      try:
        user = User.objects.get(username=s)
      except Exception as e:
        if validated['force']:
          user = User.objects.create_user(username=str(s))
          user.save()

          steam_populate(user)

        else:
          return 'not existent steamid provided - {}'.format(e), 403

    if validated['role'] is not None:
      group = Role.objects.get(id=validated['role'])

      if validated['promotion']:
        m = Membership()
        m.user = user
        m.role = group
        m.save()
      else:
        m = Membership.objects.get(user=user, role=group)
        m.delete()

    if validated['group'] is not None:
      group = Group.objects.get(id=validated['group'])

      if validated['promotion']:
        user.groups.add(group)
      else:
        user.groups.remove(group)

    if validated['roles']:
      Membership.objects.filter(user=user).delete()

      for role in validated['roles']:
        group = Role.objects.get(id=role)
        m = Membership()
        m.user = user
        m.role = group
        m.save()

    if validated['groups']:
      groups = Group.objects.filter(id__in=validated['groups'])
      user.groups.set(groups)

      user.is_active = True

    if validated['permissions'] is not None:
      base = Permission.objects.all()\
                               .annotate(encoded=F('content_type__model') + '.' + F('codename'))\
                               .filter(encoded__in=request.user.get_all_permissions())\
                               .order_by('content_type__model')
      exceptions = []
      perms = []
      for perm in validated['permissions']:
        perm = perm.split('.')
        p = base.filter(content_type__model=perm[0], codename=perm[1])

        if not p:
          exceptions.append('.'.join(perm))

        perms.extend(p)

      if exceptions:
        return {'info': 'You are trying to assign permissions that either do not exist or are out of your scope.', 'affects': exceptions}, 403

      user.user_permissions.set(perms)
      user.save()

    return ':+1:'

  elif request.method == 'DELETE':
    if u:
      try:
        user = User.objects.get(id=u)
      except Exception as e:
        return 'not existent user queried - {}'.format(e), 403

    if s:
      try:
        user = User.objects.get(username=s)
      except Exception as e:
        return 'not existent steamid provided - {}'.format(e), 403

    if validated['purge']:
      if user.is_superuser:
        return 'superuser cannot be removed', 403

      if request.user == user:
        return 'you cannot disable yourself', 403

      user.delete()

      return 'CASCADE DELETE', 200
    elif validated['reset']:
      if not user.is_active:
        return 'user not using panel', 403

      if user.is_superuser:
        return 'superuser cannot be deactivated', 403

      if request.user == user:
        return 'you cannot disable yourself', 403

      user.is_active = False
      user.is_staff = False
      user.is_superuser = False

      user.user_permissions.clear()
      user.groups.clear()
    else:
      if validated['role']:
        m = Membership.objects.get(user=user, role=validated['role'])
        m.delete()

      for role in validated['roles']:
        m = Membership.objects.get(user=user, role=role)
        m.delete()

      for group in validated['groups']:
        user.groups.remove(Group.objects.get(id=group))

      if user.groups.count() == 0:
        user.is_active = False

    user.save()