示例#1
0
def clear_cookie():
    response.set_cookie(
        COOKIE_ID,
        '',
        secret=COOKIE_SECRET,
        expires=time() - COOKIE_EXPIRE
    )
示例#2
0
def login():
    # set mobilecookie to reduce is_mobile check-time
    response.set_cookie("mobile", str(is_mobile()))
    if not PYLOAD and SETUP:
        redirect("/setup")
    else:
        return render_to_response("login.html", proc=[pre_processor])
def login():
	#Checking user and password parameters
        print "Entro a comprobar usuario y contrasena"
	user = request.forms.get("user")
	passwd = request.forms.get("passwd")
	print "Usuario y contrasena: "
	print user
	print passwd
	#If correct user, save and send an authorized token and load control panel
	if user in correct_users and correct_users[user]==passwd:
		print "Usuario correcto"
		#Generating raonom token for this user
		token=binascii.b2a_hex(os.urandom(15))
		#Storing token for the user in the dictionary
		correct_tokens[user]=token
		print "Guardo el token"
		print token
		#Set cookies with token and user for the browser
		response.set_cookie('Token_auth',token,path='/')
		response.set_cookie('User_name',user,path='/')
		print (response)
		#Return HTML page
		return template("panelsimplificado.tpl",volume=str(volumen),state=str(estado),channel=str(canal))
	#Else send html error page
	else:
		return template("error.html")		
示例#4
0
def devotional(ext=""):
    """ Lookup the daily devotional.

    """

    # Get the search terms, verse references, and context.
    devotional_date = request.query.get("date", "").strip()

    # Record what devotional is being visited.
    response.set_cookie("devotional", json.dumps(devotional_date), path="/biblesearch")

    # Lookup the specified daily devotional.
    if devotional_date.lower() == "today":
        # Today is an alias for today's date.
        devotional_date = strftime("%m.%d")
    devotional_lookup = sword_search.Lookup("Daily")
    devotional_text = devotional_lookup.get_raw_text(devotional_date)

    # Make the verse lists at the end into links.
    devotional_text = tag_regx.sub(tag_func, devotional_text.encode("utf8"))

    # Return json data to the javascript.
    if ext == ".json":
        # Return json data to the javascript.
        return {"html": devotional_text.decode("utf8")}
    else:
        return build_search_page(verses=devotional_text.decode("utf8"))
示例#5
0
def login(db, token):
    """
    Login the user with the specified token.
    """
    cookie_token = request.get_cookie(TOKEN)
    if cookie_token:
        _, name = get_voter(db, cookie_token)
        return template('message',
                        message=("Already logged in as %s" % name),
                        logout_link=True,
                        start_link=True)
    else:
        voter = get_voter(db, token)
        if voter:
            _, name = voter
            response.set_cookie('token', token, path=COOKIE_PATH)
            return template('message',
                            message=("Logged in as %s" % name),
                            logout_link=True,
                            start_link=True)
        else:
            return template('message',
                            message="Invalid token",
                            logout_link=False,
                            start_link=False)
示例#6
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."
示例#7
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)
示例#8
0
 def close(self):
     if self.sessionid == None:
         #generate a new sessionid
         if sessionSettings["store"]:
             ids = [x[len(sessionSettings["sessiondir"]):-len(sessionSettings["extension"])] for x in glob.glob(sessionSettings["sessiondir"]+"*"+sessionSettings["extension"])]
         else:
             ids = sessions.keys()
         while True:
             self.sessionid = '%08x' % random.randrange(1 << 32)
             if self.sessionid not in ids:
                 break
         sid = self.sessionid
     else:
         sid = str(self.sessionid)
     if sessionSettings["store"]:
         #save the session variables back to file
         if not os.path.exists(sessionSettings["sessiondir"]):
             os.makedirs(sessionSettings["sessiondir"])
         path = sessionSettings["sessiondir"]+sid+sessionSettings["extension"]
         f = open(path,"wb")
         pickle.dump(self.sess, f)
         f.close()
     else:
         sessions[sid] = self.sess
     #set the sessionid in the user cookie
     response.set_cookie("sessionid", self.sessionid, secret=self.secret_key)
示例#9
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)
示例#10
0
文件: kotodo.py 项目: Irchiel/kotodo
def postregister():
    username = request.forms.get('username')
    password = request.forms.get('password')
    if create_user(username, password):
        response.set_cookie("U", username, secret=secret())
        response.set_cookie("P", password, secret=secret())
        redirect('/')
示例#11
0
def login():
    username = request.forms.get('username')
    password = request.forms.get('password')
    if check_login(username, password):
        response.set_cookie("account", username, secret=SECRET_KEY)
        bottle.redirect("/")
    return template('views/error.tpl', logged=False, error_message="Login failed: username/password pair is incorrect.")
示例#12
0
文件: pi3f_21.py 项目: dpla/image-api
    def get_iiif_token(self):
        # This is the next step -- client requests a token to send to info.json
        # We're going to just copy it from our cookie.
        # JSONP request to get the token to send to info.json in Auth'z header

        callbackFn = request.query.get('callback', '')
        authcode = request.query.get('code', '')
        account = ''
        try:
            account = request.get_cookie(self.COOKIE_NAME_ACCOUNT, secret=self.COOKIE_SECRET)
            response.delete_cookie(self.COOKIE_NAME_ACCOUNT)
        except:
            pass
        if not account:
            data = {"error":"missingCredentials","description": "No login details received"}
        else:
            data = {"accessToken":account, "tokenType": "Bearer", "expiresIn": 3600}
            # Set the cookie for the image content
            response.set_cookie(self.COOKIE_NAME, account, secret=self.COOKIE_SECRET)
        dataStr = json.dumps(data)

        if callbackFn:
            return self.send("{0}({1});".format(callbackFn, dataStr), ct="application/javascript")
        else:
            return self.send(dataStr, ct="application/json")
