コード例 #1
0
ファイル: main.py プロジェクト: FlamingCodes/OlympicsProject
def controllAuthification(): 
    user_type = "None"
    checkOk = False
    olympics = sqlite3.connect('olympic.db')
    user = str(request.get_cookie("user"))
    key = str(request.get_cookie("key"))
    print "user: "******", key: " + key
    query = "SELECT SECURITY_KEY FROM BENUTZER WHERE BENUTZERNAME = '" + user + "'"
    controll_key = olympics.execute(query).fetchone()
    print controll_key
    if controll_key == None or controll_key == "":
        logout()
    else:
        controll_key = str(controll_key[0])
        if key == controll_key:
            checkOk = True
            key = str(int(random.random()*1000000000))
            query = "UPDATE BENUTZER SET SECURITY_KEY = " + key + " WHERE BENUTZERNAME = '" + user + "'"
            olympics.execute(query)
            olympics.commit()
            result = olympics.execute("SELECT USER_TYPE FROM BENUTZER WHERE BENUTZERNAME = '" + user + "'").fetchone()
            response.set_cookie("key", key,path='/')
            if result != None:
                user_type = str(result[0])
            else:
                user_type = "None"
            print "user: "******", key: " + key + ", user_type: " + user_type
        else:
            logout()
            print "user: "******"None" + ", key: " + "None"
    olympics.close()
    return user_type
コード例 #2
0
def twittear():
    if request.get_cookie("access_token", secret='some-secret-key'):
      TOKENS["access_token"]=request.get_cookie("access_token", secret='some-secret-key')
      TOKENS["access_token_secret"]=request.get_cookie("access_token_secret", secret='some-secret-key')
      return template('twittear.tpl')  
    else:
      redirect('/menu')
コード例 #3
0
	def check_session(*args, **kwargs):
		# NOTE needs to be SSL since secure cookie.
		user = fetch_user( request.get_cookie('username') )
		session_id = request.get_cookie('session', secret=user.cookie_secret)
		if session_id != user.session_id:
			return 'IMPOSTER!!!' # and ask them to login
		return func(*args, **kwargs)
コード例 #4
0
ファイル: index.py プロジェクト: shellvon/whereismymoney
def get_week_cost_details(date):
    _format = '%Y%m%d'
    username = request.get_cookie('username')
    uid = request.get_cookie('uid', secret='somekey')
    start_time, end_time = get_week_range(date)
    prev = date + datetime.timedelta(-7)
    _next = date + datetime.timedelta(7)
    columns_charts_data = get_columns_chart_data(uid, start_time, end_time)
    line_charts_data, line_charts_url = get_line_chart_data(uid, start_time, end_time)
    pie_charts_data, pie_charts_name = get_pie_chart_data(uid, start_time, end_time)
    config_map = {
        'start_time': start_time.strftime('%Y年%m月%d日'),
        'end_time': end_time.strftime('%Y年%m月%d日'),
        'prev': prev.strftime(_format),
        'next': _next.strftime(_format),
        'username': username,
        'categories': get_week_dayname_lst(),
        'lineChartsName': u"'当日合计'",
        'lineChartsData': line_charts_data,
        'pieChartsName': pie_charts_name,
        'pieChartsData': pie_charts_data,
        'columnChartsData': columns_charts_data,
        'lineChartsDataUrl': line_charts_url,
        'columnChartsNames': get_type_name_map(),
    }
    return template('index.tpl', **config_map)
コード例 #5
0
ファイル: SSLServ.py プロジェクト: ticwith/Gamify
def incmon():
    checkCookieResult = Database.checkSession(request.get_cookie('userID'), request.get_cookie('sessionID'))
    if (checkCookieResult[0]):
        return noCacheStaticFileReponse('IncrementalMoney.htm')
    else:
        response.set_cookie('lastError', checkCookieResult[1])
        redirect(redirectFix('/Login.htm'))
コード例 #6
0
ファイル: anthracite-web.py プロジェクト: jjardel/anthracite
def notify_on_close(d):
    """ sends notification msg to Slack room"""

    # put auth key on scratch server
    with open('slack_config.private') as fp:
        settings = json.load(fp)
        auth_token = settings['auth_token']

    slack = Slacker(auth_token)
    room = '#datascience-robots'
    user = d['owner']
    if request.get_cookie("user"):
        user = request.get_cookie("user")

    attachments = [{
                "fallback": "Build Failure closed",
                "pretext": ' ',
                "title": "%s failure on %s resolved by %s" % (d['job'], d['host'], user),
                "text": 'resolution: %s' % d['resolution'],
                "color": "good"
    }]

    data = json.dumps(attachments)

    try:
        # notify room
        slack.chat.post_message(room, ' ', attachments=data, username='******')
    except:
        print "Failed to Nofity Slack room on event close"
コード例 #7
0
ファイル: index.py プロジェクト: gzb1985/fun_projects
    def login(cls):
        username = request.POST.get("username")
        password = request.POST.get("password")

        beaker_session = request.environ["beaker.session"]
        if checkUser(username, password) == True:
            beaker_session["cookies_value"] = username

            if request.get_cookie("cookies_value_client", username):

                if username == request.get_cookie("cookies_value_client", username):
                    beaker_session.save()
                    response.set_cookie("cookies_value_client", username)
                    return {"username": username}
                else:
                    beaker_session.save()
                    response.set_cookie("cookies_value_client", username)
                    return {"username": username}
                    # return template( 'static/view/index.html', username=username)
            else:
                beaker_session.save()
                response.set_cookie("cookies_value_client", username)
                return {"username": username}
                # return template('static/view/index.html', username=username)
        else:
            beaker_session = request.environ["beaker.session"]
            beaker_session.delete()
            return "no user"
コード例 #8
0
ファイル: controller.py プロジェクト: Kherdu/GIW
def viewPrestamo(prestamoId=0):
    
    if not request.get_cookie("userId"):
        response.set_cookie('err', 'Por favor, introduce tus datos para entrar')
        response.set_cookie('userId', '', expires=0)
        redirect("/logout")
        
    loans = prestamo.getLoanById(prestamoId)
    
    if len(loans) == 0:
        response.set_cookie('err', 'Prestamo no encontrado')
        redirect('/prestamos')
        return 0
    
    loan = loans[0]
    viewData = {'userType': 'logged',
                'title': 'Prestamo',
                'err': '',
                'succ': '',
                'prestamo': loan}
    
    if request.get_cookie("err"):
        viewData["err"] = request.get_cookie("err")
        response.set_cookie('err', '')
    
    if request.get_cookie("succ"):
        viewData["succ"] = request.get_cookie("succ")
        response.set_cookie('succ', '')
    
    return template('prestamo', data=viewData)
