Example #1
0
def view_api_refresh_get(request):
    uid = request.matchdict['uid']

    refresh_cmd={}
    refresh_cmd['cmd']='su'
    refresh_cmd['args']=['-c','/home/pi/refresh.sh','pi']
    refresh_cmd['result']=''


    row = DBSession.query(RasPi).filter(RasPi.uuid == uid).first()
    if row is None:
        return {'status': 'error'}

    try:
        # If there are already records to be run,
        # we'll start with them in the array already
        cmd_data = json.loads(row.requested_commands)
    except (ValueError, TypeError):
        cmd_data=[]
        pass

    cmd_data.append(refresh_cmd)

    row.requested_commands = json.dumps(cmd_data)
    DBSession.flush()

    return {'status': 'OK'}
Example #2
0
def redirect_me(request):
    uid = request.matchdict['uid']
    url = "http://www.stackexchange.com"
    try:
        row = DBSession.query(RasPi).filter(RasPi.uuid == uid).first()
        if row:
            url = row.url
            logging.info("UID {uid}: {page}".format(uid=row.uuid, page=url))
        else:
            row = RasPi()
            row.uuid = uid
            row.url = "http://www.stackexchange.com"
            row.landscape = True
            row.browser = True
            DBSession.add(row)
            DBSession.flush()
            logging.warn(
                "UID {uid} NOT FOUND. ADDED TO TABLE WITH DEFAULT URL".format(
                    uid=uid))
            url = row.url
    except Exception:
        logging.error(
            "Something went south with DB when searching for {uid}".format(
                uid=uid))

    raise exc.HTTPFound(url)
Example #3
0
def main(argv=sys.argv):
    if len(argv) < 2:
        usage(argv)
    config_uri = argv[1]
    options = parse_vars(argv[2:])
    setup_logging(config_uri)
    settings = get_appsettings(config_uri, options=options)
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    Base.metadata.create_all(engine)
    with transaction.manager:
        model = RasPi()
        model.uuid = '11:22:33:44:55:66'
        model.description = "Testing Pi"
        model.url = "http://www.facebook.com"
        model.orientation = 0
        model.browser = True
        model.lastseen = datetime.now()
        DBSession.add(model)

        tag = Tags()
        tag.uuid = '11:22:33:44:55:66'
        tag.tag = 'test'
        DBSession.add(tag)

        User = UserModel()
        User.email = '*****@*****.**'
        User.AccessLevel = 2
        DBSession.add(User)

    DBSession.flush()
Example #4
0
def view_ajax_set_commands(request):
    uid = request.matchdict['uid']
    response = request.json_body

    row = DBSession.query(RasPi).filter(RasPi.uuid == uid).first()
    if row is None:
        return '{"status":"error"}'

    # convert response into something with stable sorting
    cmds = []
    tmpcmds = sorted(response.items(), key=operator.itemgetter(0))
    for tmptuple in tmpcmds:
        # extract cmdid/cmd
        cmdid = int(tmptuple[0])
        cmd = tmptuple[1]['cmd']
        del tmptuple[1]['cmd']

        # extract arguments
        tmpargs = sorted(tmptuple[1].items(), key=operator.itemgetter(0))
        args = [item[1] for item in tmpargs]

        # put into our cmd object in the correct order
        cmds.insert(cmdid, {})
        cmds[cmdid]['cmd'] = cmd
        cmds[cmdid]['args'] = args

        # command hasn't been run yet, so this is blank
        cmds[cmdid]['result'] = ''

    row.requested_commands = json.dumps(cmds)
    DBSession.flush()

    return str(cmds)