示例#13
0
def solve_dabblet():
    session_id = request.get_cookie('session_id') #TODO: decorator-ify session
    session = get_session(session_id)
    response.set_cookie('session_id', session['id'])

    dabblet_id = int(request.POST['dabblet_id'])
    choice_id  = int(request.POST['choice_id'])

    dabblet = Dabblet.get(id=dabblet_id)
    if choice_id < 0:
        choice = None
    else:
        choice  = DabChoice.get(id=choice_id)

    sol = DabSolution(dabblet=dabblet,
                      choice=choice,
                      solver_ip=request.get('REMOTE_ADDR'),
                      solver_index=session.get('cur_index', 0),
                      date_solved=datetime.now())
    sol.save()
    # replace?

    view_count = DabSolution.select().count()
    pass_count = DabSolution.select().where(choice_id=None).count()
    return { "view_count": view_count,
             "solution_count": view_count-pass_count }
示例#14
0
文件: boto.py 项目: skanish/chatbot
def chat():
    user_message = request.POST.get('msg').lower()
    boto_memory["user_name"] = request.get_cookie("user_name")
    if not boto_memory["user_name"]:
        boto_memory["user_name"] = user_message.split(" ")[0]
        response.set_cookie("user_name", boto_memory["user_name"])
        return {"animation": "giggling", "msg": "Nice to meet you " + boto_memory["user_name"]}
    if "weather" in user_message:
        r = requests.get('http://api.openweathermap.org/data/2.5/weather?q=Tel+Aviv&APPID=' + apiKey + "&units=metric")
        result = r.json()
        msg = "The weather forecast for Tel Aviv is " + str(result["main"]["temp"]) + "°C"
        return json.dumps({"animation": "excited", "msg": msg})
    elif "love" in user_message:
        return json.dumps({"animation": "inlove", "msg": "I love you!"})
    elif "time" in user_message:
        return time()
    elif "joke" in user_message or "funny" in user_message or "laugh" in user_message or "haha" in user_message or "ha"\
            in user_message or "lol" in user_message:
        return joke()
    elif "scared" in user_message or "afraid" in user_message or "scary" in user_message:
        return json.dumps({"animation": "afraid", "msg": "Don't be scared, I'm always here for you :)"})
    elif "sad" in user_message or "cry" in user_message or "upset" in user_message:
        return json.dumps({"animation": "crying", "msg": "Crying is dangerous for a robot :'("})
    elif "dog" in user_message or "bone" in user_message or "fetch" in user_message:
        return json.dumps({"animation": "dog", "msg": "Dog /dôɡ/ (noun): A mans 2nd best friend... after ROBOTS!!"})
    elif "doing" in user_message or "are" in user_message or "you" in user_message:
        return json.dumps({"animation": "ok", "msg": "I'm great! How are you?"})
    elif "like" in user_message or "do" in user_message or "spare" in user_message:
        return json.dumps({"animation": "takeoff", "msg": "I'm a robot, ain't nobody got time for that!"})
    elif "excited" in user_message or "happy" in user_message or "yay" in user_message:
        return json.dumps({"animation": "crying", "msg": "Crying is dangerous for a robot :'("})
    elif len(user_message) > 8:
        return json.dumps({"animation": "confused", "msg": "I don't understand"})
    else:
        return json.dumps({"animation": "dancing", "msg": "When in doubt... DANCE!"})
示例#15
0
文件: index.py 项目: happymap/hack
def wizard():

    #check cookie
    if request.get_cookie('cheetah') == None:
        #command = 'ls'
        command = 'java -jar /Users/yying/hack/queryauthentication/target/query-operations-1.0-SNAPSHOT.jar'
        process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
        output = process.communicate()
        retcode = process.poll()
        if retcode:
            raise subprocess.CalledProcessError(retcode, command, output=output[0])
        token = output[0].split("access token:", 1)[1]
        response.set_cookie('cheetah', token)

    else:
        print 'token gotten'

	tables = ['data', 'impressions', 'clicks', 'actions'];
	columns = {
		'data': ['advertiser_id', 'category', 'category_id', 'category_name', 'cid', 'contract_id'],
		'impressions': ['impression', 'cost', 'advertiser_id', 'impression_date', 'impression_hour', 'package_id', 'impression_id'],
        'clicks': ['data_cost', 'market_pay_data_cost', 'turn_pay_data_cost'],
        'actions': ['action', 'cta', 'order_number', 'vta']
	};

	return template("query", tables=tables, columns=columns);
示例#16
0
 def test_set_cookie(self):
     response.set_cookie("name", "value", max_age=5)
     response.set_cookie("name2", "value 2", path="/foo")
     cookies = [value for name, value in response.wsgiheader() if name.title() == "Set-Cookie"]
     cookies.sort()
     self.assertTrue(cookies[0], "name=value; Max-Age=5")
     self.assertTrue(cookies[1], 'name2="value 2"; Path=/foo')
示例#17
0
def logout():
    if not logged_in():
        redirect('/login/')
    else:
        remove_session(get_sid())
        response.set_cookie('sid', '', expires=datetime.datetime(1970, 1, 1, 0, 0, 0))
        redirect('/login/')