コード例 #9
0
ファイル: controller.py プロジェクト: Kherdu/GIW
def prestamos():
    
    if not request.get_cookie("userId"):
        response.set_cookie('err', 'Por favor, introduce tus datos para entrar')
        response.set_cookie('userId', '', expires=0)
        redirect("/logout")
        
    loans = prestamo.searchAllLoan()
    games = juego.searchAllGame()
    viewData = {'userType': 'logged',
                'title': 'Prestamos',
                'err': '',
                'succ': '',
                'prestamos': loans,
                'juegos': games}
    
    if request.get_cookie("err"):
        viewData["err"] = request.get_cookie("err")
        response.set_cookie('err', '')
    
    if request.get_cookie("succ"):
        viewData["succ"] = request.get_cookie("succ")
        response.set_cookie('succ', '')
    
    return template('prestamos', data=viewData)
コード例 #10
0
ファイル: views.py プロジェクト: minttu/short-piesome
def get_cookie(name, value):
    """Get a cookie or return the value. Expires the cookie if used"""
    if request.get_cookie(name):
        response.set_cookie(name, "", expires=0)
        return request.get_cookie(name)
    else:
        return value
コード例 #11
0
def search(ext: str=''):
    """ Search the bible and return a list of verses in the requested range.

    """

    # Get the search query and the min and max ranges.
    search_terms = request.query.get('search', '').strip()

    # Don't even search if there is nothing to search for.
    if not search_terms:
        return {'html': ''}

    # Get cookie values as fallbacks.
    min_range = json.loads(request.get_cookie('min_range', '"Genesis"'))
    max_range = json.loads(request.get_cookie('max_range', '"Revelation"'))

    # Get the other query strings.
    min_range = request.query.get('min_range', min_range).strip()
    max_range = request.query.get('max_range', max_range).strip()

    # Set the range cookies.
    response.set_cookie('min_range', json.dumps(min_range),
                        path='/biblesearch')
    response.set_cookie('max_range', json.dumps(max_range),
                        path='/biblesearch')

    # Get a list of verses.
    sorted_verse_list = do_search(search_terms, min_range, max_range)

    if ext == '.json':
        return {'references': sorted_verse_list}
    else:
        return build_page(sorted_verse_list, search_terms)
コード例 #12
0
ファイル: events.py プロジェクト: feisuzhu/thbattle
def speaker():
    idx = {
        k.split('_')[-1]: k for k in request.cookies
        if k.startswith(options.discuz_cookiepre)
    }

    if not ('auth' in idx and 'saltkey' in idx):
        response.status = 403
        return

    auth = unquote(request.get_cookie(idx['auth']))
    saltkey = unquote(request.get_cookie(idx['saltkey']))
    uid, pwd = Account.decode_cookie(auth, saltkey)
    user = Account.find(uid)
    if not user:
        return 'false'

    if user.jiecao < 0:
        return 'false'

    message = request.forms.get('message').decode('utf-8', 'ignore')
    username = user.username.decode('utf-8', 'ignore')

    interconnect.publish('speaker', [username, message])

    return 'true'
コード例 #13
0
def cookie():
	r  = """<html>\n"""
	r += """\t<head>\n"""
	r += '<script>\n'
	r += """var un = '""" + request.get_cookie('username','', secret='the sercet') + """';\n"""
	r += '</script>\n'
	r += """\t<script src='/js/google.js'></script>\n"""
	r += css()
	r += """\t</head>\n"""
	r += """\t<body>\n"""
	r += menu()
	r += '<a href="/counter_plaintext" >Counter Plain Text</a> | '
	r += '<a href="/delete_plaintext" >Delete Plain Text</a> | '
	counter_plaintext = request.get_cookie('counter_plaintext', '0')
	r += counter_plaintext + '<br>'
	r += '<a href="/counter_sercet" >Counter Sercet</a> | '
	r += '<a href="/delete_sercet" >Delete Sercet</a> | '
	counter_sercet = request.get_cookie('counter_sercet', '0', secret=secret)
	r += counter_sercet + '<br>'
	r += """ <p>[email protected]</p>\n """
	r += """ Log In """
	r += """<form action='http://""" + wwwport + """/do_login' method='post' >\n"""
	r += """Name:     <input type='text' name='username' value=""><br>\n"""
	r += """Password: <input type='password' name='password' value=""><br>\n"""
	r += """<input type='submit' value='Submit'>\n"""
	r += """</form>\n"""

	
	r += '<a href="/username" >Counter Username</a> | '
	r += '<a href="/delete_username" >Delete Username</a> |'
	u = request.get_cookie('username', '0', secret=secret)
	r += u + '<br>'
	r +=	'\t</body>\n'
	r += '</html>'
	return r
コード例 #14
0
ファイル: main.py プロジェクト: wwshen/OMOOC2py
def index():
	user = request.get_cookie('account', secret='somekey')
	conn = sqlite3.connect(stories)
	cc=conn.cursor()
	cc.execute("SELECT title, main FROM chains WHERE count=?", (0,))
	ALL = cc.fetchall()
	conn.commit()
	temallstory = root+'/allstory')
	output = template(temallstory, userid = user, rows = ALL, information='')
	if request.GET.get('save'):
		user = request.get_cookie('account',secret='somekey')
		if not users:
			output = template(temallstory, userid=user, rows = ALL, information='请登录')
		else:
			newtitle = unicode(request.GET.get('title'))
			conn = sqlite3.connect(stories)
			cc = conn.cursor()
			cc.execute("SELECT title FROM chains")
			AllTitle = cc.fetchall()
			conn.commit()	
			if checkdup(AllTitle, newtitle):
				output = template(temallstory, userid=user, rows = ALL, information='重名,请重新输入')
				return output
			else:
				newurl='/'+newtitle
				redirect (newurl)
	if request.GET.get('exit'):
		__exit()
	return output
コード例 #15
0
ファイル: screens.py プロジェクト: Xifax/suzu-web
def index():
    """Main page with random kanji"""
    lock = request.get_cookie("lock", secret="secret")
    session = request.environ.get("beaker.session")

    if lock:
        kanji = Peon(db).get(lock)
    else:
        kanji = Peon(db).random()

    favorites = request.get_cookie("favorites", secret="secret")
    fav = False
    if favorites:
        favorites = json.loads(favorites)
        if kanji.value in favorites:
            fav = True

    radicals = store.get_radicals(kanji.value)

    return render(
        "home",
        kanji=kanji,
        radicals=radicals,
        rad_info=store.get_info_for_all(radicals),
        lock=session.get("toggled", False),
        rolled=lock,
        fav=fav,
        single_item=False,
    )
コード例 #16
0
ファイル: events.py プロジェクト: AojiaoZero/thbattle
def speaker():
    idx = {
        k.split('_')[-1]: k for k in request.cookies
        if k.startswith(options.discuz_cookiepre)
    }

    if not ('auth' in idx and 'saltkey' in idx):
        response.status = 403
        return

    auth = unquote(request.get_cookie(idx['auth']))
    saltkey = unquote(request.get_cookie(idx['saltkey']))
    member = member_service.validate_by_cookie(auth, saltkey)
    if not member:
        return 'false'

    if member['credits'] < 10:
        return 'false'

    message = request.forms.get('message').decode('utf-8', 'ignore')
    username = member['username'].decode('utf-8', 'ignore')
    member_service.add_credit(member['uid'], 'credits', -10)

    Interconnect.publish('speaker', [username, message])

    return 'true'
