Exemplo n.º 1
0
    def _set_color_session(self, color, text, client, agent=None):
        """Since we can *paginate* the rendering, we need to store the already
        generated colors

        This method allows to store already generated colors in the session
        """
        sess = session._get_current_object()
        dic = {}
        if agent:
            if 'colors' in sess and agent in sess['colors']:
                dic[agent] = sess['colors'][agent]
            else:
                dic[agent] = {}
            dic[agent][client] = {
                'color': color,
                'text': text
            }
        else:
            dic[client] = {
                'color': color,
                'text': text
            }
        if 'colors' in sess:
            sess['colors'].update(dic)
        else:
            sess['colors'] = dic
Exemplo n.º 2
0
    def _session_protection_failed(self):
        sess = session._get_current_object()
        ident = self._session_identifier_generator()

        app = current_app._get_current_object()
        mode = app.config.get('SESSION_PROTECTION', self.session_protection)

        if not mode or mode not in ['basic', 'strong']:
            return False

        # if the sess is empty, it's an anonymous user or just logged out
        # so we can skip this
        if sess and ident != sess.get('_id', None):
            # Patching flask-login to use `strong` mode with permanent sessions
            # The terminology here is a bit misleading since permanent sessions
            # have an expiration date that could be 1 second.
            #
            # We're not using "remember" functionality so this change should
            # work for our use case.
            #
            # Old code `if mode == 'basic' and sess.permament:`
            if mode == 'basic':
                sess['_fresh'] = False
                session_protected.send(app)
                return False
            elif mode == 'strong':
                for k in SESSION_KEYS:
                    sess.pop(k, None)

                sess['_remember'] = 'clear'
                session_protected.send(app)
                return True

        return False
Exemplo n.º 3
0
    def _session_protection_failed(self):
        sess = session._get_current_object()
        ident = self._session_identifier_generator()

        app = current_app._get_current_object()
        mode = app.config.get('SESSION_PROTECTION', self.session_protection)

        if not mode or mode not in ['basic', 'strong']:
            return False

        # if the sess is empty, it's an anonymous user or just logged out
        # so we can skip this
        if sess and ident != sess.get('_id', None):
            if mode == 'basic' or sess.permanent:
                sess['_fresh'] = False
                session_protected.send(app)
                return False
            elif mode == 'strong':
                for k in SESSION_KEYS:
                    sess.pop(k, None)

                sess['remember'] = 'clear'
                session_protected.send(app)
                return True

        return False
Exemplo n.º 4
0
    def _session_protection(self):
        sess = session._get_current_object()
        ident = _create_identifier()

        app = current_app._get_current_object()
        mode = app.config.get("SESSION_PROTECTION", self.session_protection)

        # if there is no '_id', then take the current one for good
        if "_id" not in sess:
            sess["_id"] = ident

        # if the sess is empty, it's an anonymous user, or just logged out
        #  so we can skip this, unless 'strong' protection is active,
        #  in which case we need to double check for the remember me token
        check_protection = sess or mode == "strong"

        if check_protection and ident != sess.get("_id", None):
            if mode == "basic" or sess.permanent:
                sess["_fresh"] = False
                session_protected.send(app)
                return False
            elif mode == "strong":
                sess.clear()
                sess["remember"] = "clear"
                session_protected.send(app)
                return True

        return False
Exemplo n.º 5
0
def sign_in_newPage(to, params, error = None):

    if request.method == "POST":        
        error = check_user_info(request.form)
                    
    isLogin = len(session._get_current_object())
    if isLogin:
        isLogin = session[SessionResources().const.MEMBER_ID_INDEX]
    else:
        return render_template("signin.html")
    
    # params = {a:b, c:d}
    params = params[1:-1].encode('utf8').split(', ')
    tmp_params = params
    params = []
    
    for i in tmp_params:
        key, value = i.split(':')
        key = key.replace('\'', '')
        value = value.lstrip()
        
        if key == 'pageNum': key = 'page'
        
        params.append(key+'='+value)
    
    def getkey(item):
        return item.split('=')[0]
    
    params = sorted(params, key=getkey)
    params = '%26'.join(params) # %26 == &
    params = params.replace('u\'', '')
    params = params.replace('\'', '')
    
    return redirect(request.url_root+to+"%3F"+params) # %3F == ?
