def obj_create(self, bundle, **kwargs): data = bundle.data firstName = "" lastName = "" funcLog().debug("Creating user from %r", data) if 'firstName' in data: firstName = data['firstName'] if 'lastName' in data: lastName = data['lastName'] u = User.objects.create( username = data['username'], email = data['email'], first_name = firstName, last_name = lastName ) u.set_password(data['password']) u.save() if 'fields' in data: for f in data['fields']: field = models.Field.objects.get(id=f['id']) models.FieldValue.objects.create( field = field, value = f['value'], member = u.member ) bundle.obj = u.member return bundle
def createUser(self, username, password): funcLog().info("Creating user %s with password %s", username, password) user = User.objects.create_user(username, '*****@*****.**', password) user.save() user.identity.displayName = 'Test McTesterson' user.identity.save() return user
def createUser(self, username, password): funcLog().info("Creating user %s with password %s", username, password) user = User.objects.create_user(username, '*****@*****.**', password) user.first_name = 'Test' user.last_name = 'McTesterson' user.save() return user
def add_resource_permissions(*args, **kwargs): """ This syncdb hooks takes care of adding a view permission too all our content types. """ # for each of our content types for resource in find_api_classes('v1_api', ModelResource): auth = resource._meta.authorization content_type = ContentType.objects.get_for_model(resource._meta.queryset.model) if isinstance(auth, SpiffAuthorization): conditions = auth.conditions() operations = auth.operations() if len(conditions) == 0: conditions = (None,) for condition in conditions: for operation in operations: # build our permission slug if condition: codename = "%s_%s_%s" % (operation[0], condition[0], content_type.model) name = "Can %s %s, when %s" % (operation[1], content_type.name, condition[1]) else: codename = "%s_%s" % (operation[1], content_type.model) name = "Can %s %s" % (operation[1], content_type.name) # if it doesn't exist.. if not Permission.objects.filter(content_type=content_type, codename=codename): # add it Permission.objects.create(content_type=content_type, codename=codename, name=name[:49]) funcLog().debug("Created permission %s.%s (%s)", content_type.app_label, codename, name)
def createLineItems(self, subscription, processDate): targetIdentity = self.identity if targetIdentity is None: targetIdentity = subscription.identity planOwner = subscription.identity startOfMonth, endOfMonth = monthRange(processDate) funcLog().info("Processing subscription of %s dues for %s, billing to %s", self.rank, self.identity, planOwner) endOfMonth += datetime.timedelta(days=1) #FIXME: membershipRanges was removed #for range in targetIdentity.membershipRanges: # if range['start'] <= startOfMonth and range['end'] >= endOfMonth: # return [] # if RankLineItem.objects.filter(rank=self.rank, identity=targetIdentitiy, # activeFromDate=startOfMonth, activeToDate=endOfMonth).exists(): # return [] return [RankLineItem( rank = self.rank, identity = targetIdentity, activeFromDate = startOfMonth, activeToDate = endOfMonth ),]
def requestPasswordReset(self, request, **kwargs): self.method_check(request, allowed=['post']) data = self.deserialize(request, request.body, format=request.META.get('CONTENT_TYPE', 'application/json')) users = User.objects.filter(Q(username=data['userid']) | Q(email=data['userid'])) site = get_current_site(request) for u in users: token = models.UserResetToken.objects.create(user=u) funcLog().info("Resetting password for %s, mailing %s to %s", u.username, token.token, u.email) message = [ random.choice(settings.GREETINGS), '', 'This is Spaceman Spiff for %s'%(site.name), '', 'Someone from the IP %s has requested that your password be reset.', '', 'To reset your password, visit %s and use this temporary password to login:'******'', '%s'%(token.token), '', 'It will expire after 5 minutes. If you did not request to have your password reset, feel free to ignore this message!' '', 'Thanks!' ] send_mail('Spiff Password Reset', "\n".join(message), settings.DEFAULT_FROM_EMAIL, [u.email]) return self.create_response(request, {'success': True})
def processSubscriptions(): with transaction.atomic(): startOfMonth, endOfMonth = monthRange() lineItems = {} for planCls in find_api_classes('models', SubscriptionPlan): plans = planCls.objects.all() for plan in plans: for subscription in plan.subscriptions.filter(active=True): if subscription.identity not in lineItems: lineItems[subscription.identity] = {'subscriptions': [], 'lineItems': []} items = plan.process(subscription) funcLog().info("Processed subscription %s", subscription) if len(items) > 0 and subscription not in lineItems[subscription.identity]['subscriptions']: lineItems[subscription.identity]['subscriptions'].append(subscription) lineItems[subscription.identity]['lineItems'] += items invoices = [] for identity, data in lineItems.iteritems(): invoice = Invoice.bundleLineItems(identity, endOfMonth, data['lineItems']) if invoice: funcLog().info("Created invoice %s", invoice) invoices.append(invoice) for subscription in data['subscriptions']: subscription.save() for invoice in invoices: invoice.draft = False invoice.save()
def check_perm(self, bundle, model, name): u = getattr(model, self._attr) funcLog().info("Checking %r for ownership of %r (%r)", bundle.request.user, model, u) if u.pk == bundle.request.user.pk: return super(OwnedObjectAuthorization, self).check_perm(bundle, model, '%s_own'%(name)) return super(OwnedObjectAuthorization, self).check_perm(bundle, model, '%s_others'%(name))
def postAPI(self, endpoint, struct=None, status=201): ret = self.postAPIRaw(endpoint, struct) funcLog().debug("Got result %s: %s", ret.status_code, ret.content) self.assertEqual(ret.status_code, status) if len(ret.content): ret = json.loads(ret.content) else: ret = None return ret
def grantPermission(self, permissionName): funcLog().info("Granting %s to %s", permissionName, self.user) appName, name = permissionName.split('.', 1) perm = Permission.objects.get( codename=name, content_type__app_label=appName, ) self.user.user_permissions.add(perm) self.user.save() return perm
def contiguousPeriods(self): dates = self.contiguousDates range = MembershipPeriod.objects.filter( rank = self.rank, member = self.member, activeFromDate__gte=dates[0], activeToDate__lte=dates[1] ) funcLog().debug("Found %s!", range) return range
def revokePermission(self, permissionName): funcLog().info("Revoking %s from %s", permissionName, self.user) appName, name = permissionName.split('.', 1) perm = Permission.objects.get( codename=name, content_type__app_label=appName, ) self.user.user_permissions.remove(perm) self.user.save() return perm
def patchAPIRaw(self, endpoint, struct=None): if struct: funcLog().info("Patching %s with %r", endpoint, struct) return self.client.patch( endpoint, json.dumps(struct), content_type = 'application/json' ) funcLog().info("Patching %s", endpoint) return self.client.patch(endpoint)
def postAPIRaw(self, endpoint, struct=None): if struct: funcLog().info("Posting to %s: %r", endpoint, struct) return self.client.post( endpoint, json.dumps(struct), content_type="application/json" ) else: funcLog().info("Posting to %s", endpoint) return self.client.post(endpoint)
def deleteAPIRaw(self, endpoint, struct=None): if struct: funcLog().info("Deleting %s: %r", endpoint, struct) return self.client.delete( endpoint, json.dumps(struct), content_type="application/json" ) else: funcLog().info("Deleting %s", endpoint) return self.client.delete(endpoint)
def save(self, *args, **kwargs): if self.pk and notification: current = Invoice.objects.get(pk=self.pk) if current.draft == True or current.open == False: if self.draft == False and self.open == True and self.unpaidBalance > 0: try: self.chargeStripe() except stripe.error.CardError, e: funcLog().error("Failed to charge stripe") funcLog().exception(e) notification.send( [self.user], "card_failed", {'user': self.user, 'invoice': self})
def process(self): period, created = MembershipPeriod.objects.get_or_create( rank = self.rank, member = self.member, activeFromDate = self.activeFromDate, activeToDate = self.activeToDate, lineItem = self ) if created: u = self.member.user u.groups.add(self.rank.group) u.save() funcLog().info("Processed %s - added %s to group %s", self, self.member, self.rank.group)
def has_perm(self, perm, obj=None): funcLog().debug("Checking %s for permission %s on %r",self, perm, obj) if super(AuthenticatedUser, self).has_perm(perm, obj): funcLog().debug("Found django permission %s", perm) return True anon = get_anonymous_user() if anon.has_perm(perm, obj): funcLog().debug("Found anonymous permission %s", perm) return True app, perm = perm.split('.', 1) ret = get_authenticated_user_group().permissions.filter( content_type__app_label = app, codename=perm).exists() if ret: funcLog().debug("Found authenticated group permission %s", perm) else: funcLog().debug("Denied") return ret
def search(self, request, **kwargs): self.method_check(request, allowed=['get']) self.is_authenticated(request) self.throttle_check(request) name = request.GET['fullName'].split(' ') query = Q() if len(name) == 1: query &= Q(first_name__icontains=name[0]) | Q(last_name__icontains=name[0]) else: query &= Q(first_name__icontains=name[0]) | Q(last_name__icontains=' '.join(name[1:])) firstName, lastName = request.GET['fullName'].split(' ', 1) query &= Q(member__hidden=False) funcLog().info("User search query: %s", query) users = User.objects.filter(query) objects = [] for u in users: bundle = self.build_bundle(obj=u.member, request=request) bundle = self.full_dehydrate(bundle) objects.append(bundle) object_list = {'objects': objects} return self.create_response(request, object_list)
def createLineItems(self, subscription, processDate): targetMember = self.member if targetMember is None: targetMember = subscription.user.member planOwner = subscription.user startOfMonth, endOfMonth = monthRange(processDate) funcLog().info("Processing subscription of %s dues for %s, billing to %s", self.rank, self.member, planOwner) endOfMonth += datetime.timedelta(days=1) for range in targetMember.membershipRanges: if range['start'] <= startOfMonth and range['end'] >= endOfMonth: return [] if RankLineItem.objects.filter(rank=self.rank, member=targetMember, activeFromDate=startOfMonth, activeToDate=endOfMonth).exists(): return [] return [RankLineItem( rank = self.rank, member = targetMember, activeFromDate = startOfMonth, activeToDate = endOfMonth ),]
def login(self, request, **kwargs): self.method_check(request, allowed=['post']) data = self.deserialize(request, request.body, format=request.META.get('CONTENT_TYPE', 'application/json')) if 'username' in data and 'password' in data: username = data['username'] password = data['password'] else: username = None password = None user = authenticate(username=username, password=password) if user: if user.is_active: funcLog().info("Successful login for %s", username) token = {} token['id'] = user.id return self.create_response(request, { 'success': True, 'token': jwt.encode(token, settings.SECRET_KEY), 'passwordReset': False }) else: funcLog().warning("Good login, but %s is disabled.", username) raise ImmediateHttpResponse(response=HttpForbidden()) else: tokens = models.UserResetToken.objects.filter(user__username=username, token=password) for t in tokens: if t.created >= datetime.datetime.utcnow().replace(tzinfo=utc)-datetime.timedelta(minutes=5): user = t.user funcLog().info("Successful password reset for %s", user.username) token = {} token['id'] = user.id return self.create_response(request, { 'success': True, 'token': jwt.encode(token, settings.SECRET_KEY), 'passwordReset': True, }) else: t.delete() funcLog().warning("Invalid login for %s", username) raise ImmediateHttpResponse(response=HttpUnauthorized())
def check_perm(self, bundle, model, name): funcLog().info("Checking if %s == %s", bundle.request.user, model) if bundle.request.user.pk == model.pk: return True return super(SelfUserAuthorization, self).check_perm(bundle, model, name)
def check_perm(self, bundle, model, permName): if 'value' in bundle.data and permName == 'update': funcLog("updating perm via %s", permName) return super(SensorUpdateAuthorization, self).check_perm(bundle, model, 'update_value_on') return super(SensorUpdateAuthorization, self).check_perm(bundle, model, permName)
def check_perm(self, bundle, model, permName): permName = '%s.%s_%s' % (model.__class__._meta.app_label, permName, model.__class__._meta.module_name) ret = bundle.request.user.has_perm(permName) funcLog().debug("Checking %s for %s: %s", bundle.request.user, permName, ret) return ret
def createGroup(self, name): funcLog().info("Creating group %s", name) group = Group.objects.create(name=name) return group
def login(self): funcLog().info("Logging in with test user") self.client.login(username=self.user.username, password=self.password)
def getAPIRaw(self, endpoint, args=None): if args: funcLog().info("Requesting %s with %r", endpoint, args) return self.client.get(endpoint, args) funcLog().info("Requesting %s", endpoint) return self.client.get(endpoint)