Exemplo n.º 1
0
class AuthHelper:

    def __init__(self):
        self.user_cookie = 'uc'
        self.secure_cookie_serializer = SecureCookieSerializer(SECRET_KEY)

    def get_authenticated_user(self, request):
        """
            Reads the auth cookie from the request and returns the user entity
            associated to the cookie value.
        """
        cookie_val = request.cookies.get(self.user_cookie)
        uid = self.secure_cookie_serializer.deserialize(self.user_cookie, cookie_val)
        return uid and User.by_username(uid)


    def set_auth_cookie(self, response, uid):
        """
            Takes a valid user id and sets a secure cookie (token) in the
            response used to validate if the user is signed in.
        """
        cookie_val = self.secure_cookie_serializer.serialize(self.user_cookie, uid)
        response.set_cookie(self.user_cookie, cookie_val, httponly=True)

    def destroy_auth_cookie(self, response):
        response.delete_cookie(self.user_cookie)
Exemplo n.º 2
0
def set_cookie(self):
    cookie_val = self.request.cookies.get('uid', default = None)
    serializer = SecureCookieSerializer(app_globals.secure_cookie_pass_phrase)
    self.response.write('cookie value is %s (raw) & %s (deserialized)'%(cookie_val, serializer.deserialize('uid', cookie_val)))
    current_time = gmtime()
    self.response.set_cookie(key = 'uid', value = serializer.serialize('uid', 'lollolo'), path = '/',
      expires = datetime(current_time.tm_year + app_globals.login_cookie_expiry, current_time.tm_mon, current_time.tm_mday))
    self.response.write('----------------------------------')
Exemplo n.º 3
0
class CookieHelper():

    cookie = None
    max_age_dir = {}

    def __init__(self, secret_key=None):
        if secret_key:
            self.cookie = SecureCookieSerializer(secret_key)
        else:
            self.cookie = SecureCookieSerializer(SECRET_KEY)

    def _serialize(self, name, value):
        return self.cookie.serialize(name, value)

    def _deserialize(self, name, value, max_age=None):
        return self.cookie.deserialize(name, value, max_age=None)

    def get(self, controller, name, encrypted=True):
        value = controller.request.cookies.get(name)
        max_age = None
        if name in self.max_age_dir:
            max_age = self.max_age_dir[name]
        if encrypted:
            return self._deserialize(name, value, max_age)
        return value

    def write(self,
              controller,
              name,
              value,
              max_age=None,
              path='/',
              domain=None,
              secure=False,
              encrypted=True):
        # Saves a cookie in the client.
        if encrypted:
            value = self._serialize(name, value)
        if max_age:
            self.max_age_dir[name] = max_age
        controller.response.set_cookie(name,
                                       value,
                                       max_age=max_age,
                                       path=path,
                                       domain=domain,
                                       secure=secure)

    def delete(self, controller, name):
        # Deletes a cookie previously set in the client.
        controller.response.delete_cookie(name)

    def unset(self, controller, name):
        # Cancels a cookie previously set in the response.
        controller.response.unset_cookie(name)
Exemplo n.º 4
0
    def get_user_or_none(cls, req):
        """
        actual method that return the user or ``None``

        :param req:
        :return:
        """

        uid = None
        ut = None
        # # in case it's test. use remote user.
        # if 'REMOTE_USER' in req.environ and cls.__config_file.DEBUG:
        # token = req.environ['REMOTE_USER']
        # uid, ut = token.split("Token")[1].split("|")
        # even if in test, but the remote user is not found. then...
        if not uid and not ut:
            token = req.headers.get("Authorization")
            if token:
                ret_token = token.split("Token")[1]
                if not ret_token:
                    return None
                uid, ut = ret_token.split("|")
            else:
                scs = SecureCookieSerializer(cls.__config_file.API_APP_CFG[cls.__app_name]['SECRET_KEY'])
                token = req.cookies.get('gc_token')
                if token:
                    token_des = scs.deserialize('Token', token)
                    if not token_des:
                        return None
                    uid, ut = token_des.split("|")
                else:
                    return None
        if uid and ut:
            # user = memcache.get("%s|%s" % (uid, ut))
            # if user:
            # return user
            # else:
            if cls.__user_model.validate_auth_token(long(uid), ut):
                user = cls.__user_model.get_by_auth_token(long(uid), ut)[0]
                return user
                # store in memcace for 1 week
                # memcache.set("%s|%s" % (uid, ut), user, time=60 * 24 * 7)
        return None
Exemplo n.º 5
0
class BaseHandler(webapp2.RequestHandler):

    def initialize(self, request, response):
        super(BaseHandler, self).initialize(request, response)
        # initialise with secret key
        self.cookie_serializer = SecureCookieSerializer(SECRET)

    def write(self, *args, **kwgs):
        self.response.out.write(*args, **kwgs)

    def render_str(self, template, **params):
        t = env.get_template(template)
        return t.render(**params)

    def render(self, template, **params):
        self.write(self.render_str(template, **params))

    def get_cookie(self):
        user_cookie = self.request.cookies.get('userid')
        if user_cookie:
            user_cookie = self.cookie_serializer.deserialize(
                'userid',
                user_cookie
            )
            if not user_cookie:
                # invalid cookie signature
                return None, ''
            user_id, username = user_cookie.split('|')
            user_id = int(user_id)
            return user_id, username
        else:
            return None, ''

    def get_user(self):
        user_id, username = self.get_cookie()
        logging.info('get_user -> {}, {}'.format(user_id, username))
        if not user_id:
            # no logged in user cookie
            return None, None

        user = User.get_by_id(user_id)
        return user_id, user