Beispiel #1
0
    def authenticate(self, request):
        # In case there is an exception, tell others that the view passed
        # through Hawk authorization. The META dict is used because
        # middleware may not get an identical request object.
        # A dot-separated key is to work around potential environ var
        # pollution of META.
        request.META['hawk.receiver'] = None

        http_authorization = get_auth_header(request)
        if not http_authorization:
            log.debug('no authorization header in request')
            return None
        elif not is_hawk_request(request):
            log.debug('ignoring non-Hawk authorization header: {} '.format(
                http_authorization))
            return None

        try:
            receiver = Receiver(
                lambda cr_id: self.hawk_credentials_lookup(cr_id),
                http_authorization,
                request.build_absolute_uri(),
                request.method,
                content=request.body,
                seen_nonce=(seen_nonce if getattr(
                    settings, 'USE_CACHE_FOR_HAWK_NONCE', True) else None),
                content_type=request.META.get('CONTENT_TYPE', ''),
                timestamp_skew_in_seconds=getattr(settings,
                                                  'HAWK_MESSAGE_EXPIRATION',
                                                  default_message_expiration))
        except HawkFail as e:
            etype, val, tb = sys.exc_info()
            log.debug(traceback.format_exc())
            log.warning('access denied: {etype.__name__}: {val}'.format(
                etype=etype, val=val))
            # The exception message is sent to the client as part of the
            # 401 response, so we're intentionally vague about the original
            # exception type/value, to avoid assisting attackers.
            msg = 'Hawk authentication failed'
            if isinstance(e, BadHeaderValue):
                msg += ': The request header was malformed'
            elif isinstance(e, TokenExpired):
                msg += ': The token has expired. Is your system clock correct?'
            raise AuthenticationFailed(msg)

        # Pass our receiver object to the middleware so the request header
        # doesn't need to be parsed again.
        request.META['hawk.receiver'] = receiver
        return self.hawk_user_lookup(request, receiver.resource.credentials)
Beispiel #2
0
    def authenticate(self, request):
        if not request.json_body:
            raise AuthenticationFailed("Invalid request")

        client_id = request.json_body.get("client_id")
        client_secret = request.json_body.get("client_secret")

        invalid_pair_error = AuthenticationFailed("Invalid Client ID / Secret pair")

        if not client_id or not client_secret:
            raise invalid_pair_error

        try:
            application = ApiApplication.objects.get(client_id=client_id)
        except ApiApplication.DoesNotExist:
            raise invalid_pair_error

        if not constant_time_compare(application.client_secret, client_secret):
            raise invalid_pair_error

        try:
            return (application.sentry_app.proxy_user, None)
        except Exception:
            raise invalid_pair_error
Beispiel #3
0
    def authenticate(self, request):
        """Authenticates a request using two mechanisms:

        1. Ensure the request does not contain the X-Forwarded-For header
           (disallow access via public network)
        2. A Hawk signature in the Authorization header

        If either of these suggest we cannot authenticate, AuthenticationFailed
        is raised, as required in the DRF authentication flow
        """
        if 'HTTP_X_FORWARDED_FOR' in request.META:
            logger.warning(
                'Failed authentication: accessed from public network')
            raise AuthenticationFailed('Public network access denied')
        return self._authenticate_by_hawk(request)
Beispiel #4
0
def buy_movie(request):
    #Double checking method (I know it's unnecessary)
    if request.method == "POST":
        #Getting user's JWT token
        cookie = request.COOKIES.get('jwt')
        #Checking if token exists
        if not cookie:
            raise AuthenticationFailed("User not authenticated!")
        else:
            #Checking if token is valid, if not raising error
            try:
                payLoad = jwt.decode(cookie, 'key256', algorithms=['HS256'])
            except jwt.ExpiredSignatureError:
                raise AuthenticationFailed("User not authenticated!")
            #Getting movie id
            movie_id = request.data['id']
            #Getting user and movie
            user = Account.objects.get(id=payLoad['id'])
            movie = Movie.objects.get(id=movie_id)
            #Checking if movie exist
            if movie is None:
                raise NotFound("There is no such movie!")
            else:
                #Checking if user has sufficient funds
                if user.funds < movie.price:
                    raise PermissionDenied("Insufficient funds!")
                else:
                    #Buying a ticket
                    ticket = Ticket()
                    ticket.account_id = user
                    ticket.movie_id = movie
                    user.funds -= movie.price
                    user.save()
                    ticket.save()

                    return Response({"Message": "Ticket bought!"})
