Ejemplo n.º 1
0
    def validate(self, attrs):
        credentials = self._get_credentials(attrs)

        if all(credentials.values()):
            user = authenticate(**credentials)

            if user:
                if not user.is_active:
                    msg = 'User account is disabled.'
                    raise serializers.ValidationError(msg)

                payload = jwt_payload_handler(user)

                # Include original issued at time for a brand new token,
                # to allow token refresh
                if api_settings.JWT_ALLOW_REFRESH:
                    payload['orig_iat'] = timegm(
                        datetime.utcnow().utctimetuple()
                    )

                return {
                    'token': jwt_encode_handler(payload),
                    'user': user,
                }
            else:
                msg = 'Unable to login with provided credentials.'
                raise serializers.ValidationError(msg)
        else:
            msg = 'credentials is not correct'
            raise serializers.ValidationError(msg)
Ejemplo n.º 2
0
 def create(self, request, *args, **kwargs):
     serializer = self.get_serializer(data=request.data)
     serializer.is_valid(raise_exception=True)
     user = serializer.save()      # 注册成功,将SQL记录插入语句提交到数据库执行
     re_dict = serializer.data
     # JWT模块的加密算法得到token,降低服务器的存储压力,并提高安全性
     payload = jwt_payload_handler(user)
     re_dict["jwt_token"] = jwt_encode_handler(payload)
     headers = self.get_success_headers(serializer.data)
     return Response(re_dict, status=status.HTTP_201_CREATED, headers=headers)
Ejemplo n.º 3
0
	def create(self,request,*args,**kwargs):
		serializer = self.get_serializer(data=request.data)
		serializer.is_valid(raise_exception=True)
		user = self.perform_create(serializer)

		re_dict = serializer.data
		payload = jwt_payload_handler(user)
		re_dict["token"] = jwt_encode_handler(payload)
		re_dict["name"] = user.name if user.name else user.username

		headers = self.get_success_headers(serializer.data)
		return Response(re_dict, status=status.HTTP_201_CREATED, headers=headers)
Ejemplo n.º 4
0
    def create(self, request, *args, **kwargs):
        """
        重载CreateModelMixin的create方法,用户注册完成后返回jwt-token
        """
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = self.perform_create(serializer)

        re_dict = serializer.data
        payload = jwt_payload_handler(user)
        re_dict["token"] = jwt_encode_handler(payload)
        re_dict["name"] = user.name if user.name else user.username

        headers = self.get_success_headers(serializer.data)
        return Response(re_dict,
                        status=status.HTTP_201_CREATED,
                        headers=headers)
Ejemplo n.º 5
0
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        # self.perform_create(serializer)

        # 重写生成token
        user = self.perform_create(serializer)
        re_dict = serializer.data
        payload = jwt_payload_handler(user)
        re_dict["token"] = jwt_encode_handler(payload)
        re_dict["name"] = user.username if user.username else user.mobile

        headers = self.get_success_headers(serializer.data)
        # return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
        return Response(re_dict,
                        status=status.HTTP_201_CREATED,
                        headers=headers)
Ejemplo n.º 6
0
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        print(serializer.initial_data)
        serializer.is_valid(raise_exception=True)
        user = self.perform_create(serializer)

        # 在create 中自定义方法 -> jwt 认证
        re_dict = serializer.data
        payload = jwt_payload_handler(user)
        re_dict['token'] = jwt_encode_handler(payload)
        re_dict['name'] = user.name if user.name else user.username

        headers = self.get_success_headers(serializer.data)
        print(re_dict)
        return Response(re_dict,
                        status=status.HTTP_201_CREATED,
                        headers=headers)
Ejemplo n.º 7
0
 def create(self, request, *args, **kwargs):
     serializer = self.get_serializer(data=request.data)
     serializer.is_valid(raise_exception=True)
     user = self.perform_create(serializer)
     headers = self.get_success_headers(serializer.data)
     # 生成token
     payload = jwt_payload_handler(user)
     token = jwt_encode_handler(payload)
     ret_data = {
         'nickname': user.nickname,
         'userid': user.id,
         'token': token
     }
     ret_data.update(serializer.data)
     return Response(ret_data,
                     status=status.HTTP_201_CREATED,
                     headers=headers)
