Beispiel #1
0
    def get(self):
        request_token_key = self.request.get("oauth_token")
        request_verifier  = self.request.get('oauth_verifier')
        auth = tweepy.OAuthHandler(CONSUMER_KEY,  CONSUMER_SECRET)
        request_token = RequestToken.gql("WHERE token_key=:1",  request_token_key).get()

        if request_token is None:
            self.redirect('/')
        else:
            auth.set_request_token(request_token.token_key,  request_token.token_secret)
            access_token = auth.get_access_token(request_verifier)
            cookie.set_cookie(self, str(access_token), SESSION_EXPIRE)
            self.redirect('/')
Beispiel #2
0
def login_user(username):
    options = string.digits + string.ascii_letters
    token = "".join(random.choice(options) for _ in xrange(32))

    user = db_player.get_by_username(username)
    user.token = token
    db_player.save(user)

    cookie.set_cookie(
        cookie.Cookie("username", username, [
            cookie.CookieExpiresAttribute(datetime.datetime.utcnow() +
                                          datetime.timedelta(days=30))
        ]))
    cookie.set_cookie(
        cookie.Cookie("token", token, [
            cookie.CookieExpiresAttribute(datetime.datetime.utcnow() +
                                          datetime.timedelta(days=30))
        ]))
Beispiel #3
0
class LogoutController(object):
    def __init__(self):
        pass

    cookie.set_cookie(
        cookie.Cookie("username", "", [
            cookie.CookieExpiresAttribute(datetime.datetime.utcnow() -
                                          datetime.timedelta(days=30))
        ]))

    cookie.set_cookie(
        cookie.Cookie("token", "", [
            cookie.CookieExpiresAttribute(datetime.datetime.utcnow() -
                                          datetime.timedelta(days=30))
        ]))

    def get_view(self):
        return ".view/logout.html"
Beispiel #4
0
    def set_cookie(self, name, value, max_age=None, expires=None, path='/',\
            domain=None, secure=False, http_only=True):
        """Set a cookie with set_cookie function from cookie module."""
        cookies = cookie.set_cookie(name, value, max_age, expires, path, domain, \
                secure, http_only)

        if not hasattr(self, '_cookies'):
            self._cookies = {}
        self._cookies[name] = cookies
        self.set_header('Set-Cookie', cookies)
Beispiel #5
0
    def set_cookie(self, name, value, max_age=None, expires=None, path='/',\
            domain=None, secure=False, http_only=True):
        """Set a cookie with set_cookie function from cookie module."""
        cookies = cookie.set_cookie(name, value, max_age, expires, path, domain, \
                secure, http_only)

        if not hasattr(self, '_cookies'):
            self._cookies = {}
        self._cookies[name] = cookies
        self.set_header('Set-Cookie', cookies)
Beispiel #6
0
async def img_auth(websocket, path):
    # Waiting for client to send image URI
    name = await websocket.recv()

    # Image URI is base64 encoded and contains some extra characters
    name = (name.split(','))[-1]
    imgdata = base64.b64decode(name)
    #print(imgdata)

    # Write image received during login to disk
    filename = './images/tmp/unknown_face.jpg'
    with open(filename, 'wb') as f:
        f.write(imgdata)

    try:
        # face.py contains a method 'whoiam' to match the client's received image with
        # already registered image of client.
        match_face = face.whoiam(filename)

        if match_face == True:
            print('Matched')
            # Create a cookie object
            ck = cookies.SimpleCookie()

            # set_cookie(username) method create and generates a cookie and
            # return its value. Check cookie.py for more info.
            ck = cookie.set_cookie('kb')

            # Get cookie 'ck' value and assign it to variable 'data'
            data = ck['secret'].value

            # Send 'data' variable value to the client browser
            await websocket.send(data)
    except:
        print('Not matched')
        # Send failed message to client browser
        await websocket.send('failed')