Beispiel #5
0
 def authenticate(self, request):
     """
     Authenticate the request and return a two-tuple of (user, token).
     """
     if request._request.path == '/api/v1/auth':
         return
     token_str = request._request.GET.get('token')
     if request.META.get('HTTP_X_FORWARDED_FOR'):
         ip = request.META.get("HTTP_X_FORWARDED_FOR")
     else:
         ip = request.META.get("REMOTE_ADDR")
     token = UserToken.objects.filter(token=token_str, address=ip).first()
     if not token:
         raise AuthenticationFailed('用户未登录认证!')
     return (token.user, token)
Beispiel #6
0
def login(request):
    email = request.POST.get("email", "")
    password = request.POST.get("password", "")
    user = authenticate(username=email, password=password)
    if user is not None:
        auth_login(request, user)
        user_data = {
            'id': user.id,
            'token': Token.objects.get(user=user).key,
            'first_name': user.first_name,
            'last_name': user.last_name,
            'user_type': user.user_type
        }
        return Response(user_data)
    raise AuthenticationFailed("Username / password do not match")
Beispiel #7
0
 def authenticate(self, request):
     # 获取用户的token
     # body里的token
     # token = request.data.get('token')
     # header里的token
     token = request._request.META.get('HTTP_TOKEN','')
     if request.query_params.get('token','') != '' and token == '':
         token = request.query_params.get('token','')
     # print(token)
     if not token:
         raise AuthenticationFailed({'detail': '参数无效', 'error_code': 1001})
     # 查询用户表中是否有相应的token
     try:
         user_obj = UserProfile.objects.get(token=token)
     except UserProfile.DoesNotExist:
         # 根据token查询user不存在就认证失败
         raise AuthenticationFailed({'detail': '认证失败', 'error_code': 1002})
     else:
         if user_obj.expiration_time > datetime.now():
             # print(user_obj)
             return user_obj, token
         # 	request.user	request.auth
         else:
             raise AuthenticationFailed({'detail': '认证过期', 'error_code': 1003})
Beispiel #8
0
    def authenticate(self, request):
        """
        Authenticate the user using token introspection.

        This first checks if the token is cached. If it's not cached, the token is looked
        up in Staff SSO. An adviser is then looked up using the retrieved token data.
        """
        try:
            authorization_header = request.META['HTTP_AUTHORIZATION']
        except KeyError as exc:
            raise AuthenticationFailed(NO_CREDENTIALS_MESSAGE) from exc

        scheme, _, token = authorization_header.partition(' ')

        if scheme.lower() != 'bearer':
            raise AuthenticationFailed(INCORRECT_SCHEME)

        if not token:
            raise AuthenticationFailed(NO_CREDENTIALS_MESSAGE)

        token_data, was_cached = _look_up_token(token, request)
        if not token_data:
            raise AuthenticationFailed(INVALID_CREDENTIALS_MESSAGE)

        user = _look_up_adviser(token_data)
        if not (user and user.is_active):
            raise AuthenticationFailed(INVALID_CREDENTIALS_MESSAGE)

        # Only record real (non-cached) introspections (otherwise we'd be recording every
        # request)
        if not was_cached:
            record_user_event(request,
                              UserEventType.OAUTH_TOKEN_INTROSPECTION,
                              adviser=user)

        return user, None
