Exemplo n.º 1
0
Arquivo: api.py Projeto: alejo8591/etv
class UserProfileResource(ModelResource):
    profiles = fields.OneToOneField(UserResource, 'identification')
    
    class Meta:
        queryset = UserProfile.objects.all()
        resource_name = 'profile'
        serializer = Serializer(formats=['json'])
Exemplo n.º 2
0
class EmployeeResource(ModelResource):
    department = fields.ForeignKey(DepartmentResource, 'department')
    user = fields.OneToOneField(UserResource, 'user')
    class Meta:
        queryset = Employee.objects.all()
        resource_name = 'employees'
        always_return_data = True
        authorization = Authorization()
Exemplo n.º 3
0
class ExpositorResource(ModelResource):
    sala = fields.OneToOneField(SalaResource, 'sala', related_name='evento', full=True)

    class Meta:
        resource_name = 'expositores'
        queryset = Expositor.objects.all()
        authorization = Authorization()
        allowed_methods = ['get']
Exemplo n.º 4
0
class UsuarioResource(ModelResource):
	perfil = fields.OneToOneField(PerfilResource, 'perfil', related_name='profile', full=True)
	class Meta:
		queryset = User.objects.all()
		resource_name = 'usuario'
		fields = ['username','email','perfil']
		authorization = Authorization()
		authentication = ApiKeyAuthentication()
Exemplo n.º 5
0
class ClientResource(ModelResource):
    user = fields.OneToOneField(UserResource, 'user', full=True)

    class Meta:
        queryset = Client.object.all()
        resource_name = 'client'
        # excludes  =['password']
        # allow_method = ['post']
        authorization = DjangoAuthorization()
Exemplo n.º 6
0
class SalaResource(ModelResource):
    condicion = fields.OneToOneField(CondicionResource, 'condicion', related_name='sala', null=True, full=True)

    class Meta:
        resource_name = 'salas'
        queryset = Sala.objects.all()
        authorization = Authorization()
        allowed_methods = ['get', 'post', 'put', 'delete']
        always_return_data = True
Exemplo n.º 7
0
class StudentResource(ModelResource):
    person = fields.OneToOneField(PersonResource, 'person', full=True)
    #person_id = fields.IntegerField(attribute='person_id', null=True)
    section = fields.ForeignKey(SectionResource, 'section')

    class Meta:
        queryset = student.objects.all().select_related("person")
        resource_name = 'pupil'
        authorization = Authorization()
Exemplo n.º 8
0
class PoliticalViewResource(ModelResource):
    user = fields.OneToOneField(UserResource, 'user')
    political_index = fields.ForeignKey(PoliticalIndexResource,
                                        'political_index')

    class Meta:
        queryset = PoliticalView.objects.all()
        fields = ['user', 'political_index', 'id']
        always_return_data = True
        resource_name = 'political_view'
        authentication = JSONWebTokenAuthentication()
        authorization = Authorization()

    def get_object_list(self, request):
        user = request.GET.get('user_id')
        if not isinstance(user, int):
            try:
                user = int(user)
            except (TypeError, ValueError):
                user = request.user.id
        return super(PoliticalViewResource, self).get_object_list(request). \
            filter(user_id=user)

    def obj_create(self, bundle, **kwargs):
        political_index = bundle.data.get('political_index').lower()
        try:
            subject, created = PoliticalIndex.objects.get_or_create(
                name=political_index)
            bundle.data[
                'political_index'] = '/api/v1/political_index/{0}/'.format(
                    subject.id)
            return super(PoliticalViewResource,
                         self).obj_create(bundle, political_index=subject)
        except IndexError as err:
            logger.error(err)
        return super(PoliticalViewResource, self).obj_create(bundle, **kwargs)

    def obj_update(self, bundle, skip_errors=False, **kwargs):
        political_index = bundle.data['political_index'].lower()
        try:
            subject, created = PoliticalIndex.objects.get_or_create(
                name=political_index)
            bundle.data[
                'political_index'] = '/api/v1/political_index/{0}/'.format(
                    subject.id)
            return super(PoliticalViewResource, self).obj_update(
                bundle,
                political_index='/api/v1/political_index/{0}/'.format(
                    subject.id))
        except IndexError as err:
            logger.error(err)
        return self.save(bundle, skip_errors=skip_errors)

    def dehydrate(self, bundle):
        bundle.data["political_view"] = bundle.obj
        return bundle
Exemplo n.º 9
0
class EventoResource(ModelResource):
    sala = fields.OneToOneField(SalaResource, 'sala', related_name='evento', full=True)
    conferenciante = fields.ToManyField('projectx.api.resources.ConferencianteResource', 'conferenciante', related_name='evento', full=True)
    asistentes = fields.ToManyField('projectx.api.resources.AsistenteResource', 'asistentes', related_name='evento')

    class Meta:
        resource_name = 'eventos'
        queryset = Evento.objects.all()
        authorization = Authorization()
        allowed_methods = ['get']
