Exemplo n.º 1
0
def user_details(strategy, details, user=None, *args, **kwargs):
    """Update user details using data from provider."""
    if not user:
        return

    changed = False  # flag to track changes
    protected = ('username', 'id', 'pk', 'email') + \
                tuple(strategy.setting('PROTECTED_USER_FIELDS', []))

    # Update user model attributes with the new data sent by the current
    # provider. Update on some attributes is disabled by default, for
    # example username and id fields. It's also possible to disable update
    # on fields defined in SOCIAL_AUTH_PROTECTED_USER_FIELDS.
    for name, value in details.items():
        if value is None or not hasattr(user, name) or name in protected:
            continue

        # Check https://github.com/omab/python-social-auth/issues/671
        current_value = getattr(user, name, None)
        if current_value == value:
            continue

        changed = True
        logger.debug(
            "The {1} of the User({0}) was changed from {2} to {3}".format(
                user.email, name, current_value, value))
        setattr(user, name, value)

    if changed:
        strategy.storage.user.changed(user)
        if usercache:
            usercache.set(settings.GET_USER_KEY(user.id), user,
                          settings.USER_CACHE_TIMEOUT)
            logger.debug("Cache the user({}) data to usercache".format(
                user.email))
Exemplo n.º 2
0
        def _get_user(request):
            """
            Return the user model instance associated with the given request session.
            If no user is retrieved, return an instance of `AnonymousUser`.
            """
            logger.debug("Start to retrieve the user data from usercache")
            now = timezone.now()
            user = None
            try:
                userid = auth._get_user_session_key(request)
                userkey = settings.GET_USER_KEY(userid)
                user = usercache.get(userkey)
                if not user:
                    user = User.objects.get(pk=userid)
                    usercache.set(userkey, user, settings.USER_CACHE_TIMEOUT)
                    diff = timezone.now() - now
                    logger.debug(
                        "Spend {} milliseconds to cache the user({}) data from database to usercache"
                        .format(
                            round((diff.seconds * 1000 + diff.microseconds) /
                                  1000), user.email))
                else:
                    diff = timezone.now() - now
                    logger.debug(
                        "Spend {} milliseconds to get the user({}) data from usercache"
                        .format(
                            round((diff.seconds * 1000 + diff.microseconds) /
                                  1000), user.email))
            except KeyError:
                pass
            except ObjectDoesNotExist as ex:
                pass

            return user or anonymoususer
Exemplo n.º 3
0
 def tearDownClass(cls):
     cls.usersession.delete()
     usercache = get_usercache(cls.testuser.id)
     usercache.delete(settings.GET_USER_KEY(cls.testuser.id))
     usercache.delete(settings.GET_USERTOKEN_KEY(cls.testuser.id))
     cls.testusertoken.delete()
     cls.testuser.delete()
Exemplo n.º 4
0
 def tearDownClass(cls):
     if cls.CLEAN_TEST_CACHE_DATA:
         print("Clean the cached session data and user data")
         for testuser in cls.testusers:
             testuser.session.delete()
             usercache = get_usercache(testuser.id)
             #print("Delete session key {}".format(testuser.session.cache_key_prefix + testuser.session.session_key))
             usercache.delete(settings.GET_USER_KEY(testuser.id))
             #print("Delete user {} from cache with key({})".format(testuser.email,settings.GET_USER_KEY(testuser.id)))
             pass
Exemplo n.º 5
0
def user_details(strategy, details, user=None, *args, **kwargs):
    """Update user details using data from provider."""
    if not user:
        return

    changed = False  # flag to track changes
    protected = ('username', 'id', 'pk', 'email','first_name','last_name') + \
                tuple(strategy.setting('PROTECTED_USER_FIELDS', []))

    # Update user model attributes with the new data sent by the current
    # provider. Update on some attributes is disabled by default, for
    # example username and id fields. It's also possible to disable update
    # on fields defined in SOCIAL_AUTH_PROTECTED_USER_FIELDS.
    for name, value in details.items():
        if value is None or not hasattr(user, name) or name in protected:
            continue

        # Check https://github.com/omab/python-social-auth/issues/671
        current_value = getattr(user, name, None)
        if current_value == value:
            continue

        changed = True
        logger.debug(
            "The {1} of the User({0}) was changed from {2} to {3}".format(
                user.email, name, current_value, value))
        setattr(user, name, value)

    if not user.first_name or not user.last_name:
        nexturl = strategy.request.session.get(REDIRECT_FIELD_NAME)
        if nexturl:
            nexturl_parsed = utils.parse_url(nexturl)
            if nexturl_parsed["path"] != "/sso/profile/edit":
                nexturl = "/sso/profile/edit?{}={}".format(
                    REDIRECT_FIELD_NAME, urllib.parse.quote(nexturl))
        else:
            nexturl = "/sso/profile/edit"
        strategy.request.session[REDIRECT_FIELD_NAME] = nexturl

    if changed:
        strategy.storage.user.changed(user)
        usercache = get_usercache(user.id)
        if usercache:
            usercache.set(
                settings.GET_USER_KEY(user.id), user,
                settings.STAFF_CACHE_TIMEOUT
                if user.is_staff else settings.USER_CACHE_TIMEOUT)
            logger.debug("Cache the user({}) data to usercache".format(
                user.email))
