Python flask.session.get() Examples

The following are 30 code examples of flask.session.get(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask.session , or try the search function .
Example #1
Source Project: Penny-Dreadful-Tools   Author: PennyDreadfulMTG   File: oauth.py    License: GNU General Public License v3.0 10 votes vote down vote up
def setup_session(url: str) -> None:
    discord = make_session(state=session.get('oauth2_state'))
    token = discord.fetch_token(
        TOKEN_URL,
        client_secret=OAUTH2_CLIENT_SECRET,
        authorization_response=url)
    session.permanent = True
    session['oauth2_token'] = token
    discord = make_session(token=session.get('oauth2_token'))
    user = discord.get(API_BASE_URL + '/users/@me').json()
    session['id'] = user['id']
    session['discord_id'] = user['id']
    session['discord_locale'] = user['locale']
    guilds = discord.get(API_BASE_URL + '/users/@me/guilds').json()
    wrong_guilds = False # protect against an unexpected response from discord
    session['in_guild'] = False
    session['admin'] = False
    session['demimod'] = False
    for guild in guilds:
        if isinstance(guild, dict) and 'id' in guild:
            if guild['id'] == configuration.get('guild_id'):
                session['admin'] = (guild['permissions'] & 0x10000000) != 0 # Check for the MANAGE_ROLES permissions on Discord as a proxy for "is admin".
                session['demimod'] = (guild['permissions'] & 0x20000) != 0 # Check for the "Mention @everyone" permissions on Discord as a proxy for "is demimod".
                session['in_guild'] = True
        else:
            wrong_guilds = True
    if wrong_guilds:
        logger.warning('auth.py: unexpected discord response. Guilds: {g}'.format(g=guilds)) 
Example #2
Source Project: Penny-Dreadful-Tools   Author: PennyDreadfulMTG   File: auth.py    License: GNU General Public License v3.0 8 votes vote down vote up
def login(p: person.Person) -> None:
    session['logged_person_id'] = p.id
    session['person_id'] = p.id
    session['mtgo_username'] = p.name
    session.permanent = True
    if p.locale != session.get('discord_locale'):
        person.set_locale(p.id, session.get('discord_locale')) 
Example #3
Source Project: everyclass-server   Author: everyclass   File: views.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def is_taking(cotc: Dict) -> bool:
    """检查当前用户是否选了这门课"""
    user_is_taking = False

    if session.get(SESSION_CURRENT_USER, None):
        # 检查当前用户是否选了这门课
        student = entity_service.get_student(session[SESSION_CURRENT_USER].identifier)
        for semester in sorted(student.semesters, reverse=True):  # 新学期可能性大,学期从新到旧查找
            timetable = entity_service.get_student_timetable(session[SESSION_CURRENT_USER].identifier, semester)
            for card in timetable.cards:
                if card.course_id == cotc["course_id"] and cotc["teacher_id_str"] == teacher_list_to_tid_str(
                        card.teachers):
                    user_is_taking = True
                    break
            if user_is_taking:
                break
    return user_is_taking 
Example #4
Source Project: everyclass-server   Author: everyclass   File: views.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def show_review(cotc_id: int):
    """查看某个教学班的评价"""
    cotc_id = int(cotc_id)

    review_info = CourseReview.get_review(cotc_id)
    avg_rate = review_info['avg_rate']
    reviews = review_info['reviews']

    cotc = COTeachingClass.get_doc(cotc_id)
    if not cotc:
        return render_template('common/error.html', message=MSG_404)

    if session.get(SESSION_CURRENT_USER, None) \
            and CourseReview.get_my_review(cotc_id=cotc_id, student_id=session[SESSION_CURRENT_USER].identifier):
        reviewed_by_me = True
    else:
        reviewed_by_me = False
    return render_template('course/review.html',
                           cotc=cotc,
                           count=review_info['count'],
                           avg_rate=avg_rate,
                           reviews=reviews,
                           user_is_taking=is_taking(cotc),
                           reviewed_by_me=reviewed_by_me) 
Example #5
Source Project: everyclass-server   Author: everyclass   File: __init__.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def init_plugins():
        """初始化日志、错误追踪、打点插件"""
        from everyclass.rpc import init as init_rpc
        from everyclass.common.flask import print_config

        # Sentry
        if plugin_available("sentry"):
            sentry.init_app(app=__app)
            sentry_handler = SentryHandler(sentry.client)
            sentry_handler.setLevel(logging.WARNING)
            logging.getLogger().addHandler(sentry_handler)

            init_rpc(sentry=sentry)
            logger.info('Sentry is inited because you are in {} mode.'.format(__app.config['CONFIG_NAME']))

        # metrics
        global statsd
        statsd = DogStatsd(namespace=f"{__app.config['SERVICE_NAME']}.{os.environ.get('MODE').lower()}",
                           use_default_route=True)

        init_rpc(logger=logger)

        print_config(__app, logger) 
Example #6
Source Project: everyclass-server   Author: everyclass   File: views_api.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def login():
    """登录并获得token

    可能的错误码:
    4000 用户名或密码错误
    4100 用户不存在
    4101 密码错误
    """
    username = request.form.get("username")
    password = request.form.get("password")
    if not username:
        return generate_error_response(None, api_helpers.STATUS_CODE_INVALID_REQUEST, "请填写用户名")
    if not password:
        return generate_error_response(None, api_helpers.STATUS_CODE_INVALID_REQUEST, "请填写密码")

    if not user_service.check_password(username, password):
        raise exceptions.WrongPassword
    return generate_success_response({"token": user_service.issue_token(username)}) 
Example #7
Source Project: everyclass-server   Author: everyclass   File: views_api.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def email_verification_check():
    """验证邮箱token

    错误码:
    4000 token缺失
    4102 用户已存在,token无效
    4103 token无效
    """
    # todo 这里发出去的邮箱里面的链接还是网页版的,要换一下

    email_token = request.args.get("token")
    if not email_token:
        return generate_error_response(None, api_helpers.STATUS_CODE_INVALID_REQUEST, "token参数缺失")
    request_id = user_service.register_by_email_token_check(email_token)
    session[SESSION_EMAIL_VER_REQ_ID] = request_id
    return generate_success_response(None) 
Example #8
Source Project: everyclass-server   Author: everyclass   File: views_api.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def email_verification():
    """邮件验证-设置密码

    错误码:
    4104 验证请求不存在(内部异常)
    4105 当前VerificationRequest的状态并非STATUS_TKN_PASSED(排除网络卡了导致客户端没收到响应其实已经注册成功的情况)
    4106 密码过弱
    """
    request_id = session.get(SESSION_EMAIL_VER_REQ_ID, None)
    if not request_id:
        return generate_error_response(None, api_helpers.STATUS_CODE_INVALID_REQUEST, "无效请求,请重新点击邮件中的链接")

    password = request.form.get("password")
    if not password:
        return generate_error_response(None, api_helpers.STATUS_CODE_INVALID_REQUEST, "请输入密码")

    username = user_service.register_by_email_set_password(request_id, password)
    return generate_success_response({"token": user_service.issue_token(username)}) 
Example #9
Source Project: everyclass-server   Author: everyclass   File: service.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def register_by_password_status_refresh(request_id: str) -> Tuple[bool, str, Optional[str]]:
    """通过教务密码注册-刷新状态,返回是否成功、auth message及学号/教工号(如果成功)"""
    req = VerificationRequest.find_by_id(uuid.UUID(request_id))
    if not req:
        raise IdentityVerifyRequestNotFoundError
    if req.method != "password":
        logger.warn("Non-password verification request is trying get status from password interface")
        raise IdentityVerifyMethodNotExpectedError
    if req.method == VerificationRequest.STATUS_PWD_SUCCESS:
        raise RequestIDUsed("Request ID is used and password is set. It cannot be reused.")

    # fetch status from everyclass-auth
    with tracer.trace('get_result'):
        rpc_result = Auth.get_result(str(request_id))

    if rpc_result.success:  # 密码验证通过,设置请求状态并新增用户
        verification_req = VerificationRequest.find_by_id(uuid.UUID(request_id))
        verification_req.set_status_success()

        add_user(identifier=verification_req.identifier, password=verification_req.extra["password"], password_encrypted=True)

        return True, "SUCCESS", verification_req.identifier
    else:
        # 如果不是成功状态则返回auth服务返回的message
        return False, rpc_result.message, None 
Example #10
Source Project: everyclass-server   Author: everyclass   File: service.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def get_visitors(identifier: str) -> List[Visitor]:
    result = visit_track.get_visitors(identifier)

    visitor_list = []
    for record in result:
        # query entity to get rich results
        # todo: entity add a multi GET interface to make this process faster when the list is long
        search_result = entity_service.search(record[0])
        if len(search_result.students) > 0:
            visitor_list.append(Visitor(name=search_result.students[0].name,
                                        user_type=USER_TYPE_STUDENT,
                                        identifier_encoded=search_result.students[0].student_id_encoded,
                                        last_semester=search_result.students[0].semesters[-1],
                                        visit_time=record[1]))
        elif len(search_result.teachers) > 0:
            visitor_list.append(Visitor(name=search_result.teachers[0].name,
                                        user_type=USER_TYPE_TEACHER,
                                        identifier_encoded=search_result.teachers[0].teacher_id_encoded,
                                        last_semester=search_result.teachers[0].semesters[-1],
                                        visit_time=record[1]))
    return visitor_list 
Example #11
Source Project: video2commons   Author: toolforge   File: i18n.py    License: GNU General Public License v3.0 6 votes vote down vote up
def getlanguage():
    """Get the user language."""
    gval = g.get('language', None)
    if gval:
        return gval

    for lang in [
        request.form.get('uselang'),
        request.args.get('uselang'),
        session.get('language'),
        request.accept_languages.best,
    ]:
        if lang and _islang(lang):
            break
    else:
        lang = 'en'

    g.language = lang

    return lang 
Example #12
Source Project: Penny-Dreadful-Tools   Author: PennyDreadfulMTG   File: api.py    License: GNU General Public License v3.0 6 votes vote down vote up
def upload() -> Response:
    error = validate_api_key()
    if error:
        return error
    match_id = int(request.form['match_id'])
    if match_id == 219603564:
        return return_json({'success': True}) # Prevent infinite 500 errors.
    if request.form.get('lines'):
        lines = request.form['lines']
        importing.import_log(lines.split('\n'), match_id)
    else:
        importing.import_from_pdbot(match_id)
    start_time = int(request.form['start_time_utc'])
    end_time = int(request.form['end_time_utc'])
    match.get_match(match_id).set_times(start_time, end_time)

    return return_json({'success': True}) 
Example #13
Source Project: Penny-Dreadful-Tools   Author: PennyDreadfulMTG   File: api.py    License: GNU General Public License v3.0 6 votes vote down vote up
def post_rule_update(rule_id: int = None) -> Response:
    if rule_id is not None and request.form.get('include') is not None and request.form.get('exclude') is not None:
        inc = []
        exc = []
        for line in cast(str, request.form.get('include')).strip().splitlines():
            try:
                inc.append(parse_line(line))
            except InvalidDataException:
                return return_json({'success':False, 'msg':f"Couldn't find a card count and name on line: {line}"})
            if not cs.card_exists(inc[-1][1]):
                return return_json({'success':False, 'msg':f'Card not found in any deck: {line}'})
        for line in cast(str, request.form.get('exclude')).strip().splitlines():
            try:
                exc.append(parse_line(line))
            except InvalidDataException:
                return return_json({'success':False, 'msg':f"Couldn't find a card count and name on line: {line}"})
            if not cs.card_exists(exc[-1][1]):
                return return_json({'success':False, 'msg':f'Card not found in any deck {line}'})
        rs.update_cards(rule_id, inc, exc)
        return return_json({'success':True})
    return return_json({'success':False, 'msg':'Required keys not found'}) 
Example #14
Source Project: Penny-Dreadful-Tools   Author: PennyDreadfulMTG   File: api.py    License: GNU General Public License v3.0 6 votes vote down vote up
def person_status() -> Response:
    username = auth.mtgo_username()
    r = {
        'mtgo_username': username,
        'discord_id': auth.discord_id(),
        'admin': session.get('admin', False),
        'demimod': session.get('demimod', False),
        'hide_intro': request.cookies.get('hide_intro', False) or auth.hide_intro() or username or auth.discord_id(),
        'in_guild': session.get('in_guild', False),
        }
    if username:
        d = guarantee_at_most_one_or_retire(league.active_decks_by(username))
        if d is not None:
            r['deck'] = {'name': d.name, 'url': url_for('deck', deck_id=d.id), 'wins': d.get('wins', 0), 'losses': d.get('losses', 0)} # type: ignore
    if r['admin'] or r['demimod']:
        r['archetypes_to_tag'] = len(deck.load_decks('NOT d.reviewed'))
    active_league = league.active_league()
    if active_league:
        time_until_league_end = active_league.end_date - datetime.datetime.now(tz=datetime.timezone.utc)
        if time_until_league_end <= datetime.timedelta(days=2):
            r['league_end'] = dtutil.display_time(time_until_league_end/datetime.timedelta(seconds=1), granularity=2)
    return return_json(r) 
Example #15
Source Project: PyOne   Author: abbeyokgo   File: base_view.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def web_console():
    g = proc.Group()
    action=request.args.get('action')
    allow_action=['UpdateFile','UploadDir','Upload']
    if action not in allow_action:
        return make_response('error')
    if action in ['UploadDir','Upload']:
        local=urllib.unquote(request.args.get('local'))
        remote=urllib.unquote(request.args.get('remote'))
        user=urllib.unquote(request.args.get('user'))
        cmd=["python","-u",os.path.join(config_dir,'function.py'),action,local,remote,user]
    elif action=='UpdateFile':
        type_=request.args.get('type')
        cmd=["python","-u",os.path.join(config_dir,'function.py'),'UpdateFile',type_]
    else:
        cmd=["python","-u",os.path.join(config_dir,'function.py'),action]
    p = g.run(cmd)
    def read_process():
        while g.is_pending():
            lines = g.readlines()
            for proc, line in lines:
                yield "data:" + line + "\n\n"
        yield "data:end\n\n"
    resp=Response(read_process(), mimetype= 'text/event-stream')
    return resp 
Example #16
Source Project: PyOne   Author: abbeyokgo   File: base_view.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def stream():
    cmd_dict={
        'upgrade':"cd {} && git pull origin master && bash update.sh".format(config_dir),
        'running_log':'tail -30f {}/logs/PyOne.{}.log'.format(config_dir,'running'),
        'error_log':'tail -30f {}/logs/PyOne.{}.log'.format(config_dir,'error')
    }
    command=cmd_dict[request.args.get('command')]
    def generate():
        popen=subprocess.Popen(command,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
        global _pid
        tc=TimeCalculator()
        _pid=popen.pid
        while not popen.poll():
            msg=popen.stdout.readline()
            if msg=='end':
                yield "data:end\n\n"
                break
            yield "data:" + msg + "\n\n"
            if tc.PassNow()>=3:
                time.sleep(1)
        yield "data:end\n\n"
    return Response(generate(), mimetype= 'text/event-stream') 
Example #17
Source Project: everyclass-server   Author: everyclass   File: web_helpers.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def login_required(func):
    """
    a decorator for routes which is only available for logged-in users.
    """

    @functools.wraps(func)
    def wrapped(*args, **kwargs):
        if not session.get(SESSION_CURRENT_USER, None):
            return render_template('common/error.html', message=MSG_NOT_LOGGED_IN, action="login")
        return func(*args, **kwargs)

    return wrapped 
Example #18
Source Project: everyclass-server   Author: everyclass   File: views_api.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def register_by_email():
    """通过邮箱验证注册

    错误码:
    4000 用户名未填写
    4102 已经注册过了
    5000 内部错误

    todo:加限流
    """
    identifier = request.args.get("identifier")
    if not identifier:
        return generate_error_response(None, api_helpers.STATUS_CODE_INVALID_REQUEST, "请填写用户名")
    user_service.register_by_email(identifier)
    return generate_success_response(None) 
Example #19
Source Project: everyclass-server   Author: everyclass   File: views_api.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def apply_grant():
    to_user_id_encoded = request.args.get('to_user_id')
    if not to_user_id_encoded:
        return generate_error_response(None, api_helpers.STATUS_CODE_INVALID_REQUEST, "mising to_user_id")

    to_uid = decrypt(to_user_id_encoded, resource_type=RTYPE_STUDENT)[1]

    user_service.new_grant_request(g.user_id, to_uid)
    return generate_success_response(None) 
Example #20
Source Project: everyclass-server   Author: everyclass   File: views.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def register_choice():
    """注册:第二步:选择注册方式"""
    if not session.get(SESSION_USER_REGISTERING, None):  # 步骤异常,跳回第一步
        return redirect(url_for('user.register'))
    return render_template('user/registerChoice.html') 
Example #21
Source Project: everyclass-server   Author: everyclass   File: views.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def register_by_email():
    """注册:第三步:使用邮箱验证注册"""
    if not session.get(SESSION_USER_REGISTERING, None):  # 步骤异常,跳回第一步
        return redirect(url_for('user.register'))

    identifier = session[SESSION_USER_REGISTERING].identifier

    try:
        request_id = user_service.register_by_email(identifier)
    except Exception as e:
        return handle_exception_with_error_page(e)
    else:
        return render_template('user/emailSent.html', request_id=request_id) 
Example #22
Source Project: everyclass-server   Author: everyclass   File: views.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def password_strength_check():
    """AJAX 密码强度检查"""
    if request.form.get("password", None):
        # 密码强度检查
        score = user_service.score_password_strength(request.form["password"])
        if score < 2:
            return jsonify({"strong": False,
                            "score": score})
        else:
            return jsonify({"strong": True,
                            "score": score})
    return jsonify({"invalid_request": True}) 
Example #23
Source Project: everyclass-server   Author: everyclass   File: views.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def register_by_password_status():
    """AJAX 刷新教务验证状态"""
    if not request.args.get("request", None) or not isinstance(request.args["request"], str):
        return "Invalid request"

    try:
        success, message, identifier = user_service.register_by_password_status_refresh(request.args.get("request"))

        if success:
            # write login state to session
            flash(MSG_REGISTER_SUCCESS)
            if SESSION_PWD_VER_REQ_ID in session:
                del session[SESSION_PWD_VER_REQ_ID]

            _set_current_user(identifier)  # potential uncaught error
            return jsonify({"message": "SUCCESS"})
        elif message in ("PASSWORD_WRONG", "INTERNAL_ERROR", "INVALID_REQUEST_ID"):
            return jsonify({"message": message})
        else:
            return jsonify({"message": "NEXT_TIME"})

    except everyclass.server.user.exceptions.IdentityVerifyRequestNotFoundError:
        return "Invalid request"
    except user_service.IdentityVerifyMethodNotExpectedError:
        return "Invalid request"
    except everyclass.server.user.exceptions.AlreadyRegisteredError:
        # 已经注册成功,但不知为何(可能是网络原因)进入了中间状态,没有执行下面的删除 session 的代码,并且用户刷新页面
        if SESSION_PWD_VER_REQ_ID in session:
            del session[SESSION_PWD_VER_REQ_ID]
        flash(MSG_ALREADY_REGISTERED)
        return redirect(url_for('user.login')) 
Example #24
Source Project: video2commons   Author: toolforge   File: i18n.py    License: GNU General Public License v3.0 5 votes vote down vote up
def urlget(lang):
    """Get the i18n of language lang and output Javascript."""
    data = 'window.i18n=' + json.dumps(get(lang)) + ';'
    return Response(data, mimetype='application/javascript; charset=utf-8') 
Example #25
Source Project: video2commons   Author: toolforge   File: i18n.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get(lang):
    """Get the i18n of language lang and output dict."""
    i18nkey = 'i18n:' + lang
    gval = g.get(i18nkey, None)
    if gval:
        return gval
    if redisconnection.exists(i18nkey):
        return json.loads(redisconnection.get(i18nkey))

    data = {}
    fallbacklist = _create_fallback(lang)
    datafiles = _loadi18nfiles(fallbacklist)
    for key in datafiles['en']:
        if key == '@metadata':
            # @metadata is a dict not a string
            continue

        for code in fallbacklist:
            if key in datafiles.get(code, {}):
                data[key] = datafiles[code][key]
                # <'s and >'s aren't supposed to be here;
                # if the translation breaks due to double escaping,
                # oh well, why are you hacking this tool?
                # --XSS prevention
                data[key] = data[key].replace('<', '&lt;')
                data[key] = data[key].replace('>', '&gt;')
                break
    data['@lang'] = lang
    data['@dir'] = _dir(lang)

    setattr(g, i18nkey, data)
    redisconnection.setex(i18nkey, 60, json.dumps(data))
    return data 
Example #26
Source Project: video2commons   Author: toolforge   File: i18n.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _create_fallback(lang):
    fallbacks = _loadmetadatafile('fallbacks').get(lang, [])
    fallbacks = fallbacks if isinstance(fallbacks, list) else [fallbacks]
    return [lang] + fallbacks + ['en'] 
Example #27
Source Project: video2commons   Author: toolforge   File: i18n.py    License: GNU General Public License v3.0 5 votes vote down vote up
def translate(key):
    """Translate a key in user language."""
    return get(getlanguage()).get(key, '&lt;' + key + '&gt;') 
Example #28
Source Project: video2commons   Author: toolforge   File: i18n.py    License: GNU General Public License v3.0 5 votes vote down vote up
def is_rtl(lang):
    """Jinja2 test for rtl-ness."""
    return get(lang).get('@dir') == 'rtl' 
Example #29
Source Project: gryphon   Author: BusinessOptics   File: app.py    License: MIT License 5 votes vote down vote up
def cluster_view(cluster_name):
    authorization_data = get_authorization()
    cluster = Cluster(name=cluster_name)
    return render_template(
        "cluster.html",
        cluster=cluster,
        auth_data=authorization_data,
        region=region,
        ssh_signature=session.get("ssh_signature", ""),
    ) 
Example #30
Source Project: gryphon   Author: BusinessOptics   File: app.py    License: MIT License 5 votes vote down vote up
def ssh_parameters():
    if request.method == "POST":
        if "save" in request.form:
            session["ssh_signature"] = request.form["signature"]

        return redirect(request.args.get("next", "/"))

    return render_template(
        "ssh_parameters.html",
        ssh_signature=session.get("ssh_signature", ""),
        region=region,
    )