Exemplo n.º 1
0
 def create_role():
     query = db.session.query(Role).all()
     if not query:
         db.session.add(Role(role_name="superuser"))
         db.session.add(Role(role_name="user"))
         db.session.commit()
         print("Roles have been created.")
Exemplo n.º 2
0
    def seed_roles():
        admin = Role()
        admin.name = 'admin'
        admin.save()

        audience = Role()
        audience.name = 'watcher'
        audience.save()
Exemplo n.º 3
0
def add_role(auth, name):
    user = authenticate(username=auth.get('username'),
                        password=auth.get('password'))
    auth['tenant'] = user.site.login_base

    role = Role(role_type=name)
    role.os_manager = OpenStackManager(auth=auth, caller=user)
    role.save()
    return role
Exemplo n.º 4
0
 def __call__(self, app, *args, **kwargs):
     with create_app().app_context():
         query = db.session.query(Role).all()
         if not query:
             db.session.add(Role(role_name="superuser"))
             db.session.add(Role(role_name="user"))
             db.session.commit()
             print("Roles have been created.")
     return Server.__call__(self, app, *args, **kwargs)
Exemplo n.º 5
0
def add_role(auth, name):
    user = authenticate(username=auth.get('username'),
                        password=auth.get('password'))
    auth['tenant'] = user.site.login_base

    role = Role(role_type=name)
    role.os_manager = OpenStackManager(auth=auth, caller = user) 
    role.save()
    return role
Exemplo n.º 6
0
    def setUp(self):
        # set config variables
        application.config['TESTING'] = True
        application.config['WTF_CSRF_ENABLED'] = False
        application.config['DEBUG'] = False
        # set test admin database (sqlite)
        application.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + \
            os.path.join(tests_path, TEST_ADMIN_DB)
        # specify the test Dynamo tables (running on a LOCAL Dynamo DB instance!!!)
        application.config['DYNAMO_ENABLE_LOCAL'] = True
        application.config['DYNAMO_TABLES'] = [TEST_DYNAMODB_TABLE]

        # initialize the test client
        self.testapp = application.test_client()

        # create the dynamo db tables
        with application.app_context():
            try:
                dynamo_db.create_all()
            except OSError:
                # see https://github.com/dateutil/dateutil/issues/197
                # print(
                #   "(a dateutil bug causes an OSError Excepation to be raised by Boto3 here, which we ignore for testing)"
                # )
                pass

            # create the admin db tables and some users
            application_db.create_all()
            # admin user
            new_admin_user = User(
                TEST_ADMIN_USERNAME,
                TEST_ADMIN_PASSWORD,
                [Role('admin')]
            )
            application_db.session.add(new_admin_user)
            new_reglr_user = User(
                TEST_REGLR_USERNAME,
                TEST_REGLR_PASSWORD,
                [Role("contributor")]
            )
            application_db.session.add(new_reglr_user)
            application_db.session.commit()

        # make sure debug mode is off
        self.assertEqual(application.debug, False)
Exemplo n.º 7
0
def setup():
    recreate_db()
    Role.insert_roles()
    admin = Role.query.filter_by(name='Admin').first()
    poster = Role.query.filter_by(name='Poster').first()
    mod = Role.query.filter_by(name='Moderator').first() 

    """ Create default users account change these details in production """
    d = User(
            username='******',
            email='*****@*****.**',
            password='******',
            confirmed=True
            )
    
    d.roles.append(admin)

    a = User(
            username='******',
            email='*****@*****.**',
            password='******',
            confirmed=True
            )
    
    a.roles.append(poster)
    a.roles.append(mod)

    u = User(
            username='******',
            email='*****@*****.**',
            password='******')

    db.session.add(u)
    db.session.add(a)
    db.session.add(d)
    db.session.commit()
    
    return 'Default users created'
Exemplo n.º 8
0
def create_role(role):
    """[summary]

    Arguments:
        role {string} -- [description]

    Returns:
        instance of Role model
    """

    new_role = Role(name=role)
    db.session.add(new_role)
    db.session.commit()
    return new_role
Exemplo n.º 9
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'
Exemplo n.º 10
0
 def get_queryset(cls, queryset, info):
     return Role.get_queryset(queryset, info)
Exemplo n.º 11
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
Exemplo n.º 12
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