Exemplo n.º 10
0
class ListItemsResource(ModelResource):
    location = fields.OneToOneField(AisleItemsResource,
                                    'aisle',
                                    full=True,
                                    null=True)

    class Meta:
        queryset = GroceryItem.objects.all()
        excludes = ['id']
        include_resource_uri = False
Exemplo n.º 11
0
class RecipeResource(ModelResource):
    ingredients = fields.ToManyField(IngredientResource,
                                     'ingredients',
                                     full=True)
    author = fields.OneToOneField(AuthorResource, 'author', full=True)
    tags = fields.OneToManyField(TagResource, 'tags', full=True)

    class Meta:
        queryset = Recipe.objects.filter(shared=Recipe.SHARE_SHARED)
        excludes = ['id']
        include_resource_url = False
Exemplo n.º 12
0
class MemberResource(ModelResource):

    current_party = fields.ForeignKey(PartyResource,
                                      'current_party',
                                      null=True,
                                      blank=True)
    parties = fields.ManyToManyField(PartyResource, 'parties')
    blog = fields.OneToOneField(Blog, 'blog', blank=True, null=True)

    class Meta:
        queryset = Member.objects.all()
        resource_name = 'member'
Exemplo n.º 13
0
class UserResource(ModelResource):
    artist_id = fields.OneToOneField('artists.api.ArtistResource',
                                     'artist',
                                     null=True)
    follows = fields.ToManyField('userdata.api.FollowResource',
                                 'subscription_set',
                                 full=True)

    class Meta:
        resource_name = 'users'
        queryset = User.objects.all()
        excludes = ('date_joined', 'first_name', 'is_active', 'last_login',
                    'last_name', 'password')
Exemplo n.º 14
0
class OrganisationResource(ModelResource):
    type = fields.OneToOneField(OrganisationTypeResource, 'type', full=True, null=True)
    org_name = fields.CharField('name', null=True)

    class Meta:
        queryset = Organisation.objects.all()
        resource_name = 'organisations'
        serializer = Serializer(formats=['xml', 'json'])
        filtering = {
            # example to allow field specific filtering.
            'name': ALL,
            'abbreviation': ALL
        }
Exemplo n.º 15
0
class ResumeResource(ModelResource):
    user = fields.OneToOneField(UserResource, 'user', full=True)
    comments = fields.ManyToManyField('api.api.CommentResource',
                                      'comment_set',
                                      full=True)

    class Meta:
        queryset = Resume.objects.filter(original=False).order_by('-timestamp')
        resource_name = 'resumes'
        # Add it here.
        # authentication = BasicAuthentication()
        authorization = DjangoAuthorization()
        limit = 20
        always_return_data = True
        allowed_methods = ['get', 'post']
        filtering = {
            "featured": ("exact"),
            "user": ("exact"),
            "showcase": ("exact")
        }

    def dehydrate(self, bundle):
        """
        Return a list of resumes formatted according to what the developer expects
        """

        return bundle

    def obj_create(self, bundle, **kwargs):
        """
        Creates a new resume
        """
        try:
            user = User.objects.get(id=bundle.data["user"])
            if bundle.data['featured']:
                user.resume_points -= 20
                user.save()
            # need to check if url, anonymous, original supplied
            new_resume = Resume(user=user,
                                url=bundle.data['url'],
                                anonymous=bundle.data['anonymous'],
                                original=bundle.data['original'],
                                featured=bundle.data['featured'],
                                showcase=bundle.data['showcase'])
            new_resume.save()
            bundle.obj = new_resume
        except Exception, e:
            print e
        return bundle
Exemplo n.º 16
0
class UserResource(ModelResource):
    userprofile = fields.OneToOneField('wordgame.api.UserProfileResource',
                                       attribute='userprofile',
                                       full=True,
                                       null=True,
                                       blank=True)

    class Meta:
        queryset = User.objects.all()
        resource_name = 'players'
#        fields = ['username','resource_uri']
        authentication = Authentication()
        authorization = Authorization()
        always_return_data = True
        filtering = {
            'username': ALL_WITH_RELATIONS,
        }
        
    def obj_create(self, bundle, request=None, **kwargs):
        
        if bundle.data['username'] == '':
            m = hashlib.sha1()
            m.update(str(timezone.now()))
            m.update(bundle.data['password'])
            m.update(bundle.data['email'])
            m.update(choice(words))
            bundle.data['username'] = '******'.join(['ftg_user',m.hexdigest()])
      
        #import pdb; pdb.set_trace()

        try:
            #user_check = User.objects.get(username__exact = bundle.data['username'])
            obj = self.obj_get(request, username=bundle.data['username'])
            #The user exists, now check the password
            user = authenticate(username=bundle.data['username'], password=bundle.data['password'])
            if user is None:
                raise BadRequest('The user exists but the password does not match')
            else:
                bundle = self.build_bundle(obj=obj, request=request)
        except ObjectDoesNotExist:
            #The user does not exist, try to create it
            try:
                bundle = super(UserResource, self).obj_create(bundle, request, **kwargs)
                bundle.obj.set_password(bundle.data.get('password'))
                bundle.obj.save()
            #Theoretically this exception should never be thrown because we already checked that it doesnt exist
            except IntegrityError:
                raise BadRequest('That username already exists')
        return bundle
