Ejemplo n.º 1
0
    def save(self, *args, **kwargs):
        created = self.pk is None

        # save the object
        super(Institute, self).save(*args, **kwargs)

        if created:
            log.add(self, 'Created')
        for field in self._tracker.changed():
            log.change(self,
                       'Changed %s to %s' % (field, getattr(self, field)))

        # update the datastore
        from karaage.datastores import machine_category_save_institute
        machine_category_save_institute(self)

        # has group changed?
        if self._tracker.has_changed("group_id"):
            old_group_pk = self._tracker.previous("group_id")
            new_group = self.group
            if old_group_pk is not None:
                old_group = Group.objects.get(pk=old_group_pk)
                from karaage.datastores import remove_accounts_from_institute
                query = Account.objects.filter(person__groups=old_group)
                remove_accounts_from_institute(query, self)
            if new_group is not None:
                from karaage.datastores import add_accounts_to_institute
                query = Account.objects.filter(person__groups=new_group)
                add_accounts_to_institute(query, self)
Ejemplo n.º 2
0
    def save(self, *args, **kwargs):
        created = self.pk is None

        # save the object
        super(Institute, self).save(*args, **kwargs)

        if created:
            log.add(self, 'Created')
        for field in self._tracker.changed():
            log.change(self, 'Changed %s to %s'
                       % (field, getattr(self, field)))

        # update the datastore
        from karaage.datastores import machine_category_save_institute
        machine_category_save_institute(self)

        # has group changed?
        if self._tracker.has_changed("group_id"):
            old_group_pk = self._tracker.previous("group_id")
            new_group = self.group
            if old_group_pk is not None:
                old_group = Group.objects.get(pk=old_group_pk)
                from karaage.datastores import remove_accounts_from_institute
                query = Account.objects.filter(person__groups=old_group)
                remove_accounts_from_institute(query, self)
            if new_group is not None:
                from karaage.datastores import add_accounts_to_institute
                query = Account.objects.filter(person__groups=new_group)
                add_accounts_to_institute(query, self)
Ejemplo n.º 3
0
    def save(self, *args, **kwargs):
        created = self.pk is None

        # save the object
        super(Group, self).save(*args, **kwargs)

        if created:
            log.add(self, 'Created')
        for field in self._tracker.changed():
            log.field_change(self, field=field, new_value=getattr(self, field))

        old_name = self._tracker.previous("name")
        new_name = self.name
        if old_name is not None and old_name != new_name:
            from karaage.datastores import global_set_group_name
            global_set_group_name(self, old_name, new_name)
            from karaage.datastores import machine_category_set_group_name
            machine_category_set_group_name(self, old_name, new_name)
            log.change(self, "Renamed group")

        # update the datastore
        from karaage.datastores import global_save_group
        global_save_group(self)
        from karaage.datastores import machine_category_save_group
        machine_category_save_group(self)
Ejemplo n.º 4
0
 def approve(self, approved_by):
     created_person, created_account = \
         super(ProjectApplication, self).approve(approved_by)
     assert self.applicant is not None
     assert self.content_type.model == "person"
     person = self.applicant
     if self.project is None:
         assert self.institute is not None
         from karaage.projects.utils import get_new_pid
         project = Project(
             pid=self.pid or get_new_pid(self.institute),
             name=self.name,
             description=self.description,
             institute=self.institute,
             additional_req=self.additional_req,
             start_date=datetime.datetime.today(),
             end_date=datetime.datetime.today() +
             datetime.timedelta(days=365),
         )
         project.save()
         project.activate(approved_by)
         self.project = project
         self.save()
     if self.make_leader:
         self.project.leaders.add(person)
     if self.needs_account:
         if not person.has_account():
             log.add(self.application_ptr, 'Created account.')
             Account.create(person, self.project)
             created_account = True
         else:
             log.change(self.application_ptr, 'Account already exists')
     self.project.group.members.add(person)
     return created_person, created_account
Ejemplo n.º 5
0
    def save(self, *args, **kwargs):
        created = self.pk is None

        # save the object
        super(Group, self).save(*args, **kwargs)

        if created:
            log.add(self, 'Created')
        for field in self._tracker.changed():
            log.field_change(self, field=field, new_value=getattr(self, field))

        old_name = self._tracker.previous("name")
        new_name = self.name
        if old_name is not None and old_name != new_name:
            from karaage.datastores import global_set_group_name
            global_set_group_name(self, old_name, new_name)
            from karaage.datastores import machine_category_set_group_name
            machine_category_set_group_name(self, old_name, new_name)
            log.change(self, "Renamed group")

        # update the datastore
        from karaage.datastores import global_save_group
        global_save_group(self)
        from karaage.datastores import machine_category_save_group
        machine_category_save_group(self)