Exemplo n.º 6
0
 def _session_protection_failed(self):
     sess = session._get_current_object()
     ident = self._session_identifier_generator()
     if (sess and not (len(sess) == 1 and sess.get('csrf_token', None))
         ) and ident != sess.get('_id', None):
         return super()._session_protection_failed()
     return False
Exemplo n.º 7
0
def stripe_connect():
    # TODO :: Error responses need to be end user friendly
    usr = current_user._get_current_object()
    if not 'state' in request.args:
        return 'Unauthorized', 401
    csrf_token = request.args['state']
    if not current_app.csrf._get_token() == csrf_token:
        return 'Unauthorized', 401

    if 'code' in request.args:
        code = request.args['code']
        stripe_secret_key = current_app.config.get('STRIPE_SECRET_KEY')
        try:
            user.associate_stripe_authorization_code(usr, code,
                                                     stripe_secret_key)
        except PreviousStripeAssociationError:
            return 'Previous Stripe Connect account association found.', 409
        except ExternalAPIUsageError:
            return 'An internal error prevented your request from being completed.', 500
        except (ExternalAPIError, ExternalAPIUnavailableError):
            return 'An error occoured with an external service preventing your request from being completed.', 500

        sess = session._get_current_object()
        if sess['next']:
            url = sess['next']
            del sess['next']
            return redirect(url)

        return redirect(url_for('account.stripe_connect_success'))
    elif 'error' in request.args:
        # Redirect user to account for the connect denial in our analytics
        return redirect(url_for('account.stripe_connect_denied'))
Exemplo n.º 8
0
Arquivo: app.py Projeto: xulicny/POIT
def test_connect():
    global thread
    with thread_lock:
        if thread is None:
            thread = socketio.start_background_task(
                target=background_thread, args=session._get_current_object())
    emit('my_response', {'data': 'Connected', 'count': 0})
Exemplo n.º 9
0
Arquivo: app.py Projeto: xkassa/POIT
def test_connect():
    global thread
    with thread_lock:
        if thread is None:
            thread = socketio.start_background_task(
                target=background_thread, args=session._get_current_object())
            print('zaciatok spojenia')
Exemplo n.º 10
0
def stripe_connect():
    # TODO :: Error responses need to be end user friendly
    usr = current_user._get_current_object()
    if not 'state' in request.args:
        return 'Unauthorized', 401
    csrf_token = request.args['state']
    if not current_app.csrf._get_token() == csrf_token:
        return 'Unauthorized', 401

    if 'code' in request.args:
        code = request.args['code']
        stripe_secret_key = current_app.config.get('STRIPE_SECRET_KEY')
        try:
            user.associate_stripe_authorization_code(usr,
                                                     code,
                                                     stripe_secret_key)
        except PreviousStripeAssociationError:
            return 'Previous Stripe Connect account association found.', 409
        except ExternalAPIUsageError:
            return 'An internal error prevented your request from being completed.', 500
        except (ExternalAPIError, ExternalAPIUnavailableError):
            return 'An error occoured with an external service preventing your request from being completed.', 500

        sess = session._get_current_object()
        if sess['next']:
            url = sess['next']
            del sess['next']
            return redirect(url)

        return redirect(url_for('account.stripe_connect_success'))
    elif 'error' in request.args:
        # Redirect user to account for the connect denial in our analytics
        return redirect(url_for('account.stripe_connect_denied'))
Exemplo n.º 11
0
def handle_connect():
    session['START_EMISSION'] = 'NOT_SET'
    session['START_STORING'] = 'NOT_SET'
    global thread
    with thread_lock:
        if thread is None:
            thread = socketio.start_background_task(target=background_thread, args=session._get_current_object())
Exemplo n.º 12
0
    def _session_protection(self):
        sess = session._get_current_object()
        ident = _create_identifier()

        app = current_app._get_current_object()
        mode = app.config.get('SESSION_PROTECTION', self.session_protection)

        # if there is no '_id', that should just count as miss?
        # if '_id' not in sess:
        #     sess['_id'] = ident

        # if the sess is empty, it's an anonymous user, or just logged out
        #  so we can skip this, unless 'strong' protection is active,
        #  in which case we need to double check for the remember me token
        check_protection = sess or mode == 'strong'

        if check_protection and ident != sess.get('_id', None):
            if mode == 'basic' or sess.permanent:
                sess['_fresh'] = False
                session_protected.send(app)
                return False
            elif mode == 'strong':
                sess.clear()
                sess['remember'] = 'clear'
                session_protected.send(app)
                return True

        return False