Beispiel #9
0
    def authenticate(self, request):
        # 获取token并判断token得合法性
        token = request.query_params.get("token")

        # 1、切割
        # 2、解密第二段/判断是否过期
        # 3、验证第三段的合法性

        SALT = settings.SECRET_KEY
        try:
            # 看到了那个True了吗,但凡payload有返回值,就表示校验成功
            payload = jwt.decode(token, SALT, True)
        except exceptions.ExpiredSignatureError:
            raise AuthenticationFailed({"code": 1003, "error": "token已失效"})
        except jwt.DecodeError:
            raise AuthenticationFailed({"code": 1003, "error": "token认证失败"})
        except jwt.InvalidTokenError:
            raise AuthenticationFailed({"code": 1003, "error": "非法的token"})

        # 三种异常
        # 1、抛出异常,后续不再执行
        # 2、return一个元组(1,2),认证通过,在视图中,如果调用request.user就是元组的第一个值,request.auth就是元组的第二个值
        # 3、None
        return (payload, token)
Beispiel #10
0
    def create(self, request):
        """ Create a session with credentials """
        serializer = AuthenticationSerializer(data=request.data)

        if not serializer.is_valid():
            if 'non_field_errors' in serializer.errors:
                raise AuthenticationFailed('Invalid credentials')

            raise ValidationError(serializer.errors)

        # Credentials are valid, let's login the user
        login(request, serializer.validated_data['user'])

        serialized_session = SessionSerializer(self.session)
        return Response(serialized_session.data)
Beispiel #11
0
    def authenticate(self, request):
        auth = get_authorization_header(request).split()

        if not auth or auth[0].lower() != b"digest":
            return None

        try:
            check_lockout(request)
            if self.authenticator.authenticate(request):
                return request.user, None
            else:
                attempts = login_attempts(request)
                remaining_attempts = (
                    getattr(settings, "MAX_LOGIN_ATTEMPTS", 10) - attempts)
                raise AuthenticationFailed(
                    _("Invalid username/password. "
                      "For security reasons, after {} more failed "
                      "login attempts you'll have to wait {} minutes "
                      "before trying again.".format(
                          remaining_attempts,
                          getattr(settings, "LOCKOUT_TIME", 1800) // 60,
                      )))
        except (AttributeError, ValueError, DataError) as e:
            raise AuthenticationFailed(e)
Beispiel #12
0
    def get_queryset(self) -> QuerySet:
        queryset = super().get_queryset().order_by("name")
        if self.action == "list":
            queryset = queryset.filter(deleted=False)
        queryset = queryset.prefetch_related(
            Prefetch("items", queryset=DashboardItem.objects.filter(deleted=False).order_by("order"),)
        )
        if self.request.GET.get("share_token"):
            return queryset.filter(share_token=self.request.GET["share_token"])
        elif self.request.user.is_authenticated and not self.request.user.team:
            raise NotFound()
        elif not self.request.user.is_authenticated or "team_id" not in self.get_parents_query_dict():
            raise AuthenticationFailed(detail="You're not logged in, but also not using add share_token.")

        return queryset
Beispiel #13
0
 def authenticate(self, request):
     token = request.META.get('HTTP_TOKEN', '') or request.GET.get(
         'token', '')
     if token:
         redis_client = get_redis_connection()
         user_pickle = redis_client.get(token)
         if user_pickle:
             # 此处返回一个二元组 - (user, token)
             # request.user <----- user
             # request.auth <----- token
             redis_client.set(token, user_pickle, 3600)
             user = pickle.loads(user_pickle)
             user.is_authenticated = True
             return (user, token)
     raise AuthenticationFailed('请提供有效的身份认证信息')