コード例 #17
0
def lookup(ext=""):
    """ Lookup the verse reference and return the verse text and the verse text
    for all the verses in the requested context.

    """

    # Get the search_terms cookie as a fallback
    search_terms = json.loads(request.get_cookie("search_terms", '""'))

    # Get the context cookie as a fallback.
    context = json.loads(request.get_cookie("context", "0"))

    # Get the search terms, verse references, and context.
    search_terms = request.query.get("terms", search_terms).strip()
    verse_refs = request.query.get("verse_refs", "").strip()
    context = request.query.get("context", context, type=int)

    verse_refs = verse_refs.replace("+", " ")

    # Set the context cookie.
    response.set_cookie("context", json.dumps(context), path="/biblesearch")

    if ext == ".json":
        # Lookup the verses in verse_refs.
        lines = lookup_verses(verse_refs, search_terms, context)

        # Generate the result html.
        result_str = template("verses", output=lines)

        # Return json data to the javascript.
        return {"html": result_str}
    else:
        return build_page(make_valid(verse_refs), search_terms, context)
コード例 #18
0
ファイル: main.py プロジェクト: CSWANG/py_script
def restricted_area():
    username = request.get_cookie("username")
    username = request.get_cookie("account", secret=create_key(username))
    if username:
        return template(change(), username=username)
    else:
        return "You are not logged in. Access denied."
コード例 #19
0
def main():
    username = request.get_cookie("username", settings.cookie_secret)
    password = request.get_cookie("password", settings.cookie_secret)
    ok = api.check(username, password)
    if not ok:
        redirect("/login")
    meeting_list = api.meeting_list()

    owners = []
    for meeting in meeting_list:
        if username.lower() in settings.admins or username.lower() in meeting.get("moderator_users"):
            owners.append(meeting)
        is_running = api.is_running(meeting.get("id"))
        if is_running:
            meeting["status"] = "running"
        else:
            meeting["status"] = "stopped"

    if username.lower() in settings.admins:
        is_admin = True
        users = api.suggest("")
    else:
        is_admin = users = None
    message = request.params.get("message")
    return jinja2_template(
        "main.html",
        message=message,
        is_admin=is_admin,
        owners=owners,
        meeting_list=meeting_list,
        username=username,
        users=users,
    )
コード例 #20
0
def search(ext=""):
    """ Search the bible and return a list of verses in the requested range.

    """

    # Get the search query and the min and max ranges.
    search_terms = request.query.get("search", "").strip()

    # Don't even search if there is nothing to search for.
    if not search_terms:
        return {"html": ""}

    # Get cookie values as fallbacks.
    min_range = json.loads(request.get_cookie("min_range", '"Genesis"'))
    max_range = json.loads(request.get_cookie("max_range", '"Revelation"'))

    # Get the other query strings.
    min_range = request.query.get("min_range", min_range).strip()
    max_range = request.query.get("max_range", max_range).strip()

    # Set the range cookies.
    response.set_cookie("min_range", json.dumps(min_range), path="/biblesearch")
    response.set_cookie("max_range", json.dumps(max_range), path="/biblesearch")

    # Get a list of verses.
    sorted_verse_list = do_search(search_terms, min_range, max_range)

    if ext == ".json":
        return {"references": sorted_verse_list}
    else:
        return build_page(sorted_verse_list, search_terms)
コード例 #21
0
def chess_new(email = -1):
    r = ''
    r += '<html>\n'
    r += '<head>\n'
    r += '<script>\n'
    r += """var un = '""" + request.get_cookie('username','', secret='the sercet') + """';\n"""
    r += '</script>\n'
    r += '<script src="/js/google.js"></script>\n'
    r += '</head>\n'
    r += '<body>\n'

    if(email == 'error'):
        print('chess_new error')
        return 'chess_new error'
    else:
        r += """<form action='/chess/white/""" + email + """' >\n"""
        r += email +"""<button >White</button>"""
        r += """</form>\n"""

        u = request.get_cookie('username','', secret='the sercet')
        r += """<form action='/chess/black/""" + email + """' >\n"""
        r += u + """<button>Black</button>"""
        r += """</form>\n"""
		
    r += '</body>\n'
    r += '</html>'

    return r
コード例 #22
0
ファイル: kotodo.py プロジェクト: Irchiel/kotodo
def index():
    username = request.get_cookie('U', secret=secret())
    password = request.get_cookie('P', secret=secret())
    if check_user(username, password):
        return template('todo')
    else:
        return template('login', error=None)
コード例 #23
0
ファイル: hello4.py プロジェクト: jsjdesign/PCRHero
def badge_submit():
    if(request.get_cookie('loggedin')):
        useremail = request.get_cookie('loggedin', secret='applesauce')
        userbadges = m3.get_users_badges(pcrDB, useremail)
        issuers = m3.get_issuers(pcrDB)
        image_path = "/home/ubuntu/pythonproject/images"
        available_images = os.listdir(image_path)
        
        ## return args
        name = request.params.name
        if(m3.find_badge(pcrDB, name) != None):
            return template('base.tpl', title='PCR Hero', email= useremail) + '''\
                <h1>Welcome to PCR Hero's Admin Menu - {}</h1>
                <h2 style="color:red">A badge with that name already exists!</h2>
            '''.format(useremail) + template('admin-badge.tpl', badges=userbadges, issuers=issuers, images=available_images) + "</body>"

        else:
            description = request.params.description
            image = request.params.image
            criteria = request.params.criteria
            tags = request.params.tags
            issuer = request.params.issuer

            newBadge = m3.OpenBadge(name, description, image, criteria, tags, issuer)
            newBadge.establish_here()
            newBadge.add_badge(pcrDB)

            return template('base.tpl', title='PCR Hero', email= useremail) + '''\
                <h1>Welcome to PCR Hero's Admin Menu - {}</h1>
                <h2 style="color:blue">Your badge was successfully created!</h2>
            '''.format(useremail) + template('admin-badge.tpl', badges=userbadges, issuers=issuers, images=available_images) + "</body>"

    else:
        redirect("/login")
コード例 #24
0
ファイル: hello4.py プロジェクト: jsjdesign/PCRHero
def badge_award_submit():
    if(request.get_cookie('loggedin')):
        useremail = request.get_cookie('loggedin', secret='applesauce')
        badge_list = m3.get_badges(pcrDB) # list of all badges
        user_list = m3.get_users(pcrDB) # list of all users
        current_user = request.params.user
        current_user_badges = m3.get_users_badges(pcrDB, current_user)
        current_badge = request.params.badge
        ## check that the user doesn't already have the badge
        # if so, send back to the menu
        if(current_badge in current_user_badges):
             return template('base.tpl', title='PCR Hero', email= useremail) + '''\
                <h1>Welcome to PCR Hero's Admin Menu - {}</h1>
                <h2 style="color:red;">That user already has that badge!</h2>
            '''.format(useremail) + template('admin-award.tpl', badges=badge_list, users=user_list) + "</body>"           
        # if not, award the badge
        ## awarding badge magic
        else:
            m3.award_badge_to_user(pcrDB, current_badge, current_user)
        return template('base.tpl', title='PCR Hero', email= useremail) + '''\
            <h1>Welcome to PCR Hero's Admin Menu - {}</h1>
            <h2 style="color:blue;">Badge successfully awarded!<h2>
        '''.format(useremail) + template('admin-award.tpl', badges=badge_list, users=user_list) + "</body>"
    else:
        redirect("/login")
