예제 #1
0
 def post(self, *args, **kwargs):
     serializer = TokenSerializer(data=self.request.data)
     serializer.is_valid(raise_exception=True)
     try:
         user = User.objects.get(email=serializer.data['email'],
                                 code=serializer.data['code'])
     except User.DoesNotExist:
         return Response(data={'detail': 'Invalid email or code'},
                         status=status.HTTP_400_BAD_REQUEST)
     else:
         user.is_active = True
         user.save()
         refresh_token = RefreshToken.for_user(user)
         return Response({'token': str(refresh_token.access_token)})
예제 #2
0
def validate_token(request, *args, **kwargs):
    """Validate the token and return 200 code if valid.

    If the token is invalid this function is not executed (the request fails before)


    Params
    ------
    request: Request
        The Request object
    args: list
        List of addittional arguments. Currenlty unused
    kwargs: dict
        Dictionary with addittional keyword arguments (indexed by keys in the dict),
        one optional parameter that could be expeted is `flags`

    Returns
    -------
    Response
        The response stating that the token is valid with a 200 status code.
    """
    flags = kwargs.get("flags", None)
    no_config = flags == "no_config" or flags == "no-config"
    token_key = request.META.get("HTTP_AUTHORIZATION")[6:]
    token = Token.objects.get(key=token_key)
    data = TokenSerializer(token, context={"no_config": no_config}).data
    return Response(data)
예제 #3
0
    def post(self, request, *args, **kwargs):
        """Handle the (post) request for token.

        If the token is invalid this function is not executed (the request fails before)

        Params
        ------
        request: Request
            The Request object
        args: list
            List of addittional arguments. Currently unused
        kwargs: dict
            Dictionary with addittional keyword arguments (indexed by keys in the dict). Currenlty unused

        Returns
        -------
        Response
            The response containing the token and other user data.
        """
        if not request.user.is_authenticated or not request._auth:
            return Response(status=status.HTTP_401_UNAUTHORIZED)
        serializer = self.serializer_class(data=request.data,
                                           context={"request": request})
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data["user"]
        token = Token.objects.create(user=user)
        old_token = request._auth
        old_token.delete()

        flags = kwargs.get("flags", None)
        no_config = flags == "no_config" or flags == "no-config"
        data = TokenSerializer(token, context={"no_config": no_config}).data
        return Response(data)
예제 #4
0
    def post(self, request, *args, **kwargs):
        """Handle the (post) request for token.

        If the token is invalid this function is not executed (the request fails before)

        Params
        ------
        request: Request
            The Request object
        args: list
            List of addittional arguments. Currenlty unused
        kwargs: dict
            Dictionary with addittional keyword arguments (indexed by keys in the dict). Currenlty unused

        Returns
        -------
        Response
            The response containing the token and other user data.
        """
        serializer = self.serializer_class(data=request.data,
                                           context={"request": request})
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data["user"]
        token = Token.objects.create(user=user)
        return Response(TokenSerializer(token).data)
예제 #5
0
    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        token = serializer.create(serializer.data)
        result = TokenSerializer(token)

        return Response(result.data, status=status.HTTP_201_CREATED)
예제 #6
0
def token_view(request):

    if request.method == 'GET':
        tokens = Token.objects.all()
        serializer = TokenSerializer(tokens, many=True)

        return Response(serializer.data)
 def post(self, request, *args, **kwargs):
     username = request.data.get('username', '')
     password = request.data.get('password', '')
     user = authenticate(request, username=username, password=password)
     if user is not None:
         # login saves the user’s ID in the session,
         # using Django’s session framework.
         login(request, user)
         serializer = TokenSerializer(
             data={
                 # using drf jwt utility functions to generate a token
                 'token': jwt_encode_handler(jwt_payload_handler(user))
             })
         serializer.is_valid()
         return Response(serializer.data)
     return Response(status=status.HTTP_401_UNAUTHORIZED)
