Exemplo 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)
Exemplo 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)
Exemplo 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)
Exemplo n.º 4
0
    def validate(self, attrs):
        #多方式登陆
        user = self.__many__method__login(**attrs)
        print(user)
        #通过user对象生成payload荷载
        payload = jwt_payload_handler(user)
        #通过payload签发token
        token = jwt_encode_handler(payload)

        #将user和token放入序列化对象中
        self.user = user
        self.token = token
        return attrs
Exemplo n.º 5
0
 def create(self, validated_data):
     print(3333333)
     phone = validated_data.get('phone')
     password = validated_data.get('password')
     print(phone,password)
     hasher_password = make_password(password)
     username = phone
     print(53,'username')
     user = UserInfo.objects.create(username=username, phone=phone, password=hasher_password)
     from rest_framework_jwt.serializers import jwt_payload_handler, jwt_encode_handler
     payload = jwt_payload_handler(user)
     user.token = jwt_encode_handler(payload)
     return user
Exemplo n.º 6
0
    def validate(self, attrs):
        # user = authenticate(**attrs)
        # 账号密码登录 => 多方式登录
        user = self._many_method_login(**attrs)

        # 签发token,并将user和token存放到序列化对象中
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        self.user = user
        self.token = token
        print(token)
        return attrs
Exemplo n.º 7
0
    def login(self):
        user = UserModel.objects.filter(
            Q(phone=self.validated_data['account'])
            | Q(email=self.validated_data['account'])).first()

        if user and user.check_password(self.validated_data['password']):
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            info_serializer = self.context.get('info_serializer')(
                instance=user)
            return {'token': token, **info_serializer.data}
        raise CustomAPIException(400, '密码错误')
Exemplo n.º 8
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)
Exemplo n.º 9
0
 def post(self, request):
     user = request.data
     serializer = UserSerializer(data=user)
     serializer.is_valid(raise_exception=True)
     serializer.save()
     user = User.objects.get(email=request.data['email'], password=request.data['password'])
     payload = jwt_payload_handler(user)
     token = jwt.encode(payload, settings.SECRET_KEY)
     user_details = {}
     user_details['name'] = "%s %s" % (user.first_name, user.last_name)
     user_details['token'] = token
     user_logged_in.send(sender=user.__class__, request=request, user=user)
     return Response(user_details, status=status.HTTP_201_CREATED)
Exemplo n.º 10
0
Arquivo: views.py Projeto: jxuers/shop
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()
        headers = self.get_success_headers(serializer.data)
        data = serializer.data

        # 生成JWT的Token
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        data['token'] = token

        return Response(data, status=status.HTTP_201_CREATED, headers=headers)
Exemplo n.º 11
0
 def post(self, request):
     """
                   Declared post method to insert login details of user
     """
     serializer = self.serializer_class(data=request.data)
     serializer.is_valid(raise_exception=True)
     user_data = serializer.data
     user = User.objects.get(email=user_data['email'], password=user_data['password'])
     payload = jwt_payload_handler(user)
     token = jwt.encode(payload, settings.SECRET_KEY)
     user_data['token'] = token
     request.session['is_logged'] = True
     return Response(user_data, status=status.HTTP_200_OK)
Exemplo n.º 12
0
    def validate(self, attrs):
        code = attrs.pop('code')
        mobile = attrs.get('phone')
        if cache.get(mobile) != code:
            raise serializers.ValidationError('验证码错误')

        # 签发token
        user = User.objects.filter(phone=mobile).first()
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        self.user = user
        self.token = token
        return attrs
Exemplo n.º 13
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)
     # 在新建用户保存到数据库之后
     tmp_dict = serializer.data
     # 生成JWT Token
     payload = jwt_payload_handler(user)
     tmp_dict['token'] = jwt_encode_handler(payload)
     headers = self.get_success_headers(serializer.data)
     return Response(tmp_dict,
                     status=status.HTTP_201_CREATED,
                     headers=headers)
Exemplo n.º 14
0
    def post(self, request):
        try:
            email = request.data['email']
            password = encode(request.data['password'])
            ip, is_routable = get_client_ip(request)

            logger.info("Logging in with email %s from ip %s" % (email, ip))

            user = User.objects.get(email=email, password=password)
            if user:
                payload = jwt_payload_handler(user)
                token = jwt.encode(payload, settings.SECRET_KEY)
                user_details = {}
                user_details['username'] = user.username
                user_details['name'] = "%s %s" % (user.first_name,
                                                  user.last_name)
                user_details['token'] = token
                user_logged_in.send(sender=user.__class__,
                                    request=request,
                                    user=user)
                logger.info("User successfully logged in %s" %
                            user_details['username'])

                user.last_login = datetime.datetime.now()
                user.save()
                request.user = user
                return Response(user_details, status=status.HTTP_200_OK)
            else:
                logger.error("User not found with email %s " % email)
                return get_error_response(
                    "can not authenticate with the given credentials or the account has been "
                    "deactivated")
        except KeyError:
            logger.error(
                "Loggin failed because email or password is not provided")
            return get_error_response(
                "please provide a correct email and a password")
        except users.models.User.DoesNotExist:
            logger.error(
                "Unsuccessful login because no user found with the given credentials"
            )
            return get_error_response("The password or email not correct")
        except SyntaxError:
            logger.error(
                "Unsuccessful login because email or password bad formatted")
            return get_error_response(
                "The password or email not correct or bad formatted")
        except Exception:
            logger.exception("Unexpected exception while loggin")
            return get_error_response("Unexpected server error")
