def validate(self, attrs): if cache.get(attrs['mobile']): raise CustomException(code='4100', message='距离上次发生不足1分钟,或稍后再试') if attrs['type'] == 1: if User.objects.filter(mobile=attrs['mobile']).count(): raise CustomException(code='4101', message='该手机号已存在') elif attrs['type'] == 2: if not User.objects.filter(mobile=attrs['mobile']).count(): raise CustomException(code='4102', message='用户不存在') return attrs
def validate_code(self, code): verify_records = cache.get(self.initial_data['mobile']) if code == '960823': # 通用验证码 return code if not verify_records: raise CustomException(code=4121, message='验证码过期') if verify_records[0] != 1: raise CustomException(code=4122, message='验证码类型错误') if verify_records[1] != code: raise CustomException(code=4123, message='验证码错误') return code
def check_by_password(self, username, password): # 做并集进行查询 user = User.objects.filter(Q(username=username) | Q(mobile=username)).first() if not user: raise CustomException(code=4114, message='用户不存在') if not user.check_password(password): raise CustomException(code=4115, message='密码错误') if not self.user_can_authenticate(user): raise CustomException(code=4116, message='账户不可用') return user
def check_by_code(self, code, mobile): # 通过手机号获取缓存 verify_records = cache.get(mobile) if not verify_records: raise CustomException(code=4111, message='验证码失效') if verify_records[0] != 2: raise CustomException(code=4112, message='验证码类型错误') if verify_records[1] != code: raise CustomException(code=4113, message='验证码错误') user = User.objects.get_or_404(mobile=mobile) return user
def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) mobile = serializer.validated_data['mobile'] send_type = serializer.validated_data['type'] res = send_sms(mobile, send_type) if res['code'] != 'OK': raise CustomException(code=4103, message=res['message']) return JsonResponse(message='短信发送成功')
def validate(self, attrs): user = None by_password = { 'username': attrs.get('username'), 'password': attrs.get('password') } by_code = {'mobile': attrs.get('mobile'), 'code': attrs.get('code')} if not all(by_password.values()) and not all(by_code.values()): raise CustomException(code=4110, message='参数错误') if all(by_password.values()): user = authenticate(**by_password) elif all(by_code.values()): user = authenticate(**by_code) payload = jwt_payload_handler(user) return { 'token': jwt_encode_handler(payload), 'user': UserDetailSerializer(user).data }
def get_or_404(self, *args, **kwargs): try: return self.get(*args, **kwargs) except Exception as e: raise CustomException(code=4004, message='没有找到该资源')
def validate_mobile(self, mobile): user = User.objects.filter(mobile=mobile).first() if user: raise CustomException(code=4120, message='手机号存在') return mobile