예제 #8
0
파일: views.py 프로젝트: lokoArt/mozo
    def post(self, request):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)

        user = auth.authenticate(email=serializer.validated_data['email'],
                                 password=serializer.validated_data['password'])

        if user is None:
            raise AuthenticationFailed()

        if not Token.objects.filter(user=user).exists():
            token = Token.objects.create(user=user)
        else:
            token = Token.objects.get(user=user)

        token_serializer = TokenSerializer(data={'token': token.key})
        token_serializer.is_valid()

        return Response(data=token_serializer.data)
예제 #9
0
 def get(self, request):
     user = request.user
     if not user.is_authenticated():
         return Response(
             "Logged-in User or POST required to retrieve AuthToken",
             status=status.HTTP_403_FORBIDDEN)
     # Authenticated users have tokens
     token = lookupSessionToken(request)
     if token.is_expired():
         # Sanity Check: New tokens should be created
         # when auth token is expired.
         token = createAuthToken(user.username)
     serialized_data = TokenSerializer(token).data
     return Response(serialized_data, status=status.HTTP_200_OK)
예제 #10
0
 def post(self, request, *args, **kwargs):
     serializer = self.get_serializer(data=request.data)
     if serializer.is_valid():
         user = serializer.user
         token, _ = ExpiringToken.objects.get_or_create(user=user)
         if user:
             if token.expired():
                 token.delete()
                 return Response(data="Token expired, Login again")
             else:
                 return Response(
                     data=TokenSerializer(token).data,
                     status=status.HTTP_200_OK,
                 )
     else:
         return Response(
                 data=serializer.errors,
                 status=status.HTTP_401_UNAUTHORIZED,
                 )
예제 #11
0
 def post(self, request):
     serializer = TokenSerializer(data=request.data)
     serializer.is_valid(raise_exception=True)
     instance = serializer.save()
     return Response({'id': instance.id})
예제 #12
0
    def post(self, request):
        data = request.data
        email = data.get('email')
        passw = data.get('password')
        password = hashlib.sha256(str(passw).encode('utf-8')).hexdigest()

        # Validaciones de datos recividos
        patronPass = re.compile(r"^(?=\w*\d)(?=\w*[A-Z])(?=\w*[a-z])\S{8,16}$")
        # Correo
        if re.match('^[(a-z0-9\_\-\.)]+@[(a-z0-9\_\-\.)]+\.[(a-z)]{2,15}$',
                    email.lower()):
            if patronPass.search(passw) != None:
                pass
            else:
                mensaje = {
                    'message':
                    'La contraseña debe tener al entre 8 y 16 caracteres, al menos un dígito, al menos una minúscula y al menos una mayúscula.'
                    + ' NO puede tener otros símbolos.'
                }
                return Response(mensaje, status=status.HTTP_400_BAD_REQUEST)
        else:
            mensaje = {'message': 'Formato de correo invalido.'}
            return Response(mensaje, status=status.HTTP_400_BAD_REQUEST)

        # Se verifica si el usuario existe
        try:
            user = User.objects.get(email=email, password=password)
        except User.DoesNotExist:
            mensaje = {'message': 'Datos incorrectos.'}
            return Response(mensaje, status=status.HTTP_200_OK)

        if user:
            # Generamos token y lo guardamos
            refresh = RefreshToken.for_user(user)
            refresh_token = str(refresh)
            access_token = str(refresh.access_token)
            token = {
                'refresh': refresh_token,
                'access': access_token,
                'user': user.id
            }
            serializer = TokenSerializer(data=token)
            if serializer.is_valid():
                try:
                    serializer.save()
                except:
                    mensaje = {'message': 'Algo salio mal al guardar token.'}
                    return Response(
                        mensaje, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
                usuario = {
                    'name': user.name,
                    'lastName': user.lastName,
                    'date': user.date,
                    'age': user.age,
                    'email': user.email,
                    'tipo': user.tipo
                }
                respuesta = {'token': token, 'usuario': usuario}
                return Response(respuesta, status=status.HTTP_200_OK)
            else:
                return Response(serializer.errors,
                                status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        else:
            # El ususario no existe
            mensaje = {'message': 'Datos incorrecto.'}
            return Response(mensaje, status=status.HTTP_200_OK)