Esempio n. 1
0
 def post(self, request, *args, **kwargs):
     userData = request.data.pop('user', None)
     #userData = {}
     #userData['email'] = request.data['email']
     #userData['password'] = request.data['password']
     if not userData:
         return Response(
             {
                 'status': 'error',
                 'message': 'User data is absent'
             },
             status=400)
     print(userData)
     serializer = self.get_serializer(data=userData)
     print(type(serializer))
     if serializer.is_valid():
         user = serializer.save()
         response = {}
         response['user'] = serializer.data
         payload = jwt_payload_handler(user)
         token = token = jwt.encode(payload, settings.SECRET_KEY)
         response['token'] = token
         user_logged_in.send(sender=user.__class__,
                             request=request,
                             user=user)
         return Response(response, status=200)
     return Response(serializer.errors, status=422)
Esempio n. 2
0
def verify_otp(request):
    mobile = request.data.get('mobile', None)
    otp = request.data.get('otp', None)
    try:
        user = User.objects.get(mobile=mobile)
    except User.DoesNotExist:
        user = None
    if otp and user:
        print(otp, user)
        t = pyotp.TOTP(user.key, interval=900)
        is_verified = t.verify(otp)
        print(is_verified)
        if is_verified:
            try:
                payload = jwt_payload_handler(user)
                token = jwt.encode(payload, settings.SECRET_KEY)
                serializer = UserSerializer(user, context={'request': request})
                data = serializer.data
                data['token'] = token
                user_logged_in.send(sender=user.__class__,
                                    request=request,
                                    user=user)
                return Response(data, status=status.HTTP_200_OK)
            except Exception as e:
                raise e

    return Response(status=status.HTTP_400_BAD_REQUEST)
def authenticate_user(request):
    """
        Generate and assign token into user
    :param request: login request
    :return: jwt token
    """

    try:
        email = request.data['email']
        password = request.data['password']
        user = MyUser.objects.get(email=email)
        if user:

            try:
                # create jwt web token
                payload = jwt_payload_handler(user)
                token = jwt.encode(payload, main_settings.SECRET_KEY)
                user_details = {'name': '{first_name} {last_name}'.format(first_name=user.first_name,
                                                                          last_name=user.last_name), 'token': token}
                user_logged_in.send(sender=user.__class__, request=request, user=user)
                return Response(user_details, status=status.HTTP_200_OK)

            except Exception as e:
                raise e
        else:
            res = {
                'error': 'can not authenticate with the given credentials or the account has been deactivated'}
            return Response(res, status=status.HTTP_403_FORBIDDEN)
    except KeyError:
        res = {'error': 'please provide a email and a password'}
        return Response(res)
Esempio n. 4
0
def authenticate_user(request):
    email = request.data['email']
    password = request.data['password']
    if not (email and password):
        response = {'error': 'Please provide a email and a password'}
        return Response(response, status=status.HTTP_400_BAD_REQUEST)
    try:
        user = User.objects.get(email=email)

        if not user.check_password(password):
            res = {'error': 'Incorrect password'}
            return Response(res, status=status.HTTP_403_FORBIDDEN)

        try:
            payload = jwt_payload_handler(user)
            token = jwt.encode(payload, settings.SECRET_KEY)
            user_details = get_user_data(user)
            user_details['token'] = token
            user_logged_in.send(sender=user.__class__,
                                request=request,
                                user=user)
            cache.set(key=f'{user.id}', value=token)
            return Response(user_details, status=status.HTTP_200_OK)
        except Exception as e:
            raise e
    except ObjectDoesNotExist:
        res = {'error': 'Incorrect email'}
        return Response(res, status=status.HTTP_403_FORBIDDEN)