コード例 #25
0
ファイル: control.py プロジェクト: sim6/osmose-frontend
def update(lang):
    out = "Accept-Language: " + request.headers['Accept-Language'] + "\n"
    if request.get_cookie('lang'):
        out += "Cookie: " + request.get_cookie('lang') + "\n"
    out += "Chosen languages: " + (",".join(lang)) + "\n"
    response.content_type = "text/plain; charset=utf-8"
    return out
コード例 #26
0
    def get_language(self):
        lang = [None]

        # Remove old no longer used cookie 'lang'
        if request.get_cookie('lang'):
            response.delete_cookie('lang', path="/")

        if len(request.script_name) > 3:
            lang = [request.script_name[-3:-1], self.allowed_languages[0]]
            if lang[0] not in self.allowed_languages:
                lang = [None]
            else:
                return (lang, False)

        if not lang[0] and request.get_cookie('lang'):
            lang = [request.get_cookie('lang')]
            if lang[0] not in self.allowed_languages:
                lang = [None]

        if not lang[0] and request.get_header('Accept-Language'):
            lang = request.get_header('Accept-Language')
            lang = lang.split(',')
            lang = [x.split(";")[0] for x in lang]
            lang = [x.split("-")[0] for x in lang]
            lang = [x for x in lang if x in self.allowed_languages]

        if len(lang) > 0 and lang[0]:
            lang.append(self.allowed_languages[0])
            res = []
            for l in lang:
                if not l in res:
                    res.append(l)
            return (res, True)
        else:
            return (self.allowed_languages, True)
コード例 #27
0
ファイル: utils.py プロジェクト: Robbi373/pyload
def is_mobile():
    if request.get_cookie("mobile"):
        if request.get_cookie("mobile") == "True":
            return True
        else:
            return False
    mobile_ua = request.headers.get('User-Agent', '').lower()
    if mobile_ua.find('opera mini') > 0:
        return True
    if mobile_ua.find('windows') > 0:
        return False
    if request.headers.get('Accept', '').lower().find('application/vnd.wap.xhtml+xml') > 0:
        return True
    if re.search('(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|android)', mobile_ua) is not None:
        return True
    mobile_ua = mobile_ua[:4]
    mobile_agents = ['w3c ', 'acs-', 'alav', 'alca', 'amoi', 'audi', 'avan', 'benq', 'bird', 'blac', 'blaz', 'brew',
                     'cell', 'cldc', 'cmd-',
                     'dang', 'doco', 'eric', 'hipt', 'inno', 'ipaq', 'java', 'jigs', 'kddi', 'keji', 'leno', 'lg-c',
                     'lg-d', 'lg-g', 'lge-',
                     'maui', 'maxo', 'midp', 'mits', 'mmef', 'mobi', 'mot-', 'moto', 'mwbp', 'nec-', 'newt', 'noki',
                     'palm', 'pana', 'pant',
                     'phil', 'play', 'port', 'prox', 'qwap', 'sage', 'sams', 'sany', 'sch-', 'sec-', 'send', 'seri',
                     'sgh-', 'shar', 'sie-',
                     'siem', 'smal', 'smar', 'sony', 'sph-', 'symb', 't-mo', 'teli', 'tim-', 'tosh', 'tsm-', 'upg1',
                     'upsi', 'vk-v', 'voda',
                     'wap-', 'wapa', 'wapi', 'wapp', 'wapr', 'webc', 'winw', 'winw', 'xda ', 'xda-']
    if mobile_ua in mobile_agents:
        return True
    return False
コード例 #28
0
def lookup(ext: str=''):
    """ Lookup the verse reference and return the verse text and the verse text
    for all the verses in the requested context.

    """

    # Get the search_terms cookie as a fallback
    search_terms = json.loads(request.get_cookie('search_terms', '""'))

    # Get the context cookie as a fallback.
    context = json.loads(request.get_cookie('context', '0'))

    # Get the search terms, verse references, and context.
    search_terms = request.query.get('terms', search_terms).strip()
    verse_refs = request.query.get('verse_refs', '').strip()
    context = request.query.get('context', context, type=int)

    verse_refs = verse_refs.replace('+', ' ')

    # Set the context cookie.
    response.set_cookie('context', json.dumps(context), path='/biblesearch')

    if ext == '.json':
        # Lookup the verses in verse_refs.
        lines = lookup_verses(verse_refs, search_terms, context)

        # Generate the result html.
        result_str = template('verses', output=lines)

        # Return json data to the javascript.
        return {'html': result_str}
    else:
        return build_page(make_valid(verse_refs), search_terms, context)
コード例 #29
0
ファイル: controller.py プロジェクト: Kherdu/GIW
def viewGame(gameId=1):
    
    if not request.get_cookie("userId"):
        response.set_cookie('err', 'Por favor, introduce tus datos para entrar')
        response.set_cookie('userId', '', expires=0)
        redirect("/logout")
        return 0

    game = juego.getGameById(gameId)
    
    if len(game) == 0:
        response.set_cookie('err', 'Juego no encontrado')
        redirect('/juegos')
        return 0
    
    loans= prestamo.getLoansByGameId(gameId)
        
    viewData = {'userType': 'logged',
                'title': game[0]["nombre"],
                'err': '',
                'succ': '',
                'juego': game,
                'prestamos': loans}
    
    if request.get_cookie("err"):
        viewData["err"] = request.get_cookie("err")
        response.set_cookie('err', '')
    
    if request.get_cookie("succ"):
        viewData["succ"] = request.get_cookie("succ")
        response.set_cookie('succ', '')

    return template("juego", data=viewData)
コード例 #30
0
ファイル: boto.py プロジェクト: snag87/chatbot
def calc_response(user_message):
    user_message = user_message.lower()
    # make punctuation separate from the word, to assist with parsing
    user_message = user_message.replace("?", " ?")
    # convert the string into a list of words to assist with parsing
    words_in_message = user_message.split(" ")
    # check for curse words
    if set(CURSE_WORDS).intersection(words_in_message):
        return "no", "Please do not curse in front of me."
    # check if user wants a joke
    if set(["joke", "jokes"]).intersection(words_in_message):
        return "giggling", "I have a joke!\n" + funny_jokes[random.randint(0, len(funny_jokes) - 1)]
    if "name" in words_in_message and user_message.endswith("?"):
        return "laughing", "My name is Boto!"
    if user_message.endswith("?"):
        return "confused", parse_question(words_in_message)
    if "name" in words_in_message and "is" in words_in_message[words_in_message.index("name"):]:
        output = ""
        # assume the user name is right after the word "is", only if "is" follows "name"
        # this differentiates between "My name is Liron" and "What is your name?"
        user_name = words_in_message[words_in_message.index("is") + 1]
        response.set_cookie("user_name", user_name)
        add_to_stored_cookie_keys("user_name")
        if request.get_cookie("user_name"):
            output += "Your old username was: " + request.get_cookie("user_name") + ".\n"
        return "excited", output + "Welcome " + user_name
    elif user_message.endswith("!"):
        return "excited", "You sound excited, please tell me more."
    else:
        return "confused", "I'm sorry, I did not understand you."
