示例#1
0
def login(request):
    username = request.data.get("username")
    if username:
        username = username.lower()
    password = request.data.get("password")
    disableLogEvent = request.data.get("disableLogEvent")

    user = authenticate(username=username, password=password)
    if not user:
        #maybe email
        try:
            user2Try = User.objects.get(email__iexact=username)
            user = authenticate(username=user2Try.username, password=password)
        except Exception as ex:
            user2Try = None
            user = None
        if not user2Try:
            return Response({
                "success": False,
                "error": "login.failed"
            },
                            status=HTTP_401_UNAUTHORIZED)
    try:
        profile = Profile.objects.get(user=user)
        if not profile.mobileVerified:
            return Response({
                "success": False,
                "error": 'mobile.notverified',
                'activationKey': profile.activationKey
            })
        wallet = Wallet.objects.get(profile=profile)
        profileSerializer = ProfileSerializer(profile,
                                              context={'request': request})
    except Profile.DoesNotExist:
        return Response({
            "success": False,
            "error": "login.failed"
        },
                        status=HTTP_401_UNAUTHORIZED)

    token, _ = Token.objects.get_or_create(user=user)
    if not disableLogEvent:
        Event().createEvent('LOGIN', 'USERACTIVITY', '', profile, request)
    return Response({
        "success": True,
        "token": token.key,
        'profile': profileSerializer.data,
    })
示例#2
0
    def post(self, request, format=None):
        data = request.data
        username = data.get('username', None)
        password = data.get('password', None)

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

        if user is not None:
            if user.is_active:
                # print(user)
                print(user.id)
                login(request, user)
                token = Token.objects.get(user_id=user.id)
                print(token)

                success_user_response = {
                    "username": user.username,
                    "token": token.key
                }
                return Response(success_user_response,
                                status=status.HTTP_200_OK)
            else:
                return Response(status=status.HTTP_404_NOT_FOUND)
        else:
            error_message = {"error": ""}
            return Response(status=status.HTTP_404_NOT_FOUND)
示例#3
0
    def validate(self, attrs):
        username = attrs.get('username') or attrs.get('email')
        password = attrs.get('password')

        if username and password:
            user = authenticate(request=self.context.get('request'),
                                username=username,
                                password=password)

            if not user:
                if User.objects.filter(email=username).exists():
                    if not User.objects.get(email=username).is_active:
                        raise serializers.ValidationError(
                            'You cannot login until you have confirmed your email address.',
                            code='authorization')
                raise serializers.ValidationError(
                    'Unable to login with provided credentials.',
                    code='authorization')
        else:
            raise serializers.ValidationError(
                'Must include "username" and "password".',
                code='authorization')

        attrs['user'] = user
        return attrs
示例#4
0
    def validate(self, attrs):
        username = attrs.get('username')
        password = attrs.get('password')

        if username and password:
            user = authenticate(request=self.context.get('request'),
                                username=username,
                                password=password)

            if user:
                # From Django 1.10 onwards the `authenticate` call simply
                # returns `None` for is_active=False users.
                # (Assuming the default `ModelBackend` authentication backend.)
                if not user.is_active:
                    msg = _('User account is disabled.')
                    raise serializers.ValidationError(msg,
                                                      code='authorization')
            else:
                msg = _('Unable to log in with provided credentials.')
                raise serializers.ValidationError(msg, code='authorization')
        else:
            msg = _('Must include "username" and "password".')
            raise serializers.ValidationError(msg, code='authorization')

        attrs['user'] = user
        return attrs
    def validate(self, attrs):

        password = attrs.get("password")
        user_obj = User.objects.filter(
            email=attrs.get("login")).first() or User.objects.filter(
                username=attrs.get("login")).first()
        if user_obj is not None:
            credentials = {'username': user_obj.username, 'password': password}
            if all(credentials.values()):
                authenticated_user = authenticate(**credentials)
                if authenticated_user:
                    if not authenticated_user.is_active:
                        msg = 'User account is disabled.'
                        return {'message': msg}

                    payload = jwt_payload_handler(authenticated_user)

                    return {
                        'token': jwt_encode_handler(payload),
                        'user': authenticated_user
                    }
                else:
                    msg = 'Unable to log in with provided credentials.'
                    return {'message': msg}

            else:
                msg = 'Must include "{username_field}" and "password".'
                msg = msg.format(username_field=self.username_field)
                return {'message': msg}

        else:
            msg = 'Account with this email/username does not exists'
            return {'message': msg}
