示例#1
0
def delsession(username):
    sessionobj = Sessions(username)
    session_id = sessionobj.readsessionid(username)
    sessionobj.delsession(session_id)
    resp = make_response(jsonify(status='success'), 200)
    # socket.
    return resp
示例#2
0
def on_join(data):
    sessionobj = Sessions(data['username'])
    username = data['username']
    room = sessionobj.readsessionid(data['room'])
    # room = data['room']
    # join_room(room)
    # send(username + ' has entered the room.', room=room)
    emit('sentdirect', data, room=room, include_self=False)
示例#3
0
 def check_verification_code(verification_code, session_key, key):
     session = Sessions.get_session(session_key)
     data_decoded = Sessions.get_session_data_decoded(session)
     session_code = data_decoded[key]
     if str(verification_code) == str(session_code):
         return True
     else:
         return False
 def __init__(self, url, access_id, access_key):
     self.timer = Timer(Config.request_interval, self.task)
     self.sessions = Sessions()
     self.performance = Performance()
     self.url = url + Config.endpoint
     self.auth = (access_id, access_key)
     self.timestamp = int(time.time())
     self.start()
示例#5
0
    def post(self, *args, **kwargs):
        try:
            login = self.get_argument_smart('username',
                                            as_get=False,
                                            as_post=True,
                                            as_session=False,
                                            as_cookie=False)
            passwd = self.get_argument_smart('passwd',
                                             as_get=False,
                                             as_post=True,
                                             as_session=False,
                                             as_cookie=False)
        except Exception as err:
            abort(403)

        try:
            passwd = sha.new(passwd).hexdigest()
        except:
            abort(403)
        user = session.query(Users).filter(Users.login == login).filter(
            Users.passwd == passwd).first()
        if user is None:
            abort(403)

        flask_session['session'] = Sessions().create(user.id)

        return Response(self.get_as_json())
示例#6
0
def loginmsg(loggedin):
    print('This is {}'.format(loggedin))
    sessionobj = Sessions(loggedin['user'])
    sessionadded = sessionobj.addsession(request.sid)
    print(sessionadded)

    if sessionadded == 'error':
        # resp=make_response(jsonify(status='success'),200)
        resp = 'exist'
    else:
        # resp=make_response(jsonify(status='success'),200)
        emit('sessionadd',
             loggedin['user'],
             include_self=False,
             broadcast=True)
        resp = 'success'
    return resp
示例#7
0
 def send_verification_code(key, length=4):
     data = dict()
     verification_code = Messages.generate_verification_code(length)
     Sessions.set_session(key, verification_code)
     session_key = Sessions.get_session_key()
     data["key"] = session_key
     data["verify_code"] = verification_code
     try:
         # datas是有顺序的,所以只能用列表或元组,不能用集合
         datas = [verification_code, SMS_INTERVAL]
         data["info"] = Messages.send_message_sms(key, datas, SMS_TEMPLATE_ID)
         data["success"] = True
     except Exception as ex:
         Logs.print_current_function_name_and_line_number(ex)
         data["success"] = False
         data["info"] = ex.message
     return data
示例#8
0
 def r(self, retcode, msg, log_level):
     '''
     record Session command input/output to 'commands' table, and
     logging message facility
     '''
     l(self.line, retcode, msg, log_level)
     Sessions.Instance().insert_table_commands(
         self.line,  # @UndefinedVariable
         msg,
         retcode,
         log_level)
示例#9
0
class Feeder(object):
    def __init__(self, url):
        self.timer = Timer(Config.request_interval, self.task)
        self.sessions = Sessions()
        self.url = url
        self.timestamp = int(time.time())
        self.start()

    def __del__(self):
        self.stop()

    def start(self):
        self.timer.start_timer()

    def stop(self):
        self.timer.cancel_timer()

    def done(self):
        return Config.number_requests == self.sessions.completed and (
            not self.sessions.pending)

    def encode(self, body):
        return zlib.compress(body.encode('utf-8'))

    def task(self):
        if self.sessions.completed < Config.number_requests:
            self.send()
        else:
            self.stop()

    def send(self):
        index = self.sessions.completed
        body = "metric=metrics-sla  %d %d" % (index,
                                              int(self.timestamp + index))
        logger.debug("sending request %s ", body)
        self.sessions.add(index, body)
        response = requests.post(self.url,
                                 data=self.encode(body),
                                 headers=Config.headers)
        self.sessions.delete(index)
        logger.info("finishing request %s with %s", body, str(response))
示例#10
0
    def _check_for_auth(self):
        session_ = flask_session['session']
        uid = Sessions.check(session_)
        if uid is None:
            raise Exception('no such session!')
        user = session.query(Users).filter(Users.id == uid).first()
        if user is None:
            raise Exception('no such user!')
        try:
            user.lastupdate = datetime.datetime.now()
            session.add(user)
            session.commit()
        except Exception as err:
            logging.error('Error on save user last update: %s' % err)

        self.request.user = user
        self.request.session = session_
示例#11
0
def addsessions(username):
    sessionobj = Sessions(username)
    sessionadded = sessionobj.addsession()
    resp = make_response(jsonify(status='success'), 200)
    return resp