コード例 #31
0
def start():
    currentPlayer = request.get_cookie("player")
    if currentPlayer:
        redirect("/games")
        return
    return {"version": utils.getVersion()}
コード例 #32
0
def play(game_id):
    currentPlayer = request.get_cookie("player")
    if not currentPlayer or not controller.gameExists(game_id):
        redirect("/start")
        return
    return {"version": utils.getVersion()}
コード例 #33
0
def games():
    currentPlayer = request.get_cookie("player")
    if not currentPlayer:
        redirect("/start")
        return
    return {"version": utils.getVersion(), "games": controller.listGames()}
コード例 #34
0
ファイル: run.py プロジェクト: hojen01/BDM-Project
def do_logout():
    session_uuid = request.get_cookie(SESSION_COOKIE_NAME)
    dEngine.delete_session(session_uuid)
    return fEngine.load_and_render("message",
                                   message="You have successfully logged out.")
コード例 #35
0
def create():
    controller.createGame(request.forms.get("name"), request.get_cookie("player"))
    redirect("/games")
コード例 #36
0
def hello_again():
    if request.get_cookie("visited"):
        return "Welcome back! Nice to see you again"
    else:
        response.set_cookie("visited", "yes")
        return "Hello there! Nice to meet you"
コード例 #37
0
ファイル: hello.py プロジェクト: jackrmanuel/ibm-hackathon
def logout():
    cardnumber = request.get_cookie("account", secret=COOKIESECRET)
    response.set_cookie("account", cardnumber, secret='')
    return '<meta http-equiv="refresh" content="2;url=/" />'
コード例 #38
0
def status(game_id):
    currentPlayerName = request.get_cookie("player")
    currentPlayerAvatar = db.getAvatar(currentPlayerName)
    print(currentPlayerAvatar['avatar'])
    gameStatus = controller.generateGameStatus(game_id, currentPlayerName, currentPlayerAvatar)
    return utils.jsonResponse(response, gameStatus)
コード例 #39
0
def app_html():
    token = request.get_cookie("login_token")
    if token not in login_tokens.keys():
        redirect("/login")
        return
    return static_file("index.html", os.getcwd() + "/frontend/")
コード例 #40
0
ファイル: category.py プロジェクト: Sokhavuth/kwblog
def delete(id):
  author = request.get_cookie("logged-in", secret=config.kargs['secretKey'])
  if ((author != "Guest") and categorydb.check(author)):
    categorydb.delete(id)

  redirect('/category')
コード例 #41
0
def logout():
    sid = request.get_cookie("user")
    delete_cookie(sid)
    return template("views/logout.html")
コード例 #42
0
def get_logged_in_user():
    token = request.get_cookie('token', secret=secret)
    if token is not None:
        return logged_in_users.get(token)
    return None
コード例 #43
0
 def get_cookie(self):
     uid_cookie = request.get_cookie(self.cookie_name)
     return uid_cookie
コード例 #44
0
ファイル: app.py プロジェクト: agaonker/bottle-presentation
    def wrapper(*args, **kwargs):
        username = request.get_cookie("account", secret=SUPER_SECRET)
        if username == USER:

            return callback(*args, **kwargs)
        redirect('/login')
コード例 #45
0
def isloggedin():
    cookie = request.get_cookie('sessionid', secret='password')
    return False if cookie is None else True
コード例 #46
0
def wrong():
    if request.get_cookie("wronged"):
       return "you have wronged twice. no redirect for you."
    response.set_cookie("wronged", "yes")
    redirect("/hello/errorer/2")
コード例 #47
0
def index():
    if request.get_cookie("is_admin", "0") == "0":
        response.set_cookie("is_admin", "0")
        return NOFLAG
    return FLAG
コード例 #48
0
ファイル: session.py プロジェクト: patcon/ticketfrei
 def wrapper(*args, **kwargs):
     uid = request.get_cookie('uid', secret=db.secret)
     if uid is None:
         return redirect(self.loginpage)
     kwargs[self.keyword] = User(uid)
     return callback(*args, **kwargs)
コード例 #49
0
def settings():
    if check_passwd(request.get_cookie("mdp")) == False:
        return template('authentification', get_url=app.get_url)
    return {'get_url': app.get_url}