Exemplo n.º 13
0
    def _session_protection_failed(self):
        sess = session._get_current_object()
        ident = self._session_identifier_generator()

        app = current_app._get_current_object()
        mode = app.config.get('SESSION_PROTECTION', self.session_protection)

        if not mode or mode not in ['basic', 'strong']:
            return False

        # if the sess is empty, it's an anonymous user or just logged out
        # so we can skip this
        if sess and ident != sess.get('_id', None):
            if mode == 'basic' or sess.permanent:
                sess['_fresh'] = False
                session_protected.send(app)
                return False
            elif mode == 'strong':
                for k in SESSION_KEYS:
                    sess.pop(k, None)

                sess['remember'] = 'clear'
                session_protected.send(app)
                return True

        return False
Exemplo n.º 14
0
def sign_in():
    '''
    @@ Success sign in flash
    
    When the page redirected from sign up page,
    It display flash message.    
    '''
        
    """ main page before sign in"""
    error = None
    if request.method == 'POST':       
        error = check_user_info(request.form)
                    
    isLogin = len(session._get_current_object())
    if isLogin:
        isLogin = session[SessionResources().const.MEMBER_ID_INDEX]
        memberIdIndex = session[SessionResources().const.MEMBER_ID_INDEX]
    else:
        memberIdIndex = None
        
    return render_template(HTMLResources().const.MAIN_HTML,
                           noticeRecords = select_notices(memberIdIndex,
                                                          isLogin),
                           topCoders = select_top_coder(),
                           error = error)
Exemplo n.º 15
0
def test_connect():

    # Have to get session object this way to pass to socketio bg thread
    sessionObject = session._get_current_object()

    global thread
    with thread_lock:
        if thread is None:
            thread = socketio.start_background_task(
                background_thread, session._get_current_object())

    if 'active_timer' not in sessionObject:
        session['active_timer'] = None

    print("SessionTimerID: " + str(sessionObject['active_timer']))
    emit('connect_response', {'data': 'Connected',
                              'active_timer': sessionObject['active_timer']})
Exemplo n.º 16
0
def socketio(remaining):
    try:
        real_request = request._get_current_object()
        real_request.flask_session = session._get_current_object()
        socketio_manage(request.environ, {'/game': GameNamespace}, request=real_request)
    except:
        app.logger.error("Exception while handling socketio connect", exc_info=True)

    return Response()
Exemplo n.º 17
0
def socketio(remaining):
    try:
        real_request = request._get_current_object()
        real_request.flask_session = session._get_current_object()
        socketio_manage(request.environ, {'/game': GameNamespace},
                        request=real_request)
    except:
        app.logger.error("Exception while handling socketio connect",
                         exc_info=True)

    return Response()
Exemplo n.º 18
0
def activate(message):
    # create room for this activities timer
    join_room(message['room'])

    # save active timer info to current session
    session['active_timer'] = message['type'] + message['room']
    # session['active_timer_type'] =
    print("PREPARING TO ACTIVATE TIMER: {}".format(session['active_timer']))
    print("TIME DETAILS: {}".format(message))

    models = {'meal': Meal, 'sleep': Sleep, 'workout':
              Workout, 'weight': Weight, 'bloodpressure': BloodPressure,
              'bloodsugar': BloodSugar, 'heartrate': HeartRate}

    for key, model in models.items():
        if key == message['type']:
            # get activities current saved time from DB
            print("ACTIVATE %s TIMER" % key)
            activity = db_session.query(model).filter(
                model.id == message['room']).one()
            start_with_time = activity.duration.total_seconds()

    # elif message['type'] == 'sleep':
    #     print("ACTIVATE SLEEP TIMER")
    #     sleep = db_session.query(Sleep).filter(
    #         Sleep.id == message['room']).one()
    #     start_with_time = sleep.duration.total_seconds()

    print("START WITH TIME: {}".format(start_with_time))
    # start timer for activity
    print("Starting Timer...")
    global timerKey
    timerID = message['type'] + message['room']
    global timers
    timers = {timerID: Timer()}
    timers[timerID].start(start_with_time)

    print("Timer STARTED")
    print("activated TIMER: " + str(session['active_timer']))

    # start background websocket thread for active timer
    global thread
    with thread_lock:
        if thread is None:
            print("Background thread fire request...")
            thread = socketio.start_background_task(
                background_thread, session._get_current_object())

    # send response for log update
    emit('my_response',
         {'data': 'TIMER STARTED',
          'active_timer': session['active_timer']})