Esempio n. 5
0
    def post(self, request, *args, **kwargs):
        try:
            email = request.data['email']
            password = request.data['password']
            organization = request.data['organization']

            user = User.objects.get(email=email, password=password)
            if user:
                try:
                    payload = jwt_payload_handler(user)
                    token = jwt.encode(payload, SECRET_KEY)
                    user_details = {'name': "%s %s" % (
                        user.first_name, user.last_name
                    ), 'token': token, 'organization': organization}
                    user_logged_in.send(sender=user.__class__,
                                        request=request, user=user)
                    return Response(user_details, status=status.HTTP_200_OK)
                except Exception as e:
                    raise e

            else:
                res = {
                    'error': 'Can not authenticate with the given credentials or the account has been deactivated'
                }
                return Response(res, status=status.HTTP_403_FORBIDDEN)
        except KeyError:
            res = {'error': 'Please provide an email and a password'}
            return Response(res, status=status.HTTP_400_BAD_REQUEST)
Esempio n. 6
0
    def clean(self):
        """
        입력된 user_id가 존재하는지, 존재한다면 password는 일치하는지 확인
        """
        request = self.request
        data = self.cleaned_data
        user_id = data.get("user_id")
        password = data.get("password")
        qs = User.objects.filter(user_id=user_id)

        # 사용자에게 아이디 존재여부 비공개
        if qs.exists():
            # 사용자 인증
            user = authenticate(request, username=user_id, password=password)

            if user is None:
                messages.success(request, "아이디가 유효하지 않거나, 비밀번호가 잘못되었습니다.")
                raise forms.ValidationError("비밀번호 불일치.")
        else:
            messages.success(request, "아이디가 유효하지 않거나, 비밀번호가 잘못되었습니다.")
            raise forms.ValidationError("가입된 ID 없음.")

        login(request, user)
        self.user = user
        user_logged_in.send(user.__class__, user=user, request=request)

        return data
Esempio n. 7
0
def obtain_jwt(attrs, algorithm='HS256'):
    """
    """
    delta = getattr(
        settings,
        'JWT_EXPIRATION',
        datetime.timedelta(seconds=300),
    )
    username_field = get_user_model().USERNAME_FIELD
    credentials = {
        username_field: attrs.get(username_field),
        'password': attrs.get('password')
    }
    user = authenticate(
        **credentials
    )
    payload = {
        'user_id': user.pk,
        'exp': datetime.datetime.utcnow() + delta
    }
    key, user = get_secure_key(user.pk)
    token = jwt.encode(
        payload,
        key,
        algorithm,
    ).decode('utf-8')
    user_logged_in.send(sender=user.__class__, user=user)
    return {
        'token': token
    }
Esempio n. 8
0
def login(request, user):
    """
    Overwrite default django login function as django 1.8 breaks the ability
    to use that method with
    """
    session_auth_hash = ''
    if user is None:
        user = request.user
    if hasattr(user, 'get_session_auth_hash'):
        session_auth_hash = user.get_session_auth_hash()

    if SESSION_KEY in request.session:
        if str(request.session[SESSION_KEY]) != str(user.pk) or (
                session_auth_hash and
                request.session.get(HASH_SESSION_KEY) != session_auth_hash):
            # To avoid reusing another user's session, create a new, empty
            # session if the existing session corresponds to a different
            # authenticated user.
            request.session.flush()
    else:
        request.session.cycle_key()
    request.session[SESSION_KEY] = str(user.pk)
    request.session[BACKEND_SESSION_KEY] = user.backend
    request.session[HASH_SESSION_KEY] = session_auth_hash
    if hasattr(request, 'user'):
        request.user = user
    rotate_token(request)
    user_logged_in.send(sender=user.__class__, request=request, user=user)
Esempio n. 9
0
def signup(request):
    """
    注册视图
    :param request:
    :return:
    """

    if request.method == 'POST':
        form = SignUpForm(request.data)
        if form.is_valid():
            user = form.save()
            user.refresh_from_db()
            user.investor.mobile = form.cleaned_data.get('mobile')
            sex = Sex.objects.get(id=form.cleaned_data.get('sex') or 1)
            user.investor.sex = sex
            user.save()
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=user.username, password=raw_password)
            payload = jwt_payload_handler(user)
            user_logged_in.send(sender=user.__class__,
                                request=request,
                                user=user)
            investor = Investor.objects.get(user=user)
            investor_data = InvestorSerializer(investor)
            return Response({
                'token': jwt_encode_handler(payload),
                'user': investor_data.data
            })

        return Response({'message': form.errors},
                        status=status.HTTP_400_BAD_REQUEST)

    return Response({'message': 'Method Not Allowed'},
                    status=status.HTTP_404_NOT_FOUND)