Ejemplo n.º 6
0
    def save(self, *args, **kwargs):
        created = self.pk is None

        with transaction.atomic():
            # set group if not already set
            state = {
                'saved': False,
            }
            if self.group_id is None:
                name = self.pid
                def pre_save(group, obj, _state=state):
                    obj.group_id=group.pk
                    _state['saved'] = True
                self.group, _ = Group.objects.get_or_create_unique(
                    parent=self, name=self.pid,
                    defaults={'description': self.name},
                    pre_parent_save=pre_save,
                )

            if not state['saved']:
                # save the object
                super(Project, self).save(*args, **kwargs)

        if created:
            log.add(self, 'Created')
        for field in self._tracker.changed():
            log.change(self, 'Changed %s to %s'
                       % (field, getattr(self, field)))

        # has pid changed?
        self._tracker.has_changed("pid")
        if self._tracker.has_changed("pid"):
            old_pid = self._tracker.previous('pid')
            if old_pid is not None:
                from karaage.datastores import machine_category_set_project_pid
                machine_category_set_project_pid(self, old_pid, self.pid)
                log.change(self, 'Renamed %s to %s' % (old_pid, self.pid))

        # update the datastore
        from karaage.datastores import machine_category_save_project
        machine_category_save_project(self)

        # has group changed?
        if self._tracker.has_changed("group_id"):
            old_group_pk = self._tracker.previous("group_id")
            new_group = self.group
            if old_group_pk is not None:
                old_group = Group.objects.get(pk=old_group_pk)
                from karaage.datastores import remove_accounts_from_project
                query = Account.objects.filter(person__groups=old_group)
                remove_accounts_from_project(query, self)
            if new_group is not None:
                from karaage.datastores import add_accounts_to_project
                query = Account.objects.filter(person__groups=new_group)
                add_accounts_to_project(query, self)
Ejemplo n.º 7
0
    def save(self, *args, **kwargs):
        created = self.pk is None

        # save the object
        super(Software, self).save(*args, **kwargs)

        if created:
            log.add(self, 'Created')
        for field in self._tracker.changed():
            log.change(self, 'Changed %s to %s'
                       % (field, getattr(self, field)))
Ejemplo n.º 8
0
 def approve(self, approved_by):
     created_person, created_account = \
         super(ProjectApplication, self).approve(approved_by)
     assert self.applicant is not None
     assert self.content_type.model == "person"
     person = self.applicant
     if self.project is None:
         assert self.institute is not None
         from karaage.projects.utils import get_new_pid
         project = Project(
             pid=self.pid or get_new_pid(self.institute),
             name=self.name,
             description=self.description,
             institute=self.institute,
             additional_req=self.additional_req,
             start_date=datetime.datetime.today(),
             end_date=datetime.datetime.today()
             + datetime.timedelta(days=365),
         )
         project.save()
         for mc in self.machine_categories.all():
             project.projectquota_set.create(machine_category=mc)
         project.activate(approved_by)
         self.project = project
         self.save()
     if self.make_leader:
         self.project.add_update_project_members(
             person, is_project_leader=True,
         )
     if self.needs_account:
         found_pc = False
         for pc in self.project.projectquota_set.all():
             found_pc = True
             if not person.has_account(pc.machine_category):
                 log.add(
                     self.application_ptr,
                     'Created account on machine category %s'
                     % pc.machine_category)
                 Account.create(person, self.project, pc.machine_category)
                 created_account = True
             else:
                 log.change(
                     self.application_ptr,
                     'Account on machine category %s already exists'
                     % pc.machine_category)
         if not found_pc:
             log.change(
                 self.application_ptr,
                 'No project quotas found; no accounts created '
                 'despite being requested')
     self.project.group.members.add(person)
     return created_person, created_account
Ejemplo n.º 9
0
def add_license(request, software_id):
    software = get_object_or_404(Software, pk=software_id)

    form = LicenseForm(request.POST or None)
    if request.method == 'POST':
        if form.is_valid():
            l = form.save()
            log.add(software, "license: %s added" % l)
            return HttpResponseRedirect(software.get_absolute_url())

    return render(template_name='kgsoftware/license_form.html',
                  context=locals(),
                  request=request)
Ejemplo n.º 10
0
def join_package(request, software_id):

    software = get_object_or_404(Software, pk=software_id)
    software_license = software.get_current_license()
    person = request.user
    license_agreements = SoftwareLicenseAgreement.objects \
        .filter(person=person, license=software_license)
    agreement = None
    if license_agreements.count() > 0:
        agreement = license_agreements.latest()

    pending = False
    for hook in util.get_hooks('is_approve_join_software_pending'):
        if hook(request, software_license):
            pending = True

    failed = False
    if agreement is None and not pending and request.method == 'POST':
        approved = False

        if not approved and not software.restricted:
            log.add(software, "Approved join (not restricted)")
            approved = True

        if not approved:
            for hook in util.get_hooks('approve_join_software'):
                response = hook(request, software_license)
                if isinstance(response, HttpResponse):
                    return response
                elif bool(response):
                    log.add(software, "Approved join by %s" % hook.__module__)
                    approved = True
                    break

        if approved:
            SoftwareLicenseAgreement.objects.create(
                person=person,
                license=software_license,
                date=datetime.datetime.today(),
                )
            person.add_group(software.group)
            messages.success(request, "Approved access to %s." % software)
            return HttpResponseRedirect(reverse('kg_profile_software'))
        else:
            failed = True
            messages.error(request, "Failed granting access to %s." % software)

    return render_to_response(
        'software/accept_license.html',
        locals(),
        context_instance=RequestContext(request))
Ejemplo n.º 11
0
 def approve(self, approved_by):
     created_person, created_account = \
         super(ProjectApplication, self).approve(approved_by)
     assert self.applicant is not None
     assert self.content_type.model == "person"
     person = self.applicant
     if self.project is None:
         assert self.institute is not None
         from karaage.projects.utils import get_new_pid
         project = Project(
             pid=self.pid or get_new_pid(self.institute),
             name=self.name,
             description=self.description,
             institute=self.institute,
             additional_req=self.additional_req,
             start_date=datetime.datetime.today(),
             end_date=datetime.datetime.today() +
             datetime.timedelta(days=365),
         )
         project.save()
         for mc in self.machine_categories.all():
             project.projectquota_set.create(machine_category=mc)
         project.activate(approved_by)
         self.project = project
         self.save()
     if self.make_leader:
         self.project.leaders.add(person)
     if self.needs_account:
         found_pc = False
         for pc in self.project.projectquota_set.all():
             found_pc = True
             if not person.has_account(pc.machine_category):
                 log.add(
                     self.application_ptr,
                     'Created account on machine category %s' %
                     pc.machine_category)
                 Account.create(person, self.project, pc.machine_category)
                 created_account = True
             else:
                 log.change(
                     self.application_ptr,
                     'Account on machine category %s already exists' %
                     pc.machine_category)
         if not found_pc:
             log.change(
                 self.application_ptr,
                 'No project quotas found; no accounts created '
                 'despite being requested')
     self.project.group.members.add(person)
     return created_person, created_account
