Beispiel #1
0
 def switch_user_off(self):
     # todo 设置一个token.当开启自动计算时,自动计算token.否则需要手动提供token
     # 开启自动计算功能通过运行时修改配置达到-.-
     response = Response("switch user off")
     response.delete_cookie("god_token")
     response.delete_cookie("god_uid")
     return response
Beispiel #2
0
    def save_session(self, app: flask.Flask, session: StorageAccountSession, response: flask.Response) -> None:
        """
        Serializes the data to JSON, encrypts the data using AES
        and stores the encrypted data along with a verification tag to azure storage.
        Only stores the UUID of the table entry inside the session_cookie
        """

        domain = self.get_cookie_domain(app)
        path = self.get_cookie_path(app)
        if not session:
            if session.modified:
                self.storage.delete(session.sid)
            response.delete_cookie(app.session_cookie_name, domain=domain, path=path)
            return

        if session.modified:
            encryption_key = self.get_encryption_key_from_app_secret(app)
            self.storage.write(session.sid, dict(session), encryption_key)
        httponly = True
        secure = self.get_cookie_secure(app)
        samesite = self.get_cookie_samesite(app)
        if samesite is None:
            samesite = 'Lax'
        expires = self.get_expiration_time(app, session)
        response.set_cookie(app.session_cookie_name, session.sid, expires=expires, httponly=httponly, domain=domain,
                            path=path, secure=secure, samesite=samesite)
Beispiel #3
0
def delete_cookie():
    resp = Response("删除成功")
    #如果你要删除的 cookie 有域名限制  那么 你在删除cookie的时候也要加上 domain这个参数
    # resp.delete_cookie('username',domain=".jd.com")
    #如果你要删除的cookie 是 指定的 路径  那么 删除cookie的时候 也要加上 path参数
    resp.delete_cookie('username', path='/login/')
    return resp
Beispiel #4
0
def logout():
    """Handle logout requests

    Delete user's session entry in the sessions table
    Also, delete user's cookie whether session entry delete is successful or not
    Return 200 OK on success
    Otherwise, return 500 INTERNAL SERVER ERROR
    """
    DBSessionMaker = sessionmaker(bind=engine)
    db_session = DBSessionMaker()

    # Find and delete user's session entry in the session table
    try:
        cookie_sess_id = request.cookies.get('session')
        db_session.query(Sessions).filter(Sessions.id==cookie_sess_id).delete()
        db_session.commit()
        logout_resp = Response(status=200)
        logout_resp.delete_cookie('session')
        return logout_resp
    except Exception:
        db_session.rollback()

    # Delete user's cookie if something went wrong
    err_resp = Response(status=500)
    err_resp.delete_cookie('session')
    return err_resp
Beispiel #5
0
 def switch_user_off(self):
     # todo 设置一个token.当开启自动计算时,自动计算token.否则需要手动提供token
     # 开启自动计算功能通过运行时修改配置达到-.-
     response = Response('switch user off')
     response.delete_cookie('god_token')
     response.delete_cookie('god_uid')
     return response
Beispiel #6
0
def login():
    """Handle login requests

    On successfull login a session with a length of an hour should be generated.
    On failure an error should be thrown.
    """
    hasher = PasswordHasher()

    payload = request.json
    username = payload['user']
    password = payload['pass']

    DBSessionMaker = sessionmaker(bind=engine)
    db_session = DBSessionMaker()

    try:
        user = db_session.query(Users).get(username)
        hasher.verify(user.password, password)

        # If the hash parameters are out of date or the user update the hash
        # One example of an out of date parameter is a insufficient time cost
        if hasher.check_needs_rehash(user.password):
            user.password = hasher.hash(password)

        # calculate an expiration time one our from now
        expire = datetime.utcnow() + timedelta(hours=1)

        session_id = uuid.uuid4().hex

        user_session = Sessions(
            # This must be a uuid4 or large cryptographically secure random number
            # A other formats of UUID can have several bytes perdicted presenting
            # a potential brute forcing risk
            # This implimentation choice assumes CPython is being used.
            id=session_id,
            username=username,
            session_expire=expire
        )
        db_session.add(user_session)
        db_session.commit()

        auth_resp = Response(status=200)
        auth_resp.set_cookie('session', session_id)
        db_session.commit()
        return auth_resp

    # For security reasons only two responses may be provided
    # Thus errors do not need to be handled individually
    except Exception:
        db_session.rollback()

    # If we get to the end of this funtion something went wrong.
    # Thus make sure the user does not think they are logged in
    err_resp = Response(status=401)
    err_resp.delete_cookie('session')
    return err_resp
Beispiel #7
0
def test():
    # username = request.form['username']
    # password = request.form['password']
    cookie = request.cookies
    username2 = cookie.get("username")
    password2 = cookie.get("password")
    resp = Response("服务器返回信息")
    #设置cookie,
    resp.set_cookie('username', 'derek')
    resp.delete_cookie('username')
