Example #1
0
    def validate(self, data):
        user_obj = None
        username = data.get("username", None)
        email = data.get("email", None)
        password = data["password"]
        if email:
            email = email.lower()
        if not email and not username:
            raise serializers.ValidationError(
                "username or Email is Required to login")

        user = User.objects.filter(Q(email=email)
                                   | Q(username=username)).distinct()
        user = user.exclude(email__isnull=True).exclude(email__iexact='')
        if user.exists and user.count() == 1:
            user_obj = user.first()
        else:
            raise serializers.ValidationError(
                "A Username or Email is not valid")

        if user_obj:
            if not user_obj.is_active:
                raise serializers.ValidationError(
                    "Please Verify your confirmation Email")
            if not user_obj.check_password(password):
                raise serializers.ValidationError(
                    "Incorrect credentials please try again")

        payload = api_settings.JWT_PAYLOAD_HANDLER(user_obj)
        data["token"] = api_settings.JWT_ENCODE_HANDLER(payload)
        data['username'] = user_obj.get_username()
        return data
Example #2
0
def login(request):
    serializer = LoginSerializer(data=request.data)
    if serializer.is_valid(raise_exception=False):
        # get username
        username_or_email = serializer.data['username_or_email']
        if '@' in username_or_email:
            try:
                username = get_user_model().objects \
                    .get(email=username_or_email, social_auth__isnull=True) \
                    .username
            except get_user_model().DoesNotExist:
                username = username_or_email
        else:
            username = username_or_email

        # try credentials
        user = authenticate(username=username,
                            password=serializer.data['password'])
        if user is not None:
            # success
            payload = api_settings.JWT_PAYLOAD_HANDLER(user)
            token = api_settings.JWT_ENCODE_HANDLER(payload)
            response_payload = api_settings.JWT_RESPONSE_PAYLOAD_HANDLER(
                token, user)
            return Response(status=status.HTTP_200_OK,
                            data={
                                'authInfo': response_payload,
                                'msg': _('You have been logged in.')
                            })
    return Response(status=status.HTTP_403_FORBIDDEN,
                    data={'_error': _('Wrong username or password.')})
    def setUp(self):
        self.user = User.objects.create_user(username='******',
                                             email='*****@*****.**',
                                             password='******')
        self.payload = api_settings.JWT_PAYLOAD_HANDLER(self.user)
        self.token = api_settings.JWT_ENCODE_HANDLER(self.payload)
        self.headers = {'HTTP_AUTHORIZATION': 'JWT ' + self.token}
        self.valid_payload = {
            'username': '******',
            'email': '*****@*****.**',
        }
        self.invalid_payload = {
            'username': '******',
            'email': '*****@*****.**',
        }

        self.user1 = User.objects.create_user(username='******',
                                              email='*****@*****.**',
                                              password='******')
        self.user2 = User.objects.create_user(username='******',
                                              email='*****@*****.**',
                                              password='******')
        self.user3 = User.objects.create_user(username='******',
                                              email='*****@*****.**',
                                              password='******')
Example #4
0
    def get(self, request):
        code = request.query_params.get('code')
        if not code:
            return Response({'message': '缺少code'},
                            status=status.HTTP_400_BAD_REQUEST)

        oauthQQ = OAuthQQ()
        try:
            access_token = oauthQQ.get_access_token(code)
            open_id = oauthQQ.get_openid(access_token)
        except QQAPIError:
            return Response({'message': 'QQ服务异常'},
                            status=status.HTTP_503_SERVICE_UNAVAILABLE)

        try:
            QQ_bounded_user = OauthQQUser.objects.get(open_id__exact=open_id)
        except:
            token = oauthQQ.generate_token(open_id)
            return Response({'access_token': token})

        pay_load = api_settings.JWT_PAYLOAD_HANDLER(QQ_bounded_user.user)
        token = api_settings.JWT_ENCODE_HANDLER(pay_load)
        datas = {
            'user_id': QQ_bounded_user.id,
            'username': QQ_bounded_user.user.username,
            'token': token
        }

        return Response(datas)
