Python flask.session.get() Examples

The following are 30 code examples of flask.session.get(). 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 File: oauth.py    From Penny-Dreadful-Tools with 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 File: auth.py    From Penny-Dreadful-Tools with 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 File: api.py    From Penny-Dreadful-Tools with 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 #4
Source File: service.py    From everyclass-server with 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 #5
Source File: service.py    From everyclass-server with 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 #6
Source File: api.py    From Penny-Dreadful-Tools with 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 #7
Source File: i18n.py    From video2commons with 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 #8
Source File: base_view.py    From PyOne with 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 #9
Source File: base_view.py    From PyOne with 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 #10
Source File: api.py    From Penny-Dreadful-Tools with 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 #11
Source File: views_api.py    From everyclass-server with 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 #12
Source File: views_api.py    From everyclass-server with 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 #13
Source File: views_api.py    From everyclass-server with 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 #14
Source File: __init__.py    From everyclass-server with 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 #15
Source File: views.py    From everyclass-server with 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 #16
Source File: views.py    From everyclass-server with 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 #17
Source File: genserv.py    From genmon with GNU General Public License v2.0 5 votes vote down vote up
def lowbandwidth():

    if HTTPAuthUser != None and HTTPAuthPass != None or LdapServer != None:
        if not session.get('logged_in'):
            return render_template('login.html')
        else:
            return app.send_static_file('index_lowbandwith.html')
    else:
        return app.send_static_file('index_lowbandwith.html')

#------------------------------------------------------------------------------- 
Example #18
Source File: api.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def intro() -> Response:
    return return_json(not request.cookies.get('hide_intro', False) and not auth.hide_intro()) 
Example #19
Source File: genserv.py    From genmon with GNU General Public License v2.0 5 votes vote down vote up
def root():

    if HTTPAuthUser != None and HTTPAuthPass != None or LdapServer != None:
        if not session.get('logged_in'):
            return render_template('login.html')
        else:
            return app.send_static_file('index.html')
    else:
        return app.send_static_file('index.html')

#------------------------------------------------------------------------------- 
Example #20
Source File: api.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def get(self) -> comp.Competition:
        lg = league.active_league(should_load_decks=True)
        pdbot = request.form.get('api_token', None) == configuration.get('pdbot_api_token')
        if not pdbot:
            lg.decks = [d for d in lg.decks if not d.is_in_current_run()]
        return lg 
Example #21
Source File: auth.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def discord_id() -> Optional[int]:
    return session.get('id') 
Example #22
Source File: api.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def get(self) -> Optional[Deck]:
        blob = league.random_legal_deck()
        if blob is None:
            APP.api.abort(404, 'No legal decks could be found')
            return None
        blob['url'] = url_for('deck', deck_id=blob['id'], _external=True)
        return blob 
Example #23
Source File: league.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def retire_deck() -> wrappers.Response:
    form = RetireForm(request.form, discord_user=session.get('id'))
    if form.validate():
        d = ds.load_deck(form.entry)
        ps.associate(d, session['id'])
        lg.retire_deck(d)
        return redirect(url_for('signup'))
    return make_response(retire(form)) 
Example #24
Source File: league.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def retire(form: Optional[RetireForm] = None, deck_id: int = None) -> str:
    if form is None:
        form = RetireForm(request.form, deck_id, session.get('id'))
    view = Retire(form)
    return view.page() 
Example #25
Source File: prepare.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def set_stars_and_top8(d: Deck) -> None:
    if d.finish == 1 and d.competition_top_n >= 1:
        d.top8_safe = '<span title="Winner">①</span>'
        d.stars_safe = '★★★'
    elif d.finish == 2 and d.competition_top_n >= 2:
        d.top8_safe = '<span title="Losing Finalist">②</span>'
        d.stars_safe = '★★'
    elif d.finish == 3 and d.competition_top_n >= 3:
        d.top8_safe = '<span title="Losing Semifinalist">④</span>'
        d.stars_safe = '★★'
    elif d.finish == 5 and d.competition_top_n >= 5:
        d.top8_safe = '<span title="Losing Quarterfinalist">⑧</span>'
        d.stars_safe = '★'
    else:
        d.top8_safe = ''
        if d.get('wins') is not None and d.get('losses') is not None:
            if d.wins - 5 >= d.losses:
                d.stars_safe = '★★'
            elif d.wins - 3 >= d.losses:
                d.stars_safe = '★'
            else:
                d.stars_safe = ''
        else:
            d.stars_safe = ''

    if len(d.stars_safe) > 0:
        d.stars_safe = '<span class="stars" title="Success Rating">{stars}</span>'.format(stars=d.stars_safe) 
Example #26
Source File: main.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def image(c: str = '') -> wrappers.Response:
    names = c.split('|')
    try:
        requested_cards = oracle.load_cards(names)
        path = image_fetcher.download_image(requested_cards)
        if path is None:
            raise InternalServerError(f'Failed to get image for {c}')
        return send_file(os.path.abspath(path)) # Send abspath to work around monolith root versus web root.
    except TooFewItemsException as e:
        logger.info(f'Did not find an image for {c}: {e}')
        if len(names) == 1:
            return redirect(f'https://api.scryfall.com/cards/named?exact={c}&format=image', code=303)
        return make_response('', 400) 
Example #27
Source File: main.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def export(deck_id: int) -> Response:
    d = ds.load_deck(deck_id)
    if d.is_in_current_run():
        if not session.get('admin') and (not auth.person_id() or auth.person_id() != d.person_id):
            abort(403)
    safe_name = deck_name.file_name(d)
    return make_response(mc.to_mtgo_format(str(d)), 200, {'Content-type': 'text/plain; charset=utf-8', 'Content-Disposition': 'attachment; filename={name}.txt'.format(name=safe_name)}) 
Example #28
Source File: auth.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def hide_intro() -> bool:
    return session.get('hide_intro', False) 
Example #29
Source File: auth.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def mtgo_username() -> Optional[str]:
    return session.get('mtgo_username') 
Example #30
Source File: genserv.py    From genmon with GNU General Public License v2.0 5 votes vote down vote up
def SaveSettings(query_string):

    try:

        # e.g. {'displayunknown': ['true']}
        settings = dict(parse_qs(query_string, 1))
        if not len(settings):
            # nothing to change
            return
        CurrentConfigSettings = ReadSettingsFromFile()
        with CriticalLock:
            for Entry in settings.keys():
                ConfigEntry = CurrentConfigSettings.get(Entry, None)
                if ConfigEntry != None:
                    ConfigFile = CurrentConfigSettings[Entry][6]
                    Value = settings[Entry][0]
                    Section = CurrentConfigSettings[Entry][7]
                else:
                    LogError("Invalid setting: " + str(Entry))
                    continue
                UpdateConfigFile(ConfigFile,Section, Entry, Value)
        Restart()
    except Exception as e1:
        LogErrorLine("Error Update Config File (SaveSettings): " + str(e1))

#---------------------MySupport::UpdateConfigFile-------------------------------
# Add or update config item