コード例 #50
0
ファイル: pi3f_20_auth.py プロジェクト: azaroth42/pi3f
    def handle_GET(self, path):

        # First check auth
        if self.DEGRADE_IMAGES:
            isAuthed = request.get_cookie("loggedin", secret="abc-123-!@#")   
            authToken = request.headers.get('Authorization', '')
            hasToken = len(authToken) > 0
        else:
            isAuthed = True
            hasToken = True

        degraded = False

        # http://{server}{/prefix}   /{identifier}/{region}/{size}/{rotation}/{quality}{.format}
        bits = path.split('/')

        response['Access-Control-Allow-Origin'] =  '*'

        # Nasty but useful debugging hack
        if len(bits) == 1 and bits[0] == "list":
            return self.send(repr(self.identifiers), status=200, ct="text/plain");

        if bits:
            identifier = bits.pop(0)
            if identifier.endswith('-degraded'):
                undegraded = identifier.replace('-degraded', '')
                degraded = True
            else:
                undegraded = identifier

            if self.idRe.match(identifier) == None:
                return self.error_msg("identifier", "Identifier invalid: %r" % identifier, status=400)
            else:
                # Check []?#@ (will never find / )
                if self.badcharRe.match(identifier):
                    return self.error_msg('identifier', 'Unescaped Characters', status=400)                
                identifier = urllib.unquote(identifier)
                infoId = urllib.quote(identifier, '')
                filename = self.get_image_file(undegraded)
                if not filename:
                    return self.error_msg('identifier', 'Not found: %s' % identifier, status=404)          
        else:
            return self.error_msg("identifier", "Identifier unspecified", status=400)

        response['Link'] = '<%s>;rel="profile"' % self.compliance

        # Early cache check here
        fp = path
        if fp == identifier or fp == "%s/" % identifier:
            response.status = 303
            response['location'] = "%s%s/info.json" % (self.BASEPREF, infoId)
            return ""            
        elif len(fp) > 9 and fp[-9:] == "info.json":
            # Check request headers for application/ld+json
            inacc = request.headers.get('Accept', '')
            if inacc.find('ld+json'):
                mimetype = "application/ld+json"
            else:
                mimetype = "application/json"
        elif len(fp) > 4 and fp[-4] == '.':
            try:
                mimetype = self.extensions[fp[-3:]]
            except:
                # no such format, early break
                return self.error_msg('format', 'Unsupported format', status=400)

        if identifier.find('-degraded') == -1:
            if mimetype.endswith('json'):
                if not hasToken:
                    if self.DEGRADED_NOACCESS:
                        # No access is special degraded
                        return self.send_file(fp, mimetype, status=401)

                        # self.error_msg('auth', 'auth test', status=401)
                        # redirect('%sno-access/info.json' % BASEPREF)
                    else:
                        # Or restrict size to max edge of 400 as degradation   
                        redirect('%s%s-degraded/info.json' % (self.BASEPREF, identifier))
            elif not isAuthed:
                # Block access to images
                return self.error_msg('auth', 'Not authenticated', status=401)

        if os.path.exists(self.CACHEDIR + fp):
            # Will only ever be canonical, otherwise would redirect
            response['Link'] += ', <%s%s>;rel="canonical"' % (self.BASEPREF, fp)
            return self.send_file(fp, mimetype)                    
                    
        if bits:
            region = bits.pop(0)
            if self.regionRe.match(region) == None:
                # test for info.json
                if region == "info.json":
                    # build and return info
                    if inacc.find('ld+json'):
                        mt = "application/ld+json"
                    else:
                        mt = "application/json"
                    if not os.path.exists(infoId +'/'+region):
                        image = Image.open(filename)
                        self.make_info(infoId, image)
                        try:
                            image.close()
                        except:
                            pass
                    return self.send_file(infoId +'/' + region, mt)
                else:                
                    return self.error_msg("region", "Region invalid: %r" % region, status = 400)
        # else is caught by checking identifier in early cache check

        if bits:
            size = bits.pop(0)
            if self.sizeRe.match(size) == None:
                return self.error_msg("size", "Size invalid: %r" % size, status = 400)
        else:
            return self.error_msg("size", "Size unspecified", status=400)

        if bits:
            rotation = bits.pop(0)
            rotation = rotation.replace("%21", '!')
            m = self.rotationRe.match(rotation) 
            if m == None:
                return self.error_msg("rotation", "Rotation invalid: %r" % rotation, status = 400)
            else:
                mirror, rotation = m.groups()
        else:
            return self.error_msg("rotation", "Rotation unspecified", status=400)

        if bits:
            quality = bits.pop(0)
            dotidx = quality.rfind('.')
            if dotidx > -1:
                format = quality[dotidx+1:]
                quality = quality[:dotidx]
            else:
                return self.error_msg("format", "Format not specified but mandatory", status=400)               
            if self.qualityRe.match(quality) == None:
                return self.error_msg("quality", "Quality invalid: %r" % quality, status = 400)
            elif self.formatRe.match(format) == None:
                return self.error_msg("format", "Format invalid: %r" % format, status = 400)
        else:
            return self.error_msg("quality", "Quality unspecified", status=400)                

        # MUCH quicker to load JSON than the image to find h/w
        # Does json already exist?            
        if os.path.exists(self.CACHEDIR+infoId):
            # load JSON info file or image?
            fh = file(self.CACHEDIR + infoId +'/info.json')
            info = json.load(fh)
            fh.close()
            image = None
        else:
            # Need to load it up for the first time!     
            image = Image.open(filename)
            info = self.make_info(infoId, image)
        imageW = info['width']
        imageH = info['height']
                    
        # Check region
        if region == 'full':
            # full size of image
            x=0;y=0;w=imageW;h=imageH
        else:
            try:
                (x,y,w,h)=region.split(',')
            except:
                return self.error_msg('region', 'unable to parse region: %r' % region, status=400)
            if x.startswith('pct:'):
                x = x[4:]
                # convert pct into px
                try:
                    x = float(x) ; y = float(y) ; w = float(w) ; h = float(h)
                    x = int(x / 100.0 * imageW)
                    y = int(y / 100.0 * imageH)
                    w = int(w / 100.0 * imageW)
                    h = int(h / 100.0 * imageH)
                except:
                    return self.error_msg('region', 'unable to parse region: %r' % region, status=400)                     
            else:
                try:
                    x = int(x) ; y = int(y) ; w = int(w) ; h = int(h)
                except:
                    return self.error_msg('region', 'unable to parse region: %r' % region, status=400) 
                            
            if (x > imageW):
                return self.error_msg("region", "X coordinate is outside image", status=400)
            elif (y > imageH):
                return self.error_msg("region", "Y coordinate is outside image", status=400)
            elif w < 1:
                return self.error_msg("region", "Region width is zero", status=400)
            elif h < 1:
                return self.error_msg("region", "Region height is zero", status=400) 
            
            # PIL will create whitespace outside, so constrain
            # Need this info for next step anyway
            if x+w > imageW:
                w = imageW-x            
            if y+h > imageH:
                h = imageH-y            

        # Output Size
        if size == 'full':
            sizeW = w ; sizeH = h
        else:
            try:
                if size[0] == '!':     # !w,h
                    # Must fit inside w and h
                    (maxSizeW, maxSizeH) = size[1:].split(',')
                    # calculate both ratios and pick smaller
                    if not maxSizeH:
                        maxSizeH = maxSizeW
                    ratioW = float(maxSizeW) / w
                    ratioH = float(maxSizeH) / h
                    ratio = min(ratioW, ratioH)
                    sizeW = int(w * ratio)
                    sizeH = int(h * ratio)        
                elif size[0] == '^':  # ^w,[h]

                    # EXPERIMENTAL 2.1 FEATURE

                    sizeW, sizeH = size[1:].split(',')
                    if not sizeH:
                        sizeH = sizeW
                    sizeW = float(sizeW)
                    sizeH = float(sizeH)
                    rw = w / sizeW
                    rh = h / sizeH
                    multiplier = min(rw, rh)
                    minSizeW = sizeW * multiplier
                    minSizeH = sizeH * multiplier                    

                    x = int(((w-minSizeW)/2)+x)
                    y = int(((h-minSizeH)/2)+y)
                    w = int(minSizeW)
                    h = int(minSizeH)
                    sizeW = int(sizeW)
                    sizeH = int(sizeH)
                    ratio = 1
                elif size[-1] == ',':    # w,
                    # constrain width to w, and calculate appropriate h
                    sizeW = int(size[:-1])
                    ratio = sizeW/float(w)
                    sizeH = int(h * ratio)      
                elif size[0] == ',':     # ,h
                    # constrain height to h, and calculate appropriate w
                    sizeH = int(size[1:])
                    ratio = sizeH/float(h)
                    sizeW = int(w * ratio)

                elif size.startswith('pct:'):     #pct: n
                    # n percent of size
                    ratio = float(size[4:])/100
                    sizeW = int(w * ratio)
                    sizeH = int(h * ratio)                         
                    if sizeW < 1:
                        sizeW = 1
                    if sizeH < 1:
                        sizeH = 1
                else:    # w,h    or invalid
                    (sw,sh) = size.split(',')
                    # exactly w and h, deforming aspect (if necessary)
                    sizeW = int(sw)
                    sizeH = int(sh)  
                    # Nasty hack to get the right canonical URI
                    ratioW = sizeW/float(w)
                    tempSizeH = int(sizeH / ratioW)
                    if tempSizeH in [h, h-1, h+1]:
                        ratio = 1
                    else:
                        ratio = 0
            except:
                return self.error_msg('size', 'Size unparseable: %r' % size, status=400)      

        # Process rotation
        try:
            if '.' in rotation:
                rot = float(rotation)
                if rot == int(rot):
                    rot = int(rot)
            else:
                rot = int(rotation)
        except:
            return self.error_msg('rotation', 'Rotation unparseable: %r' % rotation, status=400)
        if rot < 0 or rot > 360:
            return self.error_msg('rotation', 'Rotation must be 0-359.99: %r' % rotation, status=400)            
        # 360 --> 0
        rot = rot % 360

        quals = info['profile'][1]['qualities']
        quals.extend(["default","bitonal"])
        if not quality in quals:
            return self.error_msg('quality', 'Quality not supported for this image: %r not in %r' % (quality, quals), status=501)
        if quality == quals[0]:
            quality = "default"
        
        nformat = format.upper()
        if nformat == 'JPG':
            nformat = 'JPEG'
        elif nformat == "TIF":
            nformat = "TIFF"
        try:
            mimetype = self.formats[nformat]
        except:
            return self.error_msg('format', 'Unsupported format', status=415)

        # Check if URI is not canonical, if so redirect to canonical URI
        # Check disk cache and maybe redirect
        if x == 0 and y == 0 and w == imageW and h == imageH:
            c_region = "full"
        else:
            c_region = "%s,%s,%s,%s" % (x,y,w,h)

        if (sizeW == imageW and sizeH == imageH) or (w == sizeW and h == sizeH):
            c_size = "full"
        elif ratio:
            c_size = "%s," % (sizeW)
        else:
            c_size = "%s,%s" % (sizeW, sizeH)

        c_rot = "!%s" % rot if mirror else str(rot) 
        c_qual = "%s.%s" % (quality, format.lower())
        paths = [infoId, c_region, c_size, c_rot, c_qual]
        fn = os.path.join(*paths)
        new_url = self.BASEPREF + fn
        response['Link'] += ', <%s>;rel="canonical"' % new_url

        if fn != path:
            response['Location'] = new_url
            return self.send("", status=301)

        # Won't regenerate needlessly as earlier cache check would have found it
        # if we're canonical already

        # And finally, process the image!
        if image == None:
            try:
                image = Image.open(filename)
            except IOError:
                return self.error_msg('identifier', 'Unsupported format for base image', status=501)

        if identifier.endswith('-degraded'):
            if self.DEGRADED_SIZE > 0:
                # resize max size
                image = image.resize((info['width'], info['height']))
            if self.DEGRADED_QUALITY:
                nquality = {'gray':'L','bitonal':'1'}[self.DEGRADED_QUALITY]
                image = image.convert(nquality)                
                
        if (w != info['width'] or h != info['height']):
            box = (x,y,x+w,y+h)
            image = image.crop(box)

        if sizeW != w or sizeH != h:
            image = image.resize((sizeW, sizeH))        
        if mirror:
            image = image.transpose(Image.FLIP_LEFT_RIGHT)

        if rot != 0:
            # NB Rotation in PIL can introduce extra pixels on edges, even for square
            # PIL is counter-clockwise, so need to reverse
            rot = 360 - rot
            try:
                image = image.rotate(rot, expand=1)
            except:
                # old version of PIL without expand
                segx = image.size[0]
                segy = image.size[1]
                angle = radians(rot)
                rx = abs(segx*cos(angle)) + abs(segy*sin(angle))
                ry = abs(segy*cos(angle)) + abs(segx*sin(angle))
                
                bg = Image.new("RGB", (rx,ry), (0,0,0))
                tx = int((rx-segx)/2)
                ty = int((ry-segy)/2)
                bg.paste(image, (tx,ty,tx+segx,ty+segy))
                image = bg.rotate(rot)

        if quality != 'default':
            nquality = {'color':'RGB','gray':'L','bitonal':'1'}[quality]
            image = image.convert(nquality)

        output = StringIO.StringIO()
        try:
            image.save(output,format=nformat, quality=self.jpegQuality)
        except SystemError:
            return self.error_msg('size', 'Unsupported size... tile cannot extend outside image', status=501)
        except IOError:
            return self.error_msg('format', 'Unsupported format for format', status=501)
        contents = output.getvalue()
        output.close()
        
        # Write to disk cache
        for p in range(1,len(paths)):
            pth = os.path.join(self.CACHEDIR, *paths[:p])
            if not os.path.exists(pth):
                os.mkdir(pth, 0775)         
        fh = file(self.CACHEDIR + fn, 'w')
        fh.write(contents)
        fh.close()

        return self.send(contents, ct=mimetype)
