Exemple #1
0
 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
Exemple #2
0
 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
Exemple #3
0
 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
Exemple #4
0
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)
Exemple #5
0
    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
      ),]
Exemple #6
0
  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})
Exemple #7
0
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()
Exemple #8
0
 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))
Exemple #9
0
 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
Exemple #10
0
 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
Exemple #11
0
 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
Exemple #12
0
 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
Exemple #13
0
 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)
Exemple #14
0
 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)
Exemple #15
0
 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)
Exemple #16
0
 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})
Exemple #17
0
 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)
Exemple #18
0
 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
Exemple #19
0
  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)
Exemple #20
0
    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
      ),]
Exemple #21
0
  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())
Exemple #22
0
 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)
Exemple #23
0
 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)
Exemple #24
0
 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
Exemple #25
0
 def createGroup(self, name):
   funcLog().info("Creating group %s", name)
   group = Group.objects.create(name=name)
   return group
Exemple #26
0
 def login(self):
   funcLog().info("Logging in with test user")
   self.client.login(username=self.user.username, password=self.password)
Exemple #27
0
 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)