Example #5
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    NotSoSecret = 'CIeUz0RK8fjRq1wJSrID'
    authn_policy = AuthTktAuthenticationPolicy(NotSoSecret,
                                               callback=groupfinder,
                                               hashalg='sha512')
    authz_policy = ACLAuthorizationPolicy()
    session_factory = SignedCookieSessionFactory(NotSoSecret)

    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    Base.metadata.bind = engine
    config = Configurator(settings=settings, root_factory=Root)
    config.set_authentication_policy(authn_policy)
    config.set_authorization_policy(authz_policy)
    config.include('velruse.providers.google_oauth2')
    config.set_session_factory(session_factory)
    config.add_google_oauth2_login_from_settings(prefix='velruse.google.')
    config.include('cornice')
    config.include('pyramid_mako')
    config.add_static_view('static', 'static', cache_max_age=3600)
    config.add_static_view('client_agent', 'client_agent', cache_max_age=3600)
    config.add_route('home', '/')
    config.add_route('tagged', '/tagged/{tags}')
    config.add_route('users', '/users')
    config.add_route('logout', '/logout')
    config.add_route('redirectme', '/go/{uid}')
    config.add_route('provision', '/provision')
    config.add_route('logs', '/logs/{uuid}')
    config.add_route('wall', '/wall/{tags}')
    config.add_request_method(LookupUser, 'user', reify=True)
    config.scan()
    return config.make_wsgi_app()
Example #6
0
def view_ajax_set_commands(request):
    uid = request.matchdict['uid']
    response = request.json_body

    row = DBSession.query(RasPi).filter(RasPi.uuid == uid).first()
    if row is None:
        return '{"status":"error"}'

    # convert response into something with stable sorting
    cmds = []
    tmpcmds = sorted(response.items(), key=operator.itemgetter(0))
    for tmptuple in tmpcmds:
        # extract cmdid/cmd
        cmdid = int(tmptuple[0])
        cmd = tmptuple[1]['cmd']
        del tmptuple[1]['cmd']

        # extract arguments
        tmpargs = sorted(tmptuple[1].items(), key=operator.itemgetter(0))
        args = [item[1] for item in tmpargs]

        # put into our cmd object in the correct order
        cmds.insert(cmdid, {})
        cmds[cmdid]['cmd'] = cmd
        cmds[cmdid]['args'] = args

        # command hasn't been run yet, so this is blank
        cmds[cmdid]['result'] = ''

    row.requested_commands = json.dumps(cmds)
    DBSession.flush()

    return str(cmds)
Example #7
0
def view_api_refresh_get(request):
    uid = request.matchdict['uid']

    refresh_cmd={}
    refresh_cmd['cmd']='su'
    refresh_cmd['args']=['-c','/home/pi/refresh.sh','pi']
    refresh_cmd['result']=''


    row = DBSession.query(RasPi).filter(RasPi.uuid == uid).first()
    if row is None:
        return {'status': 'error'}

    try:
        # If there are already records to be run,
        # we'll start with them in the array already
        cmd_data = json.loads(row.requested_commands)
    except (ValueError, TypeError):
        cmd_data=[]
        pass

    cmd_data.append(refresh_cmd)

    row.requested_commands = json.dumps(cmd_data)
    DBSession.flush()

    return {'status': 'OK'}
Example #8
0
def view_api_post_new_tag(request):
    uid=request.matchdict['uid']
    tag=request.matchdict['tag']
    newtag = Tags()
    newtag.uuid=uid
    newtag.tag=tag
    DBSession.add(newtag)
    DBSession.flush()
Example #9
0
def view_api_post_new_tag(request):
    uid=request.matchdict['uid']
    tag=request.matchdict['tag']
    newtag = Tags()
    newtag.uuid=uid
    newtag.tag=tag
    DBSession.add(newtag)
    DBSession.flush()
Example #10
0
 def setUp(self):
     self.config = testing.setUp()
     from sqlalchemy import create_engine
     engine = create_engine('sqlite://')
     from pi_director.models.models import (
         Base,
         RasPi,
         )
     DBSession.configure(bind=engine)
Example #11
0
 def setUp(self):
     self.config = testing.setUp()
     from sqlalchemy import create_engine
     engine = create_engine('sqlite://')
     from pi_director.models.models import (
         Base,
         RasPi,
     )
     DBSession.configure(bind=engine)