コード例 #51
0
def ajax():
    if check_passwd(request.get_cookie("mdp")) == False:
        return template('authentification', get_url=app.get_url)
    reader = codecs.getreader("utf-8")
    query = json.load(reader(request.body))

    ############### calculs de proba / utility assessment page #################################################
    if query['type'] == "question":
        if query['method'] == 'PE':
            return methods.PE(float(query['min_interval']),
                              float(query['max_interval']),
                              float(query['proba']), int(query['choice']),
                              str(query['mode']))
        elif query['method'] == 'LE':
            return methods.LE(float(query['min_interval']),
                              float(query['max_interval']),
                              float(query['proba']), int(query['choice']),
                              str(query['mode']))
        elif query['method'] == 'CE_Constant_Prob':
            return methods.CE(float(query['min_interval']),
                              float(query['max_interval']),
                              float(query['gain']), int(query['choice']),
                              str(query['mode']))
        else:
            return query['method']

    elif query['type'] == "calc_util":
        return fit.regressions(query['points'])

    elif query['type'] == "calc_util_multi":
        return fit.multipoints(query['points'])

    elif query['type'] == "k_calculus":
        if query['number'] == 2:
            return kcalc.calculk2(query['k']['k1'], query['k']['k2'])
        elif query['number'] == 3:
            return kcalc.calculk3(query['k']['k1'], query['k']['k2'],
                                  query['k']['k3'])
        elif query['number'] == 4:
            return kcalc.calculk4(query['k']['k1'], query['k']['k2'],
                                  query['k']['k3'], query['k']['k4'])
        elif query['number'] == 5:
            return kcalc.calculk5(query['k']['k1'], query['k']['k2'],
                                  query['k']['k3'], query['k']['k4'],
                                  query['k']['k5'])
        elif query['number'] == 6:
            return kcalc.calculk6(query['k']['k1'], query['k']['k2'],
                                  query['k']['k3'], query['k']['k4'],
                                  query['k']['k5'], query['k']['k6'])

    elif query['type'] == "utility_calculus_multiplicative":
        return kcalc.calculUtilityMultiplicative(query['k'], query['utility'])
    elif query['type'] == "utility_calculus_multilinear":
        return kcalc.calculUtilityMultilinear(query['k'], query['utility'])

    elif query['type'] == "svg":
        dictionary = query['data']
        min = query['min']
        max = query['max']
        liste_cord = query['liste_cord']
        width = query['width']
        return plot.generate_svg_plot(dictionary, min, max, liste_cord, width)

    elif query['type'] == "svg_QUALI":
        dictionary = query['data']
        list_names = query['list_names']
        width = query['width']
        return plot.generate_svg_plot_QUALI(dictionary, list_names, width)

    elif query['type'] == "pie_chart":
        names = query['names']
        probas = query['probas']
        return plot.pie_chart(names, probas)

    elif query['type'] == "export_xlsx":
        return export_xlsx.generate_fichier(query['data'])

    elif query['type'] == "export_xlsx_option":
        return export_xlsx.generate_fichier_with_specification(query['data'])

    elif query['type'] == "latex_render":
        return latex_render.render(query['formula'])

    elif query['type'] == "tree":
        return draw_tree.draw(query['gain'], query['upper_label'],
                              query['bottom_label'], query['upper_proba'],
                              query['bottom_proba'], query['assess_type'])