Example #5
0
    def setUp(self):
        user = self.user = UserFactory(username=self.test_username)
        user.set_password(self.test_password)
        user.save()

        payload = api_settings.JWT_PAYLOAD_HANDLER(user)
        self.token = api_settings.JWT_ENCODE_HANDLER(payload)
Example #6
0
    def create(self, request):
        super(UserCreateViewSet, self).create(request)

        payload = api_settings.JWT_PAYLOAD_HANDLER(self.request.user)
        token = api_settings.JWT_ENCODE_HANDLER(payload)

        return Response({'token': token}, status=201)
Example #7
0
def authenticate_user(request):

    try:
        username = request.data['username']
        password = request.data['password']

        user = User.objects.get(username=username, password=password)
        if user:
            try:
                payload = api_settings.JWT_PAYLOAD_HANDLER(user)
                token = api_settings.JWT_ENCODE_HANDLER(payload)
                user_details = {}
                user_details['name'] = "%s %s" % (user.first_name,
                                                  user.last_name)
                user_details['token'] = token
                return JsonResponse(user_details, status=status.HTTP_200_OK)

            except Exception as e:
                raise e
        else:
            res = {'error': 'Invalid credentials'}
            return JsonResponse(res, status=status.HTTP_403_FORBIDDEN)
    except KeyError:
        res = {'error': 'please provide a username and password'}
        return JsonResponse(res)
 def setUp(self):
     self.user = User.objects.create_user(username='******',
                                          email='*****@*****.**',
                                          password='******')
     self.payload = api_settings.JWT_PAYLOAD_HANDLER(self.user)
     self.token = api_settings.JWT_ENCODE_HANDLER(self.payload)
     self.headers = {'HTTP_AUTHORIZATION': 'JWT ' + self.token}
    def post(self, request):
        username = request.data['username']
        password = request.data['password']

        if username is None or password is None:
            return Response({
                "success": False,
                "message": "Tài khoản hoặc mật khẩu không đúng"
            })
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            return Response({
                "success": False,
                "message": "Tài khoản hoặc mật khẩu không đúng"
            })

        if hashers.SHA1PasswordHasher().verify(password, user.password):
            user_serializer = UserSerializer(user)
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER(
                user_serializer.data)
            return Response({
                "success": True,
                "token": jwt_encode_handler,
                "role": user.role,
                "username": user.username
            })
        else:
            return Response({
                "success": False,
                "message": "Tài khoản hoặc mật khẩu không đúng"
            })
Example #10
0
    def post(seft, request):
        phone = request.data['phone']
        mat_khau = request.data['mat_khau']

        try:
            phu_huynh = Phu_huynh.objects.get(phone=phone)
        except Exception as e:
            print("Error:", e)
            return Response({
                "success": False,
                "message": "Tài khoản không tồn tại"
            })

        if hashers.SHA1PasswordHasher().verify(mat_khau, phu_huynh.mat_khau):
            studentSerializer = SerStudent(phu_huynh)
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER(
                studentSerializer.data)
            return Response({
                "success": True,
                "token": jwt_encode_handler,
                "role": phu_huynh.role,
                "data": studentSerializer.data
            })
        else:
            return Response({
                "success": False,
                "message": "Tài khoản hoặc mật khẩu không đúng"
            })
Example #11
0
 def encode(user) -> str:
     UserModel = get_user_model()
     try:
         userinfo = user.get_jwt_userinfo()
     except UserModel.userinfo.RelatedObjectDoesNotExist:
         raise exceptions.AuthenticationFailed("用户不存在")
     return api_settings.JWT_ENCODE_HANDLER(userinfo)
Example #12
0
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')

        user = authenticate(username=username, password=password)

        if user is not None:
            if user.is_active:
                login(request, user)

                payload = api_settings.JWT_PAYLOAD_HANDLER(self.request.user)
                token = api_settings.JWT_ENCODE_HANDLER(payload)

                return Response({'token': token}, status=200)

            return Response({'details': [
                "Oops! User is banned.",
            ]},
                            status=400)

        return Response(
            {
                'details': [
                    "Oops! Our system does not recognize that username or password.",
                ]
            },
            status=400)