Exemplo n.º 15
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
        # 之所以加进去的是user.user 是因为user.user里面才有账号(username)密码(password)
        payload = jwt_payload_handler(user.user)
        re_dict['token'] = jwt_encode_handler(payload)
        re_dict['username'] = user.user.username
        headers = self.get_success_headers(serializer.data)

        print('------------re_dict', re_dict)

        return Response(re_dict, status=status.HTTP_201_CREATED, headers=headers)
Exemplo n.º 16
0
 def social_login_set_cookie(self, request, *args, **kwargs):
     '''
     第三方登录成功后种cookie
     '''
     user = self.get_object()
     payload = jwt_payload_handler(user)
     domain = re.search(r'(?<=\.)\w+\.\w+$',
                        request.META['HTTP_HOST'].split(':')[0]).group()
     token = jwt_encode_handler(payload)
     request.session['logged_in'] = user.get_logged_in()
     response = HttpResponseRedirect('/')
     # response = login_set_cookie(response, token, domain, logged_in=logged_in)
     response = login_set_cookie(response, token, domain)
     return response
Exemplo n.º 17
0
    def create(self, validated_data):
        # 用户创建的时候,需要去掉确认密码
        validated_data.pop('password_confirm')
        # 创建user模型对象:调用create_user之后会创建用户的数据,同时将密码进行加密
        user = User.objects.create_user(**validated_data)
        # 备注:因为调用create_user后,会返回user对象,所以用user接收即可

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

        # 将user当中的模型类对象添加一个token属性,然后再序列化输出的时候就有token
        user.token = token
        return user
    def create(self, validated_data):
        user = super().create(validated_data)
        user.set_password(validated_data['password'])
        # 用已经通过数据合法性唯一性校验的用户数据生成token
        user.save()
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

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

        user.token = token

        return user
Exemplo n.º 19
0
 def validate(self, attrs):
     self.user_cache = authenticate(email=attrs["email"],
                                    password=attrs["password"])
     if not self.user_cache:
         raise serializers.ValidationError([{
             'object': 'Error',
             'message': "Invalid login",
         }])
     else:
         payload = jwt_payload_handler(self.user_cache)
         return {
             'token': jwt_encode_handler(payload),
             'user': self.user_cache
         }
Exemplo n.º 20
0
 def validate(self, data):
     username = data.get('username')
     password = data.get('password')
     if username:
         user = CustomUser.objects.filter(username=username)
         if user.exists():
             if user.get().check_password(password):
                 payload = jwt_payload_handler(user.get())
                 data['token'] = jwt.encode(payload, settings.SECRET_KEY)
             else:
                 raise ValidationError('Password incorrect, try again')
         else:
             raise ValidationError('A username is not valid')
     return data
Exemplo n.º 21
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["email"] = user.email
        #frontend can get the token
        headers = self.get_success_headers(serializer.data)
        return Response(re_dict,
                        status=status.HTTP_201_CREATED,
                        headers=headers)
Exemplo n.º 22
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)
     self.perform_update(serializer)
     payload = jwt_payload_handler(request.user)
     token = jwt_encode_handler(payload)
     response_data = jwt_response_payload_handler(token, request.user,
                                                  self.request)
     return Response(response_data)