コード例 #52
0
def export(path):
    if check_passwd(request.get_cookie("mdp")) == False:
        return template('authentification', get_url=app.get_url)
    val = static_file('fichier' + path + '.xlsx', root='')
    os.remove('fichier' + path + '.xlsx')
    return val
コード例 #53
0
ファイル: main.py プロジェクト: nikialeksey/imeerk
def add_calendar_form() -> str:
    DbSessions(db)\
        .user(request.get_cookie('token', 'guest'))\
        .calendars()\
        .add(request.forms['url'], request.forms['name'])
    return redirect('/dashboard')
コード例 #54
0
 def get_cookie(self, name):
     return request.get_cookie(md5(name).hexdigest(), secret=self.secret)
コード例 #55
0
def restricted():
	username = request.get_cookie('account', secret = 'MySuperSecretSignedCookie')
	if username:
		return 'Welcome: {} to the restricted area!'.format(username)
	else:
		return 'You are not authorized'
コード例 #56
0
ファイル: user_controller.py プロジェクト: amiedes/giw-pr-1
def logout():
    if request.get_cookie("session_id"):
        response.set_cookie("session_id", '', expires=0)
    redirect('/login')
コード例 #57
0
def playerReadyHandler(game_id):
    playerName = request.get_cookie("player")
    result = controller.markPlayerReady(game_id, playerName)
    return utils.jsonResponse(response, {"result":result})
コード例 #58
0
    def check_session(request):

        session_id = request.get_cookie("session_id")

        if session_id is None:
            raise AuthenticationException("You need to log in!")
コード例 #59
0
def turnHandler(game_id):
    playerName = request.get_cookie("player")
    color = utils.reqBody(request.body, "color")
    result = controller.playTurn(game_id, playerName, color)
    return utils.jsonResponse(response, {"result":result})
コード例 #60
0
async def search(**kwargs):
    user = asyncio.ensure_future(getcurrentuser(request))

    slug = kwargs.get('slug')
    is_json = kwargs.get('is_json', '')

    query = slug.replace('-', ' ') if slug else request.query.q

    if not query:
        if is_json:
            return {'error': 'No query provided.'}
        return redirect('/')

    elif query == 'random':
        index = await store.srandmember('items:indexes')
        return redirect('/{}{}'.format(index, is_json))

    itemnames = await store.hgetall('items:names')

    if query in itemnames:
        return redirect('/{}'.format(itemnames[query]))

    t0 = time.time()

    classes = set()
    tags = set()

    priceviz = False

    if query == 'all':
        items = store.Hashes(
            [getitemkey(k.decode()) for k in await store.sort('items')])
        results = [tf2search.getsearchresult(items=items)]
    else:
        sources = ('backpack.tf', 'trade.tf')
        pricesource = request.get_cookie('price_source')
        if pricesource not in sources:
            pricesource = sources[0]

        items = {
            item['index']: item
            async for item in store.Hashes([
                getitemkey(143),  # Earbuds
                getitemkey(5021),  # Key
                getitemkey(5002),  # Refined
                getitemkey(5001),  # Reclaimed
                getitemkey(5000),  # Scrap
                getitemkey(0)  # Weapon
            ])
        }
        results = tf2search.visualizeprice(query, items, pricesource)

        input_ = tf2search.parseinput(query)
        classes = input_['classes']
        tags = input_['tags']

        if results is not None:
            if len(results) != 0:
                priceviz = True
                if not is_json:
                    items = []
                    for item in results[0]['items']:
                        items.extend([item['item']] * item['count'])
                    results[0]['items'] = items

        elif classes or tags:
            results = await getresults(classes, tags)

        else:
            itemsdict = await store.SearchHashSet(
                'items', getitemkey,
                ('index', 'name', 'image', 'classes', 'tags', 'marketprice'),
                int)

            itemsets = await store.get('items:sets')
            bundles = await store.get('items:bundles')

            results = tf2search.search(query, itemsdict, itemnames, itemsets,
                                       bundles, pricesource)

            for result in results:
                result['items'] = store.Hashes(
                    [h.key for h in result['items']])

    t1 = time.time()

    count = sum(len(result['items']) for result in results)

    all_classes = list(tf2api.getallclasses().keys())
    classes_text = getlistastext(sorted(classes, key=all_classes.index))
    tags_text = getlistastext(sorted(tags))

    if query == 'all':
        description = f'A list of all {count:,} items in TF2.'
    elif classes and tags:
        description = (
            f'A list of the {count:,} {tags_text} items for {classes_text}'
            ' in TF2.')
    elif classes:
        description = (
            f'A list of the {count:,} items for {classes_text} in TF2.')
    elif tags:
        description = f'A list of the {count:,} {tags_text} items in TF2.'
    elif priceviz:
        from_, equals, to = results[0]['title'].partition(' = ')
        to = getlistastext(to.split(' + '))
        description = (f'{from_} is the same as {to} in TF2.'
                       if equals else f'A list of {from_} items in TF2.')
    elif results and ':' in results[0]['title']:
        title = results[0]['title'].replace(':', '')
        description = f'{count:,} {title} items in TF2.'
    else:
        description = f'Search results for "{query}" items in TF2.'

    qualities = defaultdict(set)

    user = await user
    if user:
        for item in user.get('backpack', {}).get('items', []):
            qualities[item['defindex']].add(item['quality'])

    if is_json:
        for result in results:
            result['items'] = [item async for item in result['items']]
        return tojson(results)
    else:
        return await render('search.html',
                            query=query,
                            description=description,
                            results=results,
                            qualities=qualities,
                            count=count,
                            time=round(t1 - t0, 3))