def handle_get_token(self, req):
        """Handles the various `request for token and service end point(s)` calls.
        There are various formats to support the various auth servers in the
        past. Examples::

            GET <auth-prefix>/v1/<act>/auth
                X-Auth-User: <act>:<usr>  or  X-Storage-User: <usr>
                X-Auth-Key: <key>         or  X-Storage-Pass: <key>
            GET <auth-prefix>/auth
                X-Auth-User: <act>:<usr>  or  X-Storage-User: <act>:<usr>
                X-Auth-Key: <key>         or  X-Storage-Pass: <key>
            GET <auth-prefix>/v1.0
                X-Auth-User: <act>:<usr>  or  X-Storage-User: <act>:<usr>
                X-Auth-Key: <key>         or  X-Storage-Pass: <key>

        Values should be url encoded, "act%3Ausr" instead of "act:usr" for
        example; however, for backwards compatibility the colon may be included
        unencoded.

        On successful authentication, the response will have X-Auth-Token and
        X-Storage-Token set to the token to use with Swift and X-Storage-URL
        set to the URL to the default Swift cluster to use.

        The response body will be set to the account's services JSON object as
        described here::

            {"storage": {     # Represents the Swift storage service end points
                "default": "cluster1", # Indicates which cluster is the default
                "cluster1": "<URL to use with Swift>",
                    # A Swift cluster that can be used with this account,
                    # "cluster1" is the name of the cluster which is usually a
                    # location indicator (like "dfw" for a datacenter region).
                "cluster2": "<URL to use with Swift>"
                    # Another Swift cluster that can be used with this account,
                    # there will always be at least one Swift cluster to use or
                    # this whole "storage" dict won't be included at all.
             },
             "servers": {       # Represents the Nova server service end points
                # Expected to be similar to the "storage" dict, but not
                # implemented yet.
             },
             # Possibly other service dicts, not implemented yet.
            }

        One can also include an "X-Auth-New-Token: true" header to
        force issuing a new token and revoking any old token, even if
        it hasn't expired yet.

        :param req: The swob.Request to process.
        :returns: swob.Response, 2xx on success with data set as explained
                  above.
        """
        # Validate the request info
        try:
            pathsegs = split_path(req.path_info, minsegs=1, maxsegs=3,
                                  rest_with_last=True)
        except __HOLE__:
            return HTTPNotFound(request=req)
        if pathsegs[0] == 'v1' and pathsegs[2] == 'auth':
            account = pathsegs[1]
            user = req.headers.get('x-storage-user')
            if not user:
                user = unquote(req.headers.get('x-auth-user', ''))
                if not user or ':' not in user:
                    return HTTPUnauthorized(request=req)
                account2, user = user.split(':', 1)
                if account != account2:
                    return HTTPUnauthorized(request=req)
            key = req.headers.get('x-storage-pass')
            if not key:
                key = unquote(req.headers.get('x-auth-key', ''))
        elif pathsegs[0] in ('auth', 'v1.0'):
            user = unquote(req.headers.get('x-auth-user', ''))
            if not user:
                user = req.headers.get('x-storage-user')
            if not user or ':' not in user:
                return HTTPUnauthorized(request=req)
            account, user = user.split(':', 1)
            key = unquote(req.headers.get('x-auth-key', ''))
            if not key:
                key = req.headers.get('x-storage-pass')
        else:
            return HTTPBadRequest(request=req)
        if not all((account, user, key)):
            return HTTPUnauthorized(request=req)
        if user == '.super_admin' and self.super_admin_key and \
                key == self.super_admin_key:
            token = self.get_itoken(req.environ)
            url = '%s/%s.auth' % (self.dsc_url, self.reseller_prefix)
            return Response(
                request=req,
                content_type=CONTENT_TYPE_JSON,
                body=json.dumps({'storage': {'default': 'local',
                                             'local': url}}),
                headers={'x-auth-token': token,
                         'x-storage-token': token,
                         'x-storage-url': url})

        # Authenticate user
        path = quote('/v1/%s/%s/%s' % (self.auth_account, account, user))
        resp = self.make_pre_authed_request(
            req.environ, 'GET', path).get_response(self.app)
        if resp.status_int == 404:
            return HTTPUnauthorized(request=req)
        if resp.status_int // 100 != 2:
            raise Exception('Could not obtain user details: %s %s' %
                            (path, resp.status))
        user_detail = json.loads(resp.body)
        if not self.credentials_match(user_detail, key):
            return HTTPUnauthorized(request=req)
        # See if a token already exists and hasn't expired
        token = None
        expires = None
        candidate_token = resp.headers.get('x-object-meta-auth-token')
        if candidate_token:
            path = quote('/v1/%s/.token_%s/%s' %
                (self.auth_account, candidate_token[-1], candidate_token))
            delete_token = False
            try:
                if req.headers.get('x-auth-new-token', 'false').lower() in \
                        TRUE_VALUES:
                    delete_token = True
                else:
                    resp = self.make_pre_authed_request(
                        req.environ, 'GET', path).get_response(self.app)
                    if resp.status_int // 100 == 2:
                        token_detail = json.loads(resp.body)
                        if token_detail['expires'] > time():
                            token = candidate_token
                            expires = token_detail['expires']
                        else:
                            delete_token = True
                    elif resp.status_int != 404:
                        raise Exception(
                            'Could not detect whether a token already exists: '
                            '%s %s' % (path, resp.status))
            finally:
                if delete_token:
                    self.make_pre_authed_request(
                        req.environ, 'DELETE', path).get_response(self.app)
                    memcache_client = cache_from_env(req.environ)
                    if memcache_client:
                        memcache_key = '%s/auth/%s' % (self.reseller_prefix,
                                                       candidate_token)
                        memcache_client.delete(memcache_key)
        # Create a new token if one didn't exist
        if not token:
            # Retrieve account id, we'll save this in the token
            path = quote('/v1/%s/%s' % (self.auth_account, account))
            resp = self.make_pre_authed_request(
                req.environ, 'HEAD', path).get_response(self.app)
            if resp.status_int // 100 != 2:
                raise Exception('Could not retrieve account id value: '
                                '%s %s' % (path, resp.status))
            account_id = \
                resp.headers['x-container-meta-account-id']
            # Generate new token
            token = '%stk%s' % (self.reseller_prefix, uuid4().hex)
            # Save token info
            path = quote('/v1/%s/.token_%s/%s' %
                         (self.auth_account, token[-1], token))
            try:
                token_life = min(
                    int(req.headers.get('x-auth-token-lifetime',
                                        self.token_life)),
                    self.max_token_life)
            except ValueError:
                token_life = self.token_life
            expires = int(time() + token_life)
            resp = self.make_pre_authed_request(
                req.environ, 'PUT', path,
                json.dumps({'account': account, 'user': user,
                'account_id': account_id,
                'groups': user_detail['groups'],
                'expires': expires})).get_response(self.app)
            if resp.status_int // 100 != 2:
                raise Exception('Could not create new token: %s %s' %
                                (path, resp.status))
            # Record the token with the user info for future use.
            path = quote('/v1/%s/%s/%s' % (self.auth_account, account, user))
            resp = self.make_pre_authed_request(
                req.environ, 'POST', path,
                headers={'X-Object-Meta-Auth-Token': token}
            ).get_response(self.app)
            if resp.status_int // 100 != 2:
                raise Exception('Could not save new token: %s %s' %
                                (path, resp.status))
        # Get the services information
        path = quote('/v1/%s/%s/.services' % (self.auth_account, account))
        resp = self.make_pre_authed_request(
            req.environ, 'GET', path).get_response(self.app)
        if resp.status_int // 100 != 2:
            raise Exception('Could not obtain services info: %s %s' %
                            (path, resp.status))
        detail = json.loads(resp.body)
        url = detail['storage'][detail['storage']['default']]
        return Response(
            request=req,
            body=resp.body,
            content_type=CONTENT_TYPE_JSON,
            headers={'x-auth-token': token,
                     'x-storage-token': token,
                     'x-auth-token-expires': str(int(expires - time())),
                     'x-storage-url': url})
dataset/ETHPy150Open openstack/swauth/swauth/middleware.py/Swauth.handle_get_token