Esempio n. 10
0
    def clean(self):
        request = self.request
        data = self.cleaned_data
        email = data.get("email")
        password = data.get("password")
        qs = User.objects.filter(email=email)

        user = authenticate(request, username=email, password=password)
        if user is None:
            messages.success(
                request,
                "Cannot login with you've written. Please check again.")
            raise forms.ValidationError("Invalid credentials")
        login(request, user)
        self.user = user
        user_logged_in.send(user.__class__, user=user, request=request)

        login(request, user)
        self.user = user
        user_logged_in.send(user.__class__, user=user, request=request)
        try:
            pass
        except:
            pass
        return data
Esempio n. 11
0
def login_user(user, request=None):
    """
    Once user is validated, issue a token.
    """
    token, _ = Token.objects.get_or_create(user=user)
    user_logged_in.send(sender=user.__class__, request=request, user=user)
    return token
Esempio n. 12
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_active:
                    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_encode_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)
Esempio n. 13
0
    def obtain_token(self, request):
        try:
            username = request.data['username']
            password = request.data['password']
            try:
                user = Usuarios.objects.get(username=username)
                pwd_valid = password == user.password
                if pwd_valid is False:
                    user = None
            except Usuarios.DoesNotExist:
                user = None
            if user:
                try:
                    payload = jwt_payload_handler(user)
                    token = jwt.encode(payload, settings.SECRET_KEY)
                    user_logged_in.send(sender=user.__class__,
                                        request=request,
                                        user=user)
                    return Response(AuthenticationUserSerializer(user).data,
                                    status=status.HTTP_200_OK)

                except Exception as e:
                    raise e
            else:
                res = {
                    'error':
                    'can not authenticate with the given credentials or the account has been deactivated'
                }
                return Response(res, status=status.HTTP_403_FORBIDDEN)

        except KeyError:
            res = {'error': 'please provide a email and password'}
            return Response(res)
Esempio n. 14
0
    def post(self, request):
        try:
            email = request.data['email']
            password = request.data['password']

            user = User.objects.get(email=email, password=password)
            if user:

                try:
                    payload = jwt_payload_handler(user)
                    token = jwt.encode(payload, settings.SECRET_KEY)
                    user_details = {'name': user.email, 'token': token}
                    user_logged_in.send(sender=user.__class__,
                                        request=request,
                                        user=user)
                    return Response(user_details, status=status.HTTP_200_OK)
                except Exception as e:
                    raise e

            else:
                out = {
                    'error':
                    'can not authenticate with the given credentials or the account'
                }
                return Response(out, status=status.HTTP_403_FORBIDDEN)

        except KeyError:
            out = {'error': "Please provide an email and a password"}
            return Response(out)
Esempio n. 15
0
    def wrapper(cls, root, info, password, **kwargs):
        def on_resolve(values):
            user, payload = values
            payload.token = get_token(user, info.context)

            if jwt_settings.JWT_LONG_RUNNING_REFRESH_TOKEN:
                payload.refresh_token = create_refresh_token(user).get_token()

            return payload

        username = kwargs.get(get_user_model().USERNAME_FIELD)

        if get_authorization_header(info.context) is not None:
            del info.context.META[jwt_settings.JWT_AUTH_HEADER_NAME]

        user = authenticate(request=info.context,
                            username=username,
                            password=password)

        if user is None:
            raise exceptions.JSONWebTokenError(
                _('Please, enter valid credentials'))

        if hasattr(info.context, 'user'):
            info.context.user = user
        user_logged_in.send(sender=user.__class__,
                            request=info.context,
                            user=user)
        result = f(cls, root, info, **kwargs)
        values = (user, result)

        if is_thenable(result):
            return Promise.resolve(values).then(on_resolve)
        return on_resolve(values)
    def validate_user(self, username, password, client, request, *args, **kwargs):
        user_model = get_user_model()
        try:
            user = user_model.objects.get_by_natural_key(username)
        except user_model.DoesNotExist:
            user = None

        if user and FailedLoginAttempt.objects.is_locked_out(user, client):
            logger.info('User "%s" is locked out' % username)
            raise LockedOutError(request=request)

        valid = super().validate_user(
            username, password, client, request, *args, **kwargs
        )
        if valid:
            if not ApplicationUserMapping.objects.filter(
                    user=request.user, application=client).exists():
                raise RestrictedClientError(request=request)
            FailedLoginAttempt.objects.delete_failed_attempts(user, client)
            user_logged_in.send(sender=user.__class__, request=request, user=user)
            return True
        elif user:
            logger.info('User "%s" failed login' % username)
            FailedLoginAttempt.objects.add_failed_attempt(user, client)
            if FailedLoginAttempt.objects.is_lockout_imminent(user, client):
                raise LockoutImminentError(request=request)

        request.user = None
        return False
