def put(self, request, format=None): # TODO: security risk here, get username based on the partyId verified in isPhoenix -SC if not isPhoenix(self.request): return Response(status=status.HTTP_400_BAD_REQUEST) # http://stackoverflow.com/questions/12611345/django-why-is-the-request-post-object-immutable serializer_class = self.get_serializer_class() params = request.GET if 'userIdentifier' not in params: return Response({'error': 'Put method needs userIdentifier'}) obj = self.get_queryset().first() #http://stackoverflow.com/questions/18930234/django-modifying-the-request-object PW-123 data = request.data.copy() # PW-123 if 'password' in data: data['password'] = hashlib.sha1(data['password']).hexdigest() serializer = serializer_class(obj, data=data, partial=True) if serializer.is_valid(): serializer.save() #update party info if 'partyId' in serializer.data: partyId = serializer.data['partyId'] partyObj = Party.objects.all().get(partyId = partyId) if 'name' in data: name = data['name'] partyData = {'name':name} partySerializer = PartySerializer(partyObj, data=partyData, partial =True) if partySerializer.is_valid(): partySerializer.save() if 'password' in data: #data['password'] = generateSecretKey(str(obj.partyId.partyId), data['password'])#PW-254 and YM: TAIR-2493 data['loginKey'] = generateSecretKey(str(obj.partyId.partyId), data['password']) return Response(data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def put(self, request, format=None): # TODO: security risk here, get username based on the partyId verified in isPhoenix -SC if not isPhoenix(self.request): return Response(status=status.HTTP_400_BAD_REQUEST) # http://stackoverflow.com/questions/12611345/django-why-is-the-request-post-object-immutable serializer_class = CredentialSerializer params = request.GET if 'partyId' not in params: return Response({'error': 'Put method needs partyId'}) obj = self.get_queryset().first() #http://stackoverflow.com/questions/18930234/django-modifying-the-request-object PW-123 data = request.data.copy() # PW-123 if 'password' in data: data['password'] = hashlib.sha1(data['password']).hexdigest() serializer = serializer_class(obj, data=data, partial=True) if serializer.is_valid(): serializer.save() #update party info if 'partyId' in serializer.data: partyId = serializer.data['partyId'] partyObj = Party.objects.all().get(partyId=partyId) if 'name' in data: name = data['name'] partyData = {'name': name} partySerializer = PartySerializer(partyObj, data=partyData, partial=True) if partySerializer.is_valid(): partySerializer.save() return Response(data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request, format=None): if not isPhoenix(request): return HttpResponse({'error':'POST parties/consortiums/ credentialId and secretKey query parameters missing or invalid'},status=status.HTTP_400_BAD_REQUEST) data = request.data.copy() if 'partyType' not in data: return Response({'error': 'POST method needs partyType'}, status=status.HTTP_400_BAD_REQUEST) if data['partyType'] != "consortium": return Response({'error': 'POST parties/consortiums/. patyType must be consortium'}, status=status.HTTP_400_BAD_REQUEST) if 'email' in data: for partyId in Credential.objects.all().filter(email=data['email']).filter(partnerId='phoenix').values_list('partyId', flat=True): if Party.objects.all().filter(partyId=partyId).filter(partyType='consortium').exists(): return Response({'error':'This email is already used by another consortium.'}, status=status.HTTP_400_BAD_REQUEST) # if password is being passed and value of it is empty then error # not passing password in form data of POST is allowed - credential will be created with empty pwd in such case # boolean in pythin http://stackoverflow.com/questions/12644075/how-to-set-python-variables-to-true-or-false if ('password' in data): if (not data['password'] or data['password'] == ""): ### password passed and it's value is empty return Response({'error': 'POST parties/consortiums/ password must not be empty'}, status=status.HTTP_400_BAD_REQUEST) else: ### password passed and it's not empty pwd = True else: # password is not passed pwd = False partySerializer = PartySerializer(data=data) if partySerializer.is_valid(): partySerializer.save() out = [] partyReturnData = partySerializer.data out.append(partyReturnData) data['partyId'] = partySerializer.data['partyId'] if pwd == True: newPwd = data['password'] data['password'] = hashlib.sha1(newPwd).hexdigest() credentialSerializer = CredentialSerializer(data=data) else: credentialSerializer = CredentialSerializerNoPassword(data=data) if credentialSerializer.is_valid(): credentialSerializer.save() credentialReturnData = credentialSerializer.data out.append(credentialReturnData) return HttpResponse(json.dumps(out), content_type="application/json", status=status.HTTP_201_CREATED) #return Response(credentialSerializer.data, status=status.HTTP_201_CREATED) else: return Response(credentialSerializer.errors, status=status.HTTP_400_BAD_REQUEST) else: return Response(partySerializer.errors, status=status.HTTP_400_BAD_REQUEST)
def loadTestConsortium(testConsortium): for item in testConsortium: serializer = PartySerializer(data={ 'partyType':'consortium', 'name':item['name'], 'display':1, 'countryId':item['countryId'], 'consortium_id':None, }) if serializer.is_valid(): serializer.save()
def loadTestConsortium(testConsortium): for item in testConsortium: serializer = PartySerializer( data={ 'partyType': 'consortium', 'name': item['name'], 'display': 1, 'countryId': item['countryId'], 'consortium_id': None, }) if serializer.is_valid(): serializer.save()
def put(self, request, format=None): if not isPhoenix(request): return HttpResponse({'error':'PUT parties/consortiums/ credentialId and secretKey query parameters missing or invalid'},status=status.HTTP_400_BAD_REQUEST) #http://stackoverflow.com/questions/18930234/django-modifying-the-request-object data = request.data.copy() params = request.GET if not params: return Response({'error':'PUT parties/consortiums/ does not allow update without query parameters'},status=status.HTTP_400_BAD_REQUEST) if 'partyId' not in request.data: return Response({'error':'PUT parties/consortiums/ partyId required'},status=status.HTTP_400_BAD_REQUEST) consortiumId = request.data['partyId'] #get party party = Party.objects.get(partyId = consortiumId) partySerializer = PartySerializer(party, data=data) if 'email' in data: for partyId in Credential.objects.all().filter(email=data['email']).filter(partnerId='phoenix').values_list('partyId', flat=True): if Party.objects.all().filter(partyId=partyId).filter(partyType='consortium').exists(): return Response({'error':'This email is already used by another consortium.'}, status=status.HTTP_400_BAD_REQUEST) if 'password' in request.data: if (not data['password'] or data['password'] == ""): return Response({'error': 'PUT parties/consortiums/ password must not be empty'}, status=status.HTTP_400_BAD_REQUEST) else: newPwd = data['password'] data['password'] = hashlib.sha1(newPwd).hexdigest() try: credential = Credential.objects.get(partyId=party) credentialSerializer = CredentialSerializer(credential, data=data) except Credential.DoesNotExist: data['partnerId'] = 'phoenix' credentialSerializer = CredentialSerializer(data=data) else: credentialSerializer = CredentialSerializerNoPassword(credential, data=data, partial=True) #?? out = [] if partySerializer.is_valid(): partySerializer.save() partyReturnData = partySerializer.data out.append(partyReturnData) if credentialSerializer.is_valid(): credentialSerializer.save() credentialReturnData = credentialSerializer.data out.append(credentialReturnData) return HttpResponse(json.dumps(out), content_type="application/json") else: return Response(credentialSerializer.errors, status=status.HTTP_400_BAD_REQUEST) else: return Response(partySerializer.errors, status=status.HTTP_400_BAD_REQUEST)
def join_party(request): """ Joins a logged in user to a party """ user = request.user party = Party.objects.get(id=request.data['party_id']) if party not in user.party_set.all(): user.party_set.add(party) serializer = PartySerializer(data=party) serializer.is_valid() return Response(serializer.data, status=status.HTTP_200_OK)
class SongSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True, default=serializers.CurrentUserDefault()) party = PartySerializer(read_only=True) likes = serializers.SerializerMethodField(read_only=True) like = serializers.SerializerMethodField(read_only=True) class Meta: model = Song fields = ( 'id', 'user', 'party', 'player', 'source', 'name', 'date', 'likes', 'like', ) def get_likes(self, obj): return Like.objects.filter(kind=Like.Kind.SONG, like=obj.pk).count() def get_like(self, obj) -> int: return get_serializer_like(self, obj, Like.Kind.SONG)
def put(self, request, format=None): if not isPhoenix(request): return HttpResponse({'error':'credentialId and secretKey query parameters missing or invalid'},status=status.HTTP_400_BAD_REQUEST) params = request.GET data = request.data.copy() if not params: return Response({'error':'does not allow update without query parameters'},status=status.HTTP_400_BAD_REQUEST) if 'partyId' not in request.data: return Response({'error':'partyId (aka institutionId) required'},status=status.HTTP_400_BAD_REQUEST) institutionId = request.data['partyId'] #get party party = Party.objects.get(partyId = institutionId) partySerializer = PartySerializer(party, data=data) #get credential credential = Credential.objects.get(partyId = institutionId) if 'password' in request.data: if (not data['password'] or data['password'] == ""): return Response({'error': 'PUT parties/institutions/ password must not be empty'}, status=status.HTTP_400_BAD_REQUEST) else: newPwd = data['password'] data['password'] = hashlib.sha1(newPwd).hexdigest() credentialSerializer = CredentialSerializer(credential, data=data) else: credentialSerializer = CredentialSerializerNoPassword(credential, data=data, partial=True) #?? out = [] if partySerializer.is_valid(): partySerializer.save() partyReturnData = partySerializer.data out.append(partyReturnData) if credentialSerializer.is_valid(): credentialSerializer.save() credentialReturnData = credentialSerializer.data out.append(credentialReturnData) return HttpResponse(json.dumps(out), content_type="application/json") else: return Response(credentialSerializer.errors, status=status.HTTP_400_BAD_REQUEST) else: return Response(partySerializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request, format=None): if ApiKeyPermission.has_permission(request, self): serializer_class = self.get_serializer_class() data = request.data data['password'] = hashlib.sha1(data['password']).hexdigest() if 'partyId' not in data: name = data['name'] partyData = {'name':name, 'partyType':'user'} #PW-161 partyType is in PArty tbl partySerializer = PartySerializer(data=partyData, partial =True) # pu = Party(); pu.save() # data['partyId'] = pu.partyId if partySerializer.is_valid(): partySerializer.save() data['partyId'] = partySerializer.data['partyId'] serializer = serializer_class(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def loadTestUser(testUsers, partnerId): for item in testUsers: serializer = PartySerializer(data={'partyType': 'user'}) if serializer.is_valid(): serializer.save() partyId = serializer.data['partyId'] serializer = CredentialSerializer( data={ 'username': item['username'], 'password': item['password'], 'email': item['email'], 'institution': item['institution'], 'userIdentifier': item['userIdentifier'], 'partyId': partyId, 'partnerId': partnerId, }) if serializer.is_valid(): serializer.save()
def get(self, request, consortiumId, format=None): # security vulnerability: consortiumId should come from partyId in cookie that's been validated via isPhoenix -SC if not isPhoenix(request): return HttpResponse(status=400) institutions = Party.objects.get(partyId=consortiumId).party_set.all() serializer = PartySerializer(institutions, many=True) ret = [dict(s) for s in serializer.data] #for s in serializer.data: # ret_tmp = dict(s) # ret_tmp['id'] = ret_tmp['partyId'] # ret_tmp['state'] = None # ret.append(ret_tmp) return HttpResponse(json.dumps(ret), status=200)
def create_party(request): """ Creates a party for a logged in user Accepts the following POST parameters: restaurant, title, description, dictator, start time Returns a JSON object representation of the party """ leader = request.user restaurant = Restaurant.objects.get(name=request.data['restaurant']) title = request.data['title'] description = request.data['description'] dictator = request.data['dictator'].lower() == 'true' start_time = request.data['start_time'] party = Party.objects.create(leader=leader, title=title, description=description, dictator=dictator, start_time=start_time) party.restaurant.set([restaurant]) party.users.add(leader) FoodList.objects.create(party=party) serializer = PartySerializer(data=party) serializer.is_valid() return Response(serializer.data, status=status.HTTP_201_CREATED)
class CandidateDetailSerializer(serializers.ModelSerializer): public_key = serializers.CharField(source='profile.public_key', read_only=True) profile = ProfileSerializer() party = PartySerializer() class Meta: model = Candidate fields = ('id', 'profile', 'party', 'public_key', 'vote_count', 'bio', 'plans', 'is_candidate') read_only_fields = ( 'id', 'is_candidate', )
def loadTestUser(testUsers, partnerId): for item in testUsers: serializer = PartySerializer(data={'partyType':'user'}) if serializer.is_valid(): serializer.save() partyId= serializer.data['partyId'] serializer = CredentialSerializer(data={ 'username':item['username'], 'password':item['password'], 'email':item['email'], 'institution':item['institution'], 'userIdentifier':item['userIdentifier'], 'partyId':partyId, 'partnerId':partnerId, }) if serializer.is_valid(): serializer.save()
def get(self, request, partyId): ret = {} now = datetime.datetime.now() if Party.objects.all().get(partyId=partyId): consortiums = Party.objects.all().get(partyId=partyId).consortiums.all() for consortium in consortiums: consortiumActiveSubscriptions = Subscription.objects.all().filter(partyId=consortium.partyId).filter(endDate__gt=now).filter(startDate__lt=now) serializer = SubscriptionSerializer(consortiumActiveSubscriptions, many=True) partySerializer = PartySerializer(consortium) for s in serializer.data: if s['partnerId'] in ret: ret[s['partnerId']].append(partySerializer.data) else: ret[s['partnerId']] = [] ret[s['partnerId']].append(partySerializer.data) return HttpResponse(json.dumps(ret), status=200)
def get(self, request): params = request.GET if 'subscriptionId' in request.GET: subscriptionId = request.GET.get('subscriptionId') subscription = Subscription.objects.all().get(subscriptionId=subscriptionId) serializer = SubscriptionSerializer(subscription) return Response(serializer.data) elif 'partyId' in params: partyId = params['partyId'] now = datetime.datetime.now() if 'checkConsortium' in params and params['checkConsortium'] == 'true': partnerIdList = Partner.objects.all().values_list('partnerId', flat=True) idSub = [] allSub = Subscription.getById(partyId) for partnerId in partnerIdList: if allSub.filter(partnerId=partnerId).filter(endDate__gt=now).filter(startDate__lt=now).exists(): idSub.append(allSub.filter(partnerId=partnerId).filter(endDate__gt=now).filter(startDate__lt=now).latest('endDate')) serializer = SubscriptionSerializer(idSub, many=True) elif 'active' in params and params['active'] == 'true': activeSubscriptions = Subscription.objects.all().filter(partyId=partyId).filter(endDate__gt=now).filter(startDate__lt=now) serializer = SubscriptionSerializer(activeSubscriptions, many=True) else: allSubscriptions = Subscription.objects.all().filter(partyId=partyId) serializer = SubscriptionSerializer(allSubscriptions, many=True) return Response(serializer.data, status=200) elif all(param in params for param in ['partnerId', 'ipAddress', 'userIdentifier']): partnerId = params['partnerId'] ipAddress = params['ipAddress'] userIdentifier = params['userIdentifier'] idSub = None #Pw-418 subList = [] #Pw-418 ipSub = Subscription.getByIp(ipAddress).filter(partnerId=partnerId) if Credential.objects.filter(userIdentifier=userIdentifier).filter(partnerId=partnerId).exists(): partyId = Credential.objects.filter(partnerId=partnerId).filter(userIdentifier=userIdentifier)[0].partyId.partyId idSub = Subscription.getById(partyId).filter(partnerId=partnerId) if (idSub): subList = SubscriptionSerializer(ipSub, many=True).data+SubscriptionSerializer(idSub, many=True).data else: subList = SubscriptionSerializer(ipSub, many=True).data for sub in subList: if Party.objects.filter(partyId = sub['partyId']).exists(): party = PartySerializer(Party.objects.get(partyId = sub['partyId'])).data sub['partyType'] = party['partyType'] sub['name'] = party['name'] return HttpResponse(json.dumps(subList), content_type="application/json") else: return Response({"error":"Essential parameters needed."}, status=status.HTTP_400_BAD_REQUEST)
def get(self,request): params = request.GET partnerId = params['partnerId'] ipAddress = params['ipAddress'] userIdentifier = params['userIdentifier'] idSub = None #Pw-418 subList = [] #Pw-418 ipSub = Subscription.getActiveByIp(ipAddress, partnerId) if Credential.objects.filter(userIdentifier=userIdentifier).filter(partnerId=partnerId).exists(): partyId = Credential.objects.filter(partnerId=partnerId).filter(userIdentifier=userIdentifier)[0].partyId.partyId idSub = Subscription.getActiveById(partyId, partnerId) if (idSub): subList = SubscriptionSerializer(ipSub, many=True).data+SubscriptionSerializer(idSub, many=True).data else: subList = SubscriptionSerializer(ipSub, many=True).data for sub in subList: if Party.objects.filter(partyId = sub['partyId']).exists(): party = PartySerializer(Party.objects.get(partyId = sub['partyId'])).data sub['partyType'] = party['partyType'] sub['name'] = party['name'] return HttpResponse(json.dumps(subList), content_type="application/json")
def get(self, request): params = request.GET if not 'partyId' in params: return Response({'error':'partyId is required'}, status=status.HTTP_400_BAD_REQUEST) ret = {} now = datetime.datetime.now() partyId = params['partyId'] if 'active' in params and params['active'] == 'true': if Party.objects.all().get(partyId=partyId): consortiums = Party.objects.all().get(partyId=partyId).consortiums.all() for consortium in consortiums: consortiumActiveSubscriptions = Subscription.objects.all().filter(partyId=consortium.partyId).filter(endDate__gt=now).filter(startDate__lt=now) serializer = SubscriptionSerializer(consortiumActiveSubscriptions, many=True) partySerializer = PartySerializer(consortium) for s in serializer.data: if s['partnerId'] in ret: ret[s['partnerId']].append(partySerializer.data) else: ret[s['partnerId']] = [] ret[s['partnerId']].append(partySerializer.data) return Response(ret, status=200)
def get(self, request, format=None): if not isPhoenix(request): return HttpResponse( { 'error': 'credentialId and secretKey query parameters missing or invalid' }, status=status.HTTP_400_BAD_REQUEST) params = request.GET if not params['partyId']: return Response({'error': 'does not allow get without partyId'}, status=status.HTTP_400_BAD_REQUEST) out = [] partyId = params['partyId'] #get party if Party.objects.filter(partyId=partyId).exists(): party = Party.objects.get(partyId=partyId) partySerializer = PartySerializer(party) out.append(partySerializer.data) else: out.append( {'error': 'partyId ' + partyId + ' not found in Party tbl'}) #get credential if Credential.objects.filter(partyId=partyId).exists(): credential = Credential.objects.get(partyId=partyId) credentialSerializer = CredentialSerializer(credential) out.append(credentialSerializer.data) else: out.append({ 'error': 'partyId ' + partyId + ' not found in Credential tbl' }) return HttpResponse(json.dumps(out), content_type="application/json")
def get_post_parties(req): if req.method == "GET": all_parties = Party.objects.all() serializer = PartySerializer(all_parties, context={"request": req}, many=True) return Response(serializer.data) if req.method == "POST": serializer = PartySerializer(data=req.data) if serializer.is_valid(): serializer.save() return Response(status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) # @api_view(["PUT","DELETE"]) # def party_detail(req): # if req.method == "PUT": # if req.method == "DELETE": # pass
queryset = Party.objects.all().filter(partyType='organization') if actionType == 'create': partyId = None # when the party doesn't exist if not queryset.filter(name=institutionName).exists(): #create party if not Country.objects.all().filter(name=countryName): print '[Country Not Found] ' + countryName continue elif Country.objects.all().filter(name=countryName).count() >1: print '[More than one record found with country name] ' + countryName continue else: countryId = Country.objects.get(name=countryName).countryId partySerializer = PartySerializer(data={'name':institutionName, 'partyType': 'organization', 'country':countryId}, partial=True) if partySerializer.is_valid(): partySerializer.save() print '[New Party Created] ' + institutionName else: print '[Party serializer invalid] ' + \ 'type: ' + actionType + \ 'institution: ' + institutionName + \ 'start: ' + startIp + \ 'end: ' + endIp ipRangeFailed += 1 continue partyId = partySerializer.data['partyId'] childParty = Party.objects.get(partyId = partyId) parentParty = Party.objects.get(partyId = consortiumId) PartyAffiliation.objects.create(childPartyId = childParty, parentPartyId = parentParty)
startDate = entry[offset+1] endDate = entry[offset+2] if not endDate or endDate == "": endDate = "01-JAN-99 01.00.00.000000000 AM AMERICA/LOS_ANGELES" startDate = parseTime(startDate) endDate = parseTime(endDate) data = { 'name':organizationName, 'partyType':'organization', 'display':display, 'country':countryId, } serializer = PartySerializer(data=data) if serializer.is_valid(): serializer.save() partyId = serializer.data['partyId'] orgIdPartyId[organizationId]=partyId data = { 'partyId':partyId, 'partnerId':partnerId, 'startDate':startDate, 'endDate':endDate, } serializer = SubscriptionSerializer(data=data) if serializer.is_valid(): serializer.save() else:
organizationName = entry[0] countryName = entry[1] party = None countryId = None if Country.objects.all().filter(name=countryName).exists(): countryId = Country.objects.get(name=countryName).countryId else: print 'cannot find country name: ' + countryName continue if Party.objects.all().filter(name=organizationName).exists(): if Party.objects.all().filter(name=organizationName).count() > 1: print 'more than one Party returned: ' + organizationName continue party = Party.objects.get(name=organizationName) else: print 'cannot find party: ' + organizationName continue data = {'country':countryId} serializer = PartySerializer(party, data=data, partial=True) if serializer.is_valid(): serializer.save() else: print "cannot save party: " + organizationName print data print 'Loading Complete'
startDate = entry[offset + 1] endDate = entry[offset + 2] if not endDate or endDate == "": endDate = "01-JAN-99 01.00.00.000000000 AM AMERICA/LOS_ANGELES" startDate = parseTime(startDate) endDate = parseTime(endDate) data = { 'name': organizationName, 'partyType': 'organization', 'display': display, 'country': countryId, } serializer = PartySerializer(data=data) if serializer.is_valid(): serializer.save() partyId = serializer.data['partyId'] orgIdPartyId[organizationId] = partyId data = { 'partyId': partyId, 'partnerId': partnerId, 'startDate': startDate, 'endDate': endDate, } serializer = SubscriptionSerializer(data=data) if serializer.is_valid(): serializer.save() else:
def put(self, request, format=None): if not isPhoenix(request): return HttpResponse( { 'error': 'credentialId and secretKey query parameters missing or invalid' }, status=status.HTTP_400_BAD_REQUEST) data = request.data.copy() out = [] if 'partyId' not in data: return Response({'error': 'partyId (aka institutionId) required'}, status=status.HTTP_400_BAD_REQUEST) institutionId = data['partyId'] #get party party = Party.objects.get(partyId=institutionId) partySerializer = PartySerializer(party, data=data, partial=True) if any(param in CredentialSerializer.Meta.fields for param in data if param != 'partyId'): partner = Partner.objects.get(partnerId='phoenix') try: credential = Credential.objects.get(partyId=party, partnerId=partner) except: if not all(param in data for param in ('username', 'password')): return Response( {'error': 'username and password required.'}, status=status.HTTP_400_BAD_REQUEST) credential = Credential(partyId=party, partnerId=partner) if 'email' in data: for partyId in Credential.objects.all().filter( email=data['email']).filter( partnerId='phoenix').values_list('partyId', flat=True): if Party.objects.all().filter(partyId=partyId).filter( partyType='organization').exists(): return Response( { 'error': 'This email is already used by another institution.' }, status=status.HTTP_400_BAD_REQUEST) if 'password' in data: if (not data['password'] or data['password'] == ""): return Response({'error': 'password must not be empty'}, status=status.HTTP_400_BAD_REQUEST) else: newPwd = data['password'] data['password'] = hashlib.sha1(newPwd).hexdigest() credentialSerializer = CredentialSerializer(credential, data=data, partial=True) else: credentialSerializer = CredentialSerializerNoPassword( credential, data=data, partial=True) #?? if partySerializer.is_valid(): if any(param in PartySerializer.Meta.fields for param in data if param != 'partyId'): partySerializer.save() partyReturnData = partySerializer.data out.append(partyReturnData) else: return Response(partySerializer.errors, status=status.HTTP_400_BAD_REQUEST) if any(param in CredentialSerializer.Meta.fields for param in data if param != 'partyId'): if credentialSerializer.is_valid(): credentialSerializer.save() credentialReturnData = credentialSerializer.data out.append(credentialReturnData) else: return Response(credentialSerializer.errors, status=status.HTTP_400_BAD_REQUEST) return HttpResponse(json.dumps(out), content_type="application/json")
def post(self, request, format=None): if not isPhoenix(request): return HttpResponse( { 'error': 'POST parties/institutions/ credentialId and secretKey query parameters missing or invalid' }, status=status.HTTP_400_BAD_REQUEST) data = request.data.copy() if 'partyType' not in data: return Response({'error': 'POST method needs partyType'}, status=status.HTTP_400_BAD_REQUEST) if data['partyType'] != "organization": return Response( {'error': 'POST method. patyType must be organization'}, status=status.HTTP_400_BAD_REQUEST) if 'email' in data: for partyId in Credential.objects.all().filter( email=data['email']).filter( partnerId='phoenix').values_list('partyId', flat=True): if Party.objects.all().filter(partyId=partyId).filter( partyType='organization').exists(): return Response( { 'error': 'This email is already used by another institution.' }, status=status.HTTP_400_BAD_REQUEST) # if password is being passed and value of it is empty then error # not passing password in form data of POST is allowed - credential will be created with empty pwd in such case # boolean in pythin http://stackoverflow.com/questions/12644075/how-to-set-python-variables-to-true-or-false if ('password' in data): if (not data['password'] or data['password'] == ""): ### password passed and it's value is empty return Response( { 'error': 'POST parties/institutions/ password must not be empty' }, status=status.HTTP_400_BAD_REQUEST) else: ### password passed and it's not empty pwd = True else: # password is not passed pwd = False partySerializer = PartySerializer(data=data) if partySerializer.is_valid(): partySerializer.save() out = [] partyReturnData = partySerializer.data out.append(partyReturnData) data['partyId'] = partySerializer.data['partyId'] if pwd == True: newPwd = data['password'] data['password'] = hashlib.sha1(newPwd).hexdigest() credentialSerializer = CredentialSerializer(data=data) else: credentialSerializer = CredentialSerializerNoPassword( data=data) if credentialSerializer.is_valid(): credentialSerializer.save() credentialReturnData = credentialSerializer.data out.append(credentialReturnData) return HttpResponse(json.dumps(out), content_type="application/json", status=status.HTTP_201_CREATED) #return Response(credentialSerializer.data, status=status.HTTP_201_CREATED) else: return Response(credentialSerializer.errors, status=status.HTTP_400_BAD_REQUEST) else: return Response(partySerializer.errors, status=status.HTTP_400_BAD_REQUEST)
organizationName = "%s,%s" % (organizationName, entry[offset]) offset += 1 try: temp = organizationCountryArray[organizationId] countryId = temp[0] display = temp[1] except: countryId = None display = False organizationName = organizationName.decode('utf8') data = { 'name': organizationName, 'partyType': 'organization', 'display': display, 'country': countryId, } if Party.objects.all().filter(name=organizationName).exists(): for partyInstance in Party.objects.all().filter(name=organizationName): serializer = PartySerializer(partyInstance, data=data) if serializer.is_valid(): serializer.save() else: print "CANNOT SAVE PARTY" print data else: print "organizationName NOT FOUND: " + organizationName
def put(self, request, format=None): # TODO: security risk here, get username based on the partyId verified in isPhoenix -SC if not isPhoenix(self.request): return Response(status=status.HTTP_400_BAD_REQUEST) # http://stackoverflow.com/questions/12611345/django-why-is-the-request-post-object-immutable serializer_class = self.get_serializer_class() params = request.GET queryResult = self.get_queryset() if type(queryResult) == str: return Response({'error': queryResult}, status=status.HTTP_400_BAD_REQUEST) obj = self.get_queryset().first() if not obj: return Response({'error': 'cannot find any record.'}, status=status.HTTP_404_NOT_FOUND) #http://stackoverflow.com/questions/18930234/django-modifying-the-request-object PW-123 data = request.data.copy() # PW-123 partnerId = self.request.GET['partnerId'] # CIPRES-13: Decrypt user password if 'password' in data: if partnerId == 'cipres': cipher = AESCipher() try: decryptedPassword = cipher.decrypt(data['password']) except Exception as e: return Response( {'error': 'Cannot parse password: '******'password'] = hashlib.sha1( decryptedPassword.encode(cipher.charset)).hexdigest() else: data['password'] = hashlib.sha1( data['password'].encode("utf-8")).hexdigest() # CIPRES-13 end # CIPRES-26: Allow update of country code if partnerId == 'cipres' and 'countryCode' in data: try: country = Country.objects.get(abbreviation=data['countryCode']) partyObj = obj.partyId partySerializer = PartySerializer( partyObj, data={'country': country.countryId}, partial=True) if partySerializer.is_valid(): partySerializer.save() except Exception as e: return Response({'error': 'Cannot find country: ' + str(e)}, status=status.HTTP_400_BAD_REQUEST) # CIPRES-26 end serializer = serializer_class(obj, data=data, partial=True) if serializer.is_valid(): serializer.save() #update party info if 'partyId' in serializer.data: partyId = serializer.data['partyId'] partyObj = Party.objects.all().get(partyId=partyId) if 'name' in data: name = data['name'] partyData = {'name': name} partySerializer = PartySerializer(partyObj, data=partyData, partial=True) if partySerializer.is_valid(): partySerializer.save() if 'password' in data: #data['password'] = generateSecretKey(str(obj.partyId.partyId), data['password'])#PW-254 and YM: TAIR-2493 data['loginKey'] = generateSecretKey(str(obj.partyId.partyId), data['password']) return Response(data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request, format=None): if ApiKeyPermission.has_permission(request, self): serializer_class = self.get_serializer_class() data = request.data.copy() # PW-660 # CIPRES-13: Decrypt user password if 'partnerId' not in data: return Response({'error': 'partnerId is required'}, status=status.HTTP_400_BAD_REQUEST) partnerId = data['partnerId'] if partnerId == 'cipres': cipher = AESCipher() try: decryptedPassword = cipher.decrypt(data['password']) except Exception as e: return Response( {'error': 'Cannot parse password: '******'password'] = hashlib.sha1( decryptedPassword.encode(cipher.charset)).hexdigest() else: data['password'] = hashlib.sha1( data['password'].encode('utf-8')).hexdigest() # CIPRES-13 end if 'partyId' in data: partyId = data['partyId'] if Credential.objects.all().filter(partyId=partyId).exists(): return Response( { "non_field_errors": [ "There is an existing credential for the user, use PUT to update the credential." ] }, status=status.HTTP_400_BAD_REQUEST) if 'userIdentifier' in data: userIdentifier = data['userIdentifier'] if userIdentifier is not None: partnerId = data['partnerId'] if Credential.objects.all().filter( userIdentifier=userIdentifier).filter( partnerId=partnerId).exists(): return Response( { "non_field_errors": [ "User identifier already exists, use PUT to update the credential or provide an unique user identifier." ] }, status=status.HTTP_400_BAD_REQUEST) if 'partyId' not in data: if 'name' in data: name = data['name'] elif 'username' in data: name = data['username'] else: return Response({'error': 'username is required'}, status=status.HTTP_400_BAD_REQUEST) if 'display' not in data: #PW-272 display = '0' else: display = data['display'] # CIPRES-13: Require country info for user registration if partnerId == 'cipres': if 'countryCode' not in data: return Response({'error': 'countryCode is required'}, status=status.HTTP_400_BAD_REQUEST) else: try: country = Country.objects.get( abbreviation=data['countryCode']) except Exception as e: return Response( {'error': 'Cannot find country: ' + str(e)}, status=status.HTTP_400_BAD_REQUEST) partyData = { 'name': name, 'partyType': 'user', 'display': display, 'country': country.countryId } else: partyData = { 'name': name, 'partyType': 'user', 'display': display } # CIPRES-13 end # CYV-32: check unique constraint on username + partyId userAccount = Credential.objects.all().filter( username=name, partnerId=partnerId) if len(userAccount) > 0: return Response( { 'error': 'Combination of %s + %s already exists' % (name, partnerId) }, status=status.HTTP_400_BAD_REQUEST) # CYV-32 end partySerializer = PartySerializer(data=partyData, partial=True) # pu = Party(); pu.save() # data['partyId'] = pu.partyId if partySerializer.is_valid(): partySerializer.save() data['partyId'] = partySerializer.data['partyId'] serializer = serializer_class(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)