Beispiel #14
0
def token_from_header(raw_header: bytes) -> Optional[Token]:
    """raw_header in the Format of `Bearer dGVzdDp0ZXN0`"""
    auth_credentials = raw_header.decode()
    if auth_credentials == "":
        return None
    # Legacy, accept basic auth thats fully encoded (2021.3 outposts)
    if " " not in auth_credentials:
        try:
            plain = b64decode(auth_credentials.encode()).decode()
            auth_type, body = plain.split()
            auth_credentials = f"{auth_type} {b64encode(body.encode()).decode()}"
        except (UnicodeDecodeError, Error):
            raise AuthenticationFailed("Malformed header")
    auth_type, auth_credentials = auth_credentials.split()
    if auth_type.lower() not in ["basic", "bearer"]:
        LOGGER.debug("Unsupported authentication type, denying",
                     type=auth_type.lower())
        raise AuthenticationFailed("Unsupported authentication type")
    password = auth_credentials
    if auth_type.lower() == "basic":
        try:
            auth_credentials = b64decode(auth_credentials.encode()).decode()
        except (UnicodeDecodeError, Error):
            raise AuthenticationFailed("Malformed header")
        # Accept credentials with username and without
        if ":" in auth_credentials:
            _, password = auth_credentials.split(":")
        else:
            password = auth_credentials
    if password == "":  # nosec
        raise AuthenticationFailed("Malformed header")
    tokens = Token.filter_not_expired(key=password,
                                      intent=TokenIntents.INTENT_API)
    if not tokens.exists():
        raise AuthenticationFailed("Token invalid/expired")
    return tokens.first()
Beispiel #15
0
    def process_request(self, request):
        username = request.META.get('HTTP_USERNAME', None)
        password = request.META.get('HTTP_PASSWORD', None)

        if username and password:
            del request.META['HTTP_USERNAME']
            del request.META['HTTP_PASSWORD']
            try:
                user = authenticate(username=username, password=password)
                if not user:
                    raise AuthenticationFailed()
                django_login(request, user)
                request._dont_enforce_csrf_checks = True
            except Exception as ex:
                setattr(request, 'AUTHENTICATION_EXCEPTION', ex)
def user_jwt_payload_handler(user, elevated_token=None):
    payload = jwt_payload_handler(user)
    payload.pop('username')
    payload.pop('email')

    try:
        payload['identity_token'] = IdentityToken.objects.get(user=user).key
    except IdentityToken.DoesNotExist:
        raise AuthenticationFailed('Identity token does not exist!')

    payload['elevated_token'] = elevated_token
    payload['user_permissions'] = get_user_permissions_string_list(user)
    payload['service_permissions'] = get_user_service_permissions_string_list(
        user)
    return payload
Beispiel #17
0
    def post(self, request):
        username = request.data['username']
        password = request.data['password']
        user = authenticate(username=username, password=password)

        if user:
            token, _ = Token.objects.get_or_create(user=user)
        else:
            raise AuthenticationFailed()

        data = {
            'token': token.key,
            'user': UserSerializer(user).data,
        }
        return Response(data)