Example #12
0
def view_ajax_set_command_results(request):
    uid = request.matchdict['uid']

    row = DBSession.query(RasPi).filter(RasPi.uuid == uid).first()
    if row is None:
        return {'status': 'error'}

    row.requested_commands = ''
    DBSession.flush()

    return {'status': 'OK'}
Example #13
0
def view_ajax_set_command_results(request):
    uid = request.matchdict['uid']

    row = DBSession.query(RasPi).filter(RasPi.uuid == uid).first()
    if row is None:
        return {'status': 'error'}

    row.requested_commands = ''
    DBSession.flush()

    return {'status': 'OK'}
Example #14
0
 def setUp(self):
     self.config = testing.setUp()
     from sqlalchemy import create_engine
     engine = create_engine('sqlite://')
     from pi_director.models.models import (
         Base,
         RasPi,
     )
     DBSession.configure(bind=engine)
     Base.metadata.create_all(engine)
     with transaction.manager:
         model = RasPi(name='one', value=55)
         DBSession.add(model)
Example #15
0
 def setUp(self):
     self.config = testing.setUp()
     from sqlalchemy import create_engine
     engine = create_engine('sqlite://')
     from pi_director.models.models import (
         Base,
         RasPi,
         )
     DBSession.configure(bind=engine)
     Base.metadata.create_all(engine)
     with transaction.manager:
         model = RasPi(name='one', value=55)
         DBSession.add(model)
Example #16
0
def main(argv=sys.argv):
    if len(argv) < 2:
        usage(argv)
    config_uri = argv[1]
    options = parse_vars(argv[2:])
    setup_logging(config_uri)
    settings = get_appsettings(config_uri, options=options)
    engine = engine_from_config(settings, "sqlalchemy.")
    DBSession.configure(bind=engine)
    Base.metadata.create_all(engine)
    with transaction.manager:
        model = RasPi(uuid="default", url="http://www.facebook.com")
        DBSession.add(model)
Example #17
0
def get_pi_cmd_info(uid):
    tags = []
    row = DBSession.query(RasPi).filter(RasPi.uuid == uid).first()
    if row is None:
        return []
    else:
        try:
            tagset = DBSession.query(Tags).filter(Tags.uuid == uid).all()
            for tag in tagset:
                tags.append(tag.tag)
        except Exception:
            pass

    rowdict = row.get_dict()
    rowdict['tags'] = tags
    return rowdict
Example #18
0
def get_pi_cmd_info(uid):
    tags = []
    row = DBSession.query(RasPi).filter(RasPi.uuid == uid).first()
    if row is None:
        return []
    else:
        try:
            tagset = DBSession.query(Tags).filter(Tags.uuid==uid).all()
            for tag in tagset:
                tags.append(tag.tag)
        except Exception:
            pass

    rowdict = row.get_dict()
    rowdict['tags']=tags
    return rowdict
Example #19
0
def view_api_ping(request):
    uid = request.matchdict['uid']

    now = datetime.now()

    row = DBSession.query(RasPi).filter(RasPi.uuid == uid).first()
    if row is None:
        row = RasPi()
        row.uuid = uid
        row.url = "http://www.stackexchange.com"
        row.landscape = True
        row.orientation = 0
        row.description = ""

    row.lastseen = now
    DBSession.add(row)
    DBSession.flush()
Example #20
0
def groupfinder(userid,request):
  try:
    user = DBSession.query(UserModel).filter(UserModel.email==userid).one()
    if user is not None:
      if user.AccessLevel >= 0:
        return[AccessLevels[user.AccessLevel]]
  except NoResultFound, e:
    return None
Example #21
0
def login_complete_view(request):
  context = request.context
  result = {
    'provider_type': context.provider_type,
    'provider_name': context.provider_name,
    'profile': context.profile,
    'credentials': context.credentials,
  }
  email = context.profile['verifiedEmail']
  try:
    User = DBSession.query(UserModel).filter(UserModel.email==email).one()
  except NoResultFound, e:
    User = UserModel()
    User.email = email
    User.AccessLevel = 1
    DBSession.add(User)
    DBSession.flush()