Esempio n. 17
0
def shibboleth_login(request):
    headers = request.META
    # clean up headers data
    shibboleth_data = dict(zip(*zip(*shibboleth_headers(headers))))
    # resolve data used for class User
    user_data = get_user_data(shibboleth_data)

    # initialize
    user = None
    token = None

    redirect_url = TOKEN_LOGIN_URL

    shibboleth_id = user_data.get('shibboleth_id')
    if not shibboleth_id:
        e = 'No shibboleth id'
        return HttpResponseRedirect(TOKEN_LOGIN_URL + "#error=foo" % e)

    try:
        user = User.objects.get(shibboleth_id=shibboleth_id)

    except User.DoesNotExist:
        user = User.objects.create(**user_data)
        send_email_shib_user_created(user, headers['HTTP_HOST'])

    token, _ = Token.objects.get_or_create(user=user)
    user_logged_in.send(sender=user.__class__, request=request, user=user)

    token_fragment = '#token=' + token.key
    redirect_url = redirect_url + token_fragment

    return HttpResponseRedirect(redirect_url)
Esempio n. 18
0
def login(request, user):
    '''Persist a user id and a backend in the request. This way a user doesn't
    have to reauthenticate on every request.

    :param user: The user object.
    :type user: :class:`baph.auth.models.User`
    '''
    if hasattr(request, 'orm'):
        session = request.orm.sessionmaker()
    else:
        from .models import orm
        session = orm.sessionmaker()
    if user is None:
        user = request.user
    # TODO: It would be nice to support different login methods, like signed
    # cookies.
    user.last_login = datetime.now()
    session.commit()

    if SESSION_KEY in request.session:
        if request.session[SESSION_KEY] != user.id:
            # To avoid reusing another user's session, create a new, empty
            # session if the existing session corresponds to a different
            # authenticated user.
            request.session.flush()
    else:
        request.session.cycle_key()
    request.session[SESSION_KEY] = user.id
    request.session[BACKEND_SESSION_KEY] = user.backend
    if hasattr(request, 'user'):
        request.user = user
    user_logged_in.send(sender=user.__class__, request=request, user=user)
Esempio n. 19
0
 def post(self, request, *args, **kwargs):
     serializer = self.get_serializer(data=request.data)
     serializer.is_valid(raise_exception=True)
     user_logged_in.send(sender=serializer.validated_data.get("user").__class__, request=request,
                         user=serializer.validated_data.get("user"))
     response_data = {"token": serializer.validated_data.get('token')}
     return Response(response_data)
Esempio n. 20
0
 def post(self, request):
     serializer = self.get_serializer(data=request.data)
     serializer.is_valid(raise_exception=True)
     user = serializer.validated_data['user']
     login(request, user)
     user_logged_in.send(sender=user.__class__, request=self.request, user=user)
     return Response(status=status.HTTP_200_OK)
Esempio n. 21
0
def authenticate_user(request):
    try:
        username = request.data['username']
        password = request.data['password']

        user = Employee.objects.get(username=username, password=password)
        if user:
            try:
                payload = jwt_payload_handler(user)
                token = jwt.encode(payload, settings.SECRET_KEY)
                serializer = EmployeeSerializer(user)
                user_details = {'user': serializer.data, 'token': token}
                user_logged_in.send(sender=user.__class__,
                                    request=request,
                                    user=user)
                return Response(user_details, status=status.HTTP_200_OK)

            except Exception as e:
                raise e
        else:
            res = {'error': 'can not authenticate with the given credentials'}
            return Response(res, status=status.HTTP_403_FORBIDDEN)
    except KeyError:
        res = {'error': 'please provide a email and a password'}
        return Response(res)