Beispiel #8
0
    def save_session(self, app: Flask, session: ServerSideSession,
                     response: Response) -> None:
        """This is called for actual sessions returned by :meth:`open_session`
        at the end of the request.  This is still called during a request
        context so if you absolutely need access to the request you can do
        that.
        """
        domain = self.get_cookie_domain(app)
        path = self.get_cookie_path(app)
        sid = session.sid
        saved_session = (self.orm_session.query(self.sql_session_model).filter(
            self.sql_session_model.session_id == sid).first())
        if not session:
            if session.modified:
                if saved_session:
                    self.orm_session.delete(saved_session)
                    self.orm_session.commit()
                response.delete_cookie(app.session_cookie_name,
                                       domain=domain,
                                       path=path)
            return

        if not self.should_set_cookie(app, session):
            return

        httponly = self.get_cookie_httponly(app)
        secure = self.get_cookie_secure(app)
        expires = self.get_expiration_time(app, session)

        val = self.serializer.dumps(dict(session))
        if saved_session:
            saved_session.data = val
            saved_session.expiry = expires
            self.orm_session.commit()
        else:
            new_session: UserSessionTableProtocol = self.sql_session_model(
                id=self.make_id(),
                session_id=session.sid,
                data=val,
                expires_at=expires)
            self.orm_session.add(new_session)
            self.orm_session.commit()

        session_id = session.sid
        response.set_cookie(
            app.session_cookie_name,
            session_id,
            expires=expires,
            httponly=httponly,
            domain=domain,
            path=path,
            secure=secure,
            samesite=current_app.config.get("SESSION_COOKIE_SAMESITE",
                                            "Strict"),
        )
def delete_cookie():
    """删除cookie"""
    key = request.args.get('key') or 'count'
    cookies = request.cookies
    print(cookies)
    response = Response()
    response.delete_cookie(key)
    response.set_data('request cookies:<br>' + str(request.cookies) +
                      '<br><br>' + 'response header:<br>' +
                      str(response.headers))
    return response
Beispiel #10
0
def quit():
    required = ['stuid']
    values = request.form
    if not all(k in values for k in required):
        return 'Missing values', 403
    stuid = values.get('stuid')
    c*k = request.cookies
    stuid = c*k.get("stuid")
    # cok_password = c*k.get('password')
    resp = Response(render_template("quit.html"))
    resp.delete_cookie("stuid")
    resp.delete_cookie("password")
    return resp
Beispiel #11
0
 def __new__(
     cls,
     resp: Response,
     status_code: int = 200,
     cookies: dict = {},
 ):
     for k, v in cookies.items():
         if v is None:
             resp.delete_cookie(k)
         else:
             d = k.split('_httponly')
             resp.set_cookie(d[0], v, httponly=bool(d[1:]))
     return super().__new__(tuple, (resp, status_code))
Beispiel #12
0
def slo():
    """
    Revokes the delivered access token. Logs out the user
    """
    if not request.referrer or request.host not in request.referrer:
        return redirect_to('/')

    log.info('Preparing to logging out: %s' % c.user)

    g = model.Group.get(session['organization_id'])
    org_url = url_for(host=request.host,
                      controller='organization',
                      action='read',
                      id=g.name,
                      qualified=True)

    org_url = str(org_url)

    if c.user:
        client = Clients.get_client(g)
        logout_url = client.end_session_endpoint

        redirect_uri = org_url + '/logout'

        # revoke the access token (https://doc.ozwillo.com/#1-revoke-known-tokens)
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        data = 'token=' + session.get('access_token')
        data += '&token_type_hint=access_token'
        client.http_request(client.revocation_endpoint,
                            'POST',
                            data=data,
                            headers=headers)

        # Invalidate the local session (https://doc.ozwillo.com/#2-invalidate-the-applications-local-session)
        id_token = session.get('id_token')
        session.invalidate()
        c.user = None
        c.userobj = None
        response = Response()
        for cookie in request.cookies:
            response.delete_cookie(cookie)

        # redirect to IDP logout (https://doc.ozwillo.com/#3-single-sign-out)
        logout_url += '?id_token_hint=%s&' % id_token
        logout_url += 'post_logout_redirect_uri=%s' % redirect_uri

        log.info('Redirecting user to: %s' % logout_url)

        return redirect_to(str(logout_url))
    return redirect_to(org_url)
def index():
    """创建返回对象"""
    res = Response("返回对象")
    """设置cookies
        max_age=None,   最大存活时间(s)
        expires=None,   通过datetime设置准确时间
        path="/",
        domain=None,    设置子域名的cookies
    """

    res.set_cookie('name', 'jack')
    """删除cookies"""
    res.delete_cookie("")

    return res
Beispiel #14
0
def login():
    if request.method == 'GET':
        print(request.method)
        res = Response(render_template('login.html'))
        ex = datetime(year=2020, month=1, day=1, hour=0, minute=0, second=0)
        res.set_cookie('username', 'zzw', expires=ex, max_age=10)
        res.delete_cookie()
        return res
    else:
        print(request.method)
        username = request.form.get('username')
        password = request.form.get('password')
        repeatpasswd = request.form.get('repeatpasswd')
        print(username, password, repeatpasswd)
        return 'success'