Exemplo n.º 17
0
class GroceryResource(ModelResource):
    author = fields.OneToOneField(AuthorResource, 'author', full=True)
    items = fields.ToManyField(ListItemsResource, 'items', full=True)

    class Meta:
        queryset = GroceryList.objects.all()
        resource_name = 'lists'
        list_allowed_methods = [
            'get',
        ]
        authentication = BasicAuthentication()
        authorization = DjangoAuthorization()

    def apply_authorization_limits(self, request, object_list):
        return object_list.filter(author=request.user)
Exemplo n.º 18
0
class UserProfileResource(ModelResource):
    user = fields.OneToOneField(UserResource, 'user')

    class Meta:
        queryset = UserProfile.objects.all()
        authentication = Authentication()
        authorization = DjangoAuthorization()

    def obj_create(self, bundle, request=None, **kwargs):
        return super(UserProfileResource, self).obj_create(bundle,
                                                           request,
                                                           user=request.user)

    def apply_authorization_limits(self, request, object_list):
        return object_list.filter(user=request.user)
Exemplo n.º 19
0
class RealEstateResource(ModelResource):
  address = fields.OneToOneField(AddressResources, 'address', related_name='address', full=True)

  class Meta:
    queryset = RealEstate.objects.all()
    authorization = Authorization()
    resource_name = 'real_estate'
    excludes = ("approved")
    always_return_data = True

  def hydrate(self, bundle):
    latitude = bundle.data['latitude']
    longitude = bundle.data['longitude']
    bundle.data['approved'] = CoordinatesValidation().valid(latitude, longitude)
    bundle.data.pop("approved")
    return bundle
Exemplo n.º 20
0
class ComicsResource(ModelResource):
    general = fields.OneToOneField(DataResource,
                                   'general',
                                   null=True,
                                   full=True)
    pages = fields.ManyToManyField(ImageResource,
                                   'pages',
                                   null=True,
                                   full=True)

    class Meta:
        queryset = Comics.objects.all()
        resource_name = 'comics'
        filtering = {
            'id': ALL_WITH_RELATIONS,
        }
Exemplo n.º 21
0
class CommentResource(ModelResource):
    user = fields.OneToOneField(UserResource, 'user', full=True)

    class Meta:
        queryset = Comment.objects.all()
        resource_name = 'comments'
        # Add it here.
        # authentication = BasicAuthentication()
        authorization = DjangoAuthorization()
        limit = 0
        always_return_data = True
        allowed_methods = ['post']

    def dehydrate(self, bundle):
        """
        Return a list of comments for a given resume
        """
        return bundle

    def obj_create(self, bundle, **kwargs):
        """
        Creates a new comment
        """
        user = User.objects.get(id=bundle.data["user"])
        user.resume_points += 2
        user.save()
        resume = Resume.objects.get(id=bundle.data['resume'])
        new_comment = Comment(user=user,
                              resume=resume,
                              x=bundle.data['x'],
                              y=bundle.data['y'],
                              comment=bundle.data['comment'])
        new_comment.save()
        bundle.obj = new_comment
        return bundle

    def alter_list_data_to_serialize(self, request, data):
        # rename "objects" to "comments"
        data['response'] = {"comments": data["objects"]}
        del (data["objects"])
        return data

    def determine_format(self, request):
        return 'application/json'
Exemplo n.º 22
0
class OrganisationResource(ModelResource):
    """
    Resource for IATI Organisations
    """
    statistics = fields.OneToOneField(OrganisationStatisticsResource,
                                      'organisationstatistics',
                                      full=True,
                                      null=True)

    class Meta:
        queryset = Organisation.objects.all()
        resource_name = 'organisations'
        serializer = Serializer(formats=['xml', 'json'])
        excludes = ['date_created']
        filtering = {
            # example to allow field specific filtering.
            'org_name': ALL,
            'ref': ALL,
            'statistics': ALL_WITH_RELATIONS,
        }