示例#6
0
    def validate(self, attrs):
        username = attrs.get('username')
        password = attrs.get('password')

        qs = models.User.objects.order_by('pk').filter(is_active=True)
        try:
            self._email_validator(username)
            user = qs.get(email=username)
            username = user.username
        except (DjangoValidationError, models.User.DoesNotExist):
            pass
        except MultipleObjectsReturned:
            user = qs.last()
            qs.filter(email=username, pk__lt=user.pk).update(is_active=False)
            username = user.username

        if username and password:
            user = authenticate(request=self.context.get('request'),
                                username=username,
                                password=password)

            if not user:
                msg = _('토큰을 발행할 유효한 이용자가 없습니다.')
                raise serializers.ValidationError(msg, code='authorization')
        else:
            msg = _('계정과 비밀번호가 필요합니다.')
            raise serializers.ValidationError(msg, code='authorization')

        attrs['user'] = user
        return attrs
    def validate(self, attrs):
        username = attrs.get('username').strip()
        password = attrs.get('password')

        if username and password:
            user = authenticate(request=self.context.get('request'),
                                username=username,
                                password=password)

            if not user:
                raise serializers.ValidationError(
                    'Oops! We don\'t recognize that account. Check to make sure you '
                    'entered your credentials properly.',
                    code='authorization')

            attrs['username'] = username
            attrs['user'] = user

            if not attrs['user'].is_active:
                raise ValidationError(
                    'Sorry, your account is not active. Check your to see if you received a verification email after '
                    'registering with us, otherwise <a href="/contact">contact us</a> and  we\'ll help you sort '
                    'this out!')

            attrs['token'], created = Token.objects.get_or_create(
                user=attrs['user'])
            if not created:
                attrs['token'].delete()
                attrs['token'], created = Token.objects.get_or_create(
                    user=attrs['user'])

        return attrs
示例#8
0
 def post(self, request, *args, **kwargs):
     try:
         email = request.data['email']
         password = request.data['password']
     except:
         data = {
             'key error': '\'email\'key and \'password\'key must be set'
         }
         return Response(data, status=status.HTTP_400_BAD_REQUEST)
     user = authenticate(
         email=email,
         password=password,
     )
     if user:
         serializer = UserSerializer(user)
         if request.data.__contains__('device-token'):
             try:
                 APNSDevice.objects.update_or_create(
                     user=user,
                     defaults={
                         "registration_id": request.data['device-token']
                     })
             except:
                 error = {"device-token": "중복된 토큰값"}
                 return Response(error, status=status.HTTP_400_BAD_REQUEST)
         return Response(serializer.data, status=status.HTTP_200_OK)
     data = {'message': 'Invalid credentials'}
     return Response(data, status=status.HTTP_401_UNAUTHORIZED)
示例#9
0
    def post(self, request):
        username = request.data.get('userName', None)
        password = request.data.get('password', None)

        if not username or not password:
            raise exceptions.AuthenticationFailed()

        credentials = {
            get_user_model().USERNAME_FIELD: username,
            'password': password
        }
        user = authenticate(**credentials)

        if user is None:
            raise exceptions.AuthenticationFailed()
        if not user.is_active:
            raise exceptions.AuthenticationFailed()

        login(request, user)
        return JsonResponse({
            'status':
            'ok',
            'currentAuthority':
            'admin' if user.is_admin else 'user'
        })