Beispiel #18
0
 def authenticate(self, request):
     account = request.data.get("email")
     password = request.data.get("password")
     user = User.objects.filter(account=account, password=password).first()
     if user:
         token = Authentication(account).tokenMaker()
         user.token = token
         user.save()
         request.session["account"] = account
         request.session["username"] = user.user_name
         request.session.set_expiry(60 * 60 * 24 * 7)
         cache.set(account, token)
         return (user, token)
     else:
         raise AuthenticationFailed(detail="1")
    def authenticate_credentials(self, request, token_str):
        token = SystemToken.from_request(request, token_str)
        try:
            token = (token or ApiToken.objects.filter(
                token=token_str).select_related("user", "application").get())
        except ApiToken.DoesNotExist:
            raise AuthenticationFailed("Invalid token")

        if token.is_expired():
            raise AuthenticationFailed("Token expired")

        if not token.user.is_active:
            raise AuthenticationFailed("User inactive or deleted")

        if token.application and not token.application.is_active:
            raise AuthenticationFailed("UserApplication inactive or deleted")

        with configure_scope() as scope:
            scope.set_tag("api_token_type", self.token_name)
            scope.set_tag("api_token", token.id)
            scope.set_tag("api_token_is_sentry_app",
                          getattr(token.user, "is_sentry_app", False))

        return (token.user, token)
 def validate(self, attrs):
     """ method to validate user informations """
             
     email = attrs.get('email', '')
     password = attrs.get('password', '')
     
     user = auth.authenticate(email=email, password=password)
     
     if not user:
         raise AuthenticationFailed('invalid informations, try again')
     
     if not user.is_active:
         raise AuthenticationFailed('no account, contact support')
     
     if not user.is_verified:
         raise AuthenticationFailed('email not verified')
     
     return {
         'email': user.email,
         'username': user.username,
         'tokens': user.tokens
     }
     
     return super().validate(attrs)
    def validate(self, attrs):
        email = attrs.get('email', '')
        password = attrs.get('password', '')

        user = authenticate(email=email, password=password)
        if not user:
            raise AuthenticationFailed('Invalid Credential. Try again')

        return {
            'firstname': user.firstname,
            'email': user.email,
            'lastname': user.lastname,
            'date_of_birth': user.date_of_birth,
            'tokens': user.tokens
        }
    def authenticate(self, request):

        # TODO: Determine best place for app to be configured
        if not firebase_admin._apps:
            firebase_admin.initialize_app()

        auth = authentication.get_authorization_header(request)

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

        return self._authenticate_credentials(firebase_token)
Beispiel #23
0
    def authenticate(self, request):
        bearer_token = self.get_bearer_token(request)
        if bearer_token is None:
            return None

        try:
            userinfo = self.get_userinfo(bearer_token)
        except HTTPError:
            msg = _(
                'Invalid Authorization header. Unable to verify bearer token')
            raise AuthenticationFailed(msg)

        user = api_settings.OIDC_RESOLVE_USER_FUNCTION(request, userinfo)

        return user, userinfo
Beispiel #24
0
 def authenticate(self, request: request.Request):
     # if the Origin is different, the only authentication method should be temporary_token
     # This happens when someone is trying to create actions from the editor on their own website
     if (
         request.headers.get("Origin")
         and urlsplit(request.headers["Origin"]).netloc
         not in urlsplit(request.build_absolute_uri("/")).netloc
     ):
         if not request.GET.get("temporary_token"):
             raise AuthenticationFailed(
                 detail="No temporary_token set. "
                 + "That means you're either trying to access this API from a different site, "
                 + "or it means your proxy isn't sending the correct headers. "
                 + "See https://posthog.com/docs/deployment/running-behind-proxy for more information."
             )
     if request.GET.get("temporary_token"):
         user_model = apps.get_model(app_label="posthog", model_name="User")
         user = user_model.objects.filter(
             temporary_token=request.GET.get("temporary_token")
         )
         if not user.exists():
             raise AuthenticationFailed(detail="User doesnt exist")
         return (user.first(), None)
     return None
Beispiel #25
0
def show_my_movies(request):
    #Double checking method (I know it's unnecessary)
    if request.method == "GET":
        #Getting user's JWT token
        cookie = request.COOKIES.get('jwt')
        #Checking if token exists
        if not cookie:
            raise AuthenticationFailed("User not authenticated!")

        else:
            #Checking if token is valid, if not raising error
            try:
                #Decoding token, to get user's id
                payLoad = jwt.decode(cookie, 'key256', algorithms=['HS256'])
            except jwt.ExpiredSignatureError:
                raise AuthenticationFailed("User not authenticated!")
            #Getting a given user
            user_id = Account.objects.get(id=payLoad['id'])
            #Getting his tickets
            tickets = Ticket.objects.filter(account_id_id=user_id)
            #Serializing tickets to send
            serializer = TicketSerializer(tickets, many=True)
            #Returning serialized tickets
            return Response(serializer.data)