Example #22
0
def LookupUser(request):
  userid=authenticated_userid(request)
  try:
    logging.debug("Looking up user session for %s", userid)
    UserObject = DBSession.query(UserModel).filter(UserModel.email==userid).one()
    return UserObject
  except NoResultFound, e:
    return None
Example #23
0
def login_complete_view(request):
    context = request.context
    result = {
        'provider_type': context.provider_type,
        'provider_name': context.provider_name,
        'profile': context.profile,
        'credentials': context.credentials,
    }
    email = context.profile['verifiedEmail']
    try:
        User = DBSession.query(UserModel).filter(
            UserModel.email == email).one()
    except NoResultFound, e:
        User = UserModel()
        User.email = email
        User.AccessLevel = 1
        DBSession.add(User)
        DBSession.flush()
Example #24
0
def groupfinder(userid, request):
    try:
        user = DBSession.query(UserModel).filter(
            UserModel.email == userid).one()
        if user is not None:
            if user.AccessLevel >= 0:
                return [AccessLevels[user.AccessLevel]]
    except NoResultFound, e:
        return None
Example #25
0
def LookupUser(request):
    userid = authenticated_userid(request)
    try:
        logging.debug("Looking up user session for %s", userid)
        UserObject = DBSession.query(UserModel).filter(
            UserModel.email == userid).one()
        return UserObject
    except NoResultFound, e:
        return None
Example #26
0
def view_api_ping(request):
    uid = request.matchdict['uid']

    now = datetime.now()

    row = DBSession.query(RasPi).filter(RasPi.uuid == uid).first()
    if row is None:
        row = RasPi()
        row.uuid = uid
        row.url = "http://www.stackexchange.com"
        row.landscape = True
        row.orientation = 0
        row.description = ""
        row.browser = True

    row.lastseen = now
    DBSession.add(row)
    DBSession.flush()
Example #27
0
def view_ajax_get_command_results(request):
    uid = request.matchdict['uid']

    row = DBSession.query(RasPi).filter(RasPi.uuid == uid).first()
    if row is None:
        return {'status': 'error'}

    data = json.loads(row.requested_commands)

    return {'status': 'OK', 'data': data}
Example #28
0
def view_ajax_get_command_results(request):
    uid = request.matchdict['uid']

    row = DBSession.query(RasPi).filter(RasPi.uuid == uid).first()
    if row is None:
        return {'status': 'error'}

    data = json.loads(row.requested_commands)

    return {'status': 'OK', 'data': data}
Example #29
0
def redirect_me(request):
    uid = request.matchdict['uid']
    url = "http://www.stackexchange.com"
    try:
        row = DBSession.query(RasPi).filter(RasPi.uuid==uid).first()
        if row:
            url = row.url
            logging.info("UID {uid}: {page}".format(uid=row.uuid, page=url))
        else:
            row = RasPi()
            row.uuid = uid
            row.url = "http://www.stackexchange.com"
            row.landscape = True
            DBSession.add(row)
            DBSession.flush()
            logging.warn("UID {uid} NOT FOUND. ADDED TO TABLE WITH DEFAULT URL".format(uid=uid))
            url = row.url
    except Exception:
            logging.error("Something went south with DB when searching for {uid}".format(uid=uid))

    raise exc.HTTPFound(url)
Example #30
0
def get_pi_info(uid):
    tags = []
    row = DBSession.query(RasPi).filter(RasPi.uuid == uid).first()
    if row is None:
        row = RasPi()
        row.uuid = uid
        row.url = "http://www.stackexchange.com"
        row.landscape = True
        row.lastseen = datetime.now()
        row.description = ""
        row.orientation = 0
        row.browser = True
        DBSession.add(row)
        DBSession.flush()
    else:
        try:
            tagset = DBSession.query(Tags).filter(Tags.uuid == uid).all()
            for tag in tagset:
                tags.append(tag.tag)
        except Exception:
            pass

    rowdict = row.get_dict()
    rowdict['tags'] = tags
    return rowdict