示例#18
0
 def test_delete_cookie(self):
     response = BaseResponse()
     response.set_cookie('name', 'value')
     response.delete_cookie('name')
     cookies = [value for name, value in response.headerlist
                if name.title() == 'Set-Cookie']
     self.assertTrue('name=;' in cookies[0])
示例#19
0
def login():
    withsession.session = request.environ.get("beaker.session")
    loggedin = request.cookies.get("loggedin")
    if request.method == "GET" and not loggedin and loggedin not in withsession.session:
        return template("admin/views/login.jinja2")
    elif request.method == "GET" and loggedin and loggedin in withsession.session:
        redirect("index")
    else:
        try:
            postedname = request.forms.get("username")
            postedpassword = request.forms.get("password")
            if postedname and postedpassword:
                user = Users.objects.get(username=postedname, password=base64.b64encode(bytes(postedpassword, "UTF8")))
                if user:
                    global username
                    guid = uuid.uuid1()
                    username = user.username
                    withsession.session["loggedin"] = str(guid)
                    response.set_cookie("loggedin", str(guid), max_age=600)
                    return template("admin/views/index.jinja2")
                else:
                    return template("admin/views/login.jinja2", {"errorMessage": "Invalid Username or Password"})
            else:
                return template("admin/views/login.jinja2")
        except Exception as e:
            return template("admin/views/login.jinja2", {"errorMessage": str(e)})
示例#20
0
文件: web.py 项目: 0x71/cuckoo
def get_pagination_limit(new_limit):
    """Defines the right pagination limit and sets cookies accordingly.
    @params new_limit: new pagination limit
    """
    default_limit = 50

    limit_cookie = request.get_cookie("pagination_limit")
    logging.info("Got cookie: {0}".format(limit_cookie))

    cookie_expires = time.mktime((datetime.now() + timedelta(days=365)).timetuple())

    if new_limit <= 0:
        if limit_cookie:
            try:
                limit = int(limit_cookie)
                logging.info("Using limit from cookie: {0}".format(limit))
                response.set_cookie("pagination_limit", str(limit), path="/", expires=cookie_expires)
            except Exception as e:
                logging.error("Cookie: {0}, exception: {1}".format(limit_cookie, e))
                limit = default_limit
        else:
            limit = default_limit
            logging.info("Using default limit: {0}".format(limit))
    else:
        limit = new_limit
        logging.info("Setting new limit: {0}".format(limit))
        response.set_cookie("pagination_limit", str(limit), path="/", expires=cookie_expires)

    return limit
示例#21
0
def login_success():
    token = request.forms.get('token')
    session = rauth.OAuth2Session(config.GOOGLE_CLIENT_ID, config.GOOGLE_CLIENT_SECRET, token)
    json = session.get('https://www.googleapis.com/oauth2/v1/userinfo').json()
    if json is None:
        return

    def convert(inputt):
        if isinstance(inputt, dict):
            return {convert(key): convert(value) for key, value in inputt.iteritems()}
        elif isinstance(inputt, list):
            return [convert(element) for element in inputt]
        elif isinstance(inputt, unicode):
            return inputt.encode('utf-8')
        else:
            return input
    json = convert(json)
    name = json['name'].replace(" ", "_")
    user = User(name, json['picture'], "NASA", "For the Benefit of All")
    gameToken = user.name
    gameToken = gameToken.replace(" ", "_")
    USERS.addUser(user, gameToken)
    response.set_cookie("cosmosium_login", gameToken, max_age=60 * 60 * 5)
    loginTokens.append({'name': user.name, 'social_token': token, 'game_token': gameToken})

    # now that we're logged in, send the user where they were trying to go, else to main page
    target = request.query.target or '/play'
    redirect(target)
示例#22
0
    def create(self):
        timestamp = calendar.timegm(time.gmtime())

        self.cookie['session_id'] = self.crypt.md5(uuid.uuid4().get_bytes())
        self.cookie['ip_address'] = request.remote_addr
        self.cookie['user_agent'] = request.environ.get('HTTP_USER_AGENT', '')[0:50]
        self.cookie['last_activity'] = timestamp

        max_age = self.lifetime if self.lifetime else self.one_day
        expires = timestamp + max_age

        params = {}
        if max_age:
            params['max_age'] = max_age
        if expires:
            params['expires'] = expires
        params['domain'] = self.domain
        params['path'] = self.path
        if self.secure:
            params['secure'] = self.secure
        if self.httponly:
            params['httponly'] = self.httponly

        data = phpserialize.dumps(
            self.data, object_hook=phpserialize.phpobject)
        self.redis.set(self.cookie['session_id'], data)
        self.redis.expire(self.cookie['session_id'], max_age)
        response.set_cookie(self.name, urllib.quote_plus(
            self.crypt.encrypt(phpserialize.dumps(self.cookie))), **params)
示例#23
0
def login(db):
    login_id = request.forms.get('login_id')
    password = request.forms.get('password')
    via = request.forms.get('via')
    account_id = '00000000-0000-0000-0000-000000000000'
    if login_id != '*****@*****.**':
        client = Authenticator()
        ok = client.authenticate(login_id, password)
        if(not ok):
            return HTTPError(401, 'Unauthorized')
        #check if the loginid already exists in db , else add loginid to db
        login_method = db.query(entity.LoginMethod).filter_by(via=via, login_id=login_id).first()
        if not login_method:
            account_id = str(uuid.uuid4())
            login_method = entity.LoginMethod(via, login_id, account_id)
            account = entity.Account(account_id, '', '')
            db.add(login_method)
            db.add(account)
        account_id = login_method.account_id
    loginToken = db.query(entity.LoginToken).filter_by(token=request.get_cookie("loginToken")).first()
    if loginToken is not None:
        db.delete(loginToken)
    # new login token, set in cookie
    token = uuid.uuid4()
    expire_date = datetime.date.today() + datetime.timedelta(days=7)
    login_token = entity.LoginToken(str(token), account_id, expire_date);
    db.add(login_token)
    response.set_cookie("loginToken", str(token), expires=expire_date, path="/")