Ejemplo n.º 12
0
def add_license(request, software_id):
    software = get_object_or_404(Software, pk=software_id)

    form = LicenseForm(request.POST or None)
    if request.method == 'POST':
        if form.is_valid():
            l = form.save()
            log.add(software, "license: %s added" % l)
            return HttpResponseRedirect(software.get_absolute_url())

    return render(
        template_name='kgsoftware/license_form.html',
        context=locals(),
        request=request)
Ejemplo n.º 13
0
def add_license(request, software_id):
    software = get_object_or_404(Software, pk=software_id)

    form = LicenseForm(request.POST or None)
    if request.method == 'POST':
        if form.is_valid():
            l = form.save()
            log.add(software, "license: %s added" % l)
            return HttpResponseRedirect(software.get_absolute_url())

    return render_to_response(
        'software/license_form.html',
        locals(),
        context_instance=RequestContext(request))
Ejemplo n.º 14
0
    def save(self, *args, **kwargs):
        created = self.pk is None

        # save the object
        super(Person, self).save(*args, **kwargs)

        if created:
            log.add(self, 'Created')
        for field in self._tracker.changed():
            if field != "password":
                log.change(
                    self,
                    'Changed %s to %s' % (field, getattr(self, field)))

        # update datastores
        from karaage.datastores import save_account
        for ua in self.account_set.filter(date_deleted__isnull=True):
            save_account(ua)

        # has locked status changed?
        if self._tracker.has_changed("login_enabled"):
            if self.login_enabled:
                for ua in self.account_set.filter(date_deleted__isnull=True):
                    ua.unlock()
            else:
                for ua in self.account_set.filter(date_deleted__isnull=True):
                    ua.lock()

        # has the institute changed?
        if self._tracker.has_changed("institute_id"):
            from karaage.institutes.models import Institute
            old_institute_pk = self._tracker.previous("institute_id")
            new_institute = self.institute
            if old_institute_pk is not None:
                old_institute = Institute.objects.get(pk=old_institute_pk)
                from karaage.datastores import remove_accounts_from_institute
                query = self.account_set
                remove_accounts_from_institute(query, old_institute)
            if new_institute is not None:
                from karaage.datastores import add_accounts_to_institute
                query = self.account_set
                add_accounts_to_institute(query, new_institute)

        if self._raw_password is not None:
            for ua in self.account_set.filter(date_deleted__isnull=True):
                ua.set_password(self._raw_password)
                ua.save()
            log.change(self, 'Changed Password')
            self._raw_password = None
Ejemplo n.º 15
0
    def save(self, *args, **kwargs):
        created = self.pk is None

        # save the object
        super(Person, self).save(*args, **kwargs)

        if created:
            log.add(self, 'Created')
        for field in self._tracker.changed():
            if field != "password":
                log.change(
                    self,
                    'Changed %s to %s' % (field, getattr(self, field)))

        # update datastores
        from karaage.datastores import save_account
        for ua in self.account_set.filter(date_deleted__isnull=True):
            save_account(ua)

        # has locked status changed?
        if self._tracker.has_changed("login_enabled"):
            if self.login_enabled:
                for ua in self.account_set.filter(date_deleted__isnull=True):
                    ua.unlock()
            else:
                for ua in self.account_set.filter(date_deleted__isnull=True):
                    ua.lock()

        # has the institute changed?
        if self._tracker.has_changed("institute_id"):
            from karaage.institutes.models import Institute
            old_institute_pk = self._tracker.previous("institute_id")
            new_institute = self.institute
            if old_institute_pk is not None:
                old_institute = Institute.objects.get(pk=old_institute_pk)
                from karaage.datastores import remove_accounts_from_institute
                query = self.account_set
                remove_accounts_from_institute(query, old_institute)
            if new_institute is not None:
                from karaage.datastores import add_accounts_to_institute
                query = self.account_set
                add_accounts_to_institute(query, new_institute)

        if self._raw_password is not None:
            for ua in self.account_set.filter(date_deleted__isnull=True):
                ua.set_password(self._raw_password)
                ua.save()
            log.change(self, 'Changed Password')
            self._raw_password = None
Ejemplo n.º 16
0
    def save(self, *args, **kwargs):
        created = self.pk is None

        # save the object
        super(Machine, self).save(*args, **kwargs)

        if created:
            log.add(self, 'Created')
        for field in self._tracker.changed():
            if field == "password":
                log.change(self, 'Changed %s' % field)
            else:
                log.change(
                    self,
                    'Changed %s to %s' % (field, getattr(self, field)))
Ejemplo n.º 17
0
    def save(self, *args, **kwargs):
        created = self.pk is None

        # save the object
        super(MachineCategory, self).save(*args, **kwargs)

        if created:
            log.add(self, 'Created')
        for field in self._tracker.changed():
            log.change(
                self, 'Changed %s to %s' % (field,  getattr(self, field)))

        # check if datastore changed
        if self._tracker.has_changed("datastore"):
            old_datastore = self._tracker.previous("datastore")
            from karaage.datastores import set_mc_datastore
            set_mc_datastore(self, old_datastore, self)