Beispiel #26
0
    def get(self, request, userID):
        # get JWT token which is set as cookie.
        token = request.COOKIES.get('jwt')
        print(userID)
        
        # user is not loged in.
        if not token:
            raise AuthenticationFailed('Unauthenticated!')

         
        try:
            payload = jwt.decode(token, 'secret', algorithms=['HS256'])
        except jwt.ExpiredSignatureError:
            # jwt decode failed , JWT token is not correct
            raise AuthenticationFailed('Unauthenticated!')
        
        # the url userID and payload userID does not match
        if userID != payload['id']:
            raise AuthenticationFailed('Unauthenticated!')
        user = MyUser.objects.filter(id=userID).first()

        bookings = Booking.objects.filter(user=user)
        serialized =  BookingSerializer(bookings,many=True)
        return Response(serialized.data,status = status.HTTP_200_OK)   
Beispiel #27
0
    def validate(self, attrs):
        email = attrs.get('email', '')
        password = attrs.get('password','')

        user =  auth.authenticate(email=email, password=password)
        if not user:
            raise AuthenticationFailed("invalid credentials, please try again") 

        if not user.is_active:
            raise AuthenticationFailed("Account Dissabled, Please Contact Admin") 

        if not user.is_verified:
            raise AuthenticationFailed("Email Not Verified, Please verify") 


        

        return{
            'email': user.email,
            'username': user.username,
            'tokens': user.tokens
        }

        return super().validate(attrs)
    def authenticate(self, request):
        if 'token' not in request.query_params:
            raise AuthenticationFailed(
                _('Invalid token. No credentials provided.'))

        # Get token from request query params
        token = request.query_params.get('token').encode("utf-8")

        # Decrypt token
        cipher_suite = Fernet(settings.TOKEN_ENCRYPTION_KEY)
        try:
            json_str = cipher_suite.decrypt(token)
        except InvalidToken:
            raise AuthenticationFailed(
                _('Invalid token. Token should be enrypted data.'))

        # read json data
        try:
            payload = json.loads(json_str)
        except json.decoder.JSONDecodeError:
            raise AuthenticationFailed(
                _('Invalid token. Token should countain json data.'))

        # validate expiration time
        try:
            exp = int(payload["exp"])
        except ValueError:
            raise AuthenticationFailed(
                _('Invalid token. Expiration Time claim (exp) must be an integer.'
                  ))

        now = timegm(datetime.utcnow().utctimetuple())
        if exp < now:
            raise AuthenticationFailed(_("Invalid token. Token has expired."))

        return self.authenticate_credentials(payload["token"])
Beispiel #29
0
 def wrapper(request: HttpRequest):
     if not request.user.is_authenticated:
         try:
             auth_result = PersonalAPIKeyAuthentication.authenticate(
                 request)
             if isinstance(
                     auth_result,
                     tuple) and auth_result[0].__class__.__name__ == "User":
                 request.user = auth_result[0]
             else:
                 raise AuthenticationFailed(
                     "Authentication credentials were not provided.")
         except AuthenticationFailed as e:
             return JsonResponse({"detail": e.detail}, status=401)
     return endpoint(request)
Beispiel #30
0
    def validate(self, attrs):
        email = attrs.get('email', '')
        password = attrs.get('password', '')
        #filtered_user_by_email = User.objects.filter(email=email)
        user = auth.authenticate(email=email, password=password)

        #if filtered_user_by_email.exists() and filtered_user_by_email[0].auth_provider != 'email':
        #    raise AuthenticationFailed(
        #        detail='Please continue your login using ' + filtered_user_by_email[0].auth_provider)

        if not user:
            raise AuthenticationFailed('Invalid credentials, try again')
        if not user.is_active:
            raise AuthenticationFailed('Account disabled, contact admin')
        if not user.emailConf:
            raise AuthenticationFailed('Email is not verified')

        return {
            'email': user.email,
            'username': user.username,
            'tokens': user.tokens
        }

        return super().validate(attrs)