Esempio n. 22
0
def login(request, user=None):
    """
    Persist a user id and a backend in the request. This way a user doesn't
    have to reauthenticate on every request. Note that data set during
    the anonymous session is retained when the user logs in.
    """
    session_auth_hash = ''
    if user is None:
        user = request.user
    if hasattr(user, 'get_session_auth_hash'):
        session_auth_hash = user.get_session_auth_hash()

    if SESSION_KEY in request.session:
        if get_user_session_key(request) != user.pk or (
                session_auth_hash and
                request.session.get(HASH_SESSION_KEY) != session_auth_hash):
            # To avoid reusing another user's session, create a new, empty
            # session if the existing session corresponds to a different
            # authenticated user.
            request.session.flush()
    else:
        request.session.cycle_key()
    request.session[SESSION_KEY] = str(user.pk)
    request.session[
        BACKEND_SESSION_KEY] = 'django_mongoengine.auth.backends.MongoEngineBackend'
    request.session[HASH_SESSION_KEY] = session_auth_hash
    if hasattr(request, 'user'):
        request.user = user
    rotate_token(request)
    user_logged_in.send(sender=user.__class__, request=request, user=user)
Esempio n. 23
0
def authenticate_user(request):
    try:
        email = request.data['email']
        password = request.data['password']

        user = User.objects.get(email=email, password=password)
        if user:
            try:
                payload = jwt_payload_handler(user)
                token = jwt.encode(payload, settings.SECRET_KEY)
                user_details = {}
                user_details['name'] = "%s %s" % (user.name, user.surname)
                user_details['token'] = token
                # TODO: Add balance and photo of a user
                user_logged_in.send(sender=user.__class__,
                                    request=request,
                                    user=user)
                return Response(user_details, status=status.HTTP_200_OK
                                )  # Возвращает токен и пользователя

            except Exception as e:
                raise e
        else:
            res = {
                'error':
                'can not authenticate with the given credentials or the account has been deactivated'
            }
            return Response(res, status=status.HTTP_403_FORBIDDEN
                            )  # Если пароль/логин неправильные
    except KeyError:
        res = {'error': 'please provide a email and a password'}
        return Response(res, status=status.HTTP_400_BAD_REQUEST
                        )  # Если в запросе не было логина/пароля
Esempio n. 24
0
def login(request, user):
    '''Persist a user id and a backend in the request. This way a user doesn't
    have to reauthenticate on every request.

    :param user: The user object.
    :type user: :class:`baph.auth.models.User`
    '''
    if hasattr(request, 'orm'):
        session = request.orm.sessionmaker()
    else:
        from .models import orm
        session = orm.sessionmaker()
    if user is None:
        user = request.user
    # TODO: It would be nice to support different login methods, like signed
    # cookies.
    user.last_login = datetime.now()
    session.commit()

    if SESSION_KEY in request.session:
        if request.session[SESSION_KEY] != user.id:
            # To avoid reusing another user's session, create a new, empty
            # session if the existing session corresponds to a different
            # authenticated user.
            request.session.flush()
    else:
        request.session.cycle_key()
    request.session[SESSION_KEY] = user.id
    request.session[BACKEND_SESSION_KEY] = user.backend
    if hasattr(request, 'user'):
        request.user = user
    user_logged_in.send(sender=user.__class__, request=request, user=user)    