Ejemplo n.º 18
0
def software_detail(request, software_id):
    software = get_object_or_404(Software, pk=software_id)
    software_license = software.get_current_license()
    person = request.user
    license_agreements = SoftwareLicenseAgreement.objects \
        .filter(person=person, license=software_license)
    agreement = None
    if license_agreements.count() > 0:
        agreement = license_agreements.latest()

    # we only list applications for current software license

    applications = SoftwareApplication.objects.filter(
        software_license__software=software_license)
    applications = applications.exclude(state='C')
    applications_table = ApplicationTable(applications)
    config = tables.RequestConfig(request, paginate={"per_page": 5})
    config.configure(applications_table)

    open_applications = SoftwareApplication.objects.get_for_applicant(person)
    open_applications = open_applications.filter(
        software_license=software_license)

    if agreement is None and software_license is not None \
            and len(open_applications) == 0 and request.method == 'POST':

        if software.restricted and not util.is_admin(request):
            log.add(software, "New application created for %s" % request.user)
            return new_application(request, software_license)

        SoftwareLicenseAgreement.objects.create(
            person=person,
            license=software_license,
            date=datetime.datetime.today(),
        )
        person.add_group(software.group)
        log.add(
            software,
            "Approved join (not restricted) for %s" % request.user)
        messages.success(request, "Approved access to %s." % software)
        return HttpResponseRedirect(reverse('kg_profile_software'))

    return render_to_response(
        'kgsoftware/software_detail.html',
        locals(),
        context_instance=RequestContext(request))
Ejemplo n.º 19
0
    def save(self, *args, **kwargs):
        created = self.pk is None

        # save the object
        super(MachineCategory, self).save(*args, **kwargs)

        if created:
            log.add(self, 'Created')
        for field in self._tracker.changed():
            log.change(self,
                       'Changed %s to %s' % (field, getattr(self, field)))

        # check if datastore changed
        if self._tracker.has_changed("datastore"):
            old_datastore = self._tracker.previous("datastore")
            from karaage.datastores import set_mc_datastore
            set_mc_datastore(self, old_datastore, self)
Ejemplo n.º 20
0
    def save(self, *args, **kwargs):
        created = self.pk is None
        if not self.pk:
            self.created_by = get_current_person()
            self.expires = datetime.datetime.now() + datetime.timedelta(days=7)
            parent = list(self._meta.parents.keys())[0]
            subclasses = parent._meta.get_all_related_objects()
            for klass in subclasses:
                if isinstance(klass, RelatedObject) and klass.field.primary_key and klass.opts == self._meta:
                    self._class = klass.get_accessor_name()
                    break

        super(Application, self).save(*args, **kwargs)

        if created:
            log.add(self, "Created")
        for field in self._tracker.changed():
            log.change(self, "Changed %s to %s" % (field, getattr(self, field)))
Ejemplo n.º 21
0
    def save(self, *args, **kwargs):
        created = self.pk is None

        # set group if not already set
        if self.group_id is None:
            name = self.pid
            self.group, _ = Group.objects.get_or_create(name=name)

        # save the object
        super(Project, self).save(*args, **kwargs)

        if created:
            log.add(self, 'Created')
        for field in self._tracker.changed():
            log.change(self, 'Changed %s to %s'
                       % (field, getattr(self, field)))

        # has pid changed?
        self._tracker.has_changed("pid")
        if self._tracker.has_changed("pid"):
            old_pid = self._tracker.previous('pid')
            if old_pid is not None:
                from karaage.datastores import set_project_pid
                set_project_pid(self, old_pid, self.pid)
                log.change(self, 'Renamed %s to %s' % (old_pid, self.pid))

        # update the datastore
        from karaage.datastores import save_project
        save_project(self)

        # has group changed?
        if self._tracker.has_changed("group_id"):
            old_group_pk = self._tracker.previous("group_id")
            new_group = self.group
            if old_group_pk is not None:
                old_group = Group.objects.get(pk=old_group_pk)
                from karaage.datastores import remove_accounts_from_project
                query = Account.objects.filter(person__groups=old_group)
                remove_accounts_from_project(query, self)
            if new_group is not None:
                from karaage.datastores import add_accounts_to_project
                query = Account.objects.filter(person__groups=new_group)
                add_accounts_to_project(query, self)
Ejemplo n.º 22
0
    def save(self, *args, **kwargs):
        created = self.pk is None

        # set group if not already set
        if self.group_id is None:
            name = self.pid
            self.group, _ = Group.objects.get_or_create(name=name)

        # save the object
        super(Project, self).save(*args, **kwargs)

        if created:
            log.add(self, 'Created')
        for field in self._tracker.changed():
            log.change(self,
                       'Changed %s to %s' % (field, getattr(self, field)))

        # has pid changed?
        self._tracker.has_changed("pid")
        if self._tracker.has_changed("pid"):
            old_pid = self._tracker.previous('pid')
            if old_pid is not None:
                from karaage.datastores import set_project_pid
                set_project_pid(self, old_pid, self.pid)
                log.change(self, 'Renamed %s to %s' % (old_pid, self.pid))

        # update the datastore
        from karaage.datastores import save_project
        save_project(self)

        # has group changed?
        if self._tracker.has_changed("group_id"):
            old_group_pk = self._tracker.previous("group_id")
            new_group = self.group
            if old_group_pk is not None:
                old_group = Group.objects.get(pk=old_group_pk)
                from karaage.datastores import remove_accounts_from_project
                query = Account.objects.filter(person__groups=old_group)
                remove_accounts_from_project(query, self)
            if new_group is not None:
                from karaage.datastores import add_accounts_to_project
                query = Account.objects.filter(person__groups=new_group)
                add_accounts_to_project(query, self)