示例#10
0
    def validate(self, attrs):

        # 'user' 객체를 꺼내는 과정에서 발생하는 Exception을 아래처럼 raise하는 것보다
        # 이 전체 과정 자체를 email user의 AuthTokenSerailizing 과정보다 앞에서 두고
        # try ~ except 문으로 감싸는 방법을 사용해서 기존의 모든 Exception이 정상
        # 작동하도록 함.
        # try:
        email = attrs.get('username')
        user = User.objects.get(email=email)
        username = user.username
        # except:
        #     raise CustomException(detail='계정이 존재 하지 않습니다.', status_code=status.HTTP_409_CONFLICT)

        password = attrs.get('password')

        if username and password:
            user = authenticate(request=self.context.get('request'),
                                username=username,
                                password=password)

            # The authenticate call simply returns None for is_active=False
            # users. (Assuming the default ModelBackend authentication
            # backend.)
            if not user:
                msg = _('Unable to log in with provided credentials.')
                raise serializers.ValidationError(msg, code='authorization')
        else:
            msg = _('Must include "username" and "password".')
            raise serializers.ValidationError(msg, code='authorization')

        attrs['user'] = user
        return attrs
示例#11
0
    def validate(self, attrs):
        email = attrs.get('email')
        password = attrs.get('password')

        if email and password:

            try:
                user_get = User.objects.get(email=email)

                username = user_get.username

                user = authenticate(request=self.context.get('request'),
                                    username=username,
                                    password=password)

                # The authenticate call simply returns None for is_active=False
                # users. (Assuming the default ModelBackend authentication
                # backend.)
                if not user:

                    raise serializers.ValidationError(
                        {'w': 'Contraseña Incorrecta.'})

            except User.DoesNotExist:

                raise serializers.ValidationError(
                    {'w': "Correo Electrónico Incorrecto."})
        else:
            msg = _('Must include "username" and "password".')
            raise serializers.ValidationError(msg, code='authorization')

        attrs['user'] = user
        return attrs
示例#12
0
def login_user(request):
    authentication_classes = (
        SessionAuthentication
    )  #(TokenAuthentication, SessionAuthentication, BasicAuthentication)
    permission_classes = (IsAuthenticated, )
    language = 'ar'
    translation.activate(language)
    username = request.data.get("username")
    password = request.data.get("password")
    encoded = make_password(password)
    check_password(password, encoded)
    user = authenticate(username=username, password=password)
    print(user)
    if user is not None:
        login(request, user)
        user = User.objects.get(pk=user.id)
        query = 'select full_name, address, phone_number from api_userprofile where user_id=user.id'
        user1 = UserProfile.objects.get(pk=request.user.pk)
        print(user1)
        print(user1.phone_number)
        rs = {
            'id': user.id,
            'username': user.username,
            'email': user.email,
            'full_name': user1.full_name,
            'address': user1.address,
            'phone_number': user1.phone_number
        }
        ldata = {
            'status': 200,
            'response': rs,
            'msg': "User Successfully Logged"
        }
        return Response(ldata)
    else:
        if user is not None:
            if user.is_active:
                login(request, user)
                rs = {
                    'id': user.id,
                    'username': user.username,
                    'email': user.email,
                    'full_name': user.userprofile.full_name
                }
                ldata = {
                    'status': 200,
                    'response': rs,
                    'msg': "User Successfully Login"
                }
                return Response(ldata)
            else:
                u1data = {'status': 501, 'msg': "User account is not valid"}
                return Response(u1data)
        else:
            u1data = {'status': 501, 'msg': "Invalid Username or Password"}
            return Response(u1data)
    l1data = {'status': 501, ' msg': "Invalid Username or Password"}
    return Response(l1data)