Example #31
0
def view_api_screenshow_show(request):
    uid = request.matchdict['uid']
    shot = DBSession.query(Screenshot).filter(Screenshot.uuid == uid).first()
    if shot:
        with BytesIO() as ss:
            ss.write(shot.image)
            return Response(content_type='image/png', content_length=len(ss.getvalue()), body=ss.getvalue())
    else:
        with BytesIO() as ss:
            emptypng = '89504E470D0A1A0A0000000D49484452000000010000000108000000003A7E9B550000000A4944' \
                       '4154789C63FA0F0001050102CFA02ECD0000000049454E44AE426082'.decode('hex')
            ss.write(emptypng)
            return Response(content_type='image/png', content_length=len(ss.getvalue()), body=ss.getvalue())
Example #32
0
def view_api_screenshow_show(request):
    uid = request.matchdict['uid']
    shot = DBSession.query(Screenshot).filter(Screenshot.uuid == uid).first()
    if shot:
        with BytesIO() as ss:
            ss.write(shot.image)
            return Response(content_type='image/png', content_length=len(ss.getvalue()), body=ss.getvalue())
    else:
        with BytesIO() as ss:
            emptypng = '89504E470D0A1A0A0000000D49484452000000010000000108000000003A7E9B550000000A4944' \
                       '4154789C63FA0F0001050102CFA02ECD0000000049454E44AE426082'.decode('hex')
            ss.write(emptypng)
            return Response(content_type='image/png', content_length=len(ss.getvalue()), body=ss.getvalue())
Example #33
0
def view_json_set_pi(request):
    # TODO: move into controller(s)
    uid = request.matchdict['uid']
    response = request.json_body

    row = DBSession.query(RasPi).filter(RasPi.uuid == uid).first()
    if row is None:
        row = RasPi()
        row.uuid = uid
    row.url = response['url']
    row.description = response['description']
    row.orientation = response['orientation']
    row.browser = response['browser']
    DBSession.add(row)
    DBSession.flush()
    rowdict = {
        'uuid': row.uuid,
        'url': row.url,
        'description': row.description,
        'orientation': row.orientation,
        'browser': row.browser
    }
    return rowdict
Example #34
0
def view_json_set_pi(request):
    # TODO: move into controller(s)
    uid = request.matchdict['uid']
    response = request.json_body

    row = DBSession.query(RasPi).filter(RasPi.uuid == uid).first()
    if row is None:
        row = RasPi()
        row.uuid = uid
    row.url = response['url']
    row.description = response['description']
    row.orientation = response['orientation']
    row.browser = response['browser']
    DBSession.add(row)
    DBSession.flush()
    rowdict = {
        'uuid': row.uuid,
        'url': row.url,
        'description': row.description,
        'orientation': row.orientation,
        'browser': row.browser
    }
    return rowdict
Example #35
0
def get_tagged_pis(tags):
    splitter = shlex.shlex(tags)
    splitter.whitespace += ','
    splitter.whitespace += ';'
    splitter.whitespace_split = True
    taglist = list(splitter)

    taglist_str = ""
    for tag in taglist:
        taglist_str += "\'{tag}\',".format(tag=tag)
    taglist_str = taglist_str.rstrip(taglist_str[-1:])

    tagged_pis = []

    if (len(taglist) > 1):
        query_str = """
    SELECT t1.uuid,count(*) AS ct
      FROM Tags t1
      JOIN Tags t2 ON t1.tag!=t2.tag AND t1.uuid==t2.uuid
     WHERE 1
       AND t1.tag IN ({taglist})
       AND t2.tag IN ({taglist})
  GROUP BY t1.uuid
    HAVING ct >= {args}
        """.format(taglist=taglist_str, args=len(taglist))

        result = DBSession.get_bind().execute(query_str)

        for row in result:
            tagged_pis.append(row[0])
    else:
        PisWithTags = DBSession.query(Tags).filter(Tags.tag.in_(taglist)).all()
        for pi in PisWithTags:
            tagged_pis.append(pi.uuid)

    PiList = DBSession.query(RasPi).filter(RasPi.uuid.in_(tagged_pis)).order_by(desc(RasPi.lastseen)).all()
    return PiList