class Monitor(object):

    def __init__(self, url, access_id, access_key):
        self.timer = Timer(Config.request_interval, self.task)
        self.sessions = Sessions()
        self.performance = Performance()
        self.url = url + Config.endpoint
        self.auth = (access_id, access_key)
        self.timestamp = int(time.time())
        self.start()

    def __del__(self):
        self.stop()

    def start(self):
        self.timer.start_timer()

    def stop(self):
        self.timer.cancel_timer()

    def done(self):
        return Config.number_requests == self.sessions.completed and (not self.sessions.pending)

    def build_body(self, start_time, end_time):
        return '{"%s":[{"%s":"%s","%s":"%s"}],"%s": %d,"%s":%d, "%s": %d, "%s": %d}' % \
               (Header.query, Header.query,
                Config.metric_query,
                Header.row_id, Config.row_id,
                Header.start_time, start_time,
                Header.end_time, end_time,
                Header.requested_data_points, Config.requested_data_points,
                Header.max_data_points, Config.max_data_points)

    def task(self):
        if self.sessions.completed < Config.number_requests:
            self.send()
        else:
            self.stop()

    def query(self, time_range):
        index = Index(self.sessions.completed, time_range)
        end_time = int(self.timestamp + self.sessions.completed) * 1000
        body = self.build_body(end_time - time_range, end_time)
        logger.debug("sending request %s ", body)
        self.sessions.add(index, body)
        perf_start = time.time()
        response = requests.post(self.url, data=body, headers=Config.query_headers, auth=self.auth)
        perf_end = time.time()
        results = response.json()
        try:
            data_points = results['response'][0]['results'][0]['datapoints']['value']
            quantization = results['queryInfo']['actualQuantizationInSecs']
        except Exception as e:
            logger.warning("Metrics sla monitor query exception %s" % str(e))
            data_points = []
            quantization = 1

        query = Query(perf_start, perf_end, body, time_range, data_points, quantization)
        self.performance.add_query(index, query)

        self.sessions.delete(index)
        logger.debug("finishing request (%d, %d) %s %s with %s in %f seconds", index.index, index.time_range, str(Config.query_headers), body, str(response), (perf_end - perf_start))

    def send(self):
        logger.debug("sending request with time_ranges %s", str(Config.query_ranges))
        self.sessions.complete()
        for time_range in Config.query_ranges:
            self.query(time_range)
        logger.debug("finishing request with time_ranges %s", str(Config.query_ranges))
示例#13
0
 def dispatch(self, *args, **kwargs):
     Sessions().delete(self.request.user.id)
     return Response(redirect(url_for('admin:login')))