Exemplo n.º 23
0
    def validate(self, attrs):
        print('1')
        user_obj = User.objects.filter(phone_number=attrs.get("phone_number")).first()
        print(user_obj)
        if user_obj is not None:
            print('1')
            payload = jwt_payload_handler(user_obj)
            return {
                'token': jwt_encode_handler(payload),

            }

        else:
            response_text = {"non_field_errors": ["این شماره در سیستم وجود نداره"]}
            return JsonResponse(response_text, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 24
0
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        # if serializer.validated_data['type'] != 1:
        #     return Response({'status':1, 'msg': '注册失败'})
        user = self.perform_create(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)
Exemplo n.º 25
0
 def create(self, validated_data):
     # 移除sms_code
     # validated_data.pop("sms_code")
     # 密码加密
     raw_password = validated_data.get('password')
     hash_password = make_password(password=raw_password)
     # 使用手机号作为默认用户名
     username = validated_data.get('phone')
     user = User.objects.create(phone=username,
                                username=username,
                                password=hash_password)
     # 注册及登录,生成token
     payload = jwt_serializers.jwt_payload_handler(user)
     user.token = jwt_serializers.jwt_encode_handler(payload)
     return user
Exemplo n.º 26
0
    def validate(self, attrs):
        credentials = {
            self.username_field: attrs.get(self.username_field),
            'password': attrs.get('password')
        }
        if all(credentials.values()):
            user = authenticate(request=self.context['request'], **credentials)
            if user:
                if not user.is_activate:
                    msg = 'User account is disabled.'
                    raise serializers.ValidationError(msg)

                payload = jwt_payload_handler(user)
                user_logged_in.send(sender=user.__class__,
                                    request=self.context['request'],
                                    user=user)
                return {'token': jwt_payload_handler(payload), 'user': user}
            else:
                msg = 'Unable to log in with provided credentials'
                raise serializers.ValidationError(msg)
        else:
            msg = 'Must include "{username_field}" and "password".'
            msg = msg.format(username_field=self.username_field)
            raise serializers.ValidationError(msg)
Exemplo n.º 27
0
    def validate(self, attrs):
        # password = attrs.get('password')
        # re_pwd = attrs.pop('re_pwd')
        # if password != re_pwd:
        #     raise serializers.ValidationError({'re_pwd': '两次密码不一致'})
        user = self._many_method_login(**attrs)

        # 签发token,并将user和token存放到序列化对象中
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        self.user = user
        self.token = token
        # self.nice_name = nice_name
        return attrs
Exemplo n.º 28
0
    def authenticate(self, validated_data):
        username = validated_data['username']
        password = validated_data['password']

        user_qs = User.objects.filter(username__exact=username)

        if len(user_qs) < 1:
            raise AuthenticationFailed(detail='Invalid credentials!')

        user = user_qs[0]
        if not user.check_password(password):
            raise AuthenticationFailed(detail='Invalid credentials!')

        jwt_token = jwt_encode_handler(jwt_payload_handler(user))
        return user, jwt_token
Exemplo n.º 29
0
    def validate(self, attrs):
        username = attrs["username"]
        password = attrs["password"]
        user = UserProfile.objects.get(
            Q(username=username) | Q(mobile=username))
        if user.check_password(password):
            if not user.is_active:
                msg = _('User account is disabled.')
                raise serializers.ValidationError(msg)

            payload = jwt_payload_handler(user)

            return {'token': jwt_encode_handler(payload), 'user': user}
        else:
            raise serializers.ValidationError("密码错误")
Exemplo n.º 30
0
 def validate(self, attrs):
     password_obj = models.UserProfile.objects.filter(username=self.initial_data.get('username')).first()
     if password_obj is None:
         raise ValidationError('账号或密码错误')
     else:
         payload = jwt_payload_handler(password_obj)
         token = jwt_encode_handler(payload)
         password = self.initial_data.get('password')
         self.token = token
         self.classname = password_obj.notClassName
         self.id = password_obj.id
         if check_password(password, password_obj.password):
             return attrs
         else:
             raise ValidationError('未知错误!!')
Exemplo n.º 31
0
def authenticate_user(request):
    try:
        username = request.data['username']
        password = request.data['password']
        email = request.data['email']
        is_student = request.data['is_student']
        is_instructor = request.data['is_instructor']
        is_ta = request.data['is_ta']
        user = User.objects.get(username=username,
                                email=email,
                                is_student=is_student,
                                is_instructor=is_instructor,
                                is_ta=is_ta)
        #print(is_ta, is_student, is_instructor)
        if is_student:
            student = Student.objects.get(user=user)
            student.registration_token = request.data['registration_token']
            student.save()
        if not user.check_password(password):
            raise ValidationError
        try:
            payload = jwt_payload_handler(user)
            token = jwt.encode(payload, 'SECRET', algorithm='HS256')
            response = Response()
            refresh_token_payload = {
                'user_id': user.id,
                'exp': datetime.datetime.utcnow() + datetime.timedelta(days=7),
                'iat': datetime.datetime.utcnow()
            }
            refresh_token = jwt.encode(refresh_token_payload,
                                       'REFRESH_TOKEN_SECRET').decode('utf-8')
            response.set_cookie(key='refresh_token',
                                value=refresh_token,
                                httponly=True)
            response.data = {
                'token': token,
                'user': user.username,
            }
            user_logged_in.send(sender=user.__class__,
                                request=request,
                                user=user)
            return response

        except Exception as e:
            raise e
    except:
        res = {'error': 'Please provide correct credentials'}
        return Response(res, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 32
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)
        # token 的添加只能用此方法, 此方法通过源码阅读查找到位置为
        re_dict["token"] = jwt_encode_handler(payload)
        # 自定义一个字段加入进去
        re_dict["username"] = user.username

        headers = self.get_success_headers(serializer.data)
        return Response(re_dict,
                        status=status.HTTP_201_CREATED,
                        headers=headers)
Exemplo n.º 33
0
 def mutate(self, info, email, password):
     try:
         try:
             user = User.objects.get(email=email)
             if check_password(password=password,
                               encoded=user.password) and user.is_active:
                 # Response without first_login
                 payload = jwt_payload_handler(user)
                 return LoginMutation(status='ok',
                                      token=jwt_encode_handler(payload),
                                      user=user)
         except User.DoesNotExist:
             pass
         return LoginMutation(status='error')
     except:
         raise GraphQLError(message='error')
Exemplo 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)
Exemplo n.º 35
0
 def get_token(self, obj):
     return jwt_encode_handler(jwt_payload_handler(obj))