Beispiel #15
0
def del_info():
    required = ['stuid']
    values = request.form
    if not all(k in values for k in required):
        return 'Missing values', 403
    stuid = values.get('stuid')
    userdb.db_delete_user_info(stuid)
    stu_img_path = os.path.abspath(f'./static/vc_images/{stuid}_img.png')
    if os.path.exists(stu_img_path):
        os.remove(stu_img_path)
    resp = Response("<h1>delete success</h1>")
    resp.delete_cookie("stuid")
    gen_log.warning(
        f"学号 {stuid} ,通过浏览器删除了自己信息,时间为{datetime.datetime.now().strftime('%m/%d/%Y, %H:%M:%S')}"
    )
    return resp, 200
Beispiel #16
0
 def logout(self):
     log.info('Logging out user: %s' % session.get('user'))
     response = Response()
     session['user'] = None
     session.save()
     g = model.Group.get(session['organization_id'])
     for cookie in request.cookies:
         response.delete_cookie(cookie)
     if g:
         org_url = url_for(host=request.host,
                           controller='organization',
                           action='read',
                           id=g.name,
                           qualified=True)
         redirect_to(str(org_url))
     else:
         redirect_to('/')
Beispiel #17
0
def logout():
    eid = int(request.cookies.get('eID'))
    time = str(logged_in[eid])
    del logged_in[eid]
    print(logged_in)
    database.save_logout_info(eid, time)
    resp=Response()

    return redirect(url_for('index')), resp.delete_cookie("eID")
Beispiel #18
0
    def save_session(self, app: Flask, session: Session, response: Response):
        if session is None:
            # This should never be the case
            return
        domain = self.get_cookie_domain(app)
        path = self.get_cookie_path(app)
        if not session:
            # ``not session`` equates to an empty session
            if session.modified or not session.authenticated:
                # The session has been modified. This indicates, that
                # a session has been invalidated by deleting it or
                # removing authentication. Thus, we try to remove any
                # traces
                self._redis.delete(self.get_key(session.sid))
                response.delete_cookie(
                    app.session_cookie_name, domain=domain, path=path
                )
            return

        httponly = self.get_cookie_httponly(app)
        secure = self.get_cookie_secure(app)
        expires = self.get_expiration_time(app, session)
        samesite = self.get_cookie_samesite(app)

        raw_session = self._serializer.dumps(session)
        # ``setex`` is used to create an entry that expires
        self._redis.setex(
            name=self.get_key(session.sid),
            time=app.permanent_session_lifetime,
            value=raw_session,
        )
        sid_signed = self._signer.sign(session.sid)
        response.set_cookie(
            app.session_cookie_name,
            sid_signed,
            domain=domain,
            path=path,
            httponly=httponly,
            expires=expires,
            secure=secure,
            samesite=samesite,
        )
Beispiel #19
0
def COOKIE():
    # response = Response("设置cookie")
    # response.set_cookie("name", "laobian")
    """
    key, cookie的键
    value="",cookie的值
    max_age = None,cookie的寿命
    expires = None,cookie的过期时间
    path = "/", cookie在当前项目的作用域
    domain = None, cookie起作用的子域名
    """
    cookie = request.cookies.get("name")  #获取cookie
    print(cookie)
    response = Response("设置cookie")
    response.set_cookie("name", "laobian")
    response.delete_cookie("name")  #删除cookie

    # 设置session
    session["username"] = "******"  #设置session的值
    session.get("username")  #获取session
    del session["username"]  #删除session
    return "设置session"
Beispiel #20
0
def delete_cookie():
    response = Response('<b>范冰冰</b>')
    response.delete_cookie('user')
    return response
Beispiel #21
0
def delcookie():
    res = Response(response='删除cookie')
    res.delete_cookie(key='username')
    return res
Beispiel #22
0
def Logout():
    response = Response("")
    response.delete_cookie('refresh_token')
    return response
Beispiel #23
0
def logout():
    response = Response('用户注销')
    response.delete_cookie('user')
    return response
Beispiel #24
0
def del_cookie():
    html = render_template('js_cookie.html')
    response = Response(html) 
    response.delete_cookie('mooc')
    return response
Beispiel #25
0
def logout():
    resp = Response('', 200)
    resp.delete_cookie('token')
    return resp
Beispiel #26
0
 def delete(self):
     response = Response(None, 204)
     response.delete_cookie('access_token')
     return response
def del_cookie():
    resp = Response('删除Cookie')
    resp.delete_cookie('username')
    return resp
Beispiel #28
0
def logout(response: Response):
    response.delete_cookie(auth_cookie_name)
Beispiel #29
0
def delete_cookie():
    resp = Response("删除cookie")
    resp.delete_cookie('username')
    return resp
Beispiel #30
0
def del_cookie():
    resp = Response('aaa')
    resp.delete_cookie('cookie_key')
    return resp
Beispiel #31
0
def delete():
    req = Response('delect')
    req.delete_cookie('username')
    return req