Exemplo n.º 23
0
class CountryResource(ModelResource):
    """
    Resource for Countries
    """
    statistics = fields.OneToOneField(CountryStatisticResource,
                                      'countrystatistics',
                                      full=True,
                                      null=True)

    class Meta:
        queryset = Country.objects.all()
        resource_name = 'countries'
        serializer = Serializer(formats=['xml', 'json'])
        filtering = {
            'statistics': ALL_WITH_RELATIONS,
        }

    def dehydrate(self, bundle):
        obj = self.obj_get(iso=bundle.data['iso'])
        bundle.data['name'] = obj.get_iso_display()
        return super(CountryResource, self).dehydrate(bundle)
Exemplo n.º 24
0
class JobResource(ModelResource):
    company = fields.OneToOneField(CompanyResource, 'company', full=True)

    class Meta:
        queryset = Job.objects.all()
        resource_name = 'jobs'
        authorization = DjangoAuthorization()
        limit = 100
        always_return_data = True
        allowed_methods = ['get', 'post', 'put']
        filtering = {}

    def obj_create(self, bundle, **kwargs):
        """
        Create or delete a new job
        """
        print 1
        try:
            if 'deactivate' in bundle.data.keys(
            ) and bundle.data['deactivate']:
                print 2
                existing_job = Job.objects.get(id=bundle.data['job_id'])
                existing_job.deactivate = True
                existing_job.save()
                bundle.obj = existing_job
            else:
                print 3
                company = Company.objects.get(id=bundle.data['company_id'])
                new_job = Job(name=bundle.data['name'],
                              job_type=bundle.data['job_type'],
                              location=bundle.data['location'],
                              description=bundle.data['description'],
                              company=company)
                new_job.save()
                bundle.obj = new_job
        except Exception, e:
            print e
            raise e
        return bundle
Exemplo n.º 25
0
class UserResource(ModelResource):
    orders = fields.ToManyField('api.api.OrderResource',
                                'orders',
                                null=True,
                                blank=True,
                                readonly=True)
    address = fields.OneToOneField('api.api.AddressResource',
                                   'address',
                                   full=True,
                                   null=True)

    class Meta:
        queryset = User.objects.all()
        resource_name = 'user'
        authorization = Authorization()
        always_return_data = True

    def hydrate(self, bundle):
        data_keys = bundle.data.keys()
        if 'id' not in data_keys:
            exists = User.objects.filter(
                username=bundle.data['username']).exists()
            if not exists:
                if 'password' not in bundle.data.keys():
                    bundle.data['password'] = '******'
            else:
                user = User.objects.get(username=bundle.data['username'])
                bundle.data['id'] = user.id
        else:
            user = User.objects.get(id=bundle.data['id'])
        # bundle.obj=user
        # if 'address' in bundle.data.keys():
        #     bundle.data['address']['user'] = bundle.obj
        if 'address' in data_keys:
            bundle.data['address']['user'] = bundle.obj
        return bundle

    def dehydrate(self, bundle):
        return bundle
Exemplo n.º 26
0
class PresenterResource(ModelResource):
    platform = fields.ForeignKey(PlatformResource, 'platform', full=True)
    tags = fields.ToManyField(TagResource, 'tag', full=True)
    detail = fields.OneToOneField(PresenterDetailResource,
                                  'presenterdetail',
                                  full=True)

    def apply_sorting(self, obj_list, options=None):
        if options and "sort" in options:
            if options['sort'] == 'showing':
                return obj_list.order_by('-presenterdetail__showing')
            else:
                return obj_list.order_by(options['sort'])
        return super(PresenterResource, self).apply_sorting(obj_list, options)

    # showing = fields.BooleanField(readonly=True)
    # def dehydrate_showing(self, bundle):
    #     print type(bundle.obj), type(bundle.data)
    #     print dir(type(bundle.obj))
    #     return bundle.obj.presenterdetail.showing

    # def build_filters(self, filters=None):
    #     print filters
    #     if filters is None:
    #         filters = {}

    #     orm_filters = super(PresenterResource, self).build_filters(filters)
    #     print type(orm_filters), orm_filters
    #     if 'q' in filters:
    #         pass
    #     return orm_filters
    class Meta:
        queryset = Presenter.objects.all()
        allowed_methods = ['get']

        filtering = {
            "nickname": ALL,
        }
Exemplo n.º 27
0
class UserProfileResource(ModelResource):
    user = fields.OneToOneField(UserResource, 'user')

    class Meta:
        queryset = UserProfile.objects.all()
        allowed_methods = ['get', 'put', 'patch']
        resource_name = 'user-profile'
        authentication = BasicAuthentication()
        authorization = DjangoAuthorization()
        filtering = {
            'user': ALL_WITH_RELATIONS,
            'email_verified': ALL,
            'user_name': ALL,
            'full_name': ALL,
            'user_bio': ALL,
            'user_home_city': ALL,
            'zip_code': ALL,
            'longitude': ALL,
            'last_updated': ALL,
            'website': ALL,
            'interests': ALL_WITH_RELATIONS,
            'user_photo': ALL_WITH_RELATIONS,
        }
