Пример #1
0
class AddFriend(ViewSet):
	""" Add a new friend """
	
	authentication_classes = [TokenAuthentication]
	permission_classes = [IsAuthenticated & partial(APIAccessPermission, API().get_api_name('friend', 'add'))]
	renderer_classes = [JSONRenderer]
	serializer_class = AddFriendSerializer

	def __init__(self, **kwargs):
		super().__init__(**kwargs)
		self.commons = Commons()
		self.status = Status()
		self.error_msg = _('Something wrong. Please try again.')
	
	def create(self, request):
		self.commons.active_language(language=request.META.get('HTTP_LANGUAGE', getattr(settings, 'LANGUAGE_CODE')))
		serializer = self.serializer_class(data=request.data)
		
		if serializer.is_valid(raise_exception=True):
			try:
				obj_user = Users.objects.get(id=serializer.data['user_id'])
				obj_friend, created = Friend.objects.update_or_create(
					id=obj_user.id,
					first_name=obj_user.first_name,
					last_name=obj_user.last_name,
					sex=obj_user.sex,
					email=obj_user.email,
					social_network=obj_user.social_network,
					city=obj_user.city
				)
				request.user.friend.add(obj_friend)
				return self.commons.response(
					_status=self.status.HTTP_2000_OK,
					message=_('You have successfully sent a friend request.')
				)
			except Users.DoesNotExist as e:
				self.commons.logs(level=2, message=str(e), name=__name__)
				self.error_msg = _('The user does not exists.')
			except Exception as e:
				self.commons.logs(level=3, message=str(e), name=__name__)
		else:
			self.error_msg = serializer.errors
		return self.commons.response(
			_status=self.status.HTTP_4000_BAD_REQUEST,
			error_msg=self.error_msg
		)
Пример #2
0
class Login(ViewSet):
    """ API Login """

    authentication_classes = []
    permission_classes = [
        partial(APIAccessPermission,
                API().get_api_name('auth', 'login'))
    ]
    renderer_classes = [JSONRenderer]
    serializer_class = LoginSerializer

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.token = ''
        self.status = Status()
        self.commons = Commons()
        self.message = _('You are successfully logged in.')
        self.error_msg = _('Something wrong. Please try again.')

    def create(self, request):
        self.commons.active_language(language=request.META.get(
            'HTTP_LANGUAGE', getattr(settings, 'LANGUAGE_CODE')))
        serializer = self.serializer_class(data=request.data)

        if serializer.is_valid():
            obj_user = authenticate(username=serializer.data['username'],
                                    password=serializer.data['password'])

            if obj_user is not None:
                data = {'token': self.commons.init_token(obj_user)}
                login(request, obj_user)
                self.commons.logs(level=1,
                                  message=str(obj_user) +
                                  ' has successfully logged in.',
                                  name=__name__)
                return self.commons.response(_status=self.status.HTTP_2000_OK,
                                             data=data,
                                             message=self.message)
            self.error_msg = _('User does not exists.')
        else:
            self.error_msg = serializer.errors

        self.commons.logs(level=2, message=self.error_msg, name=__name__)
        return self.commons.response(_status=self.status.HTTP_4000_BAD_REQUEST,
                                     error_msg=self.error_msg)
Пример #3
0
class Logout(ViewSet):
    """ Logout to system """

    authentication_classes = [TokenAuthentication]
    permission_classes = [
        IsAuthenticated & partial(APIAccessPermission,
                                  API().get_api_name('auth', 'logout'))
    ]
    renderer_classes = [JSONRenderer]

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.status = Status()
        self.commons = Commons()
        self.message = _('Logout successful.')
        self.error_msg = _('You must be login to system.')

    def create(self, request):
        self.commons.active_language(language=request.META.get(
            'HTTP_LANGUAGE', getattr(settings, 'LANGUAGE_CODE')))
        try:
            self.request.user.auth_token.delete()
            logout(request)
            self.commons.logs(level=1, message=self.message, name=__name__)
            return self.commons.response(_status=self.status.HTTP_2000_OK,
                                         message=self.message)
        except Exception as e:
            self.error_msg = str(e)
            self.commons.logs(level=3, message=self.error_msg, name=__name__)

        self.commons.logs(level=2, message=self.error_msg, name=__name__)
        return self.commons.response(_status=self.status.HTTP_4000_BAD_REQUEST,
                                     error_msg=self.error_msg)
Пример #4
0
class Register(ViewSet):
	""" Register your account. """
	
	authentication_classes = []
	permission_classes = [partial(APIAccessPermission, API().get_api_name('auth', 'register'))]
	renderer_classes = [JSONRenderer]
	serializer_class = RegisterSerializer
	
	def __init__(self, **kwargs):
		super().__init__(**kwargs)
		self.status = Status()
		self.commons = Commons()
		self.message = _('Congratulations. You have successfully registered.')
		self.error_msg = _('Something wrong. Please try again.')
		
	@transaction.atomic()
	def create(self, request):
		self.commons.active_language(language=request.META.get('HTTP_LANGUAGE', getattr(settings, 'LANGUAGE_CODE')))
		serializer = self.serializer_class(data=self.request.data)
		if serializer.is_valid():
			if not serializer.compare_pwd(data=request.data):
				obj_user, created = Users.objects.get_or_create(username=serializer.data['username'], defaults={
					'password': make_password(serializer.data['password'])
				})
				
				if created:
					data = {
						'token': self.commons.init_token(obj_user)
					}
					self.commons.logs(level=1, message=str(obj_user) + ' has successfully registered.', name=__name__)
					return self.commons.response(_status=self.status.HTTP_2000_OK, data=data, message=self.message)
				self.error_msg = _('User always exists.')
			else:
				self.error_msg = _('Password does not match.')
		else:
			self.error_msg = serializer.errors
		
		self.commons.logs(level=2, message=self.error_msg, name=__name__)
		return self.commons.response(_status=self.status.HTTP_4000_BAD_REQUEST, error_msg=self.error_msg)
class RemoveFriend(ViewSet):
    """ Remove a friend """

    authentication_classes = [TokenAuthentication]
    permission_classes = [
        IsAuthenticated & partial(APIAccessPermission,
                                  API().get_api_name('friend', 'remove'))
    ]
    renderer_classes = [JSONRenderer]
    serializer_class = RemoveFriendSerializer

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.commons = Commons()
        self.status = Status()
        self.error_msg = _('Something wrong. Please try again.')

    def create(self, request):
        serializer = self.serializer_class(data=request.data)

        if serializer.is_valid():
            try:
                with transaction.atomic():
                    obj_friend = Friend.objects.get(
                        id=serializer.data['friend_id'])
                    request.user.friend.remove(obj_friend)
                return self.commons.response(
                    _status=self.status.HTTP_2000_OK,
                    message=_('Successfully deleted a friend.'))
            except Exception as e:
                self.commons.logs(level=2, message=str(e), name=__name__)
                self.error_msg = _('Friend does not exists.')
        else:
            self.error_msg = serializer.errors
        return self.commons.response(_status=self.status.HTTP_4000_BAD_REQUEST,
                                     error_msg=self.error_msg)