Exemplo n.º 19
0
def start_stop(message):
    global thread, flag
    #ak stlacim tlacidlo start, spustim background_thread
    if message['value'] == 'start':
        flag = 1
        with thread_lock:
            if thread is None:
                thread = socketio.start_background_task(
                    target=background_thread,
                    args=session._get_current_object())
    if message['value'] == 'stop':
        flag = 0
        thread = None
Exemplo n.º 20
0
    def _get_color_session(self, client, agent=None):
        """Since we can *paginate* the rendering, we need to store the already
        generated colors

        This method allows to retrieve already generated colors if any
        """
        sess = session._get_current_object()
        if 'colors' in sess:
            colors = sess['colors']
            if agent and agent in colors:
                return colors[agent].get(client)
            elif not agent:
                return colors.get(client)
        return None
Exemplo n.º 21
0
    def _get_color_session(self, client, agent=None):
        """Since we can *paginate* the rendering, we need to store the already
        generated colors

        This method allows to retrieve already generated colors if any
        """
        sess = session._get_current_object()
        if "colors" in sess:
            colors = sess["colors"]
            if agent and agent in colors:
                return colors[agent].get(client)
            elif not agent:
                return colors.get(client)
        return None
Exemplo n.º 22
0
    def __init__(self, backends=None, name=None):
        sess = session._get_current_object()
        self.active = False
        self.authenticated = sess.get('authenticated', False)
        self.backends = backends
        self.name = name
        self.real = None

        for back in self.backends:
            u = back.user(self.name)
            res = u.get_id()
            if res:
                self.id = res
                self.active = True
                break
Exemplo n.º 23
0
    def __init__(self, backends=None, name=None):
        sess = session._get_current_object()
        self.active = False
        self.authenticated = sess.get('authenticated', False)
        self.backends = backends
        self.name = name
        self.real = None

        for back in self.backends:
            u = back.user(self.name)
            res = u.get_id()
            if res:
                self.id = res
                self.active = True
                break
Exemplo n.º 24
0
 def login(self, passwd=None):
     """See :func:`burpui.misc.auth.interface.BUIuser.login`"""
     if not self.real:
         self.authenticated = False
         for back in self.backends:
             u = back.user(self.name)
             res = u.get_id()
             if u.login(passwd):
                 self.authenticated = True
                 self.id = res
                 self.real = u
                 break
     elif self.real:  # pragma: no cover
         self.authenticated = self.real.login(passwd)
     sess = session._get_current_object()
     sess['authenticated'] = self.authenticated
     return self.authenticated
Exemplo n.º 25
0
 def login(self, passwd=None):
     """See :func:`burpui.misc.auth.interface.BUIuser.login`"""
     if not self.real:
         self.authenticated = False
         for back in self.backends:
             u = back.user(self.name)
             res = u.get_id()
             if u.login(passwd):
                 self.authenticated = True
                 self.id = res
                 self.real = u
                 break
     elif self.real:  # pragma: no cover
         self.authenticated = self.real.login(passwd)
     sess = session._get_current_object()
     sess['authenticated'] = self.authenticated
     return self.authenticated
Exemplo n.º 26
0
def json_url_validator():
    if 'form_json' not in session or \
       session['form_json'].get('validated', False):
        abort(403)

    v = session['form_json'].get('validator')

    if v is not None:
        if v > time() - 5:
            abort(429)
    else:
        session['form_json']['validator'] = time()

    validator = WebValidator(session._get_current_object(), 'form_json')
    return Response(utils.stream_with_ctx_and_exc(
        validator(session['form_json']['url'])
    ), mimetype="text/event-stream")
Exemplo n.º 27
0
def json_url_validator():
    if 'form_json' not in session or \
       session['form_json'].get('validated', False):
        abort(403)

    v = session['form_json'].get('validator')

    if v is not None:
        if v > time() - 5:
            abort(429)
    else:
        session['form_json']['validator'] = time()

    validator = WebValidator(session._get_current_object(), 'form_json')
    return Response(utils.stream_with_ctx_and_exc(
        validator(session['form_json']['url'])),
                    mimetype="text/event-stream")