Ejemplo n.º 23
0
    def save(self, *args, **kwargs):
        created = self.pk is None
        if not self.expires:
            self.expires = datetime.datetime.now() + datetime.timedelta(days=7)
        if not self.pk:
            self.created_by = get_current_person()

            # Find the accessor from Application to type(self) class
            if hasattr(Application._meta, 'get_fields'):
                # Django >= 1.8
                fields = [
                    f for f in Application._meta.get_fields()
                    if isinstance(f, OneToOneRel) and
                    f.field.primary_key and
                    f.auto_created
                ]

            else:
                # Django <= 1.8
                fields = [
                    f for f in Application._meta.get_all_related_objects()
                    if isinstance(f, OneToOneRel) and
                    f.field.primary_key
                ]

            for rel in fields:
                # Works with Django < 1.8 and => 1.8
                related_model = getattr(rel, 'related_model', rel.model)

                # if we find it, save the name
                if related_model == type(self):
                    self._class = rel.get_accessor_name()
                    break

        super(Application, self).save(*args, **kwargs)

        if created:
            log.add(self, 'Created')
        for field in self._tracker.changed():
            log.change(
                self,
                'Changed %s to %s' % (field, getattr(self, field)))
Ejemplo n.º 24
0
    def save(self, *args, **kwargs):
        created = self.pk is None

        super(InstituteQuota, self).save(*args, **kwargs)

        if created:
            log.add(self.institute,
                    'Quota %s: Created' % self.machine_category)
        for field in self._tracker.changed():
            log.change(
                self.institute, 'Quota %s: Changed %s to %s' %
                (self.machine_category, field, getattr(self, field)))

        from karaage.datastores import machine_category_save_institute
        machine_category_save_institute(self.institute)

        if created:
            from karaage.datastores import add_accounts_to_institute
            query = Account.objects.filter(person__groups=self.institute.group)
            add_accounts_to_institute(query, self.institute)
Ejemplo n.º 25
0
 def approve(self, approved_by):
     created_person, created_account = \
         super(ProjectApplication, self).approve(approved_by)
     assert self.applicant is not None
     assert self.content_type.model == "person"
     person = self.applicant
     if self.project is None:
         assert self.institute is not None
         from karaage.projects.utils import get_new_pid
         project = Project(
             pid=self.pid or get_new_pid(self.institute),
             name=self.name,
             description=self.description,
             institute=self.institute,
             additional_req=self.additional_req,
             start_date=datetime.datetime.today(),
             end_date=datetime.datetime.today() +
             datetime.timedelta(days=365),
         )
         project.save()
         project.activate(approved_by)
         self.project = project
         self.save()
     if self.make_leader:
         self.project.leaders.add(person)
     if self.needs_account:
         if not person.has_account():
             log.add(
                 self.application_ptr,
                 'Created account.'
             )
             Account.create(person, self.project)
             created_account = True
         else:
             log.change(
                 self.application_ptr,
                 'Account already exists'
             )
     self.project.group.members.add(person)
     return created_person, created_account
Ejemplo n.º 26
0
    def save(self, *args, **kwargs):
        created = self.pk is None
        if not self.expires:
            self.expires = datetime.datetime.now() + datetime.timedelta(days=7)
        if not self.pk:
            self.created_by = get_current_person()

            # Find the accessor from Application to type(self) class
            if hasattr(Application._meta, 'get_fields'):
                # Django >= 1.8
                fields = [
                    f for f in Application._meta.get_fields()
                    if isinstance(f, OneToOneRel) and f.field.primary_key
                    and f.auto_created
                ]

            else:
                # Django <= 1.8
                fields = [
                    f for f in Application._meta.get_all_related_objects()
                    if isinstance(f, OneToOneRel) and f.field.primary_key
                ]

            for rel in fields:
                # Works with Django < 1.8 and => 1.8
                related_model = getattr(rel, 'related_model', rel.model)

                # if we find it, save the name
                if related_model == type(self):
                    self._class = rel.get_accessor_name()
                    break

        super(Application, self).save(*args, **kwargs)

        if created:
            log.add(self, 'Created')
        for field in self._tracker.changed():
            log.change(self,
                       'Changed %s to %s' % (field, getattr(self, field)))
Ejemplo n.º 27
0
def software_detail(request, software_id):
    software = get_object_or_404(Software, pk=software_id)
    software_license = software.get_current_license()
    person = request.user
    license_agreements = SoftwareLicenseAgreement.objects \
        .filter(person=person, license=software_license)
    agreement = None
    if license_agreements.count() > 0:
        agreement = license_agreements.latest()

    # we only list applications for current software license

    applications = get_applications(software_license)
    application_table = get_application_table(request, applications)
    open_applications = get_applications_for_person(person, software_license)

    if agreement is None and software_license is not None \
            and len(open_applications) == 0 and request.method == 'POST':

        if software.restricted and not util.is_admin(request):
            log.add(software, "New application created for %s" % request.user)
            return new_application(request, software_license)

        SoftwareLicenseAgreement.objects.create(
            person=person,
            license=software_license,
            date=datetime.datetime.today(),
        )
        person.add_group(software.group)
        log.add(
            software,
            "Approved join (not restricted) for %s" % request.user)
        messages.success(request, "Approved access to %s." % software)
        return HttpResponseRedirect(reverse('kg_profile_software'))

    return render(
        template_name='kgsoftware/software_detail.html',
        context=locals(),
        request=request)
