Example #1
0
    def form_valid(self, form):
        self.source = BlacklistSource.objects.get(id=1)
        self.expiry = form.cleaned_data.get('expiry_date', None)
        if not self.expiry:
            self.expiry = now() + timedelta(days=50*365) # 50 year default
        self.level = form.cleaned_data.get('level', 0)
        self.reason = form.cleaned_data.get('reason', 'No reason provided')

        # Blacklist email address
        self.blacklist_item(BLACKLIST_TYPE_EMAIL, self.blacklist_user.email)

        # Blacklist API keys
        for account in self.blacklist_user.eveaccount_set.all():
            self.blacklist_item(BLACKLIST_TYPE_APIUSERID, account.api_user_id)

        # Blacklist Characters
        for character in EVEPlayerCharacter.objects.filter(eveaccount__user=self.blacklist_user).distinct():
            self.blacklist_item(BLACKLIST_TYPE_CHARACTER, character.name)

        # Blacklist Reddit accounts
        if installed('reddit'):
            for account in self.blacklist_user.redditaccount_set.all():
                self.blacklist_item(BLACKLIST_TYPE_REDDIT, account.username)

        messages.add_message(self.request, messages.INFO, "User %s has been blacklisted" % self.blacklist_user.username )

        # Disable the account if requested
        if form.cleaned_data.get('disable', None) and self.request.user.has_perm('auth.change_user') and self.request.user.has_perm('sso.delete_serviceaccount'):
            self.blacklist_user.active = False
            self.blacklist_user.save()
            messages.add_message(self.request, messages.INFO, "User %s disabled" % self.blacklist_user.username)

        update_user_access.delay(user=self.blacklist_user.id)

        return HttpResponseRedirect(reverse('sso-viewuser', args=[self.blacklist_user.username]))
Example #2
0
    def handle(self, **options):

        if not options.get('alliance', None) and not options.get('corporation', None):
            raise CommandError("Please provide either a corporation or alliance")

        if options.get('alliance', None) and options.get('corporation', None):
            raise CommandError("Use either alliance or corporation, not both")

        if not options.get('group', None):
            raise CommandError("You need to specify a domain")

        alliance = options.get('alliance', None)
        corporation = options.get('corporation', None)
        group = Group.objects.get(id=options.get('group'))

        args = {'eveaccount__api_status': API_STATUS_OK}

        if alliance:
            args['eveaccount__characters__corporation__alliance__id'] = alliance
        elif corporation:
            args['eveaccount__characters__corporation__id'] = corporation

        users = User.objects.select_related('groups').filter(**args).exclude(groups__id=group.id).distinct()
        print "%s user(s) to update." % users.count()
        for user in users:
            if not group in user.groups.all():
                user.groups.add(group)
                update_user_access.delay(user.id)
        print "Done."
Example #3
0
 def user_update_access(self, request, queryset):
     for obj in queryset:
         update_user_access.delay(obj.id)
     if queryset.count() == 1:
         message_bit = '1 user'
     else:
         message_bit = '%s users' % queryset.count()
     self.message_user(request, "%s queued for updating." % message_bit)
Example #4
0
def accept_request(request, requestid, email_text_template='groups/email/accepted.txt', email_html_template='groups/email/accepted.html'):

    obj = get_object_or_404(GroupRequest, id=requestid)

    if request.user in obj.group.groupinformation.admins.all() or request.user.is_superuser:
        obj.status = REQUEST_ACCEPTED
        obj.user.groups.add(obj.group)
        obj.changed_by = request.user
        obj.save()
        update_user_access.delay(obj.user.id)

        messages.add_message(request, messages.INFO, "%s has been accepted into %s" % (obj.user, obj.group))
        send_group_email(obj, [obj.user.email], '[Auth] Your membership to %s has been accepted.' % obj.group.name, email_text_template, email_html_template)

    return HttpResponseRedirect(reverse('groups.views.admin_group', args=[obj.group.id]))
Example #5
0
    def handle_noargs(self, **options):
        g = Group.objects.get(name="Alliance Directors")

        users = []
        for char in EVEPlayerCharacter.objects.filter(corporation__alliance__name="Test Alliance Please Ignore",roles__name="roleDirector"):
            if char.eveaccount_set.count() and char.eveaccount_set.all()[0].user and not (char.corporation.group and char.corporation.group.id in settings.IGNORE_CORP_GROUPS):
                users.append(char.eveaccount_set.all()[0].user)

        add = set(users) - set(g.user_set.all())
        rem = set(g.user_set.all()) - set(users)

        for m in rem:
            m.groups.remove(g)
            update_user_access.delay(m.id)

        for m in add:
            m.groups.add(g)
            update_user_access.delay(m.id)