示例#24
0
def set_cookie(username):
    response.set_cookie(
        'omm-account',
        username,
        secret=COOKIE_SECRET,
        expires=time() + COOKIE_EXPIRE
    )
示例#25
0
def signup():
    email = request.forms.get("email")
    username = request.forms.get("username")
    password = request.forms.get("password")
    verify = request.forms.get("verify")

    # set these up in case we have an error case
    errors = {'username': cgi.escape(username), 'email': cgi.escape(email)}
    if validate_signup(username, password, verify, email, errors):

        if not users.add_user(username, password, email):
            # this was a duplicate
            errors['username_error'] = "Username already in use. Please choose another"
            return template("welcome/signin", errors)

        session_id = sessions.start_session(username)
        print session_id
        response.set_cookie("session", session_id)
        redirect("/")

    else:

        print "user did not validate"
        return template("welcome/signin", errors.items() + dict(stylesheet=['login.css']).items() )

    return template("welcome/signup")
示例#26
0
def do_logout():
    response.set_cookie("username","",expires=0)
    response.set_cookie("testplan","",expires=0)
    response.set_cookie("buildName","",expires=0)
    response.set_cookie("apiKey","",expires=0)
    response.set_cookie("testRunner","",expires=0)
    return template('Views/landingpage.tpl')
示例#27
0
def nexPage(pageid):
	busqueda = request.get_cookie("busqueda")
	result_index=int(request.cookies.get("result_index"))
	if result_index > 0:
		result_index -= 25
	response.set_cookie("result_index",str(result_index),path="/")
	return busqueda_next(busqueda,pageid,result_index)
示例#28
0
def login():
    has_cookie = request.get_cookie("visited")
    if has_cookie and has_cookie == "yes":
        return "Welcome back! Nice to see you again"
    else:
        response.set_cookie("visited", "yes")
        return "Hello there! Nice to meet you"
示例#29
0
def devotional(ext: str=''):
    """ Lookup the daily devotional.

    """

    # Get the search terms, verse references, and context.
    devotional_date = request.query.get('date', '').strip()

    # Record what devotional is being visited.
    response.set_cookie('devotional', json.dumps(devotional_date),
                        path='/biblesearch')

    # Lookup the specified daily devotional.
    if devotional_date.lower() == 'today':
        # Today is an alias for today's date.
        devotional_date = strftime('%m.%d')
    devotional_lookup = sword_search.Lookup('Daily')
    devotional_text = devotional_lookup.get_raw_text(devotional_date)

    # Make the verse lists at the end into links.
    devotional_text = tag_regx.sub(tag_func, devotional_text)

    # Return json data to the javascript.
    if ext == '.json':
        # Return json data to the javascript.
        return {'html': devotional_text}
    else:
        return build_search_page(verses=devotional_text)
示例#30
0
def callback():
    code = request.params.get('code')
    response.set_cookie('code', code)
    credentials = flow.step2_exchange(code)

    http = credentials.authorize(httplib2.Http())
    service = build('oauth2', 'v1', http=http)
    user = service.userinfo()
    info = user.get().execute()
    email = info['email']

    rd = redis_endpoint()
    rd.set(code, email)

    if rd.get(email) is None:

        service = build('calendar', 'v3', http=http)
        cals = service.calendarList()
        info = cals.list().execute()

        cal_info = [dict(name=d['summary'], busy=True, cid=d['id']) 
                for d in info['items']]

        uinfo = {'code':code, 
                'cals':cal_info,
                'cred':credentials}
        pred_set(rd, email, uinfo)

    if email.endswith(ending):
        email = email[:-len(ending)]
    return redirect('/' + email)
示例#31
0
def hello_again():
    name = request.cookies.name
    #name = request.cookies.getunicode('name')  # encoding='utf-8' (default)
    if name == None:
        name = 'shinil.kim'
    response.set_cookie('name', name)
    try:
        name = name
        #name = request.cookies.get('name', '').decode('utf-8')
    except UnicodeError:
        name = u''

    if request.get_cookie("visited"):
        return "Welcome back! Nice to see you again ~ " + name
    else:
        response.set_cookie("visited", "yes")
        return "Hello there! Nice to meet you ~ " + name
示例#32
0
def do_login():
    username=request.forms.get("username")
    password=request.forms.get("password")
    if not username or not password:
        return abort(400)

    if username not in users:
        return abort(400, "login failed")

    if users[username]["password_hash"] != sha1(salt + password.encode()).hexdigest():
        return abort(400, "login failed")

    token = uuid4().hex
    login_users[token] = username

    response.set_cookie("login_token", token, path="/")
    redirect("/")
示例#33
0
def handleLogout(request):
    nicknameFromCookie = request.get_cookie('nickname')
    sessionFromCookie = request.get_cookie('session_id')
    with connection.cursor() as cursor:
        sql = "SELECT * FROM users WHERE nickname='{}' AND session_id='{}'".format(
            nicknameFromCookie, sessionFromCookie)
        cursor.execute(sql)
        result = cursor.fetchone()
        if not result:
            return False
        else:
            sql = "UPDATE users SET session_id=NULL WHERE nickname='{}'".format(
                nicknameFromCookie)
            cursor.execute(sql)
            connection.commit()
            response.set_cookie('session_id', "")
            return True