Exemplo n.º 28
0
class InstitutionResource(StarsApiResource):
    """
        Resource for accessing any Institution.
    """
    submission_sets = fields.OneToManyField(
       SUBMISSIONS_RESOURCE_PATH + "NestedSubmissionSetResource",
       'submissionset_set', full=True)
    current_report = fields.OneToOneField(
        SUBMISSIONS_RESOURCE_PATH + "NestedSubmissionSetResource",
        'rated_submission', full=True, null=True)
    postal_code = fields.CharField(readonly=True)
    city = fields.CharField(readonly=True)
    state = fields.CharField(readonly=True)

    class Meta(StarsApiResource.Meta):
        queryset = models.Institution.objects.get_rated().order_by('name')
        resource_name = 'institutions'
        fields = ['name', 'is_member', 'country']
        allowed_methods = ['get']

    def dehydrate_city(self, bundle):
        if bundle.obj.profile:
            return bundle.obj.profile.city

    def dehydrate_state(self, bundle):
        if bundle.obj.profile:
            return bundle.obj.profile.state

    def dehydrate_postal_code(self, bundle):
        if bundle.obj.profile:
            return bundle.obj.profile.postal_code

    def dehydrate_submission_sets(self, bundle):
        """Filter unrated submission sets."""
        rated_submissions = [ss for ss in bundle.data['submission_sets']
                             if ss.obj.rating]
        return rated_submissions