Ejemplo n.º 28
0
def software_detail(request, software_id):
    software = get_object_or_404(Software, pk=software_id)
    software_license = software.get_current_license()
    person = request.user
    license_agreements = SoftwareLicenseAgreement.objects \
        .filter(person=person, license=software_license)
    agreement = None
    if license_agreements.count() > 0:
        agreement = license_agreements.latest()

    # we only list applications for current software license

    applications = get_applications(software_license)
    application_table = get_application_table(request, applications)
    open_applications = get_applications_for_person(person, software_license)

    if agreement is None and software_license is not None \
            and len(open_applications) == 0 and request.method == 'POST':

        if software.restricted and not util.is_admin(request):
            log.add(software, "New application created for %s" % request.user)
            return new_application(request, software_license)

        SoftwareLicenseAgreement.objects.create(
            person=person,
            license=software_license,
            date=datetime.datetime.today(),
        )
        person.add_group(software.group)
        log.add(
            software,
            "Approved join (not restricted) for %s" % request.user)
        messages.success(request, "Approved access to %s." % software)
        return HttpResponseRedirect(reverse('kg_profile_software'))

    return render(
        template_name='kgsoftware/software_detail.html',
        context=locals(),
        request=request)
Ejemplo n.º 29
0
    def save(self, *args, **kwargs):
        created = self.pk is None

        super(InstituteQuota, self).save(*args, **kwargs)

        if created:
            log.add(
                self.institute,
                'Quota %s: Created' % self.machine_category)
        for field in self._tracker.changed():
            log.change(
                self.institute,
                'Quota %s: Changed %s to %s' %
                (self.machine_category, field, getattr(self, field)))

        from karaage.datastores import machine_category_save_institute
        machine_category_save_institute(self.institute)

        if created:
            from karaage.datastores import add_accounts_to_institute
            query = Account.objects.filter(person__groups=self.institute.group)
            add_accounts_to_institute(query, self.institute)
Ejemplo n.º 30
0
    def save(self, *args, **kwargs):
        created = self.pk is None
        if not self.pk:
            self.created_by = get_current_person()
            self.expires = datetime.datetime.now() + datetime.timedelta(days=7)
            parent = list(self._meta.parents.keys())[0]
            subclasses = parent._meta.get_all_related_objects()
            for klass in subclasses:
                if isinstance(klass, RelatedObject) \
                        and klass.field.primary_key \
                        and klass.opts == self._meta:
                    self._class = klass.get_accessor_name()
                    break

        super(Application, self).save(*args, **kwargs)

        if created:
            log.add(self, 'Created')
        for field in self._tracker.changed():
            log.change(
                self,
                'Changed %s to %s' % (field, getattr(self, field)))
Ejemplo n.º 31
0
    def save(self, *args, **kwargs):
        created = self.pk is None

        # save the object
        super(Account, self).save(*args, **kwargs)

        if created:
            log.add(
                self.person,
                'Account %s: Created' % self)
        for field in self._tracker.changed():
            if field != "password":
                log.change(
                    self.person,
                    'Account %s: Changed %s to %s'
                    % (self, field, getattr(self, field)))

        # check if it was renamed
        if self._tracker.has_changed('username'):
            old_username = self._tracker.previous('username')
            if old_username is not None:
                new_username = self.username
                if self.date_deleted is None:
                    from karaage.datastores import set_account_username
                    set_account_username(self, old_username, new_username)
                log.change(
                    self.person,
                    'Account %s: Changed username from %s to %s' %
                    (self, old_username, new_username))

        # check if deleted status changed
        if self._tracker.has_changed('date_deleted'):
            if self.date_deleted is not None:
                # account is deactivated
                from karaage.datastores import delete_account
                delete_account(self)
                log.delete(
                    self.person,
                    'Account %s: Deactivated account' % self)
                # deleted
            else:
                # account is reactivated
                log.add(
                    self.person,
                    'Account %s: Activated' % self)

        # makes sense to lock non-existant account
        if self.date_deleted is not None:
            self.login_enabled = False

        # update the datastore
        if self.date_deleted is None:
            from karaage.datastores import save_account
            save_account(self)

            if self._password is not None:
                from karaage.datastores import set_account_password
                set_account_password(self, self._password)
                log.change(
                    self.person,
                    'Account %s: Changed Password' % self)
                self._password = None