示例#34
0
def do_login():
    username = request.forms.get('username')
    password = get_salted_password()

    current_user = user.get_by_username(username)
    logined = current_user and current_user.salted_password == password

    if logined:
        response.set_cookie('ssl_uid', str(current_user.id))
        response.set_cookie('ssl_pw', password)
        return redirect('/')

    return template('login',
                    username=username,
                    message='User not found.'
                    if not current_user else 'Password is incorrect.',
                    salt=config.USER_SALT)
示例#35
0
def api_mpw():
    name = request.forms.get('name')
    mailbox = request.forms.get('mailbox')
    db_information = posts.find_one({'mailbox': mailbox})
    if db_information == None:
        return red_writing_1(u'邮箱不存在', '/mpw', u'点击重新输入')
    if name <> db_information['name']:
        return red_writing_2(u'用户名不正确', '/mpw', u'点击重新输入', '/retrieve_user',
                             u'点击找回用户名')
    send_email2(mailbox)
    response.set_cookie('cookie_name2',
                        '%s' % (mailbox),
                        domain='libsm.com',
                        path='/',
                        secret='asf&*45691')
    return red_writing_2(u'查看邮箱后进行选择', '/mpw_mail_ver', u'点击验证', '/mpw',
                         u'点击重新输入') + u'<h3>备注:邮件发送有延迟,等两分钟后再进行选择</h3>'
示例#36
0
def register_mailver():
    mailbox = request.forms.get('mailbox')
    db_information = posts.find_one('mailbox')
    if register_check_m(mailbox) == -1:
        return red_writing_2(u'邮箱已存在', '/register', u'点击返回注册', '/todo',
                             u'点击进入todo主页')
    if register_check_m2(mailbox) == -1:
        return red_writing_1(u'邮箱格式不正确', '/register',
                             u'点击返回注册') + u'<h3>格式为:登录名@主机名.域名<h3>'
    send_email2(mailbox)
    mailbox = str(mailbox)
    response.set_cookie('cookie_name3',
                        '%s' % (mailbox),
                        domain='libsm.com',
                        path='/',
                        secret='asf&*4561')
    redirect('/register_mail_ver')
示例#37
0
def show_form():
    sid = request.get_cookie('sid', default='nil')
    if sid == 'nil':
        new_id = uuid.uuid4()
        sid = str(new_id)
        r = requests.put('http://localhost:5100/', json={sid: [0, 0]})

    r = requests.get('http://localhost:5100/' + sid)
    count1 = r.json()[sid][0]
    count2 = r.json()[sid][1]

    count1 = int(count1) + 1

    r = requests.put('http://localhost:5100/', json={sid: [count1, count2]})
    response.set_cookie('sid', sid)

    return template('counter.tpl', counter1=count1, counter2=count2)
示例#38
0
def signin():
    username = request.forms.get('username')
    password = request.forms.get('password')
    print(username)
    print(password)
    try:
        user = User.get(User.username == username)
        print(user)
    except:
        return "User does not exist!"

    if user.password == password:
        response.set_cookie("username", str(user.id))
        return redirect("/choosesub")
    else:

        return "Invalid Credentials!!"
示例#39
0
def login():
    if not db.exists("session"):
        random_value = str(random.getrandbits(128))
        db.set("session", random_value)
        db.expire("session", 60)
        db.bgsave()
        response.set_cookie("session", random_value)

        ledThread = threading.Thread(None, robotControl.toggleLED)
        ledThread.start()
        ledThread._Thread__stop()
        return 'connected'
    elif request.get_cookie("session") and db.get(
            "session") == request.get_cookie("session"):
        return 'connected'
    else:
        return 'waiting'
示例#40
0
def logout():
    """Handler for GET requests to ``/logout/`` path.

    * Logs a user out by setting their "logged_in_as" cookie to ""
    * Loads alerts for display
    * Uses "templates/logged_out.html" as its template

    This handler returns an **empty** context dictionary.

    :returns: a context dictionary (as described above) to be used by
        @jinja2_view to render a template.

    :rtype: dict

    """
    response.set_cookie("logged_in_as", "", path="/")
    return {}
示例#41
0
def professorSignIn():
    #print 'Checking if user exists..'
    entity = request.body.read()
    entity = json.loads(entity)
    #print "username:"******"professor returned: ",  professor
    if professor != None and professor['password'] == entity['password']:

        #Also set session id in the browser cookie
        session_id = sessionobj.start_session(professor['username'])
        response.set_cookie("session", session_id)
        data = professor
    else:
        data = None

    return MongoEncoder().encode(data)
示例#42
0
def user_login():

    if request.POST.get('save', '').strip():
        username = request.POST.get('username', '').strip()
        password = request.POST.get('password', '').strip()

        if username == '' or password == '':
            response.status = 400
            return {"message": "some parameter is not correct"}

        if not check_username(username, password):
            response.status = 403
            return {"message": "Invalid user or password"}

        else:
            response.set_cookie("username", username[::-1])
            redirect('/v1.0/users/inbox/{}'.format(username))
示例#43
0
def get_session(request, response):
    session_id = request.cookies.get("session_id", None)
    if session_id == None:
        session_id = str(uuid.uuid4())
        session = {
            'session_id': session_id,
            'username': '******',
            'time': int(time.time())
        }
        db['session'].insert(session)
        response.set_cookie('session_id', session_id)
    else:
        session = db['session'].find_one(session_id=session_id)
        if session == None:
            response.delete_cookie('session_id')
            session = get_session(request, response)
    return session