Exemplo n.º 28
0
 def _session_protection(self):
     sess = session._get_current_object()
     ident = _create_identifier()
     if "_id" not in sess:
         sess["_id"] = ident
     elif ident != sess["_id"]:
         app = current_app._get_current_object()
         mode = app.config.get("SESSION_PROTECTION", self.session_protection)
         if mode == "basic" or sess.permanent:
             sess["_fresh"] = False
             session_protected.send(app)
             return False
         elif mode == "strong":
             sess.clear()
             sess["remember"] = "clear"
             session_protected.send(app)
             return True
     return False
Exemplo n.º 29
0
 def _session_protection(self):
     sess = session._get_current_object()
     ident = _create_identifier()
     if "_id" not in sess:
         sess["_id"] = ident
     elif ident != sess["_id"]:
         app = current_app._get_current_object()
         mode = app.config.get("SESSION_PROTECTION",
                               self.session_protection)
         if mode == "basic" or sess.permanent:
             sess["_fresh"] = False
             session_protected.send(app)
             return False
         elif mode == "strong":
             sess.clear()
             sess["remember"] = "clear"
             session_protected.send(app)
             return True
     return False
Exemplo n.º 30
0
    def _session_protection(self):
        sess = session._get_current_object()
        ident = _create_identifier()

        if '_id' not in sess:
            sess['_id'] = ident
        elif ident != sess['_id']:
            app = current_app._get_current_object()
            mode = app.config.get('SESSION_PROTECTION',
                                  self.session_protection)
            if mode == 'basic' or sess.permanent:
                sess['_fresh'] = False
                session_protected.send(app)
                return False
            elif mode == 'strong':
                sess.clear()
                sess['remember'] = 'clear'
                session_protected.send(app)
                return True
        return False
Exemplo n.º 31
0
    def _session_protection(self):
        sess = session._get_current_object()
        ident = _create_identifier()

        if '_id' not in sess:
            sess['_id'] = ident
        elif ident != sess['_id']:
            app = current_app._get_current_object()
            mode = app.config.get('SESSION_PROTECTION',
                                  self.session_protection)
            if mode == 'basic' or sess.permanent:
                sess['_fresh'] = False
                session_protected.send(app)
                return False
            elif mode == 'strong':
                sess.clear()
                sess['remember'] = 'clear'
                session_protected.send(app)
                return True
        return False
Exemplo n.º 32
0
    def _set_color_session(self, color, text, client, agent=None):
        """Since we can *paginate* the rendering, we need to store the already
        generated colors

        This method allows to store already generated colors in the session
        """
        sess = session._get_current_object()
        dic = {}
        if agent:
            if "colors" in sess and agent in sess["colors"]:
                dic[agent] = sess["colors"][agent]
            else:
                dic[agent] = {}
            dic[agent][client] = {"color": color, "text": text}
        else:
            dic[client] = {"color": color, "text": text}
        if "colors" in sess:
            sess["colors"].update(dic)
        else:
            sess["colors"] = dic
def unknown_error(error=None):
    from GradeServer.utils.utilArticleQuery import select_notices
    from GradeServer.utils.utilRankQuery import select_top_coder

    from GradeServer.resource.htmlResources import HTMLResources
    from GradeServer.resource.sessionResources import SessionResources

    #from GradeServer.GradeServer_logger import Log

    isLogin = len(session._get_current_object())
    if isLogin:
        isLogin = session[SessionResources().const.MEMBER_ID_INDEX]
        memberIdIndex = session[SessionResources().const.MEMBER_ID_INDEX]
    else:
        memberIdIndex = None

    return render_template(HTMLResources().const.MAIN_HTML,
                           noticeRecords=select_notices(
                               memberIdIndex, isLogin),
                           topCoders=select_top_coder(),
                           error=error)
Exemplo n.º 34
0
def reactivate_validator():
    if 'form_reactivate' not in session or \
       session['form_reactivate'].get('validated', False):
        abort(403)

    p = ISP.query.get(session['form_reactivate']['isp_id'])
    if not p:
        abort(403)

    v = session['form_reactivate'].get('validator')

    if v is not None:
        if v > time() - 5:
            abort(429)
    else:
        session['form_reactivate']['validator'] = time()

    validator = PrettyValidator(session._get_current_object(), 'form_reactivate')
    return Response(utils.stream_with_ctx_and_exc(
        validator(p.json_url, p.cache_info or {})
    ), mimetype="text/event-stream")