Example #6
0
def create_request(request, groupid, email_text_template='groups/email/request.txt', email_html_template='groups/email/request.html'):

    group = get_object_or_404(Group, id=groupid)

    if request.user in group.user_set.all() or not group.groupinformation.requestable:
        return HttpResponseRedirect(reverse('groups.views.group_list'))

    if group.groupinformation.parent_groups.count() and not set(group.groupinformation.parent_groups.all()) & set(request.user.groups.all()):
       return HttpResponseRedirect(reverse('groups.views.group_list'))

    if group.requests.filter(status=REQUEST_PENDING,user=request.user).count():
        messages.add_message(request, messages.INFO, "You already have a pending request for %s" % group.name)
        return HttpResponseRedirect(reverse('groups.views.group_list'))

    if not group.groupinformation.moderated:
        # Unmoderated group, so accept the application
        request.user.groups.add(group)
        update_user_access.delay(request.user.id)
        messages.add_message(request, messages.INFO, "You are now a member of %s" % (group))
        return HttpResponseRedirect(reverse('groups.views.group_list'))

    if request.method == 'POST':
        form = GroupRequestForm(request.POST)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.user = request.user
            obj.group = group
            obj.changed_by = request.user
            obj.save()

            messages.add_message(request, messages.INFO, "You membership request has been created.")
            to_email = obj.group.groupinformation.admins.values_list('email', flat=True)
            # If no group admins are set, send to the superusers
            if len(to_email) == 0:
                to_email = User.objects.filter(is_superuser=True).values_list('email', flat=True)
            send_group_email(obj, to_email, '[Auth] %s has requested membership to %s' % (obj.user.username, obj.group.name), email_text_template, email_html_template)

            return HttpResponseRedirect(reverse('groups.views.group_list')) # Redirect after POST
    else:
        form = GroupRequestForm() # An unbound form

    return render_to_response('groups/create_request.html', locals(), context_instance=RequestContext(request))
Example #7
0
def kick_member(request, groupid, userid):

    group = get_object_or_404(Group, id=groupid)
    user = get_object_or_404(User, id=userid)

    if not group.groupinformation.type in [GROUP_TYPE_MANAGED]:
        if user == request.user:
            if user in group.groupinformation.admins.all():
                group.groupinformation.admins.remove(user)
            user.groups.remove(group)
            update_user_access.delay(user.id)
            messages.add_message(request, messages.INFO, "You have left the group %s" % group.name)

        elif request.user in group.groupinformation.admins.all() or request.user.is_superuser:
            if not user in group.groupinformation.admins.all():
                user.groups.remove(group)
                update_user_access.delay(user.id)
                messages.add_message(request, messages.INFO, "%s has been removed from %s." % (user.username, group.name))
            else:
                messages.add_message(request, messages.INFO, "%s is a admin of %s and cannot be removed." % (user.username, group.name))

            return HttpResponseRedirect(reverse('groups.views.admin_group', args=[groupid]))

    return HttpResponseRedirect(reverse('groups.views.group_list'))