def get_accepted_language_codes(firstshot=False):
    """
    Findet heraus, welche Sprache eingestellt wurde und gibt eine Liste mit
    möglichen Ländercodes, sortiert nach Priorität, zurück.

    Zuerst wird in der URL nachgesehen, ob eine Sprache angefordert wird.
    Wenn nicht, dann wird das Language-Cookie ausgewertet.
    Dann wird der Request nach der Spracheinstellung des Browsers durchsucht.

    Wird die Sprache über die URL übergeben, dann wird diese zusätzlich in das
    Language-Cookie geschrieben.

    :param firstshot: Wenn True, dann wird die erste mögliche Sprache zurück
        geliefert. Es wird nicht lange nach anderen Sprachen gesucht.
    """

    LANGUAGE_CODES = config.LANGUAGES.value

    language_code = None
    lang_items = []

    # Path Info
    path_list = [item for item in cherrypy.request.path_info.split("/") if item]
    if path_list:
        if path_list[0] in LANGUAGE_CODES:
            language_code = path_list[0]
            if firstshot:
                return [language_code]
            lang_items.append([3.0, language_code])
            # Neue Sprache in das Language-Cookie eintragen
            cookie.set_cookie(cookie.LANGUAGE, language_code)

    # Language-Cookie
    if not language_code:
        lang_cookie = cookie.get_cookie(cookie.LANGUAGE)
        if lang_cookie in LANGUAGE_CODES:
            language_code = lang_cookie
            if firstshot:
                return [language_code]
            lang_items.append([2.0, language_code])

    # Browser
    accept_language = cherrypy.request.headers.get("ACCEPT-LANGUAGE")
    if accept_language:
        accept_language = accept_language.replace("-", "_").lower()
        # Möglichkeit 1: da, en-gb;q=0.8, en;q=0.7
        # Möglichkeit 2: de-de;q=1.0,de;q=0.8,en-us;q=0.5,en;q=0.3
        raw_items = [item.strip() for item in accept_language.split(",") if item.strip()]
        for raw_item in raw_items:
            if ";" in raw_item:
                try:
                    lang, q = [item.strip() for item in raw_item.split(";", 1) if item.strip()]
                    lang_items.append([float(q.split("=")[1].strip()), lang])
                except IndexError:
                    pass
            else:
                lang_items.append([1.0, raw_item])

    # Standardsprache anhängen
    lang_items.append([0.0, LANGUAGE_CODES[0]])

    # Einträge nach Priorität sortieren und zurück geben
    lang_items.sort(reverse=True)
    ret_items = []
    for lang_item in lang_items:
        if lang_item[1] in LANGUAGE_CODES:
            if lang_item[1] not in ret_items:
                ret_items.append(lang_item[1])
    return ret_items
Beispiel #8
0
    def post(self):
        """
            Handles the /register endpoint.
            ODTF registration.
        """
        json_data = {}
        for arg in self.request.arguments():
            json_data[arg] = self.POST(arg)

        if self.POST("first_name") and self.POST("last_name") \
           and self.POST("email") and self.POST("street_address") \
           and self.POST("province") and self.POST("city") \
           and self.POST("password") and self.POST("confirm_password"):
            user_exist = User.check_user(email=self.POST("email"))
            if user_exist:
                message = "Sorry, it looks like "
                message += self.POST("email")
                message += " belongs to an existing account. If this is yours, please login using your account."
                error_message(self, message)

                data = base64.b64encode(json.dumps(json_data))
                set_cookie(self, name="_rm_", value=data)
            else:
                user = User.create_new_user(
                    first_name=self.POST("first_name"),
                    middle_name=self.POST("middle_name"),
                    last_name=self.POST("last_name"),
                    street_address=self.POST("street_address"),
                    province=self.POST("province"),
                    city=self.POST("city"),
                    password=self.POST("password"),
                    mobile=self.POST("mobile_number"),
                    email=self.POST("email"),
                    office_order_number=self.POST('office_order_number'),
                    redirect=self.POST("redirect"))

                query = UserGroup.query()
                query = query.filter(UserGroup.invited_users == user.current_email)
                user_groups = query.fetch()

                if user_groups:
                    for group in user_groups:
                        if user.key not in group.users:
                            group.users.append(user.key)
                        if user.current_email in group.invited_users:
                            group.invited_users.remove(user.current_email)
                        group.put()

                        if group.key in user.user_groups:
                            user.user_groups.append(str(group.key.id()))
                            user.put()

                success = "Thank you for your registration. "
                success += "We sent you a verification email, "
                success += "please open the email and verify your account "
                success += "to complete the registration."
                success_message(self, success)
        else:
            message = "We were unable to create your account. "
            message += "Please fill in all required fields."
            error_message(self, message)

            data = base64.b64encode(json.dumps(json_data))
            set_cookie(self, name="_rm_", value=data)

        url = "/register"
        if self.POST("redirect"):
            url += "?redirect="
            url += self.POST("redirect")

        self.redirect(url)