Exemplo n.º 35
0
    def _session_protection(self):
        sess = session._get_current_object()
        ident = self._session_identifier_generator()
        app = current_app._get_current_object()
        mode = app.config.get('SESSION_PROTECTION', self.session_protection)

        # 用了endpoint区别之后,不能直接 用sess来判断session有没有值
        # 用sess.get(self._get_endpoint + '_user_id',None) 来判断当前用户session标志存不存在
        if sess.get(self._get_endpoint + '_user_id', None) and ident != sess.get(self._get_endpoint + '_id', None):
            if mode == 'basic' or sess.permanent:
                sess[self._get_endpoint + '_fresh'] = False
                session_protected.send(app)
                return False
            elif mode == 'strong':

                for k in SESSION_KEYS:
                    sess.pop(self._get_endpoint + '_' + k, None)
                sess[self._get_endpoint + '_remember'] = 'clear'
                session_protected.send(app)
                return True
        return False
def unknown_error(error = None):    
    from GradeServer.utils.utilArticleQuery import select_notices
    from GradeServer.utils.utilRankQuery import select_top_coder
    
    from GradeServer.resource.htmlResources import HTMLResources
    from GradeServer.resource.sessionResources import SessionResources
    
    #from GradeServer.GradeServer_logger import Log
    
    isLogin = len(session._get_current_object())
    if isLogin:
        isLogin = session[SessionResources().const.MEMBER_ID_INDEX]
        memberIdIndex = session[SessionResources().const.MEMBER_ID_INDEX]
    else:
        memberIdIndex = None
        
    return render_template(HTMLResources().const.MAIN_HTML,
                           noticeRecords = select_notices(memberIdIndex,
                                                          isLogin),
                           topCoders = select_top_coder(),
                           error = error)
Exemplo n.º 37
0
    def _session_protection_failed(self):
        sess = session._get_current_object()
        ident = self._session_identifier_generator()
        mode = self._config['SESSION_PROTECTION']

        if not mode or mode not in ['basic', 'strong']:
            return False

        # if the sess is empty, it's an anonymous user or just logged out
        # so we can skip this
        if ident != session.get(self._config['SESSION_ID_KEY'], None):
            if mode == 'basic' or sess.permanent:
                sess[self._config['SESSION_FRESH_KEY']] = False
                return False
            elif mode == 'strong':
                for k in _SESSION_KEYS:
                    sess.pop(k, None)

                sess[self._config['COOKIE_SESSION_STATE_KEY']] = 'clear'
                return True

        return False
Exemplo n.º 38
0
    def _session_protection(self):
        sess = session._get_current_object()
        ident = _create_identifier()

        app = current_app._get_current_object()
        mode = app.config.get('SESSION_PROTECTION', self.session_protection)

        # if the sess is empty, it's an anonymous user or just logged out
        # so we can skip this

        if sess and ident != sess.get('_id', None):
            if mode == 'basic' or sess.permanent:
                sess['_fresh'] = False
                session_protected.send(app)
                return False
            elif mode == 'strong':
                sess.clear()
                sess['remember'] = 'clear'
                session_protected.send(app)
                return True

        return False
Exemplo n.º 39
0
def reactivate_validator():
    if 'form_reactivate' not in session or \
       session['form_reactivate'].get('validated', False):
        abort(403)

    p = ISP.query.get(session['form_reactivate']['isp_id'])
    if not p:
        abort(403)

    v = session['form_reactivate'].get('validator')

    if v is not None:
        if v > time() - 5:
            abort(429)
    else:
        session['form_reactivate']['validator'] = time()

    validator = PrettyValidator(session._get_current_object(),
                                'form_reactivate')
    return Response(utils.stream_with_ctx_and_exc(
        validator(p.json_url, p.cache_info or {})),
                    mimetype="text/event-stream")
Exemplo n.º 40
0
    def _session_protection(self):
        sess = session._get_current_object()
        ident = _create_identifier()

        app = current_app._get_current_object()
        mode = app.config.get('SESSION_PROTECTION', self.session_protection)

        # if the sess is empty, it's an anonymous user or just logged out
        # so we can skip this

        if sess and ident != sess.get('_id', None):
            if mode == 'basic' or sess.permanent:
                sess['_fresh'] = False
                session_protected.send(app)
                return False
            elif mode == 'strong':
                sess.clear()
                sess['remember'] = 'clear'
                session_protected.send(app)
                return True

        return False