Exemplo n.º 29
0
class UserResource(ModelResource):
    member = fields.OneToOneField(
        MemberResource, 'member',
        full=True)  #Member is linked to only one user according to the model

    class Meta:
        authentication = ApiKeyAuthentication(
        )  # This resource requires to be logged in
        queryset = User.objects.all()  # Get all the user
        include_resource_uri = False  # Remove the uri in the json
        fields = ["email",
                  "username"]  # Only keep the email and username fields
        resource_name = 'user'
        filtering = {
            'username': ALL_WITH_RELATIONS  # The only result is your
        }

    # Redefine url for login and logout
    def prepend_urls(self):
        return [
            url(r"^(?P<resource_name>%s)/login%s$" %
                (self._meta.resource_name, trailing_slash()),
                self.wrap_view('login'),
                name="api_login"),
            url(r'^(?P<resource_name>%s)/logout%s$' %
                (self._meta.resource_name, trailing_slash()),
                self.wrap_view('logout'),
                name='api_logout'),
            url(r'^(?P<resource_name>%s)/register%s$' %
                (self._meta.resource_name, trailing_slash()),
                self.wrap_view('register'),
                name='api_register'),
            url(r'^(?P<resource_name>%s)/save_settings%s$' %
                (self._meta.resource_name, trailing_slash()),
                self.wrap_view('save_settings'),
                name='api_save_settings'),
        ]

    # register method for mobile registration
    def register(self, request, **kwargs):
        # Allows POST request
        self.method_check(request, allowed=['post'])

        # Deserialize the JSon response
        data = self.deserialize(request,
                                request.raw_post_data,
                                format=request.META.get(
                                    'CONTENT_TYPE', 'application/json'))

        # Get the needed datas
        username = data.get('username', '')
        email = data.get('email', '')
        password1 = data.get('password1', '')
        password2 = data.get('password2', '')

        if len(username
               ) == 0:  # If password1 and password2 don't match, return error
            return self.create_response(request, {
                'success': False,
                'reason': 'username is empty',
            })
        elif len(User.objects.filter(username=username)
                 ) != 0:  # the username is already taken, return error
            return self.create_response(request, {
                'success': False,
                'reason': 'user already exist',
            })
        elif len(email) == 0:  # If email is empty, return error
            return self.create_response(request, {
                'success': False,
                'reason': 'email is empty',
            })
        elif not email_re.match(
                email):  # If email data is not a good email, return error
            return self.create_response(request, {
                'success': False,
                'reason': 'email not valid',
            })
        elif len(User.objects.filter(
                email=email)) != 0:  # If email already exist, return error
            return self.create_response(request, {
                'success': False,
                'reason': 'email already in use',
            })
        elif len(password1) == 0:  # If password is empty, return error
            return self.create_response(request, {
                'success': False,
                'reason': "passwords don't exist",
            })
        elif password1 != password2:  # If password1 and password2 don't match, return error
            return self.create_response(request, {
                'success': False,
                'reason': "passwords don't match",
            })
        else:  # If already is ok, let's go for regisrtation
            # create a user and authenticate him (needed for login)
            user = User.objects.create_user(username, email, password1)
            user = authenticate(username=username, password=password1)
            # If user exist and is active, log him
            if user:
                if user.is_active:
                    login(request, user)

            # Create a member object and link the user to it
            member = Member()
            member.user = user
            member.save()

            # Create a dictionnary for json response and delete unuse datas
            member = member.__dict__
            del member["_state"]
            del member["user_id"]
            # Add his api_key
            api_key = ApiKey.objects.get(user=user).key
            member["api_key"] = api_key

            # Return success = True and the member object
            return self.create_response(request, {
                'success': True,
                'member': member
            })

    # login method witch check user authentification
    def login(self, request, **kwargs):
        # Allows POST request
        self.method_check(request, allowed=['post'])

        # Deserialize the JSon response
        data = self.deserialize(request,
                                request.raw_post_data,
                                format=request.META.get(
                                    'CONTENT_TYPE', 'application/json'))

        # Get the needed datas
        username = data.get('username', '')
        password = data.get('password', '')

        # Try to authenticate the user
        user = authenticate(username=username, password=password)
        # If user exist and is active
        if user:
            if user.is_active:
                # Get the associated member
                member = Member.objects.get(user_id=user.id)
                memberDict = member.__dict__
                preferedCategoryIDs = member.preferedCategoryIDs.all()
                memberDict['preferedCategories'] = [
                    cat.name for cat in preferedCategoryIDs
                ]
                del memberDict["_state"]
                del memberDict["user_id"]

                # Log the user
                login(request, user)
                api_key = ApiKey.objects.filter(user=user)
                if len(api_key) == 0:
                    api_key = ApiKey(user=user)
                    api_key.save()
                else:
                    api_key = api_key[0]

                # Add the ApiKey
                memberDict["api_key"] = api_key.key

                # Return success=True and the member object
                return self.create_response(request, {
                    'success': True,
                    'member': memberDict,
                })
            else:
                # If user not active, return success = False and disabled
                return self.create_response(request, {
                    'success': False,
                    'reason': 'disabled',
                }, HttpForbidden)
        else:
            # If user does not exist, return success=False and incorrect
            return self.create_response(request, {
                'success': False,
                'reason': 'incorrect',
            }, HttpUnauthorized)

    # logout user
    def logout(self, request, **kwargs):
        # Allows GET request
        self.method_check(request, allowed=['get'])
        api_key = ApiKey.objects.filter(key=request.GET['api_key'])
        if len(api_key) == 1:
            user = api_key[0].user
            # If user exist and is log, Logout
            if user and user.is_authenticated():
                api_key = ApiKey.objects.filter(user=user)[0]
                api_key.delete()
                logout(request)
                return self.create_response(request, {'success': True})
        else:
            # Else, return Unauthorized
            return self.create_response(request, {'success': False},
                                        HttpUnauthorized)

    def save_settings(self, request, **kwargs):
        # Allows POST request
        self.method_check(request, allowed=['post'])

        # Deserialize the JSon response
        data = self.deserialize(request,
                                request.raw_post_data,
                                format=request.META.get(
                                    'CONTENT_TYPE', 'application/json'))

        # Get the needed datas
        userId = User.objects.filter(id=data.get('userId', ''))
        twitter = data.get('twitter', '')
        facebook = data.get('facebook', '')
        gplus = data.get('gplus', '')
        autoshare = data.get('autoshare', '')
        geoloc = data.get('geoloc', '')
        pays = data.get('pays', '')
        ville = data.get('ville', '')
        maxArticle = data.get('maxArticle', '')
        preferedCategoryIDs = data.get('preferedCategoryIDs', '')

        # If user exist and is active
        if userId:
            member_qs = Member.objects.filter(user=userId[0])
            if member_qs:
                member = member_qs[0]
                member.twitter = twitter
                member.facebook = facebook
                member.gplus = gplus
                member.autoshare = autoshare
                member.geoloc = geoloc
                member.pays = pays
                member.ville = ville
                member.maxArticle = maxArticle
                member.preferedCategoryIDs = preferedCategoryIDs
                member.save()

                if member:
                    return self.create_response(request, {
                        'success': True,
                        'member': member,
                    })
                else:
                    # If user not active, return success = False and disabled
                    return self.create_response(
                        request, {
                            'success': False,
                            'reason': 'Error while saving member',
                        }, BadRequest)
            else:
                # If user not active, return success = False and disabled
                return self.create_response(
                    request, {
                        'success': False,
                        'reason': "You can't edit you preferences",
                    }, BadRequest)
        else:
            # If user does not exist, return success=False and incorrect
            return self.create_response(request, {
                'success': False,
                'reason': 'You can\'t edit this user',
            }, HttpForbidden)