示例#44
0
def login(data, db_session, *args, **kw):
    try:
        rtn = user_controller.get_profile(data.get('username'), db_session,
                                          *args, **kw)
        if rtn.get("store"):
            response.set_cookie("userid", rtn.get("id"))
            response.set_header("location", "/statics/store-home")
            response.status = 302
            return response
            page_rtn = html_serve("store-home.tpl.html")
        else:
            page_rtn = html_serve("profile.html")
        page_rtn.set_cookie("userid", rtn.get("id"))
        return page_rtn
    except Exception as e:
        print(e)
        return html_serve("login.html")
示例#45
0
def get_session(request, response):
    session_id = request.cookies.get("session_id",None)
    if session_id == None:
        session_id = str(uuid.uuid4())
        session = { 'session_id':session_id, "username":"******", "time":int(time.time()) }
        db['session'].insert(session)
        response.set_cookie("session_id",session_id)
    else:
        session=db['session'].find_one(session_id=session_id)
        if session == None:
            session_id = str(uuid.uuid4())
            session = { 'session_id':session_id, "username":"******", "time":int(time.time()) }
            db['session'].insert(session)
            response.set_cookie("session_id",session_id)

            # session = {"message":"no session found with the id =" + session_id}
    return session
示例#46
0
def do_login():
    username = request.forms.get('login_user_name')
    password = request.forms.get('login_user_password')
    if (username, password) == (USERNAME, PASSWORD):
        # cookie生存時間を1時間に設定
        response.set_cookie('login_status',
                            True,
                            max_age=3600,
                            secret=SECRET_KEY)
        return template('message_page',
                        login_status=True,
                        error=False,
                        message='ログインしました。')
    else:
        return template('login',
                        message="ユーザー名またはパスワードが正しくありません。",
                        login_status=False)
示例#47
0
def login_post():
    name = request.POST.getunicode("name")
    password = request.POST.getunicode("password")
    conn = sqlite3.connect('dekita.db')
    c = conn.cursor()
    c.execute("select id from user where name = ? and pass = ?;",
              (name, password))
    user_id = c.fetchone()
    conn.close()
    if user_id is not None:
        # print(user_id)
        user_id = user_id[0]
        response.set_cookie("user_id", user_id,
                            secret=secret_cookie)  #Webブラウザ上にcookieを置く
        return redirect('/dekita')
    else:
        return template("top")
示例#48
0
def signIn():
    print 'Checking if user exists..'
    entity = request.body.read()
    entity = json.loads(entity)
    print "username:"******"user returned: ", user
    if user != None and user['password'] == entity['password']:

        #Also set session id in the browser cookie
        session_id = sessionobj.start_session(user['username'])
        response.set_cookie("session", session_id)
        data = {"result": True, "payload": user}
    else:
        data = {"result": False}

    return MongoEncoder().encode(data)
示例#49
0
def check_session(db_file):
    """ Gets the current session used by the client if it exists, if not a new session key is created and added
        to the finn maps database.
    """
    key = request.get_cookie("sessionid")
    result = execute_sql(db_file,
                         f"SELECT key FROM edit_sessions WHERE key='{key}'",
                         return_result=True)
    if result:
        logger.info(f"Returning User With Key: {key}")
        return True

    key = str(uuid.uuid4())
    execute_sql(db_file, f"INSERT INTO edit_sessions VALUES ('{key}')")
    response.set_cookie("sessionid", key, max_age=31540000)
    logger.info(f"Adding new session with key: {key}")
    return False
示例#50
0
def do_ny_skra():
    username = request.forms.get('username')
    password = request.forms.get('password')
    name = request.forms.get('name')

    # hér væri hægt að nota csv skrá til að bera saman við notendur og lykilorð
    # harðkóðuð lausn

    if er_notandinn_til(username, password):
        return """
        <h1>username/password nú þegar til</h1>
        <h1>sláðu inn nýtt usrename/password</1h>
        """
    else:
        response.set_cookie("logged", username, secret='some-secret-key')
        nyr_notandi(username, password, name)
        return redirect("/restricted")
示例#51
0
def check_pass(mongodb):
    username = request.forms.get('username')
    password = request.forms.get('password')

    userRole = check_login(mongodb, username, password)

    if userRole > 0:
        cookie = 'r' + str(userRole) + str(random()).split('.')[1]
        mongodb.sessions.insert_one({
            'user': username,
            'cookie': cookie,
            'created_at': datetime.utcnow()
        })
        response.set_cookie('auth', cookie, max_age=31536000)
        redirect('/')
    else:
        redirect('/ingreso/?login_error=1')
示例#52
0
def show_name():
    email = request.params.email
    password = request.params.password
    hashword = m3.shaHash(password, "deadsea")
    ### need to begin with checking for username (email) - otherwise we'll get a keyerror
    if(m3.get_person(pcrDB, email) == None):
        return template('base.tpl', title='PCR Hero', email=request.get_cookie('loggedin', secret='applesauce')) + "Sorry - this username is not registered!"
    else:
        ### need to load up the user's hashword for comparison purposes
        loginHashword = m3.get_user_hashword(pcrDB, email)
        if(hashword != loginHashword):
            return template('base.tpl', title='PCR Hero', email=request.get_cookie('loggedin', secret='applesauce')) + "Sorry - your password is incorrect!"
        elif(hashword == loginHashword):
            response.set_cookie('loggedin', email, max_age= 600, secret='applesauce', path='/')
            return template('base.tpl', title='PCR Hero', email=request.get_cookie('loggedin', secret='applesauce')) + "<h2>Hello, {}!<p>Welcome back!</p></h2>".format(request.POST.email)
        else:
            return template('base.tpl', title='PCR Hero', email=request.get_cookie('loggedin', secret='applesauce'))+ "Sorry, something went wrong!"