示例#14
0
settings = dict(
    MOTOR_URI='mongodb://*****:*****@app.middleware('request')
async def add_session(request):
    request['session'] = session


app.config.AUTH_LOGIN_URL = '/Signin'
auth = Sessions(app)

from beacons.controllers.login import login_page
from beacons.controllers.map import map_page
from beacons.controllers.beacon import beacon_page
from beacons.controllers.photo_controller import photo_page

app.blueprint(login_page)
app.blueprint(map_page)
app.blueprint(beacon_page)
app.blueprint(photo_page)
def main(argv):
    URL = "https://xx-csa.bbcollab.com"
    
    COMMAND = ''
    ALL = False
    AUTH = False
    SESSION = False
    RECORDING = False
    CONTEXT = False
    USER = False
    CLEANUP = False

    usageStr = "\nCollabRestDemo.py -t|--target <target root URL> -c|--command <command>\n"
    usageStr += "e.g CollabRestDemo.py -t www.collabserver.com -c authorize."

    if len(sys.argv) > 1: #there are command line arguments
        try:
            opts, args = getopt.getopt(argv,"ht:c:",["target=","command="])
        except getopt.GetoptError:
            print (usageStr)
            sys.exit(2)
        for opt, arg in opts:
            if opt == '-h':
                print (usageStr)
                sys.exit()
            elif opt == '-d':
                print ("Deleting at end of run.")
                CLEANUP = True
            elif opt in ("-t", "--target"):
                URL = arg.lstrip()
            elif opt in ("-c", "--command"):
                COMMAND = arg
            else:
                COMMAND = "Run All"
        print ('[main] Target is:', URL)
        print ('[main] Command is:', COMMAND)


    else:
        print(usageStr)
        sys.exit(2)


    #Set up some booleans for processing flags and order of processing
    if "context" in COMMAND:
        print("[main] Run context command")
        CONTEXT = True
    elif "user" in COMMAND:
        print("[main] Run user command")
        USER = True
    elif "recording" in COMMAND:
        print("[main] Run recording command")
        RECORDING = True
    elif "session" in COMMAND:
        print("[main] Run session command")
        SESSION = True
    elif "authorize" in COMMAND:
        print("[main] Run authorization command")
        AUTH = True
    else:
        print("[main] Empty Command: Run All\n")
        ALL = True


    print ('\n[main] Acquiring auth token...\n')
    authorized_session = AuthToken(URL)
    authorized_session.setToken()
    print ('\n[main] Returned token: ' + authorized_session.getToken() + '\n')
    
    if not AUTH:
        #run commands in required order if running ALL
        if USER or ALL:
            user_object = Users(URL, authorized_session.getToken())
            #process user command
            print("\n[main] Run user command: " + ('ALL' if ALL else COMMAND) + '...')
            
            user_object.getUsers(authorized_session.getToken())
            user_object.createUser(authorized_session.getToken())
            user_object.patchUser(authorized_session.getToken())
            user_object.putUser(authorized_session.getToken())
            user_object.getUser(authorized_session.getToken())
            
        if SESSION or ALL:
            #process Sessions command
            print("\n[main] Run sessions command: " + ('ALL' if ALL else COMMAND) + '...')
            session_object = Sessions(URL, authorized_session.getToken())
            
            session_object.getSessions(authorized_session.getToken())
            session_object.createSession(authorized_session.getToken())
            session_object.patchSession(authorized_session.getToken())
            session_object.putSession(authorized_session.getToken())
            session_object.getSession(authorized_session.getToken())
            session_object.getInstances(authorized_session.getToken())
            session_object.enrollModerator(user_object.getUserId(),authorized_session.getToken())
            session_object.readModeratorUrl(authorized_session.getToken())
                
        if RECORDING or ALL:
            #process Recordings command
            print("\n[main] Run recording_object command: " + ('ALL' if ALL else COMMAND) + '...')
            recording_object = Recordings(URL, authorized_session.getToken())
            
            recording_object.getRecordings(authorized_session.getToken())

        if CONTEXT or ALL:
            #process course command
            print("\n[main] Run Context command: " + ('ALL' if ALL else COMMAND) + '...')
            context_object = Contexts(URL, authorized_session.getToken())
                            
            context_object.getContexts(authorized_session.getToken())

    #clean up if not using individual commands
    if ALL:
        print('\n[main] Completing Demo and deleting created objects...')
        #print ("[main] Deleting Session")
        session_object.deleteSession(authorized_session.getToken())
        print ("[main] Deleting User")
        user_object.deleteUser(authorized_session.getToken())
    else:
        print("\nRemember to delete created demo objects!")


    print("[main] Processing Complete")
示例#16
0
def main():
    # check '~/.pyraxshell' and config files exist, create them if missing
    if not check_dir_home():
        print("This is the first time 'pyraxshell' runs, please, configure "
              "'%s' according to your needs" % CONFIG_FILE)
        #create db
        DB()
        Sessions.Instance().create_table_sessions()  # @UndefinedVariable
        Sessions.Instance().create_table_commands()  # @UndefinedVariable
        # create default configuration file
        Configuration.Instance()  # @UndefinedVariable
        sys.exit(0)

    # ########################################
    # VERSION CHECK
    if not version.check_version_file():
        sys.exit(1)

    # ########################################
    # LOGGING
    start_logging()
    logging.debug('starting')

    #     from baseconfigfile import BaseConfigFile
    #     bcf = BaseConfigFile()

    # ########################################
    # ACCOUNTS
    accounts = Account.Instance()  # @UnusedVariable @UndefinedVariable

    # config file is read by 'BaseConfigFile' constructor
    # ########################################
    # CONFIGURATION
    cfg = Configuration.Instance()  # @UndefinedVariable
    # override settings with CLI params
    cfg.parse_cli(sys.argv)
    logging.debug("configuration: %s" % cfg)

    # set user's log level if specified
    if not Configuration.Instance().log_level == None:  # @UndefinedVariable
        l = logging.getLogger()
        for h in l.handlers:
            h.setLevel(cfg.log_level)

    # ########################################
    # START SESSION
    Sessions.Instance().start_session()  # @UndefinedVariable
    #     Sessions.Instance().insert_table_commands('IN', 'OUT')  # @UndefinedVariable

    # ########################################
    # DO STUFF
    # handle configuration
    if cfg.pyrax_http_debug == True:
        pyrax.set_http_debug(True)
    if cfg.pyrax_no_verify_ssl == True:
        # see: https://github.com/rackspace/pyrax/issues/187
        pyrax.set_setting("verify_ssl", False)
    # start notifier
    Notifier().start()
    # main loop
    Cmd_Pyraxshell().cmdloop()
示例#17
0
from sessions import Sessions
import pprint

pp = pprint.PrettyPrinter(indent=4)
s = Sessions()
pp.pprint(s.get_session(148).get_session_mps())
示例#18
0
def test_disconnect():
    print(f'Client disconnected {request.sid}')
    session_del = Sessions.delsession(request.sid)
    print(f'a delete {session_del}')
    emit('sessiondel', session_del, include_self=False, broadcast=True)
示例#19
0
 def __init__(self, url):
     self.timer = Timer(Config.request_interval, self.task)
     self.sessions = Sessions()
     self.url = url
     self.timestamp = int(time.time())
     self.start()
示例#20
0
def getsession(username):
    sessionobj = Sessions(username)
    onlinesessions = sessionobj.readsession()
    resp = make_response(jsonify(sessions=onlinesessions), 200)
    return resp