Exemplo n.º 30
0
class SubmissionSetResource(StarsApiResource):
    """
        Resource for accessing any (published) SubmissionSet.
    """
    creditset = fields.OneToOneField(CREDITS_RESOURCE_PATH +
                                     'NestedCreditSetResource',
                                     'creditset',
                                     full=True)
    category_submissions = fields.ToManyField(
        SUBMISSIONS_RESOURCE_PATH + 'NestedCategorySubmissionResource',
        'categorysubmission_set',
        full=True)
    institution = fields.OneToOneField(INSTITUTIONS_RESOURCE_PATH +
                                       'NestedInstitutionResource',
                                       'institution',
                                       full=True)
    rating = fields.CharField(readonly=True)

    class Meta(StarsApiResource.Meta):
        queryset = SubmissionSet.objects.get_rated().filter(is_locked=False)
        resource_name = 'submissions'
        allowed_methods = ['get']
        # exclude submission_boundary becauses it raises
        # "'ascii' codec can't decode byte ... in position ...: ordinal not
        # in range(128)"
        excludes = [
            'is_locked', 'is_visible', 'date_reviewed', 'date_registered',
            'status', 'reporter_status', 'submission_boundary'
        ]

    def dehydrate(self, bundle):
        bundle.data['rating'] = str(bundle.obj.rating)

        if bundle.obj.reporter_status:
            bundle.data['score'] = None

        return bundle

    def prepend_urls(self):
        # The detail URL for each resource must be listed before the list URL.
        return [
            url(
                r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/category"
                "/(?P<catpk>\w[\w/-]*)%s$" %
                (self._meta.resource_name, trailing_slash()),
                self.wrap_view('get_category_detail')),
            url(
                r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/category%s$" %
                (self._meta.resource_name, trailing_slash()),
                self.wrap_view('get_category_list')),
            url(
                r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/subcategory"
                "/(?P<subcatpk>\w[\w/-]*)%s$" %
                (self._meta.resource_name, trailing_slash()),
                self.wrap_view('get_subcategory_detail')),
            url(
                r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/subcategory%s$" %
                (self._meta.resource_name, trailing_slash()),
                self.wrap_view('get_subcategory_list')),
            url(
                r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/credit"
                "/(?P<credpk>\w[\w/-]*)%s$" %
                (self._meta.resource_name, trailing_slash()),
                self.wrap_view('get_credit_detail')),
            url(
                r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/credit%s$" %
                (self._meta.resource_name, trailing_slash()),
                self.wrap_view('get_credit_list')),
            url(
                r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/field"
                "/(?P<fieldpk>\w[\w/-]*)%s$" %
                (self._meta.resource_name, trailing_slash()),
                self.wrap_view('get_field_detail')),
        ]

    def get_category_list(self, request, **kwargs):
        """Get a list of categories for the SubmissionSet with
        id = kwargs['pk']."""
        # Need to check CategorySubmissionResource.Meta.allowed_methods
        # explicitly because the URL fiddling done above
        # bypasses the usual check:
        if (request.method.lower()
                not in CategorySubmissionResource.Meta.allowed_methods):
            return HttpMethodNotAllowed()
        self.is_authenticated(request)
        basic_bundle = self.build_bundle(request=request)
        try:
            obj = self.cached_obj_get(bundle=basic_bundle,
                                      **self.remove_api_resource_names(kwargs))
        except ObjectDoesNotExist:
            return HttpGone()
        except MultipleObjectsReturned:
            return HttpMultipleChoices(
                "More than one resource is found at this URI.")

        category_submission_resource = CategorySubmissionResource()
        return category_submission_resource.get_list(request,
                                                     submissionset=obj.pk)

    def get_category_detail(self, request, **kwargs):
        """Get the CategorySubmission that matches the Category
        where id = kwargs['catpk']."""
        # Need to check CategorySubmissionResource.Meta.allowed_methods
        # explicitly because the URL fiddling done above
        # bypasses the usual check:
        if (request.method.lower()
                not in CategorySubmissionResource.Meta.allowed_methods):
            return HttpMethodNotAllowed()
        self.is_authenticated(request)
        category_id = kwargs.pop('catpk')
        basic_bundle = self.build_bundle(request=request)
        try:
            obj = self.cached_obj_get(bundle=basic_bundle,
                                      **self.remove_api_resource_names(kwargs))
        except ObjectDoesNotExist:
            return HttpGone()
        except MultipleObjectsReturned:
            return HttpMultipleChoices(
                "More than one resource is found at this URI.")
        return CategorySubmissionResource().get_detail(request,
                                                       submissionset_id=obj.pk,
                                                       category_id=category_id)

    def get_subcategory_list(self, request, **kwargs):
        """Get the list of SubcategorySubmissions for the SubmissionSet
        where id = kwargs['pk']."""
        # Need to check SubcategorySubmissionResource.Meta.allowed_methods
        # explicitly because the URL fiddling done above
        # bypasses the usual check:
        if (request.method.lower()
                not in SubcategorySubmissionResource.Meta.allowed_methods):
            return HttpMethodNotAllowed()
        self.is_authenticated(request)
        basic_bundle = self.build_bundle(request=request)
        try:
            obj = self.cached_obj_get(bundle=basic_bundle,
                                      **self.remove_api_resource_names(kwargs))
        except ObjectDoesNotExist:
            return HttpGone()
        except MultipleObjectsReturned:
            return HttpMultipleChoices(
                "More than one resource is found at this URI.")

        return SubcategorySubmissionResource().get_list(
            request, submissionset_id=obj.pk)

    def get_subcategory_detail(self, request, **kwargs):
        """Get the SubcategorySubmission for the Subcategory where
        id = kwargs['subcatpk']."""
        # Need to check SubcategorySubmissionResource.Meta.allowed_methods
        # explicitly because the URL fiddling done above
        # bypasses the usual check:
        if (request.method.lower()
                not in SubcategorySubmissionResource.Meta.allowed_methods):
            return HttpMethodNotAllowed()
        self.is_authenticated(request)
        subcategory_id = kwargs.pop('subcatpk')
        # Make sure the submission set is valid:
        basic_bundle = self.build_bundle(request=request)
        try:
            obj = self.cached_obj_get(bundle=basic_bundle,
                                      **self.remove_api_resource_names(kwargs))
        except ObjectDoesNotExist:
            return HttpGone()
        except MultipleObjectsReturned:
            return HttpMultipleChoices(
                "More than one resource is found at this URI.")

        kwargs['subcatpk'] = subcategory_id
        kwargs['submissionset'] = obj
        return SubcategorySubmissionResource().get_detail(request, **kwargs)

    def get_credit_list(self, request, **kwargs):
        """Get a list of credits for the SubmssionSet where
        id = kwargs['pk'].
        """
        # Need to check CreditSubmissionResource.Meta.allowed_methods
        # explicitly because the URL fiddling done above
        # bypasses the usual check:
        if (request.method.lower()
                not in CreditSubmissionResource.Meta.allowed_methods):
            return HttpMethodNotAllowed()
        self.is_authenticated(request)
        basic_bundle = self.build_bundle(request=request)
        try:
            obj = self.cached_obj_get(bundle=basic_bundle,
                                      **self.remove_api_resource_names(kwargs))
        except ObjectDoesNotExist:
            return HttpGone()
        except MultipleObjectsReturned:
            return HttpMultipleChoices(
                "More than one resource is found at this URI.")

        return CreditSubmissionResource().get_list(request,
                                                   submissionset_id=obj.pk)

    def get_credit_detail(self, request, **kwargs):
        """Get the CreditSubmissionResource that matches the Credit
        where id = kwargs['credpk'] and the SubmissionSet where
        id = kwargs['pk'].
        """
        # Need to check CreditSubmissionResource.Meta.allowed_methods
        # explicitly because the URL fiddling done above
        # bypasses the usual check:
        if (request.method.lower()
                not in CreditSubmissionResource.Meta.allowed_methods):
            return HttpMethodNotAllowed()
        self.is_authenticated(request)
        credit_id = kwargs.pop('credpk')
        basic_bundle = self.build_bundle(request=request)
        try:
            submissionset = self.cached_obj_get(
                bundle=basic_bundle, **self.remove_api_resource_names(kwargs))
        except ObjectDoesNotExist:
            return HttpGone()
        except MultipleObjectsReturned:
            return HttpMultipleChoices(
                "More than one resource is found at this URI.")

        kwargs.pop('pk')
        kwargs['credpk'] = credit_id
        kwargs['submissionset'] = submissionset
        credit_submission_resource = CreditSubmissionResource()
        detail = credit_submission_resource.get_detail(request, **kwargs)
        return detail

    def get_field_detail(self, request, **kwargs):
        """Given the id's of a SubmissionSet (kwargs['pk']) and
        a DocumentationField (kwargs['fieldpk']), get the
        DocumentationFieldSubmissionResource that matches.
        """
        # Need to check
        # DocumentationFieldSubmissionResource.Meta.allowed_methods
        # explicitly because the URL fiddling done above bypasses the
        # usual check:
        if (request.method.lower() not in
                DocumentationFieldSubmissionResource.Meta.allowed_methods):
            return HttpMethodNotAllowed()
        self.is_authenticated(request)
        for field_resource_type in (
                NumericSubmissionResource, TextSubmissionResource,
                NumericSubmissionResource, TextSubmissionResource,
                LongTextSubmissionResource, DateSubmissionResource,
                URLSubmissionResource, UploadSubmissionResource,
                BooleanSubmissionResource, ChoiceSubmissionResource,
                MultiChoiceSubmissionResource):
            resources = field_resource_type().obj_get_list(
                request, submissionset_id=kwargs['pk'])
            try:
                resources.get(documentation_field__id=kwargs['fieldpk'])
                break
            except ObjectDoesNotExist:
                pass
        else:
            return HttpGone()

        kwargs['submissionset_id'] = kwargs.pop('pk')
        field_submission_resource = field_resource_type()
        detail = field_submission_resource.get_detail(request, **kwargs)
        return detail