Exemplo n.º 6
0
    def load_user(userid):
        """
        Return the user model instance associated with the given request session.
        If no user is retrieved, return an instance of `AnonymousUser`.
        """
        user = None
        try:
            #try to get user data from user cache
            userkey = settings.GET_USER_KEY(userid)
            usercache = get_usercache(userid)
            
            performance.start_processingstep("get_user_from_cache")
            try:
                user = usercache.get(userkey)
            except:
                pass
            finally:
                performance.end_processingstep("get_user_from_cache")
                pass

            if not user:
                #Can't find the user in user cache, retrieve it from database
                performance.start_processingstep("fetch_user_from_db")
                try:
                    user = User.objects.get(pk = userid)
                finally:
                    performance.end_processingstep("fetch_user_from_db")
                    pass
                #cache the user object into user cache
                performance.start_processingstep("set_user_to_cache")
                try:
                    usercache.set(userkey,user,settings.STAFF_CACHE_TIMEOUT if user.is_staff else settings.USER_CACHE_TIMEOUT)
                except:
                    pass
                finally:
                    performance.end_processingstep("set_user_to_cache")
                    pass

        except KeyError:
            pass
        except ObjectDoesNotExist as ex:
            #user does not exist.
            #if the current request is auth2_auth, return AUTH_REQUIRED_RESPONSE
            #if the current request is auth2_optional, return AUTH_NOT_REQUIRED_RESPONSE
            #otherwise. logout the user
            raise UserDoesNotExistException()

        return user or anonymoususer
Exemplo n.º 7
0
        def _get_user(request):
            """
            Return the user model instance associated with the given request session.
            If no user is retrieved, return an instance of `AnonymousUser`.
            """
            user = None
            try:
                userid = auth._get_user_session_key(request)
                userkey = settings.GET_USER_KEY(userid)
                user = usercache.get(userkey)
                if not user:
                    user = User.objects.get(pk=userid)
                    usercache.set(userkey, user, settings.USER_CACHE_TIMEOUT)
            except KeyError:
                pass
            except ObjectDoesNotExist as ex:
                pass

            return user or anonymoususer
Exemplo n.º 8
0
    def setUpClass(cls):
        print("Prepare {} test users".format(cls.TEST_USER_NUMBER))
        testemails = [
            "testuser_{:0>4}@dbca.wa.gov.au".format(i)
            for i in range(cls.TEST_USER_BASEID, cls.TEST_USER_BASEID +
                           cls.TEST_USER_NUMBER)
        ]

        if not cls.DOWNLOAD_TEST_DATA and cls.TEST_DATA_FILE:
            with open(cls.TEST_DATA_FILE, 'r') as f:
                testdata = json.loads(f.read())

            settings.CACHE_SESSION_SERVER = testdata["CACHE_SESSION_SERVER"]
            settings.CACHE_USER_SERVER = testdata["CACHE_USER_SERVER"]
            settings.CACHE_SERVER = testdata["CACHE_SERVER"]
            settings.SESSION_COOKIE_NAME = testdata.get("SESSION_COOKIE_NAME")
            settings.CACHE_KEY_PREFIX = testdata.get("CACHE_KEY_PREFIX")
            cachesessionstore.SessionStore.cache_key_prefix = "{}_session".format(
                settings.CACHE_KEY_PREFIX
            ) if settings.CACHE_KEY_PREFIX else "session"
            usersessiondata = testdata["usersession"]

            cls.TESTED_SERVER = testdata["TESTED_SERVER"]
            cls.auth_url = "{}/sso/authperformance".format(cls.TESTED_SERVER)
            cls.CLEAN_TEST_CACHE_DATA = False
            cls.TEST_TIME = testdata["TEST_TIME"]
            cls.TEST_REQUESTS = testdata["TEST_REQUESTS"]
            cls.REQUEST_INTERVAL = testdata["REQUEST_INTERVAL"] / 1000

            cls.testusers = []
            for email in testemails:
                userdata = usersessiondata[email]
                testuser = models.User(email=email, id=userdata["id"])

                usersession = cachesessionstore.SessionStore(
                    userdata["sessionkey"])

                testuser.session = usersession
                cls.testusers.append(testuser)
            print("Loaded {1} test users from file({0})".format(
                cls.TEST_DATA_FILE, cls.TEST_USER_NUMBER))
        else:
            cls.testusers = []

            userid = cls.TEST_USER_BASEID * -1
            for testemail in testemails:
                testuser = models.User(username=testemail,
                                       email=testemail,
                                       first_name="",
                                       last_name="",
                                       systemuser=True,
                                       is_staff=True,
                                       is_superuser=False,
                                       id=userid)
                usergroups = models.UserGroup.find_groups(testemail)[0]
                userid -= 1

                usercache = get_usercache(testuser.id)
                usercache.set(settings.GET_USER_KEY(testuser.id), testuser,
                              86400 * 14)
                usersession = cachesessionstore.SessionStore()

                usersession[USER_SESSION_KEY] = str(testuser.id)
                usersession[
                    BACKEND_SESSION_KEY] = "django.contrib.auth.backends.ModelBackend"
                usersession[HASH_SESSION_KEY] = ""
                usersession["session_timeout"] = 600

                usersession.save()

                #print("create the session({1}) for user({0})".format(testuser,usersession.session_key))

                testuser.session = usersession
                cls.testusers.append(testuser)
Exemplo n.º 9
0
def _save_user(key, value, expireat):
    userid = int(key)
    _save(get_usercache(userid), settings.GET_USER_KEY(userid), value,
          expireat)