Esempio n. 25
0
def login(request, user=None):
    """
    Persist a user id and a backend in the request. This way a user doesn't
    have to reauthenticate on every request. Note that data set during
    the anonymous session is retained when the user logs in.
    """
    session_auth_hash = ''
    if user is None:
        user = request.user
    if hasattr(user, 'get_session_auth_hash'):
        session_auth_hash = user.get_session_auth_hash()

    if SESSION_KEY in request.session:
        if get_user_session_key(request) != user.pk or (
                session_auth_hash and
                request.session.get(HASH_SESSION_KEY) != session_auth_hash):
            # To avoid reusing another user's session, create a new, empty
            # session if the existing session corresponds to a different
            # authenticated user.
            request.session.flush()
    else:
        request.session.cycle_key()
    request.session[SESSION_KEY] = str(user.pk)
    request.session[BACKEND_SESSION_KEY] = 'django_mongoengine.auth.backends.MongoEngineBackend'
    request.session[HASH_SESSION_KEY] = session_auth_hash
    if hasattr(request, 'user'):
        request.user = user
    rotate_token(request)
    user_logged_in.send(sender=user.__class__, request=request, user=user)
Esempio n. 26
0
def login(data: Login, request: Request):
    user = get_login_user(request, LoginChallengeIn(username=data.response_data.username))
    host = request.headers.get("Host")
    validate_login_request(data.response_data, data, user, "login", host)
    ret = LoginOut.from_orm(user)
    user_logged_in.send(sender=user.__class__, request=None, user=user)
    return ret
    def validate_user(self, username, password, client, request, *args,
                      **kwargs):
        user_model = get_user_model()
        try:
            user = user_model.objects.get_by_natural_key(username)
        except user_model.DoesNotExist:
            user = None

        if user and FailedLoginAttempt.objects.is_locked_out(user, client):
            logger.info('User "%s" is locked out' % username)
            raise LockedOutError(request=request)

        valid = super().validate_user(username, password, client, request,
                                      *args, **kwargs)
        if valid:
            if not ApplicationUserMapping.objects.filter(
                    user=request.user, application=client).exists():
                raise RestrictedClientError(request=request)
            FailedLoginAttempt.objects.delete_failed_attempts(user, client)
            user_logged_in.send(sender=user.__class__,
                                request=request,
                                user=user)
            return True
        elif user:
            logger.info('User "%s" failed login' % username)
            FailedLoginAttempt.objects.add_failed_attempt(user, client)
            if FailedLoginAttempt.objects.is_lockout_imminent(user, client):
                raise LockoutImminentError(request=request)

        request.user = None
        return False
Esempio n. 28
0
    def login(self, request, *args, **kwargs):
        outer_serializer = AuthenticationLoginSerializer(data=request.data)
        outer_serializer.is_valid(raise_exception=True)

        response_raw = outer_serializer.validated_data["response"]
        response = msgpack_decode(response_raw)
        signature = outer_serializer.validated_data["signature"]

        context = {"host": request.get_host()}
        serializer = AuthenticationLoginInnerSerializer(data=response,
                                                        context=context)
        serializer.is_valid(raise_exception=True)

        bad_login_response = self.validate_login_request(
            request, serializer.validated_data, response_raw, signature,
            "login")
        if bad_login_response is not None:
            return bad_login_response

        username = serializer.validated_data.get("username")
        user = self.get_login_user(username)

        data = self.login_response_data(user)

        user_logged_in.send(sender=user.__class__, request=request, user=user)

        return Response(data, status=status.HTTP_200_OK)
Esempio n. 29
0
    def post(self, request):
        if 'email' in request.data and 'password' in request.data:
            user = get_object_or_404(Profile.objects.all(),
                                     email=request.data['email'])
            if user.confirmed_at is None:
                return Response('Please activate your account',
                                status=status.HTTP_400_BAD_REQUEST)

            auth_user = authenticate(username=request.data['email'],
                                     password=request.data['password'])
            try:
                payload = jwt_payload_handler(auth_user)
                token = jwt.encode(payload, settings.SECRET_KEY)
                user_details = {
                    'token': token,
                    'user': model_to_dict(auth_user)
                }
                user_logged_in.send(sender=auth_user.__class__,
                                    request=request,
                                    user=auth_user)
                return Response(user_details, status=status.HTTP_200_OK)

            except Exception as e:
                raise e
        else:
            return Response('Wrong credentials',
                            status=status.HTTP_400_BAD_REQUEST)
    def post(self, request, format=None):
        token_limit_per_user = self.get_token_limit_per_user()
        if token_limit_per_user is not None:
            now = timezone.now()
            token = request.user.auth_token_set.filter(expiry__gt=now)
            if token.count() >= token_limit_per_user:
                return Response(
                    {
                        "error":
                        "Maximum amount of tokens allowed per user exceeded."
                    },
                    status=status.HTTP_403_FORBIDDEN)

        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.user
        user_logged_in.send(sender=user.__class__, request=request, user=user)

        token_ttl = self.get_token_ttl()
        instance, token = AuthToken.objects.create(user, token_ttl)

        data = {
            'expiry': self.format_expiry_datetime(instance.expiry),
            'token': token
        }
        return Response(data, status=status.HTTP_200_OK)