Ejemplo n.º 32
0
def project_application_approve(request, token):
    """
    Must manually set fairshare, disk and e-mail user.
    """
    project_application = get_object_or_404(ProjectApplication,
                                            secret_token=token)

    if project_application.state in [
            ProjectApplication.COMPLETE, ProjectApplication.ARCHIVED
    ]:
        messages.error(request, "This application has already been approved")
        return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
    if project_application.state == ProjectApplication.DECLINED:
        messages.error(request, "This application was delined")
        return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
    if project_application.state != ProjectApplication.WAITING_FOR_ADMIN:
        messages.error(request, "Only submitted applications can be approved")
        return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

    # by default lookup requested associated project, unless admin looks up
    # different project
    associated = None
    if request.method == 'POST':
        post = request.POST.copy()
        if 'proj_try' in post.keys():
            associated = post['proj_try']

    initial = {
        'proj_try': '',
        'proj_title': project_application.title,
        'proj_desc': project_application.summary,
        'host': '',
        'faculty': None,
        'school': None
    }
    try:
        proj_try = Project.objects.get(pid=associated)
        initial['proj_try'] = proj_try.pid
    except Project.DoesNotExist:
        proj_try = None

    proj_ids = Project.objects.values_list('pid', flat=True)

    queryset = ProjectApplicationMember.objects.filter(
        project_application=project_application)
    # should only be one of supervisor and applicant
    supervisor = queryset.get(is_supervisor=True)
    applicant = queryset.get(is_applicant=True)
    # any other leaders
    leaders = queryset.filter(project_application=project_application,
                              is_leader=True,
                              is_supervisor=False,
                              is_applicant=False)
    members = [supervisor]
    if applicant != supervisor:
        members.append(applicant)
    for leader in leaders:
        members.append(leader)

    # Institute must exist before Approval
    try:
        host = Institute.objects.get(name__exact=supervisor.institute)
        initial['host'] = host
    except Institute.DoesNotExist:
        messages.error(request,
                       "Fix/Create the host institute before Approving")
        return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

    # pass list to javascript
    inst_fac_sch = ProjectApplicationFaculty.objects.all()
    all_choices = {}
    for item in inst_fac_sch:
        all_choices.setdefault(item.institute.id,
                               {}).setdefault(item.faculty,
                                              []).append(item.school)

    # Add data entered for supervisor
    inst = Institute.objects.get(name__iexact=supervisor.institute).id
    fac = supervisor.faculty
    sch = supervisor.department
    initial['faculty'] = fac
    initial['school'] = sch
    if ((inst not in all_choices) or (fac not in all_choices[inst])
            or (sch not in all_choices[inst][fac])):
        all_choices.setdefault(inst, {}).setdefault(fac, []).append(sch)

    all_choices = json.dumps(all_choices)

    if request.method == 'POST':
        form = ProjectApplicationApproveForm(request.POST, initial=initial)
        if form.is_valid() and 'approve' in request:
            data = form.cleaned_data

            new_text = u'\nProject Application approved on: %s\n' % datetime.date.today(
            ).strftime('%d, %b %Y')
            new_text += u'Approved by %s' % request.user
            new_text += u'Application number: %s (%s)\n' % (
                project_application.id,
                request.build_absolute_uri(
                    reverse('view_project_application',
                            args=[project_application.id])))
            new_text += u'Supervisor: %s\n' % supervisor.get_full_name()
            new_text += u'Host: %s, %s, %s\n' % (
                data['host'].name, data['faculty'], data['school'])

            proj_try_data = data['proj_try'].upper()
            try:
                project = Project.objects.get(pid=proj_try_data)
                created = False
                ## TODO: need to check institute hasn't changed
                ## Warn, confirm change of host!!!
                prev_leaders = ', '.join([
                    leader.get_full_name() for leader in project.leaders.all()
                ])
                new_text += u'Previous Title: %s\n' % project.name
                new_text += u'Previous Leaders: %s\n' % prev_leaders
                new_text += u'Previous Host: %s\n' % project.institute
                new_text += u'Previous Description: %s\n\n' % project.description
            except (Project.DoesNotExist, Project.IntegrityError):
                project = Project(pid=proj_try_data, institute=data['host'])
                project.save()
                # add approving admin as leader of new project
                project.leaders.add(request.user)
                created = True

            project.additional_req = '%s%s' % (new_text,
                                               (project.additional_req or ''))
            project.name = data['proj_title']
            project.description = data['proj_desc']
            project.institute = data['host']
            project.save()
            ProjectQuota.objects.get_or_create(
                project=project,
                machine_category=MachineCategory.objects.get_default())
            project.activate(request.user)
            project.save()
            project_application.project = project
            project_application.host_institute = data[
                'host'].name  ## save name for archiving
            project_application.host_faculty = data['faculty']
            project_application.host_school = data['school']
            project_application.state = ProjectApplication.COMPLETE
            project_application.save()
            # save faculty and school in case they are new
            ProjectApplicationFaculty.objects.get_or_create(
                institute=data['host'],
                faculty=data['faculty'],
                school=data['school'])
            log.add(project_application, 'Approved by %s' % request.user)
            messages.info(request, "%s approved" % project_application)
            return HttpResponseRedirect(reverse('project_application_list'))
    else:
        form = ProjectApplicationApproveForm(initial=initial)

    return render(
        request,
        'project_application/admin_confirm_approve.html',
        {
            'project_application': project_application,
            'proj_try': proj_try,
            'host': host,
            'faculty': fac,
            'school': sch,
            'all_choices': all_choices,
            'members': members,
            'proj_ids': proj_ids,
            'form': form
        },
    )