Example #13
0
 def obtain(cls, user):
     from rest_framework_jwt.settings import api_settings
     payload = api_settings.JWT_PAYLOAD_HANDLER(user)
     return {
         'token': api_settings.JWT_ENCODE_HANDLER(payload),
         'user': user
     }
Example #14
0
 def login(self, username, password):
     user = auth.authenticate(username=username, password=password)
     if user is not None:
         token = api_settings.JWT_ENCODE_HANDLER(
             api_settings.JWT_PAYLOAD_HANDLER(user))
         update_last_login(None, user)
         return user, token
     return None, None
Example #15
0
def generate_read_jwt():
    from rest_framework_jwt.settings import api_settings
    payload = {
        'id': None,
        'username': None,
        'exp': time.mktime((datetime.datetime.now() + api_settings.JWT_EXPIRATION_DELTA).timetuple()),
    }
    return api_settings.JWT_ENCODE_HANDLER(payload)
Example #16
0
 def generate_jwt_token(self):
     """
     Generates JWT token and updates last login
     :return: JWT token
     """
     payload = api_settings.JWT_PAYLOAD_HANDLER(self)
     jwt_token = api_settings.JWT_ENCODE_HANDLER(payload)
     update_last_login(None, self)
     return jwt_token
Example #17
0
    def get_token(obj):
        """

        Retrieve the token associated with the object

        """
        payload = api_settings.JWT_PAYLOAD_HANDLER(obj)
        token = api_settings.JWT_ENCODE_HANDLER(payload)
        return token
Example #18
0
 def generate_api_token(self, user, **payload_overrides):
     """
     Creates a jwt token for this user.
     """
     from rest_framework_jwt.settings import api_settings
     payload = api_settings.JWT_PAYLOAD_HANDLER(user)
     payload.update(payload_overrides)
     token = api_settings.JWT_ENCODE_HANDLER(payload)
     return token
Example #19
0
 def _generate_token(self):
     return api_settings.JWT_ENCODE_HANDLER({
         'username':
         self.username,
         'email':
         self.email,
         'time':
         datetime.now().strftime('%c')
     })
Example #20
0
 def post(self, request, *args, **kwargs):
     resp = {}
     email = request.data.get('email')
     password = request.data.get('password')
     user = User.objects.filter(email=email).first()
     if user and user.check_password(password):
         payload = api_settings.JWT_PAYLOAD_HANDLER(user)
         jwt_token = api_settings.JWT_ENCODE_HANDLER(payload)
         resp["message"] = "User Logged in "
         resp["access_token"] = jwt_token
     return Response(resp, status=status.HTTP_200_OK)
Example #21
0
 def generate_token(self, request):
     user = request.user
     payload = {
         # 'id': user.id,
         'username':
         user.username,
         'exp':
         time.mktime((datetime.datetime.now() +
                      api_settings.JWT_EXPIRATION_DELTA).timetuple()),
     }
     return api_settings.JWT_ENCODE_HANDLER(payload)
Example #22
0
 def validate(self, data):
     email = data.get("email", None)
     password = data.get("password", None)
     user = authenticate(email=email, password=password)
     if user is None:
         raise serializers.ValidationError(
             "A user with this email and password is not found.")
     payload = api_settings.JWT_PAYLOAD_HANDLER(user)
     jwt_token = api_settings.JWT_ENCODE_HANDLER(payload)
     update_last_login(None, user)
     return {"email": user.email, "token": jwt_token}
Example #23
0
def make_token(user, expired=False):
    """Creates a valid jwt for the given user"""
    from rest_framework_jwt.settings import api_settings
    from datetime import timedelta

    payload = api_settings.JWT_PAYLOAD_HANDLER(user)
    if expired:
        payload['exp'] += timedelta(days=-1)  # expire it one day ago

    token = api_settings.JWT_ENCODE_HANDLER(payload)

    return token