Esempio n. 31
0
    def perform_create(self, serializer):
        super(RegistrationWithTokenView, self).perform_create(serializer)

        user = serializer.instance
        user_logged_in.send(sender=user.__class__,
                            request=self.request,
                            user=user)
Esempio n. 32
0
def authenticate_user(request):
    try:
        email = request.data['email']
        password = request.data['password']

        user = User.objects.get(email=email, password=password)
        if user:
            try:
                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_200_OK)

            except Exception as e:
                raise e
        else:
            res = {
                'error':
                'can not authenticate with the given credentials or the account has been deactivated'
            }
            return Response(res, status=status.HTTP_403_FORBIDDEN)
    except KeyError:

        res = {'error': 'please provide a email and a password'}
        return Response(res)
Esempio n. 33
0
 def post(self, request, *args, **kwargs):
     serializer = self.serializer_class(data=request.data)
     serializer.is_valid(raise_exception=True)
     user = serializer.validated_data['user']
     token, created = Token.objects.get_or_create(user=user)
     user_logged_in.send(sender=user.__class__, request=request, user=user)
     return Response(data={'token': token.key}, status=HTTP_200_OK)
Esempio n. 34
0
def user_login(request):
    try:
        email = request.POST.get('email')
        password = request.POST.get('password')

        user = User.objects.filter(email=email,
                                   password=password).values("user_id")[0]
        print(user)

        if user:
            payload = jwt_payload_handler(user)
            token = jwt.encode(payload, settings.SECRET_KEY)
            user_details = {
                'token': token.decode('ascii'),
                'user_id': user['user_id']
            }

            user_logged_in.send(sender=user.__class__,
                                request=request,
                                user=user)
            return HttpResponse(json.dumps(user_details),
                                content_type='application/json',
                                status=status.HTTP_200_OK)

        else:  # no matching user
            return HttpResponse(status=status.HTTP_401_UNAUTHORIZED)

    except KeyError:
        return HttpResponse(status=status.HTTP_400_BAD_REQUEST)
Esempio n. 35
0
def authenticate_user(request):
    try:
        email = request.data['email']
        password = request.data['password']
        user = None
        try:
            user = User.objects.get(email=email, password=password)
        except ObjectDoesNotExist as ex:
            pass
        if user:
            payload = jwt_payload_handler(user)
            token = jwt.encode(payload, SECRET_KEY)
            user_details = {}
            user_details['name'] = user.user_name
            user_details['token'] = token
            user_details['user_id'] = user.id
            user_logged_in.send(sender=user.__class__,
                                request=request,
                                user=user)
            return Response({
                'res': user_details,
                'error': ''
            },
                            status=status.HTTP_200_OK)
        else:
            res = {
                'res':
                '',
                'error':
                'can not authenticate with the given credentials or the account has been deactivated'
            }
            return Response(res, status=status.HTTP_403_FORBIDDEN)
    except KeyError:
        res = {'res': '', 'error': 'please provide a email and a password'}
        return Response(res, status=status.HTTP_400_BAD_REQUEST)