示例#13
0
    def validate(self, attrs):
        access_token = attrs.get('access_token')
        if access_token:
            user = authenticate(access_token=access_token)
            if not user:
                raise serializers.ValidationError('액세스 토큰이 올바르지 않습니다.')
        else:
            raise serializers.ValidationError('액세스 토큰이 필요합니다.')

        attrs['user'] = user
        return attrs
示例#14
0
def login(request):
    if request.method == 'POST':
        id = request.data.get("id")
        password = request.data.get("password")

        user = authenticate(username=id, password=password, request=request)
        if not user:
            return Response({"detail": "비밀번호나 아이디가 일치 하지 않습니다."},
                            status=status.HTTP_400_BAD_REQUEST)

        return Response(UserSerializer(user, allow_null=True).data,
                        status=HTTP_200_OK)
示例#15
0
    def validate(self, data):
        # The `validate` method is where we make sure that the current
        # instance of `LoginSerializer` has "valid". In the case of logging a
        # user in, this means validating that they've provided an email
        # and password and that this combination matches one of the users in
        # our database.
        email = data.get('email', None)
        password = data.get('password', None)

        # Raise an exception if an
        # email is not provided.
        if email is None:
            raise serializers.ValidationError(
                'An email address is required to log in.'
            )

        # Raise an exception if a
        # password is not provided.
        if password is None:
            raise serializers.ValidationError(
                'A password is required to log in.'
            )

        # The `authenticate` method is provided by Django and handles checking
        # for a user that matches this email/password combination. Notice how
        # we pass `email` as the `username` value since in our User
        # model we set `USERNAME_FIELD` as `email`.
        user = authenticate(username=email, password=password)

        # If no user was found matching this email/password combination then
        # `authenticate` will return `None`. Raise an exception in this case.
        if user is None:
            raise serializers.ValidationError(
                'A user with this email and password was not found.'
            )

        # Django provides a flag on our `User` model called `is_active`. The
        # purpose of this flag is to tell us whether the user has been banned
        # or deactivated. This will almost never be the case, but
        # it is worth checking. Raise an exception in this case.
        if not user.is_active:
            raise serializers.ValidationError(
                'This user has been deactivated.'
            )

        # The `validate` method should return a dictionary of validated data.
        # This is the data that is passed to the `create` and `update` methods
        # that we will see later on.
        return {
            'email': user.email,
            'username': user.username,
            'token': user.token
        }
示例#16
0
    def post(self, request):
        # request.data에
        #   access_token
        #   facebook_user_id
        #       데이터가 전달됨

        # Debug결과의 NamedTuple
        class DebugTokenInfo(NamedTuple):
            app_id: str
            application: str
            expires_at: int
            is_valid: bool
            # issued_at: int
            scopes: list
            type: str
            user_id: str

        # token(access_token)을 받아 해당 토큰을 Debug
        def get_debug_token_info(token):
            app_id = settings.FACEBOOK_APP_ID
            app_secret_code = settings.FACEBOOK_SECRET_CODE
            app_access_token = f'{app_id}|{app_secret_code}'

            url_debug_token = 'https://graph.facebook.com/debug_token'
            params_debug_token = {
                'input_token': token,
                'access_token': app_access_token,
            }
            response = requests.get(url_debug_token, params_debug_token)
            print(response)
            return DebugTokenInfo(**response.json()['data'])

        # request.data로 전달된 access_token값을 페이스북API쪽에 debug요청, 결과를 받아옴
        debug_token_info = get_debug_token_info(request.data['access_token'])

        if debug_token_info.user_id != request.data['facebook_user_id']:
            raise APIException('페이스북 토큰의 사용자와 전달받은 facebook_user_id가 일치하지 않음')

        if not debug_token_info.is_valid:
            raise APIException('페이스북 토큰이 유효하지 않음')

        # FacebookBackend를 사용해서 유저 인증
        user = authenticate(facebook_user_id=request.data['facebook_user_id'])
        # 인증에 실패한 경우 페이스북유저 타입으로 유저를 만들어줌
        if not user:
            user = User.objects.create_user(
                username=f'fb_{request.data["facebook_user_id"]}',
                user_type=User.USER_TYPE_FACEBOOK,
            )
        # 유저 시리얼라이즈 결과를 Response

        return Response(UserSerializer(user).data)