示例#53
0
def do_login():
    b9y = B9y('http://b9y.redis.sg:8050', 'admin', 'XXXXXXXXX')
    pin = request.query['pin']
    # cp = request.query['g-recaptcha-response']
    lab_data = b9y.get("lab:" + str(pin))

    #if cp == None or cp == "":
    #    return template('form', message="Are you a robot?")

    if lab_data == None:
        return template('form', message="Invalid PIN. Please try again!")

    try:
        lab = json.loads(lab_data)
        info = lab["info"]
        session = request.get_cookie("session")
    except:
        return template('msg', msg="Something wrent horribly wrong.")

    if session == None:
        session = str(uuid.uuid4()).replace("-", "")
        response.set_cookie("session", str(session), expires=1666908083)

    session_data_key = "lab:" + str(pin) + ":" + session

    sessioninfo = b9y.get(session_data_key)

    # get a resource if session info is empty
    if sessioninfo == None or sessioninfo == "None":
        sessioninfo = b9y.pop("stuff")
        b9y.set(session_data_key, sessioninfo)

    # if still empty we ran out of resources
    if sessioninfo == None or sessioninfo == "None":
        return template(
            'msg',
            msg=
            "This lab has no more available resources. Sorry! <a href='/logout'> (logout)</a>"
        )

    return template('session',
                    labid=pin,
                    labsession=session,
                    labinfo=info,
                    sessioninfo=sessioninfo)
示例#54
0
def do_verify():
    # handle username/password
    # TODO: CSRF protection
    username = request.forms.get('username')
    password = request.forms.get('password')
    if username and password:
        logging.info('Verifying username %s and password...', username)
        handler = OdooAuthHandler()
        data, session_id = handler.check_login(username, password)
        if session_id:
            hotp = pyotp.HOTP(HOTP_SECRET)
            counter, code = db.next_hotp_id(session_id)
            key = hotp.at(counter)
            if not send_mail(username, key):
                message = 'Mail with security code not sent.'
                logging.error(message)
                return template('login', dict(theme_params, error=message))
            return template(
                'hotp', dict(theme_params.items(), counter=counter, code=code))
        else:
            # TODO: brute force protection
            #       (block for X minutes after X attempts)
            message = 'Invalid username or password.'
            logging.info(message)
            return template('login', dict(theme_params, error=message))

    # check HOTP
    counter = request.forms.get('counter')
    code = request.forms.get('code')
    hotp_code = request.forms.get('hotp_code')
    if code and counter and hotp_code:
        hotp = pyotp.HOTP(HOTP_SECRET)
        if not hotp.verify(hotp_code, int(counter)):
            message = 'Invalid security code.'
            return template('login', dict(theme_params, error=message))
        session_id = db.verify_code_and_expiry(counter, code)
        if not session_id:
            message = 'Invalid security code (2).'
            return template('login', dict(theme_params, error=message))
        db.save_session(session_id, EXPIRY_INTERVAL)
        logging.info('Setting session cookie: %s', session_id)
        response.set_cookie("session_id", session_id, path='/')
        return redirect('/')

    return redirect('/')
示例#55
0
def get_or_create_session(db):
    """Get the current sessionid either from a
    cookie in the current request or by creating a
    new session if none are present.

    If a new session is created, a cookie is set in the response.

    Returns the session key (string)
    """
    if request.get_cookie('session') is not None:
        # Fetch from DB
        session_key = request.get_cookie('session')
        cursor = db.cursor()
        cursor.execute("SELECT sessionid FROM sessions WHERE sessionid=?",
                       (session_key, ))
        row = cursor.fetchone()
        if not row:
            # no existing session in database then we will have create a new one (Exception Handling)
            response.delete_cookie('session')
            session_key = str(uuid.uuid4())
            cart = []
            item = {'id': '', 'quantity': '', 'name': '', 'cost': ''}
            cart.append(item)
            data = json.dumps(cart)
            cursor = db.cursor()
            cursor.execute("INSERT INTO sessions VALUES (?,?)",
                           (session_key, data))
            db.commit()
            response.set_cookie('session', session_key)
        else:
            session_key = row['sessionid']

    else:
        # Create a new Session and insert it to DB
        session_key = str(uuid.uuid4())
        cart = []
        item = {'id': '', 'quantity': '', 'name': '', 'cost': ''}
        cart.append(item)
        data = json.dumps(cart)
        cursor = db.cursor()
        cursor.execute("INSERT INTO sessions VALUES (?,?)",
                       (session_key, data))
        db.commit()
        response.set_cookie('session', session_key)
    return session_key
示例#56
0
def edit_item(id_shed):
    try:
        rqstSession = request.get_cookie('pysessionid',
                                         secret=prop('cookieSecret'))
        if check_session(rqstSession) is True:
            if request.forms.get('save', '').strip():
                id_shed = request.forms.get('id_shed', '').strip()
                state = request.forms.get('state', '').strip()
                time = request.forms.get('time', '').strip()

                conn_string = prop('database')
                conn = psycopg2.connect(conn_string)
                cursor = conn.cursor()
                sql = """
                        update schedule set time = %(time)s, state = %(state)s where id_shed = %(id_shed)s
                        """
                cursor.execute(sql, {
                    'time': time,
                    'state': state,
                    'id_shed': id_shed
                })
                conn.commit()
                return template('scheduleConf')
            else:
                conn_string = prop('database')
                conn = psycopg2.connect(conn_string)
                cursor = conn.cursor()
                sql = """
                        select id_shed, day, time, state from schedule where id_shed = %(id_shed)s
                        """
                cursor.execute(sql, {'id_shed': id_shed})
                cur_data = cursor.fetchone()

                return template('edit_schedule', old=cur_data, id_shed=id_shed)
        else:
            pysessionid = ''
            response.set_cookie('pysessionid',
                                pysessionid,
                                secret=prop('cookieSecret'),
                                Expires='Thu, 01-Jan-1970 00:00:10 GMT',
                                httponly=True)
            redirect('/login')
    except Exception as e:
        logging.debug(e)
        return '<p>Error</p>'