Esempio n. 36
0
 def action(self, serializer):
     user = serializer.user
     token, _ = Token.objects.get_or_create(user=user)
     user_logged_in.send(sender=user.__class__, request=self.request, user=user)
     return Response(
         data=serializers.TokenSerializer(token).data,
         status=status.HTTP_200_OK,
     )
 def generate_response(self, request, user):
     user_logged_in.send(sender=user.__class__, request=request, user=user)
     bundle = self.build_bundle(obj=user, request=request)
     bundle = self.full_dehydrate(bundle)
     apikey = ApiKey.objects.get_or_create(user=user)[0].key
     bundle.data['apikey'] = apikey
     social_access_token = SocialToken.get_user_tokens(user)
     if social_access_token:
         bundle.data['social_access_token'] = social_access_token
     return self.create_response(request, bundle)
Esempio n. 38
0
def login(scope, user, backend=None):
    """
    Persist a user id and a backend in the request.
    This way a user doesn't have to re-authenticate on every request.
    Note that data set during the anonymous session is retained when the user logs in.
    """
    if "session" not in scope:
        raise ValueError(
            "Cannot find session in scope. You should wrap your consumer in SessionMiddleware."
        )
    session = scope["session"]
    session_auth_hash = ""
    if user is None:
        user = scope.get("user", None)
    if user is None:
        raise ValueError(
            "User must be passed as an argument or must be present in the scope."
        )
    if hasattr(user, "get_session_auth_hash"):
        session_auth_hash = user.get_session_auth_hash()
    if SESSION_KEY in session:
        if _get_user_session_key(session) != user.pk or (
            session_auth_hash
            and not constant_time_compare(
                session.get(HASH_SESSION_KEY, ""), session_auth_hash
            )
        ):
            # To avoid reusing another user's session, create a new, empty
            # session if the existing session corresponds to a different
            # authenticated user.
            session.flush()
    else:
        session.cycle_key()
    try:
        backend = backend or user.backend
    except AttributeError:
        backends = _get_backends(return_tuples=True)
        if len(backends) == 1:
            _, backend = backends[0]
        else:
            raise ValueError(
                "You have multiple authentication backends configured and therefore must provide the `backend` "
                "argument or set the `backend` attribute on the user."
            )
    session[SESSION_KEY] = user._meta.pk.value_to_string(user)
    session[BACKEND_SESSION_KEY] = backend
    session[HASH_SESSION_KEY] = session_auth_hash
    scope["user"] = user
    # note this does not reset the CSRF_COOKIE/Token
    user_logged_in.send(sender=user.__class__, request=None, user=user)
Esempio n. 39
0
    def test_check_pioneer_badge(self):
        """
        Check pionner badge is awarded to user after some time
        """
        assert not self.user1.has_badge(PIONEER_BADGE)

        # first login won't affect the badge
        user_logged_in.send(User, user=self.user1)
        assert not self.user1.has_badge(PIONEER_BADGE)

        time.sleep(1)

        # after settings.PIONEER_BADGE_LIMIT, new logins does award the badge
        user_logged_in.send(User, user=self.user1)
        assert self.user1.has_badge(PIONEER_BADGE)
Esempio n. 40
0
def login(request, user):
    session_auth_hash = ''
    if user is None:
        user = request.user
    if hasattr(user, 'get_session_auth_hash'):
        session_auth_hash = user.get_session_auth_hash()

    if SESSION_KEY in request.session:
        if _get_user_session_key(request) != user.pk or (
                    session_auth_hash and
                        request.session.get(HASH_SESSION_KEY) != session_auth_hash):
            request.session.flush()
    else:
        request.session.cycle_key()

    request.session[SESSION_KEY] = user.pk
    request.session[BACKEND_SESSION_KEY] = user.backend
    request.session[HASH_SESSION_KEY] = session_auth_hash
    if hasattr(request, 'user'):
        request.user = user
    rotate_token(request)
    user_logged_in.send(sender=user.__class__, request=request, user=user)
Esempio n. 41
0
def login_user(request, user):
    token, _ = settings.TOKEN_MODEL.objects.get_or_create(user=user)
    if settings.CREATE_SESSION_ON_LOGIN:
        login(request, user)
    user_logged_in.send(sender=user.__class__, request=request, user=user)
    return token
Esempio n. 42
0
def login_user(request, user):
    token, _ = authtoken.models.Token.objects.get_or_create(user=user)
    user_logged_in.send(sender=user.__class__, request=request, user=user)
    return token