示例#17
0
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')

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

        if user:
            token, __ = Token.objects.get_or_create(user=user)
            data = {
                'token': token.key,
            }
            return Response(data)
        raise AuthenticationFailed('인증정보가 올바르지 않습니다')
示例#18
0
def login(request):
    username = request.data.get("username")
    password = request.data.get("password")
    if username is None or password is None:
        return Response({'error': 'Please provide both username and password'},
                        status=HTTP_400_BAD_REQUEST)
    user = authenticate(username=username, password=password)
    if not user:
        return Response({'error': 'Invalid Credentials'},
                        status=HTTP_404_NOT_FOUND)
    token, _ = Token.objects.get_or_create(user=user)
    return Response({'token': token.key},
                    status=HTTP_200_OK)
示例#19
0
    def validate(self, attrs):
        access_token = attrs.get('access_token')
        if access_token:
            user = authenticate(access_token=access_token)
            if not user:
                raise CustomException(detail='페이스북 액세스 토큰이 올바르지 않습니다.',
                                      status_code=status.HTTP_401_UNAUTHORIZED)
        else:
            raise CustomException(detail='페이스북 액세스 토큰이 필요합니다.',
                                  status_code=status.HTTP_400_BAD_REQUEST)

        attrs['user'] = user
        return attrs
示例#20
0
    def post(self, request, *args, **kwargs):
        if request.method == 'POST':
            username = request.data.get('username')
            password = request.data.get('password')
            user = authenticate(username=username, password=password)
            if user:
                token, token_created = Token.objects.get_or_create(user=user)
                serializer = UserSerializer(user)

                data = {"token": token.key, "user": serializer.data},
            else:
                data = {"error": "user is not authenticated"}
            return Response(data, status=status.HTTP_200_OK)
示例#21
0
 def post(self, request, format=None):
     data = JSONParser().parse(request)
     user = User.objects.filter(email=data['email']).first()
     if user is not None:
         user = authenticate(username=user.username,
                             password=data['password'])
         if user is not None:
             if user.is_active:
                 token = Token.objects.get_or_create(user=user)
                 return Response({'token': token[0].key})
         else:
             return HttpResponse(status=401)
     else:
         return HttpResponse(status=401)
示例#22
0
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        user = authenticate(username=username, password=password)

        if user:
            token, _ = Token.objects.get_or_create(user=user)

            data = {
                'token': token.key,
            }
            return Response(data, status=status.HTTP_200_OK)
        else:
            return Response('ID 또는 비밀번호를 확인해 주세요.',
                            status=status.HTTP_400_BAD_REQUEST)
示例#23
0
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        user = authenticate(username=username, password=password)

        if user:
            token, _= Token.objects.get_or_create(user=user)

            data = {
                'token' : token.key,

            }
            return Response(data, status=status.HTTP_200_OK)
        else:
            return AuthenticationFailed()
示例#24
0
    def validate(self, attrs):
        username = attrs.get('username')
        password = attrs.get('password')

        if username and password:
            user = authenticate(request=self.context.get('request'),
                                username=username,
                                password=password)
            if not user:
                raise serializers.ValidationError('不能登录', code='authorization')
        else:
            raise serializers.ValidationError('必须输入同时输入名称和密码',
                                              code='authorization')
        attrs['user'] = user
        return attrs