Ejemplo n.º 33
0
    def save(self, *args, **kwargs):
        created = self.pk is None

        # save the object
        super(Account, self).save(*args, **kwargs)

        if created:
            log.add(
                self.person,
                'Account %s: Created on %s' % (self, self.machine_category))
            log.add(
                self.machine_category,
                'Account %s: Created on %s' % (self, self.machine_category))
        for field in self._tracker.changed():
            if field != "password":
                log.change(
                    self.person, 'Account %s: Changed %s to %s' %
                    (self, field, getattr(self, field)))
                log.change(
                    self.machine_category, 'Account %s: Changed %s to %s' %
                    (self, field, getattr(self, field)))

        # check if machine_category changed
        moved = False
        if self._tracker.has_changed('machine_category_id'):
            old_machine_category_pk = self._tracker.previous(
                'machine_category_id')
            if old_machine_category_pk is not None:
                old_machine_category = MachineCategory.objects.get(
                    pk=old_machine_category_pk)
                old_username = self._tracker.previous('username')

                new_machine_category = self.machine_category
                new_username = self.username

                # set old values so we can delete old datastore
                self.machine_category = old_machine_category
                self.username = old_username

                from karaage.datastores import machine_category_delete_account
                machine_category_delete_account(self)
                log.change(self.person, 'Account %s: Removed account' % self)
                log.change(self.machine_category,
                           'Account %s: Removed account' % self)

                # set new values again
                self.machine_category = new_machine_category
                self.username = new_username

                log.change(self.person, 'Account %s: Added account' % self)
                log.change(self.machine_category,
                           'Account %s: Added account' % self)

                moved = True

        # check if it was renamed
        if self._tracker.has_changed('username'):
            old_username = self._tracker.previous('username')
            if old_username is not None:
                new_username = self.username
                if self.date_deleted is None and not moved:
                    from karaage.datastores \
                        import machine_category_set_account_username
                    machine_category_set_account_username(
                        self, old_username, new_username)
                log.change(
                    self.person, 'Account %s: Changed username from %s to %s' %
                    (self, old_username, new_username))
                log.change(
                    self.machine_category,
                    'Account %s: Changed username from %s to %s' %
                    (self, old_username, new_username))

        # check if deleted status changed
        if self._tracker.has_changed('date_deleted'):
            if self.date_deleted is not None:
                # account is deactivated
                from karaage.datastores import machine_category_delete_account
                machine_category_delete_account(self)
                log.delete(self.person,
                           'Account %s: Deactivated account' % self)
                log.delete(self.machine_category,
                           'Account %s: Deactivated account' % self)
                # deleted
            else:
                # account is reactivated
                log.add(self.person, 'Account %s: Activated' % self)
                log.add(self.machine_category, 'Account %s: Activated' % self)

        # makes sense to lock non-existant account
        if self.date_deleted is not None:
            self.login_enabled = False

        # update the datastore
        if self.date_deleted is None:
            from karaage.datastores import machine_category_save_account
            machine_category_save_account(self)

            if self._password is not None:
                from karaage.datastores \
                    import machine_category_set_account_password
                machine_category_set_account_password(self, self._password)
                log.change(self.person, 'Account %s: Changed Password' % self)
                log.change(self.machine_category,
                           'Account %s: Changed Password' % self)
                self._password = None
Ejemplo n.º 34
0
    def save(self, *args, **kwargs):
        created = self.pk is None

        # save the object
        super(Account, self).save(*args, **kwargs)

        if created:
            log.add(
                self.person,
                'Account %s: Created on %s' % (self, self.machine_category))
            log.add(
                self.machine_category,
                'Account %s: Created on %s' % (self, self.machine_category))
        for field in self._tracker.changed():
            if field != "password":
                log.change(
                    self.person,
                    'Account %s: Changed %s to %s'
                    % (self, field,  getattr(self, field)))
                log.change(
                    self.machine_category,
                    'Account %s: Changed %s to %s'
                    % (self, field,  getattr(self, field)))

        # check if machine_category changed
        moved = False
        if self._tracker.has_changed('machine_category_id'):
            old_machine_category_pk = self._tracker.previous(
                'machine_category_id')
            if old_machine_category_pk is not None:
                old_machine_category = MachineCategory.objects.get(
                    pk=old_machine_category_pk)
                old_username = self._tracker.previous('username')

                new_machine_category = self.machine_category
                new_username = self.username

                # set old values so we can delete old datastore
                self.machine_category = old_machine_category
                self.username = old_username

                from karaage.datastores import machine_category_delete_account
                machine_category_delete_account(self)
                log.change(
                    self.person,
                    'Account %s: Removed account' % self)
                log.change(
                    self.machine_category,
                    'Account %s: Removed account' % self)

                # set new values again
                self.machine_category = new_machine_category
                self.username = new_username

                log.change(
                    self.person,
                    'Account %s: Added account' % self)
                log.change(
                    self.machine_category,
                    'Account %s: Added account' % self)

                moved = True

        # check if it was renamed
        if self._tracker.has_changed('username'):
            old_username = self._tracker.previous('username')
            if old_username is not None:
                new_username = self.username
                if self.date_deleted is None and not moved:
                    from karaage.datastores \
                        import machine_category_set_account_username
                    machine_category_set_account_username(
                        self, old_username, new_username)
                log.change(
                    self.person,
                    'Account %s: Changed username from %s to %s' %
                    (self, old_username, new_username))
                log.change(
                    self.machine_category,
                    'Account %s: Changed username from %s to %s' %
                    (self, old_username, new_username))

        # check if deleted status changed
        if self._tracker.has_changed('date_deleted'):
            if self.date_deleted is not None:
                # account is deactivated
                from karaage.datastores import machine_category_delete_account
                machine_category_delete_account(self)
                log.delete(
                    self.person,
                    'Account %s: Deactivated account' % self)
                log.delete(
                    self.machine_category,
                    'Account %s: Deactivated account' % self)
                # deleted
            else:
                # account is reactivated
                log.add(
                    self.person,
                    'Account %s: Activated' % self)
                log.add(
                    self.machine_category,
                    'Account %s: Activated' % self)

        # makes sense to lock non-existant account
        if self.date_deleted is not None:
            self.login_enabled = False

        # update the datastore
        if self.date_deleted is None:
            from karaage.datastores import machine_category_save_account
            machine_category_save_account(self)

            if self._password is not None:
                from karaage.datastores \
                    import machine_category_set_account_password
                machine_category_set_account_password(self, self._password)
                log.change(
                    self.person,
                    'Account %s: Changed Password' % self)
                log.change(
                    self.machine_category,
                    'Account %s: Changed Password' % self)
                self._password = None