Example #36
0
def view_api_reqcommands_post(request):
    uid = request.matchdict['uid']
    results = request.json_body
    results['data'] = json.loads(results['data'])

    row = DBSession.query(RasPi).filter(RasPi.uuid == uid).first()
    if row is None:
        return {'status': 'error'}

    cmd_data = json.loads(row.requested_commands)
    new_data = []

    for i, cmdinfo in enumerate(cmd_data):
        if results['status'] == 'OK':
            cmdinfo['result'] = results['data'][i]
        else:
            cmdinfo['result'] = results['msg']

        new_data.append(cmdinfo)

    row.requested_commands = json.dumps(new_data)
    DBSession.flush()

    return {'status': 'OK'}
Example #37
0
def get_tagged_pis(tags):
    splitter = shlex.shlex(tags)
    splitter.whitespace += ','
    splitter.whitespace += ';'
    splitter.whitespace_split = True
    taglist = list(splitter)

    taglist_str = ""
    for tag in taglist:
        taglist_str += "\'{tag}\',".format(tag=tag)
    taglist_str = taglist_str.rstrip(taglist_str[-1:])

    tagged_pis = []

    if (len(taglist) > 1):
        query_str = """
        SELECT t1.uuid,count(*)
        FROM "Tags" t1
        JOIN "Tags" t2 ON t1.tag!=t2.tag AND t1.uuid=t2.uuid
        WHERE t1.tag IN ({taglist})
        AND t2.tag IN ({taglist})
        GROUP BY t1.uuid
        HAVING count(*) >= {args};
        """.format(taglist=taglist_str, args=len(taglist))

        result = DBSession.get_bind().execute(query_str)

        for row in result:
            tagged_pis.append(row[0])
    else:
        PisWithTags = DBSession.query(Tags).filter(Tags.tag.in_(taglist)).all()
        for pi in PisWithTags:
            tagged_pis.append(pi.uuid)

    PiList = DBSession.query(RasPi).filter(RasPi.uuid.in_(tagged_pis)).order_by(desc(RasPi.lastseen)).all()
    return PiList
Example #38
0
def view_api_reqcommands_post(request):
    uid = request.matchdict['uid']
    results = request.json_body
    results['data'] = json.loads(results['data'])

    row = DBSession.query(RasPi).filter(RasPi.uuid == uid).first()
    if row is None:
        return {'status': 'error'}

    cmd_data = json.loads(row.requested_commands)
    new_data = []

    for i, cmdinfo in enumerate(cmd_data):
        if results['status'] == 'OK':
            cmdinfo['result'] = results['data'][i]
        else:
            cmdinfo['result'] = results['msg']

        new_data.append(cmdinfo)

    row.requested_commands = json.dumps(new_data)
    DBSession.flush()

    return {'status': 'OK'}
Example #39
0
def view_api_screenshot_save(request):
    uid = request.matchdict['uid']
    imgblob = request.POST['screenshot'].file

    '''first, delete previous screenshot'''
    DBSession.query(Screenshot).filter(Screenshot.uuid == uid).delete()

    '''Now, lets make a new screenshot'''
    foo = Screenshot()
    foo.uuid = uid
    foo.image = imgblob.read()
    DBSession.add(foo)
    DBSession.flush()
Example #40
0
def view_api_screenshot_save(request):
    uid = request.matchdict['uid']
    imgblob = request.POST['screenshot'].file

    '''first, delete previous screenshot'''
    DBSession.query(Screenshot).filter(Screenshot.uuid == uid).delete()

    '''Now, lets make a new screenshot'''
    foo = Screenshot()
    foo.uuid = uid
    foo.image = imgblob.read()
    DBSession.add(foo)
    DBSession.flush()