示例#57
0
文件: api.py 项目: zheel/moulinette
    def login(self, password, profile='default'):
        """Log in to an authenticator profile

        Attempt to authenticate to a given authenticator profile and
        register it with the current session - a new one will be created
        if needed.

        Keyword arguments:
            - password -- A clear text password
            - profile -- The authenticator profile name to log in

        """
        # Retrieve session values
        s_id = request.get_cookie('session.id') or random_ascii()
        try:
            s_secret = self.secrets[s_id]
        except KeyError:
            s_hashes = {}
        else:
            s_hashes = request.get_cookie('session.hashes',
                                          secret=s_secret) or {}
        s_hash = random_ascii()

        try:
            # Attempt to authenticate
            auth = self.actionsmap.get_authenticator(profile)
            auth(password, token=(s_id, s_hash))
        except MoulinetteError as e:
            if len(s_hashes) > 0:
                try:
                    self.logout(profile)
                except:
                    pass
            raise error_to_response(e)
        else:
            # Update dicts with new values
            s_hashes[profile] = s_hash
            self.secrets[s_id] = s_secret = random_ascii()

            response.set_cookie('session.id', s_id, secure=True)
            response.set_cookie('session.hashes',
                                s_hashes,
                                secure=True,
                                secret=s_secret)
            return m18n.g('logged_in')
示例#58
0
def do_login(get_token=None, *args):
    url = tgt_addr
    ctst = request.query.get('contest', None)
    if ctst != None:
        try:
            ctst = int(ctst)
        except ValueError:
            ctst = 0
            contests = []
        else:
            contests = bj.contest_list(tgt_addr, None)
        if ctst not in range(len(contests)):
            return pkgutil.get_data(
                'ejui',
                'error.html').decode('utf-8').format(message='Invalid contest')
        url = contests[ctst][0]
    if get_token == None:
        login = request.forms.get('login', default=None)
        if login != None:
            login = login.encode('latin-1').decode('utf-8', 'replace')
        pass_ = request.forms.get('pass', default=None)
        if pass_ != None:
            pass_ = pass_.encode('latin-1').decode('utf-8', 'replace')
    else:
        login = pass_ = None
    message = None
    try:
        url, cookie = bj.login(
            url, login, pass_,
            **({
                'token': get_token(*args)
            } if get_token != None else {}))
    except (BruteError, socket.error) as e:
        message = str(e)
    except Exception:
        raise
        message = "Internal server error"
    if message != None:
        return pkgutil.get_data(
            'ejui',
            'error.html').decode('utf-8').format(message=html.escape(message))
    session_id = os.urandom(16).hex()
    sessions[session_id] = (url, cookie)
    response.set_cookie('credentials', session_id)
    return redirect('/')
示例#59
0
    def set_kwargs(self, **kwargs):
        """set(self, **kwargs)
        set session values as keyword args.
        Because of the way Bottle handles cookies-- you should NOT set session values multiple times
        as it could have unexpected results.
        
        example
          > session.set_kwargs(first_name='Ricky', last_name='LeFleur')
        """
        # first, check if session cookie exists
        sid = request.get_cookie(self.cookie_name, default=None, secret=self.secret)
        if sid:
            sess_key = {'_id':sid}
            data = self.db.sessions.find_one(sess_key)
            if data:
                # existing session record, convert to dictionary
                data = dict(data)
            else:
                # could not find session record, change the sid to None
                # (this should not happen in normal circustances, but need to anticipate)
                # at this point it looks like a fresh new session
                sid = None

        if sid is None:
            # prepare a new record with a timestamp
            data = {'_timestamp_':int(time.time())}
            
        for key, value in kwargs.items():
            # add the kwargs to the data, note-- we will allow
            # programmer to possibly affect important values without raising an error
            # which is a programmer choice ;-)
            data[key] = value
            
        # write the data
        if sid:
            # update existing record in the database
            self.db.sessions.update_one(sess_key, {'$set': data})
        else:
            # this is a new record, so need to set the cookie
            sid = self.db.sessions.insert_one(data).inserted_id
            response.set_cookie(name=self.cookie_name, value=sid,
                                secret=self.secret,
                                path='/',
                                max_age=self.max_age)
        self.clean_up_expired()
示例#60
0
def set_login_cookie(_user, uid, pw, rem):
    if _user:  # if user has existing login (in python memory)
        if uid in demoIDs or False:  # TODO: replace this false with password check
            login_token = uid + ''.join(
                random.choice(string.ascii_letters + string.digits) for _ in range(5))
            user_obj = getDemoProfile(uid)
            try:
                USERS.addUser(user_obj, login_token)
            except ValueError as e:
                print e.message

            response.set_cookie("cosmosium_login", login_token, max_age=60 * 60 * 5)
            # redirect('/play')
    elif False:  # if user is in database
        # TODO: load user into USERS (python memory)
        pass
    else:
        return user_login('user not found')