Example #1
0
 def authenticate_credentials(self, key):
     cache_user =  cache.get(key)
     if cache_user:
         return key, cache_user
     model = self.get_model()
     try:
         token = model.objects.select_related('user').get(key=key)
         # 自定义处理相关数据
         time_now = datetime.now()
         if token:
             if token.started <= time_now <= token.expires:
                 if token.user.category == '0':
                     token.expires = time_now + timedelta(hours=12)
                 elif token.user.category == '1':
                     token.expires = time_now + timedelta(days=15)
                 else:
                     raise exceptions.AuthenticationFailed(_('user type invalid.'))
                 token.save()
             else:
                 raise exceptions.AuthenticationFailed(_('token expired.'))
             if token:
                 cache.set(key, token.user, 30 * 60)
             return token, token.user
         else:
             raise exceptions.AuthenticationFailed(_('Invalid token.'))
     except model.DoesNotExist:
         raise exceptions.AuthenticationFailed(_('Invalid token.'))
Example #2
0
def sendConfirmInfo(request):
    token = request.query_params['token']
    try:
        tokenVaild = Token.objects.get(key=token)
    except:
        raise exceptions.AuthenticationFailed('token does not right')
    data = request.data
    confirmList = data['confirmList']
    try:
        for c in confirmList:
            confirmId = c.get('confirmId')
            status = c.get('status')
            server_money = c.get('server_money')
            total_money = c.get('total_money')
            confirmOrderInfo = ConfirmOrderInfo.objects.filter(
                id=confirmId).update(status=status,
                                     server_money=server_money,
                                     total_money=total_money)
        data['sccess'] = 1
        data['detail'] = u'成功'
        return Response(data)
    except:
        traceback.print_exc()
        return Response(data={"detail:error"},
                        status=status.HTTP_500_INTERNAL_SERVER_ERROR)
Example #3
0
    def authenticate(self, request):
        auth = get_authorization_header(request).split()

        if not auth or auth[0].lower() != self.keyword.lower().encode():
            return None

        if len(auth) == 1:
            msg = _('Invalid token header. No credentials provided.')
            raise exceptions.AuthenticationFailed(msg)
        elif len(auth) > 2:
            msg = _('Invalid token header. Token string should not contain spaces.')
            raise exceptions.AuthenticationFailed(msg)

        try:
            token = auth[1].decode()
        except UnicodeError:
            msg = _('Invalid token header. Token string should not contain invalid characters.')
            raise exceptions.AuthenticationFailed(msg)

        return self.authenticate_credentials(token)
Example #4
0
    def get_token(self, request):
        """
        获取用力的token
        :param request: 
        :return: 
        """
        # 向注册中心请求用户信息
        user_data = sdc_carrier_client.verify_user_ticket(request.user.get('ticket'))
        user = self._process_user_info(user_data)

        if user and user.is_active:
            try:
                token = AuthToken.objects.filter(user=user)
                # 自定义处理相关数据
                time_now = datetime.now()
                if token.started > time_now or token.expires < time_now:
                    if cache.has_key(token.key):
                        cache.delete(token.key)
                    token.delete()
                token = AuthToken(user=user)
            except AuthToken.DoesNotExist:
                token = AuthToken(user=user)
            except:
                token = None
            if token:
                if token.user.category == '0':
                    token.expires = datetime.now() + timedelta(hours=12)
                elif token.user.category == '1':
                    token.expires = datetime.now() + timedelta(days=15)
                else:
                    token.expires = datetime.now()
                token.save()
                cache.set(token.key, user, 30 * 60)
                return token.key
        elif user and user.is_active:
            AuthToken.objects.filter(user=user).delete()
            raise exceptions.AuthenticationFailed(_('User inactive or deleted.'))
        else:
            raise exceptions.AuthenticationFailed(_('Invalid ticket.'))
Example #5
0
    def _request(self,
                 op,
                 url,
                 data=None,
                 blocking=True,
                 retry_after_auth=False):
        retried = 0
        while True:
            try:
                if (op.upper() == 'GET'):
                    (status, content) = self._http_get(url,
                                                       headers=self._headers,
                                                       query_params=data)
                elif (op.upper() == 'POST'):
                    (status, content) = self._http_post(url,
                                                        body=data,
                                                        headers=self._headers)
                elif (op.upper() == 'DELETE'):
                    (status,
                     content) = self._http_delete(url,
                                                  body=data,
                                                  headers=self._headers)
                elif (op.upper() == 'PUT'):
                    (status, content) = self._http_put(url,
                                                       body=data,
                                                       headers=self._headers)
                else:
                    raise ValueError
            except ConnectionError as e:
                if not blocking:
                    raise

                retried += 1
                time.sleep(1)
                self._create_api_server_session()
                continue

            if status == 200:
                return content

            # Exception Response, see if it can be resolved
            if status == 401:
                if retry_after_auth:
                    raise exceptions.AuthenticationFailed(content)
                else:
                    self._headers = self._authenticate(content, self._headers)
                    # Recursive call after authentication (max 1 level)
                    content = self._request(op,
                                            url,
                                            data=data,
                                            retry_after_auth=True)
                return content
            elif status == 404:
                raise exceptions.NoIdError(
                    'Error: oper %s url %s body %s response %s' %
                    (op, url, data, content))
            elif status == 403:
                raise exceptions.PermissionDenied(content)
            elif status == 409:
                raise exceptions.RefsExistError(content)
            elif status == 504:
                # Request sent to API server, but no response came within lb timeout
                raise exceptions.TimeOutError('Gateway Timeout 504')
            elif status in [502, 503]:
                # 502: API server died after accepting request, so retry
                # 503: no API server available even before sending the request
                if not blocking:
                    raise exceptions.ServiceUnavailableError(
                        'Service Unavailable Timeout %d' % status)

                retried += 1
                time.sleep(1)
                continue
            elif status == 400:
                raise exceptions.BadRequest(status, content)
            else:  # Unknown Error
                raise exceptions.HttpError(status, content)
Example #6
0
 def authenticate(self, request):
     if not request.jwt_user:
         msg = u'请先授权'
         raise exceptions.AuthenticationFailed(msg)
     return (request.jwt_user, request.jwt_user.uuid)