Example #41
0
def view_api_log_save(request):
    uid = request.matchdict['uid']
    pi_log = request.POST['pi_log']
    filename = request.POST['filename']
    DBSession.query(Logs).filter(
        Logs.uuid == uid).filter(
        Logs.filename == filename).delete()

    new_log = Logs()
    new_log.filename = filename
    new_log.uuid = uid
    new_log.log = pi_log
    DBSession.add(new_log)
    DBSession.flush()
Example #42
0
def view_api_log_save(request):
    uid = request.matchdict['uid']
    pi_log = request.POST['pi_log']
    filename = request.POST['filename']
    DBSession.query(Logs).filter(
        Logs.uuid == uid).filter(
        Logs.filename == filename).delete()

    new_log = Logs()
    new_log.filename = filename
    new_log.uuid = uid
    new_log.log = pi_log
    DBSession.add(new_log)
    DBSession.flush()
Example #43
0
def make_an_admin(request):
    email = request.matchdict['email']
    '''First, make sure there aren't already admins in the system'''
    res = DBSession.query(UserModel).filter(UserModel.AccessLevel == 2).first()
    if res != None:
        msg = "User already an admin: {user}".format(user=res.email)
        return False
    user = DBSession.query(UserModel).filter(UserModel.email == email).first()
    if user == None:
        user = UserModel()
        user.email = email
        DBSession.add(user)
    user.AccessLevel = 2
    DBSession.flush()
    return True
Example #44
0
def make_an_admin(request):
    email=request.matchdict['email']

    '''First, make sure there aren't already admins in the system'''
    res=DBSession.query(UserModel).filter(UserModel.AccessLevel==2).first()
    if res != None:
        msg="User already an admin: {user}".format(user=res.email)
        return False
    user=DBSession.query(UserModel).filter(UserModel.email==email).first()
    if user == None:
        user=UserModel()
        user.email=email
        DBSession.add(user)
    user.AccessLevel=2
    DBSession.flush()    
    return True
Example #45
0
def get_users():
    UserList = DBSession.query(UserModel).all()
    return UserList
Example #46
0
def view_json_delete_pi(request):
    uid = request.matchdict['uid']
    DBSession.query(RasPi).filter(RasPi.uuid == uid).delete()
Example #47
0
def view_json_delete_pi(request):
    uid = request.matchdict['uid']
    pi = DBSession.query(RasPi).filter(RasPi.uuid == uid).first()
    for tag in pi.tags:
        DBSession.query(Tags).filter(and_(Tags.uuid == uid, Tags.tag == tag.tag)).delete()
    DBSession.query(RasPi).filter(RasPi.uuid == uid).delete()
Example #48
0
def get_log(uuid, filename):
    log = DBSession.query(Logs).filter(
          Logs.uuid == uuid).filter(
          Logs.filename == filename).first()

    return log
Example #49
0
def get_logs(uuid):
    logs = DBSession.query(Logs).filter(Logs.uuid==uuid).all()
    return logs
Example #50
0
def view_api_delete_tag(request):
    uid=request.matchdict['uid']
    tag=request.matchdict['tag']
    DBSession.query(Tags).filter(and_(Tags.uuid == uid,Tags.tag == tag)).delete()
Example #51
0
 def tearDown(self):
     DBSession.remove()
     testing.tearDown()
Example #52
0
def delete_user(email):
    DBSession.query(UserModel).filter(UserModel.email == email).delete()
Example #53
0
def authorize_user(email):
    user = DBSession.query(UserModel).filter(UserModel.email == email).one()
    user.AccessLevel = 2
    DBSession.flush()
Example #54
0
 def tearDown(self):
     DBSession.remove()
     testing.tearDown()
Example #55
0
def get_log(uuid, filename):
    log = DBSession.query(Logs).filter(
        Logs.uuid == uuid).filter(
        Logs.filename == filename).first()

    return log
Example #56
0
def view_api_delete_tag(request):
    uid=request.matchdict['uid']
    tag=request.matchdict['tag']
    DBSession.query(Tags).filter(and_(Tags.uuid == uid,Tags.tag == tag)).delete()