Example #8
0
def import_apikey_func(api_userid, api_key, user=None, force_cache=False, log=logging.getLogger(__name__)):
    log.debug('Importing %s/%s' % (api_userid, api_key))

    try:
        account = EVEAccount.objects.get(pk=api_userid)
    except EVEAccount.DoesNotExist:
        account = None

    # Use CAK if enabled and either a new key or flagged as so
    if (gargoyle.is_active('eve-cak') and (not account or account.is_cak)):
        auth_params = {'keyid': api_userid, 'vcode': api_key}
        keycheck = CachedDocument.objects.api_query('/account/APIKeyInfo.xml.aspx', params=auth_params, no_cache=True)
        doc = basic_xml_parse_doc(keycheck)['eveapi']

        if not 'error' in doc:
            if not account:
                account, created = EVEAccount.objects.get_or_create(pk=api_userid)
                if user:
                    account.user = User.objects.get(id=user)
            if not account.api_key == api_key:
                account.api_key = api_key

            keydoc = doc['result']['key']
            if keydoc['type'] == 'Character':
                account.api_keytype = API_KEYTYPE_CHARACTER
            elif keydoc['type'] == 'Corporation':
                account.api_keytype = API_KEYTYPE_CORPORATION
            elif keydoc['type'] == 'Account':
                account.api_keytype = API_KEYTYPE_ACCOUNT
            account.api_accessmask = int(keydoc['accessMask'])
            if not keydoc['expires'] == '':
                account.api_expiry = datetime.strptime(keydoc['expires'], '%Y-%m-%d %H:%M:%S').replace(tzinfo=utc)

            # Checks account status to see if the account is still active
            if not account.api_keytype == API_KEYTYPE_CORPORATION:

                if account.has_access(25):
                    status = CachedDocument.objects.api_query('/account/AccountStatus.xml.aspx', params=auth_params, no_cache=True)
                    status = basic_xml_parse_doc(status)['eveapi']
                    if not status.get('error', None):
                        paiddate = datetime.strptime(status['result']['paidUntil'], '%Y-%m-%d %H:%M:%S').replace(tzinfo=utc)
                        if paiddate <= now():
                            account.api_status = API_STATUS_ACC_EXPIRED
                        else:
                            account.api_status = API_STATUS_OK
                else:
                    account.api_status = API_STATUS_INVALID_PERMISSIONS

                if not account.check_access(getattr(settings, 'EVE_API_MINIMUM_KEYMASK', 59638024)):
                    account.api_status = API_STATUS_INVALID_PERMISSIONS
            else:
                # If its a corp key, and we've not errored so far, assume is OK.
                account.api_status = API_STATUS_OK

            # Remove deleted or traded characters
            newcharlist = [int(char['characterID']) for char in doc['result']['key']['characters']]
            for char in account.characters.all().exclude(id__in=newcharlist):
                account.characters.remove(char)

            # Schedule a task to update the characters
            if account.user:
                cb = update_user_access.subtask(kwargs={'user': account.user.id })
            else:
                cb = None
            import_eve_characters.delay(newcharlist, key_id=account.pk, callback=cb)

        else:
            # No account object, just return
            if not account:
                return

            if not account.api_key == api_key:
                # Attempted change of key failed, ignore
                return

            error = doc['error']['code']
            if int(error) >= 500:
                # API disabled, down or rejecting, return without changes
                return
            elif error in ['202', '203', '204', '205', '212']:
                account.api_status = API_STATUS_AUTH_ERROR
            elif error == '211':
                account.api_status = API_STATUS_ACC_EXPIRED
            elif error in ['222', '223']:
                account.api_status = API_STATUS_KEY_EXPIRED
            elif error in ['221']:
                account.api_status = API_STATUS_INVALID_PERMISSIONS
            else:
                account.api_status = API_STATUS_OTHER_ERROR

            if account.user:
                update_user_access.delay(account.user.id)

    else:
        auth_params = {'userid': api_userid, 'apikey': api_key}
        account_doc = CachedDocument.objects.api_query('/account/Characters.xml.aspx', params=auth_params, no_cache=force_cache)
        doc = basic_xml_parse_doc(account_doc)['eveapi']

        if not 'error' in doc:
            if not account:
                account, created = EVEAccount.objects.get_or_create(pk=api_userid)
            if user and not account.user:
                account.user = User.objects.get(id=user)
            if not account.api_key == api_key:
                account.api_key = api_key
            account.api_status = API_STATUS_OK

            if not account.api_keytype or account.api_keytype == API_KEYTYPE_UNKNOWN:
                keycheck = CachedDocument.objects.api_query('/account/AccountStatus.xml.aspx', params=auth_params, no_cache=True)
                keydoc = basic_xml_parse_doc(keycheck)['eveapi']
                if 'error' in keydoc:
                    account.api_keytype = API_KEYTYPE_LIMITED
                elif not 'error' in keydoc:
                    account.api_keytype = API_KEYTYPE_FULL
                else:
                    account.api_keytype = API_KEYTYPE_UNKNOWN

            # Remove deleted or traded characters
            newcharlist = [int(char['characterID']) for char in doc['result']['characters']]
            for char in account.characters.all().exclude(id__in=newcharlist):
                account.characters.remove(char)

            # Schedule a task to update the characters
            if account.user:
                cb = update_user_access.subtask(kwargs={'user': account.user.id })
            else:
                cb = None
            import_eve_characters.delay(newcharlist, key_id=account.pk, callback=cb)

        else:
            # No account object, just return
            if not account:
                return

            if not account.api_key == api_key:
                # Attempted change of key failed, ignore
                return

            error = doc['error']['code']
            if int(error) >= 500:
                # API disabled, down or rejecting, return without changes
                return
            elif error in ['202', '203', '204', '205', '212']:
                account.api_status = API_STATUS_AUTH_ERROR
            elif error in ['211', '223']:
                account.api_status = API_STATUS_ACC_EXPIRED
            else:
                account.api_status = API_STATUS_OTHER_ERROR

            if account.user:
                update_user_access.delay(account.user.id)

    account.api_last_updated = now()
    account.save()
    return account