Exemplo n.º 41
0
    def _session_protection(self):
        sess = session._get_current_object()
        ident = self._session_identifier_generator()

        app = current_app._get_current_object()
        mode = app.config.get("SESSION_PROTECTION", self.session_protection)

        # if the sess is empty, it's an anonymous user or just logged out
        # so we can skip this

        if sess and ident != sess.get("_id", None):
            if mode == "basic" or sess.permanent:
                sess["_fresh"] = False
                session_protected.send(app)
                return False
            elif mode == "strong":
                for k in SESSION_KEYS:
                    sess.pop(k, None)

                sess["remember"] = "clear"
                session_protected.send(app)
                return True

        return False
Exemplo n.º 42
0
    def _update_prefs(self):
        """update prefs"""
        args = self.parser.parse_args()
        sess = session._get_current_object()
        ret = {}
        req = MultiDict()
        for loc in ['values', 'json']:
            data = getattr(request, loc, None)
            if data:
                req.update(data)
        for key in args.keys():
            if key not in req:
                continue
            temp = args.get(key)
            if temp:
                if key == 'language':
                    self._user_language(temp)
                sess[key] = temp
            elif key in sess:  # pragma: no cover
                del sess[key]
            ret[key] = temp
            self._store_prefs(key, temp)

        return ret
Exemplo n.º 43
0
    def _session_protection(self):
        sess = session._get_current_object()
        ident = _create_identifier()

        app = current_app._get_current_object()
        mode = app.config.get("SESSION_PROTECTION", self.session_protection)

        # if the sess is empty, it's an anonymous user or just logged out
        # so we can skip this

        if sess and ident != sess.get("_id", None):
            if mode == "basic" or sess.permanent:
                sess["_fresh"] = False
                session_protected.send(app)
                return False
            elif mode == "strong":
                for k in SESSION_KEYS:
                    sess.pop(k, None)

                sess["remember"] = "clear"
                session_protected.send(app)
                return True

        return False
Exemplo n.º 44
0
    def _update_prefs(self):
        """update prefs"""
        args = self.parser.parse_args()
        sess = session._get_current_object()
        ret = {}
        req = MultiDict()
        for loc in ['values', 'json']:
            data = getattr(request, loc, None)
            if data:
                req.update(data)
        for key in args.keys():
            if key not in req:
                continue
            temp = args.get(key)
            if temp:
                if key == 'language':
                    self._user_language(temp)
                sess[key] = temp
            elif key in sess:  # pragma: no cover
                del sess[key]
            ret[key] = temp
            self._store_prefs(key, temp)

        return ret
Exemplo n.º 45
0
def logout():
    sess = session._get_current_object()
    if 'authenticated' in sess:
        sess.pop('authenticated')
    logout_user()
    return redirect(url_for('.home'))
Exemplo n.º 46
0
 def is_kvsession():
     return str(isinstance(session._get_current_object(), KVSession))
Exemplo n.º 47
0
 def _set():
     assert request.environ.has_key("beaker.session")
     assert isinstance(session._get_current_object(), SessionObject)
     session['key'] = "value"
     return "ok"
Exemplo n.º 48
0
def show_session():
    from flask.ext.kvsession import SessionID
    print '=== session created time:', SessionID.unserialize(session.sid_s).created
    print '=== session object', session._get_current_object()
    return json.dumps(dict(session), indent=4)
Exemplo n.º 49
0
 def wrapper(*args, **kwargs):
   admin = session._get_current_object().get('admin', None)
   if admin is None or admin not in app.config['ADMINISTRATORS']:
     return redirect(url_for('admin_login'))
   return f(*args, **kwargs)
Exemplo n.º 50
0
def stripe():
    sess = session._get_current_object()
    url = request.args.get('next', None)
    if url is not None:
        sess['next'] = url
    return render_template('account/stripe_connect.html')
Exemplo n.º 51
0
def stripe():
    sess = session._get_current_object()
    url = request.args.get('next', None)
    if url is not None:
        sess['next'] = url
    return render_template('account/stripe_connect.html')
Exemplo n.º 52
0
def setSessionInfo():
    sessioninfo = login_session._get_current_object()
    response = make_response(
        json.dumps(sessioninfo, 200))
    response.headers['Content-Type'] = 'application/json'
    return response
Exemplo n.º 53
0
 def wrapper(*args, **kwargs):
     if not session._get_current_object().get('sudo', False):
         abort(403)
     elif not session._get_current_object().get('oauth2_token', False):
         return redirect(url_for('login'))
     return f(*args, **kwargs)