Example #24
0
    def create(self, validate_data):
        phone = validate_data.get("phone")
        password = validate_data.get("password")

        user = User.objects.create_user(
            phone=phone,
            username=phone,
            password=password
        )
        payload = api_settings.JWT_PAYLOAD_HANDLER(user)
        user.token = api_settings.JWT_ENCODE_HANDLER(payload)
        return user
Example #25
0
 def create(self, request):
     """
     :param request: {'username': '******', 'password': '******'}
     :return:  {'token': 'abcdef123456'}
     """
     account = authenticate(**request.data)
     if not account:
         raise serializers.ValidationError({'error': 'Incorrect Username or Password'})
     pre_payload = api_settings.JWT_PAYLOAD_HANDLER(account)
     token = api_settings.JWT_ENCODE_HANDLER(pre_payload)
     token = api_settings.JWT_RESPONSE_PAYLOAD_HANDLER(token)
     return Response(token)
 def create(self, validated_data):
     """
     @brief      account registration logic.
     """
     if validated_data['password'] != validated_data['confirm_password']:
         raise serializers.ValidationError({'error': 'Passwords must match'})
     else:
         del validated_data['confirm_password']
     account = User.objects.create_user(**validated_data)
     pre_payload = api_settings.JWT_PAYLOAD_HANDLER(account)
     token = api_settings.JWT_ENCODE_HANDLER(pre_payload)
     account.token = api_settings.JWT_RESPONSE_PAYLOAD_HANDLER(token)
     return account
Example #27
0
 def _get_session_key(self):
     """
     Most session backends don't need to override this method, but we do,
     because instead of generating a random string, we want to actually
     generate a JWT Token with DRF-JWT.
     """
     session_cache = getattr(self, '_session_cache', {})
     return api_settings.JWT_ENCODE_HANDLER({
         **session_cache, 'exp':
         datetime.utcnow() + timedelta(seconds=settings.SESSION_COOKIE_AGE)
         # any other JWT fields like 'iss' etc. could be added here...
         # see: https://github.com/GetBlimp/django-rest-framework-jwt/blob/master/rest_framework_jwt/utils.py#L11
     })
Example #28
0
 def post(self, request):
     serializer = LoginSerializer(data=request.data)
     serializer.is_valid(raise_exception=True)
     user = serializer.validated_data['user']
     if not user:
         return Response(status=status.HTTP_404_NOT_FOUND)
     payload = api_settings.JWT_PAYLOAD_HANDLER(user)
     token = api_settings.JWT_ENCODE_HANDLER(payload)
     return Response({
         **payload,
         'token': token,
         'exp': settings.JWT_AUTH['JWT_EXPIRATION_DELTA'].total_seconds()
     })
Example #29
0
def add_api_token_to_response(response, user):
    # Generate API token and add it to the json response.
    payload = jwt_api_settings.JWT_PAYLOAD_HANDLER(user)
    token = jwt_api_settings.JWT_ENCODE_HANDLER(payload)
    if hasattr(response, 'data'):
        response.data['token'] = token
    # Also include the API token in a session cookie, so that it is available
    # for universal frontend apps.
    response.set_cookie('jwt_api_auth_token',
                        token,
                        max_age=settings.SESSION_COOKIE_AGE or None,
                        secure=settings.SESSION_COOKIE_SECURE or None,
                        httponly=settings.SESSION_COOKIE_HTTPONLY or None)

    return response
 def validate(self, data):
     username = data.get("username", None)
     password = data.get("password", None)
     user = authenticate(username=username, password=password)
     if user is None:
         raise serializers.ValidationError(
             'A user with this username and password is not found.')
     try:
         payload = api_settings.JWT_PAYLOAD_HANDLER(user)
         jwt_token = api_settings.JWT_ENCODE_HANDLER(payload)
         update_last_login(None, user)
     except CustomUser.DoesNotExist:
         raise serializers.ValidationError(
             'User with given username and password does not exists')
     return {'username': user.username, 'token': jwt_token}