Ejemplo n.º 8
0
    def validate(self, attrs):
        username = attrs.get('username')
        password = attrs.get('password')
        user = models.User.objects.filter(username=username,
                                          is_delete=False).first()
        if not user:
            raise ValidationError('该用户不存在')
        if not user.check_password(str(password)):
            raise ValidationError('密码错误')
        self.user = user

        self.user_icon = os.path.join(f'{settings.BASE_URL}/media/',
                                      str(user.user_icon))
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        self.token = token
        return attrs
Ejemplo n.º 9
0
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        now_user = self.perform_create(serializer)

        now_payload = jwt_payload_handler(now_user)
        now_token = jwt_encode_handler(now_payload)

        now_dict = serializer.data
        now_dict["token"] = now_token
        now_dict[
            "name"] = now_user.name if now_user.name else now_user.username

        headers = self.get_success_headers(serializer.data)
        return Response(now_dict,
                        status=status.HTTP_201_CREATED,
                        headers=headers)
Ejemplo n.º 10
0
    def post(self, request):
        data = request.data  # 获取微信数据
        code = data.get('code', '')
        if not code:
            return Response({'msg': '缺少code'}, status=status.HTTP_404_NOT_FOUND)

        # url = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code" \
        #     .format(settings.APP_ID, settings.APP_KEY, code)
        # r = requests.get(url)
        # res = json.loads(r.text)
        # session_key = res['session_key'] if 'session_key' in res else None
        # res.pop('session_key', None)
        # 封装方法:微信返回的json数据
        wx = WxLogin()
        res = wx.getUserInfo(code)

        openid = res['openid'] if 'openid' in res else None
        if not openid:
            return Response({'message': '微信调用失败'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)

        # 判断用户是否第一次登录
        try:
            user = User.objects.get(openid=openid)
        except Exception:
            # 微信用户第一次登陆,新建用户

            # username = request.data.get('nickname')
            # sex = request.data.get('sex')

            # 微信传递过来的openid,储存到数据库。
            # 微信再次请求,如果有openid就不新建,直接返回token给微信登录
            user = User.objects.create(username=openid,openid=openid)
            user.set_password(openid)
            user.save()

        # token
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        resp_data = {
            "user_id": user.id,
            "username": user.username,
            "token": token,
        }

        return Response(resp_data,status=status.HTTP_201_CREATED)
Ejemplo n.º 11
0
    def demo_post(self, request, *args, **kwargs):
        account = request.data.get("account")
        pwd = request.data.get("pwd")

        if re.match(r'.+@.+', account):
            user_obj = User.objects.filter(email=account).first()
        elif re.match(r'1[3-9][0-9]{9}', account):
            user_obj = User.objects.filter(phone=account).first()
        else:
            user_obj = User.objects.filter(username=account).first()

        if user_obj and user_obj.check_password(pwd):
            payload = jwt_payload_handler(user_obj)
            token = jwt_encode_handler(payload)
            return APIResponse(results={"username:user_obj.username"},
                               token=token)
        return APIResponse(data_message="错误了")
Ejemplo n.º 12
0
 def post(self, request, *args, **kwargs):
     params = json.loads(request.body)
     username = params['username']
     password = params['password']
     user_obj = auth.authenticate(username=username, password=password)
     if user_obj and user_obj.is_active:
         payload = jwt_payload_handler(user_obj)
         token = jwt_encode_handler(payload)
         token_key = CACHE_PREFIX + token
         user_info = {
             'username': username,
         }
         cache.set(token_key, token, CACHE_TIMEOUT)
         login()  # 爬虫登陆网站
         return loginSuccess(user_info=user_info, token=token)
     else:
         return error('用户名或密码错误!')
Ejemplo n.º 13
0
def view_sign_in(request):
    """
    This view is used for login and generates json for user access.
    :param request: contain username and password of user.
    :return: json for generate UI dynamically.
    """
    response = {}
    body = None
    try:
        body_unicode = request.body.decode('utf-8')
        body = ast.literal_eval(body_unicode)
        username = body['Username']
        password = body['Password']
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.finalized:
                user_obj = User.objects.filter(username=user)

                locality_obj = locality_mapping.objects.get(user_id=user_obj)
                key = locality_obj.locality_key

                response["Status"] = 0
                response['Username'] = username
                response['Locality'] = key
                response['UserId'] = (list(user_obj)[0]).id
                response['LocalityId'] = locality_obj.id

                user = User.objects.get(username=username)
                # Generating token for access another view.
                payload = jwt_payload_handler(user)
                token = jwt_encode_handler(payload)
                response["Token"] = token

            else:
                response = {"Status": 3}
        else:
            # Not login access.
            response = {"Status": 2}
    except Exception as e:
        response = {"Status": 1}
        logger.error("Body of Request is'{0}' and Exception is '{1}'".format(
            body, e),
                     exc_info=True)

    return HttpResponse(json.dumps(response), content_type='application/json')
Ejemplo n.º 14
0
    def post(request):
        try:
            # get
            platform = request.query_params['platform']
            device_id = request.query_params['device_id']

            # post
            phone = request.data['phone']
            password = request.data['password']
            code = request.data['code']
        except KeyError:
            return error_request(ErrBaseParams)

        if not is_phone(phone):
            return error_request(ErrBaseParams)

        if not is_password(password):
            return error_request(ErrBaseParams)

        if not is_code(code):
            return error_request(ErrBaseParams)

        exists = Profile.objects.filter(phone=phone).exists()

        if exists:
            return error_request(ErrUserDoesExist)

        user = Profile.objects.create(
            uid=gen_uid(),
            phone=phone,
            password=make_password(password),
            platform=platform,
            username='******' + phone,
            register_ip=gen_ip(request),
            device_id=device_id,
        )

        Balance.objects.create(user=user, )

        return_data = dict_success()
        return_data['msg'] = '注册成功'
        return_data['data'] = serializer_data(user, ProfileSerializer, request)
        return_data['data']['token'] = jwt_encode_handler(
            jwt_payload_handler(user))
        return success_request(return_data)
Ejemplo n.º 15
0
 def create(self, validated_data):
     """
     保存数据的操作。
     :param validated_data: 验证后的数据
     :return:
     """
     # 1.对密码进行加密后存储
     print(validated_data, '进行保存数据')
     phone = validated_data.get('phone')
     password = validated_data.get('password')
     # 2.处理用户名,随机字符串或者是phone
     user = UserInfo.objects.create(username=phone,
                                    password=make_password(password))
     # 3.为注册的用户进行手动生成token
     payload = jwt_payload_handler(user)
     token = jwt_encode_handler(payload)
     user.token = token
     return user
Ejemplo n.º 16
0
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = self.perform_create(serializer)

        re_dict = serializer.data
        payload = jwt_payload_handler(user)
        re_dict["token"] = jwt_encode_handler(payload)
        re_dict["name"] = user.name if user.name else user.username

        headers = self.get_success_headers(serializer.data)
        return Response({
            "msg": "注册成功",
            "data": re_dict,
            "code": 200
        },
                        status=status.HTTP_201_CREATED,
                        headers=headers)
Ejemplo n.º 17
0
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = self.perform_create(serializer)

        re_dict = serializer.data
        print('=====创建用户======', user)
        payload = jwt_payload_handler(user)
        print('========', payload, '========')
        print('========', type(payload), '========')
        # 添加token 和name 让用户注册完毕后就登陆
        re_dict["token"] = jwt_encode_handler(payload)
        re_dict["name"] = user.name if user.name else user.username

        headers = self.get_success_headers(serializer.data)
        return Response(re_dict,
                        status=status.HTTP_201_CREATED,
                        headers=headers)
Ejemplo n.º 18
0
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        #user = self.perform_create(serializer)
        user = User(username=request.data.username,
                    password=request.data.password,
                    gender=request.data.gender,
                    avatarUrl=request.data.avatarUrl)

        re_dict = serializer.data
        payload = jwt_payload_handler(user)
        re_dict["token"] = jwt_encode_handler(payload)
        re_dict["name"] = user.name if user.name else user.username

        headers = self.get_success_headers(serializer.data)
        return Response(re_dict,
                        status=status.HTTP_201_CREATED,
                        headers=headers)
Ejemplo n.º 19
0
 def create(self, request, *args, **kwargs):
     data = request.data
     serializer = UserSerializer(data=data)
     if serializer.is_valid():
         user = User.objects.create(**serializer.validated_data)
         user.set_password(data['password'])
         user.save()
         payload = jwt_payload_handler(user)
         token = {'token': jwt_encode_handler(payload)}
         return Response(token, status=status.HTTP_201_CREATED)
     return Response(
         {
             'status':
             'Неправильный запрос',
             'message':
             'Учетная запись не может быть создана с полученными данными'
         },
         status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 20
0
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = self.perform_create(serializer)

        # 为了实现注册完成帮你自动登录,则注册完成后必须返回token,所以要重载CreateModelMixin里面的create函数,
        # 原create函数只是保存了当前的model(user),但是并没有返回该model。我们要想获取到user model 就必须重写让它返回model,
        # 然后在执行perform_create之后插入我们自己的逻辑。分析jwt的源码实现,找到它哪部分才是生成token的。然后将其找出,并返回

        re_dict = serializer.data
        payload = jwt_payload_handler(user)
        re_dict["token"] = jwt_encode_handler(payload)
        re_dict["name"] = user.name if user.name else user.username

        headers = self.get_success_headers(serializer.data)
        return Response(re_dict,
                        status=status.HTTP_201_CREATED,
                        headers=headers)
Ejemplo n.º 21
0
    def create(self, request, *args, **kwargs):
        """
        重载函数,再注册完成后返回生成的token完成注册后即登录
        """
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = self.perform_create(serializer)

        # 使用jwt取出生成的token
        re_dict = serializer.data
        payload = jwt_payload_handler(user)
        # 可以自定义添加想要返回的任何参数
        re_dict["token"] = jwt_encode_handler(payload)

        headers = self.get_success_headers(serializer.data)
        return Response(re_dict,
                        status=status.HTTP_201_CREATED,
                        headers=headers)
Ejemplo n.º 22
0
 def create(self, request, *args, **kwargs):
     """
     rewrite the create function
     :param request:
     :param args:
     :param kwargs:
     :return: Response:
     """
     serializer = self.get_serializer(data=request.data)
     serializer.is_valid(raise_exception=True)
     user = self.perform_create(serializer=serializer)
     re_dict = serializer.data
     payload = jwt_payload_handler(user)
     re_dict["token"] = jwt_encode_handler(payload)
     headers = self.get_success_headers(serializer.data)
     return Response(re_dict,
                     status=status.HTTP_201_CREATED,
                     headers=headers)
Ejemplo n.º 23
0
def register(request):
    post = request.data
    username = post.get("username", None)
    password = post.get("password", None)
    email = post.get("email", None)
    print(password)
    if username is None or password is None or email is None:
        return HttpResponseBadRequest()
    user = User.objects.create_user(username, email, password)
    user.save()
    return Response({
        "user":
        UserSerializer(user, context={
            "request": request
        }).data,
        "token":
        jwt_encode_handler(jwt_payload_handler(user))
    })
Ejemplo n.º 24
0
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        if not serializer.is_valid(raise_exception=False):
            return JsonResponse({'errmsg': serializer._errors, 'errcode': -1})
        user = self.perform_create(serializer)
        # 授权信息绑定
        state = request.COOKIES.get('state')
        if state:
            state_dict = eval(base64.b64decode(state).decode('utf-8'))
            # 绑定店铺信息
            shop, _ = self.get_shop_info(state_dict['access_token'])
            state_dict['shop'] = shop
            # 商品信息同步,异步任务
            task_product_info.apply_async(queue='product_router')
            # 绑定用户
            state_dict['user'] = user
            JdAuthUserModel.objects.update_or_create(uid=state_dict['uid'],
                                                     defaults=state_dict)

        else:
            # 直接注册的用户获取获取授权信息,state为传递绑定的账户
            jd_web_auth_obj = JdWebAuthorized(
                code='', state=f'username:{user.username}')
            redirect_url = jd_web_auth_obj.get_code_url()
            re_dict = {}
            re_dict["errcode"] = 2
            re_dict["errmsg"] = '注册成功'
            re_dict["redirect_url"] = redirect_url
            return Response(re_dict, status=status.HTTP_200_OK)

        re_dict = serializer.data
        payload = jwt_payload_handler(user)
        re_dict["token"] = jwt_encode_handler(payload)
        re_dict["username"] = user.username
        re_dict["errmsg"] = '注册成功'
        re_dict["errcode"] = 0

        headers = self.get_success_headers(serializer.data)
        response = Response(re_dict,
                            status=status.HTTP_201_CREATED,
                            headers=headers)
        # 删除该cookie信息
        response.set_cookie('state', '')
        return response
Ejemplo n.º 25
0
    def create(self, request, *args, **kwargs):
        """
        重载create方法,设置name和token,实现注册后立即登录
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = self.perform_create(serializer)

        re_dict = serializer.data
        payload = jwt_payload_handler(user)
        re_dict["token"] = jwt_encode_handler(payload)
        re_dict["name"] = user.name if user.name else user.username

        headers = self.get_success_headers(serializer.data)
        return Response(re_dict, status=status.HTTP_201_CREATED, headers=headers)
Ejemplo n.º 26
0
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 接收刚刚登录的用户对象
        user = self.perform_create(serializer)

        # =====token的定制化
        # 获取返回序列化后要的对象
        re_dict = serializer.data
        # 给登录的用户对象添加token信息
        payload = jwt_payload_handler(user)
        # 给返回的对象添加token信息
        re_dict['token'] = jwt_encode_handler(payload)
        re_dict['name'] = user.name if user.name else user.username
        # ====结束
        headers = self.get_success_headers(serializer.data)
        return Response(re_dict,
                        status=status.HTTP_201_CREATED,
                        headers=headers)
Ejemplo n.º 27
0
    def validate(self, attrs):
        credentials = {
            self.username_field: attrs.get(self.username_field),
            'password': attrs.get('password')
        }

        if all(credentials.values()):
            user = authenticate(**credentials)

            if user:
                if not user.is_active:
                    msg = _('User account is disabled.')
                    # 用户账户不能使用;
                    raise serializers.ValidationError(msg)

                user.last_login = datetime.now()
                payload = jwt_payload_handler(user)
                # 【待登陆成功前的处理逻辑】

                # from .blacklist.utils import UserCache
                # user.token = jwt_encode_handler(payload)
                # _stat = UserCache(user=user, remote_addr="a").seccuss_cache_init()
                # if _stat["stat"] != 0:
                #     msg = _('封禁时间段内')
                #     raise serializers.ValidationError(msg)

                ## END_USET
                return {'token': jwt_encode_handler(payload), 'user': user}
            else:
                # 【失败登陆的处理逻辑】
                # from .blacklist.utils import UserCache
                # _stat = UserCache(self.object.get("request")).failed_cache_init()
                # if _stat["stat"] == -1:
                #     msg = _('封禁时间段内')
                #     raise serializers.ValidationError(msg)

                msg = _('Unable to login with provided credentials.')
                raise serializers.ValidationError(msg)
        else:
            # YOU can rewrite this msg, but no active
            msg = _('Must include "{username_field}" and "password".')
            msg = msg.format(username_field=self.username_field)
            raise serializers.ValidationError(msg)
Ejemplo n.º 28
0
    def validate(self, attrs):
        if not attrs.get('name'):
            msg = _('必须提供App名字。')
            raise serializers.ValidationError(msg)
        apps = AppVersion.objects.filter(
            app_name=attrs.get('name')).order_by('-date_pub')
        if not apps:
            raise serializers.ValidationError('对象不存在。', 'dose_not_exit')

        payload = {
            'app_name': apps[0].app_name,
            'ver_code': apps[0].ver_code,
            'exp': timezone.now() + settings.JWT_AUTH['APP_TOKEN_EXP_DELTA']
        }

        return {
            'token': jwt_encode_handler(payload),
            'app_version': AppVersionSerializer(apps[0]).data
        }
Ejemplo n.º 29
0
    def post(self, request, format=None):
        params = request.query_params if len(
            request.data) == 0 else request.data
        company = request.headers["company"]
        username = params.get("email", None)
        password = params.get("password", None)
        company_obj = Company.objects.filter(sub_domain=company).first()
        if not company_obj:
            company_field = "doesnot exit"
            msg = _("company with this subdomin {company_field}")
            msg = msg.format(company_field=company_field)
            return Response({"status": "failure", "message": msg}, status=400)
            # raise APIException(msg)
        if not username:
            username_field = "User Name/Email"
            msg = _('Must include "{username_field}"')
            msg = msg.format(username_field=username_field)
            return Response({"status": "failure", "message": msg}, status=400)
            # raise APIException(msg)

        user = User.objects.filter(email=username, company=company_obj).first()
        if not user:
            return Response(
                {
                    "status": "failure",
                    "message": "user not avaliable in our records"
                },
                status=400,
            )
        if user.check_password(password):
            payload = jwt_payload_handler(user)
            response_data = {
                "token": jwt_encode_handler(payload),
                "status": "success",
                "company": user.company.id,
                "subdomin": company_obj.sub_domain,
            }
            return Response(response_data)
        else:
            password_field = "doesnot match"
            msg = _("Email and password {password_field}")
            msg = msg.format(password_field=password_field)
            return Response({"status": "failure", "message": msg}, status=400)
Ejemplo n.º 30
0
    def validate(self, attrs):
        username = attrs.get("username")
        password = attrs.get("password")

        if re.match(r'.+@.+', username, re.I):
            user = UserInfo.objects.filter(email=username).first()
        elif re.match(r'1[3-9][0-9]{9}', username):
            user = UserInfo.objects.filter(mobile=username).first()
        else:
            user = UserInfo.objects.filter(username=username).first()

        if user and user.check_password(password):
            # 签发token
            payload = jwt_payload_handler(user)
            self.token = jwt_encode_handler(payload)

            return attrs

        raise serializers.ValidationError({'data': '数据有误'})
Ejemplo n.º 31
0
 def test_other_user_permission_api(self):
     data = self.create_item()
     data_id = data.get('id')
     user = User.objects.create(username='******')
     payload = jwt_payload_handler(user)
     print(payload)
     token = jwt_encode_handler(payload)
     print(token)
     self.client.credentials(HTTP_AUTHORIZATION='JWT ' + token)
     rud_url = api_reverse('api-status:detail', kwargs={'id': data_id})
     rud_data = {
         'content': 'permission test'
     }
     get_ = self.client.get(rud_url, format='json')
     put_ = self.client.put(rud_url, rud_data, format='json')
     delete_ = self.client.delete(rud_url, format='json')
     self.assertEqual(get_.status_code, status.HTTP_200_OK)
     self.assertEqual(put_.status_code, status.HTTP_403_FORBIDDEN)
     self.assertEqual(delete_.status_code, status.HTTP_403_FORBIDDEN)
Ejemplo n.º 32
0
 def create(self, request, *args, **kwargs):
     """
     用户注册(注意username填写手机号)
     覆写,以将token加入response给用户(实现注册完自动登录)
     """
     serializer = self.get_serializer(data=request.data)
     # Serializer中做验证并可能抛出异常,出错时将自动返回相应的HTTP状态码
     serializer.is_valid(raise_exception=True)
     user = self.perform_create(serializer)
     print("用户保存化好了")
     re_dict = serializer.data
     payload = jwt_payload_handler(user)
     re_dict["token"] = jwt_encode_handler(payload)
     re_dict["name"] = user.name if user.name else user.username
     print("返回的字典做好了")
     headers = self.get_success_headers(serializer.data)
     return Response(re_dict,
                     status=status.HTTP_201_CREATED,
                     headers=headers)
Ejemplo n.º 33
0
    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance,
                                         data=request.data,
                                         partial=partial)
        serializer.is_valid(raise_exception=True)
        user = self.perform_update(serializer)

        re_dict = serializer.data
        payload = jwt_payload_handler(user)
        re_dict['token'] = jwt_encode_handler(payload)

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}

        return Response(re_dict)
Ejemplo n.º 34
0
    def validate(self, attrs):
        username = attrs.get('username').lower()
        password = attrs.get('password')

        user = plex_authentication(username=username, password=password)

        if user:
            if not user[0].is_active:
                logger.warn('The user {} attempted to login, but their account is disabled'.format(username))
                msg = 'User account is disabled.'
                raise serializers.ValidationError(msg)

            payload = jwt_payload_handler(user[0])

            return {
                'token': jwt_encode_handler(payload)
            }
        else:
            msg = 'Unable to login with provided credentials.'
            raise serializers.ValidationError(msg)
Ejemplo n.º 35
0
 def get_token(self, obj):
     return jwt_encode_handler(jwt_payload_handler(obj))
Ejemplo n.º 36
0
Archivo: apis.py Proyecto: joway/Chirp
 def login(self, request, *args, **kwargs):
     # payload = jwt_payload_handler(user)
     return Response({'jwt': jwt_encode_handler(payload), 'username': user.username})  # 回傳JWT token及使用者帳號