示例#25
0
文件: views.py 项目: 915646637/blog
    def post(self, request):

        username = request.data['username']
        password = request.data['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
            else:
                return Response({"error": "用户已被管理员禁止"}, status=404)

        else:
            return Response({"error": "用户名或密码错误"}, status=404)

        return Response({"username": user.username, "user_id": user.id})
示例#26
0
    def validate(self, data):
        email, password = data.values()

        if not email or not password:
            msg = _('Must include "email" and "password".')
            raise serializers.ValidationError(msg, code='authorization')

        user = authenticate(request=self.context.get('request'),
                            email=email,
                            password=password)
        if not user:
            msg = _('Unable to log in with provided credentials.')
            raise serializers.ValidationError(msg, code='authorization')

        self.user = user
        return data
示例#27
0
文件: views.py 项目: jaimeplier/taxi
 def post(self, request):
     serializer = ChangePasswordSerializer(data=request.data)
     serializer.is_valid(raise_exception=True)
     u = authenticate(email=self.request.user.email,
                      password=serializer.validated_data.get('old'))
     if u is not None:
         u.set_password(serializer.validated_data.get('new'))
         u.save()
     else:
         return Response(
             {
                 "result": 0,
                 "error": "La contraseña anterior no coincide"
             },
             status=status.HTTP_200_OK)
     return Response({"result": 1}, status=status.HTTP_200_OK)
示例#28
0
    def validate(self, attrs):
        email = attrs.get('email')
        password = attrs.get('password')

        if email and password:
            user = authenticate(request=self.context.get('request'),
                                email=email,
                                password=password)
            if not user:
                msg = '이메일 혹은 비밀번호가 잘못되었습니다.'
                raise serializers.ValidationError(msg, code='authorization')
        else:
            msg = '이메일과 비밀번호는 필수 항목입니다'
            raise serializers.ValidationError(msg, code='authorization')

        attrs['user'] = user
        return attrs
示例#29
0
    def validate(self, attrs):
        email = attrs.get('email')
        password = attrs.get('password')

        if email and password:
            user = authenticate(request=self.context.get('request'),
                                email=email, password=password)

            if not user:
                msg = _('Unable to log in with provided credentials.')
                raise serializers.ValidationError(msg, code='authorization')
        else:
            msg = _('Must include "email" and "password".')
            raise serializers.ValidationError(msg, code='authorization')

        attrs['user'] = user
        return attrs
    def authenticate_credentials(self, userid, password, request=None):
        """
        Authenticate the userid and password against username and password
        with optional request for context.
        """
        credentials = {
            get_user_model().USERNAME_FIELD: userid,
            'password': password
        }
        user = authenticate(request=request, **credentials)

        if user is None:
            raise exceptions.AuthenticationFailed(_('Invalid username/password.'))

        if not user.is_active:
            raise exceptions.AuthenticationFailed(_('User inactive or deleted.'))

        return (user, None)
    def authenticate_credentials(self, userid, password, request=None):
        """
        Authenticate the userid and password against username and password
        with optional request for context.
        """
        credentials = {
            get_user_model().USERNAME_FIELD: userid,
            'password': password
        }
        user = authenticate(request=request, **credentials)

        if user is None:
            raise exceptions.AuthenticationFailed(_('Invalid username/password.'))

        if not user.is_active:
            raise exceptions.AuthenticationFailed(_('User inactive or deleted.'))

        return (user, None)
    def validate(self, attrs):
        username = attrs.get('username')
        password = attrs.get('password')

        if username and password:
            user = authenticate(request=self.context.get('request'),
                                username=username, password=password)

            if user:
                # From Django 1.10 onwards the `authenticate` call simply
                # returns `None` for is_active=False users.
                # (Assuming the default `ModelBackend` authentication backend.)
                if not user.is_active:
                    msg = _('User account is disabled.')
                    raise serializers.ValidationError(msg, code='authorization')
            else:
                msg = _('Unable to log in with provided credentials.')
                raise serializers.ValidationError(msg, code='authorization')
        else:
            msg = _('Must include "username" and "password".')
            raise serializers.ValidationError(msg, code='authorization')

        attrs['user'] = user
        return attrs
 def authenticate(self, request):
     user = authenticate(remote_user=request.META.get(self.header))
     if user and user.is_active:
         return (user, None)