internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: dotkom/onlineweb4

Issue:
Information "leak" through phone numbers
It has been reported that searching for phone numbers will reveal the user even though the user has hidden the information. Just confirmed this. 

Do we consider this a problem? On one side if you already have the number, what is the problem? On the other side, users explicitly hide the information. 



Discussion:
this is a problem.

This is why I wanted to reverse the flow here so that instead of going User.objects.filter() bla bla, and then close all the endpoints in templates etc., we query a washed model or queryset that includes user controlled fields. Like, PublicUser or something. This model will never pass data a user has restricted outside the database, i.e they queryset will never contain restricted data in the first place.


Resolving patch:
diff --git a/apps/authentication/models.py b/apps/authentication/models.py
--- a/apps/authentication/models.py
+++ b/apps/authentication/models.py
@@ -298,4 +298,4 @@ class Meta:
 
 
 # Register OnlineUser in watson index for searching
-watson.register(OnlineUser)
+watson.register(OnlineUser, fields=('first_name', 'last_name', 'ntnu_username', 'nickname'))
diff --git a/apps/profiles/forms.py b/apps/profiles/forms.py
--- a/apps/profiles/forms.py
+++ b/apps/profiles/forms.py
@@ -35,7 +35,7 @@ class PrivacyForm(forms.ModelForm):
 
     class Meta:
         model = Privacy
-        exclude = ['user']
+        exclude = ['user', 'expose_nickname']
 
 
 class MailSettingsForm(forms.ModelForm):


Test patch:
Repository: dotkom/onlineweb4

Issue:
"Administrasjon" is not showing when viewing certain profiles
Normally the menu show the following elements:
- ADMINISTRASJON
- MIN SIDE
- LOGG UT

But when viewing certain profiles ADMINISTRASJON is gone. 

Maren and Didrik are two such profiles I've found so far. 

https://online.ntnu.no/profile/marenpg/
https://online.ntnu.no/profile/didrikpa/



Discussion:

Resolving patch:
diff --git a/apps/profiles/views.py b/apps/profiles/views.py
--- a/apps/profiles/views.py
+++ b/apps/profiles/views.py
@@ -397,7 +397,7 @@ def search_for_users(query, limit=10):
 def view_profile(request, username):
     user = get_object_or_404(User, username=username)
     if user.privacy.visible_for_other_users or user == request.user:
-        return render(request, 'profiles/view_profile.html', {'user': user})
+        return render(request, 'profiles/view_profile.html', {'user_profile': user})
 
     messages.error(request, _(u'Du har ikke tilgang til denne profilen'))
     return redirect('profiles')


Test patch:
Repository: dotkom/onlineweb4

Issue:
Votes cast in genfors on secret mode should randomize the vote list
Votes show in the order they are placed. This means if there is one person having trouble and cast his/her vote after everyone else, people can pretty much see what this person votes. Especially if the voter is called up by the tellekorps.



Discussion:

Resolving patch:
diff --git a/apps/genfors/views.py b/apps/genfors/views.py
--- a/apps/genfors/views.py
+++ b/apps/genfors/views.py
@@ -7,6 +7,7 @@
 from django.utils import timezone
 from django.http import HttpResponse, HttpResponseServerError
 from django.views.decorators.http import require_http_methods
+from django.views.decorators.cache import cache_page
 from apps.genfors.forms import LoginForm, MeetingForm, QuestionForm, RegisterVoterForm, AlternativeFormSet
 from apps.genfors.models import Meeting, Question, RegisteredVoter, AnonymousVoter, Alternative, BooleanVote, MultipleChoice, Result
 from apps.genfors.models import BOOLEAN_VOTE, MULTIPLE_CHOICE
@@ -458,6 +459,8 @@ def genfors_end(request):
 def api_admin(request):
     return HttpResponse(json.dumps({"error": "Du har ikke tilgang til dette endepunktet."}))
 
+# Simple cached JSON Api-like endpoint to dynamically update stats via AJAX
+@cache_page(10)
 def api_user(request):
     if is_registered(request):
         m = get_active_meeting()
@@ -486,6 +489,10 @@ def api_user(request):
                         genfors["question"]["votes"] = [[unicode(v.voter.anonymousvoter), v.answer] for v in votes]
                     elif q.question_type == 1:
                         genfors["question"]["votes"] = [[unicode(v.voter.anonymousvoter), v.answer.description] if v.answer else [unicode(v.voter.anonymousvoter), "Blankt"] for v in votes]
+                    
+                    # Shuffle the order of votes so you cannot infer who cast what vote when there are few voters left
+                    random.shuffle(genfors['question']['votes'])
+
                 else:
                     if q.question_type == 0:
                         genfors["question"]["votes"] = [[unicode(v.voter.registeredvoter), v.answer] for v in votes]


Test patch:
Repository: dotkom/onlineweb4

Issue:
Toggling emails for deleting, verifying or setting as primary is broken
None of the buttons work in the profile window for email settings.



Discussion:

Resolving patch:
diff --git a/apps/profiles/views.py b/apps/profiles/views.py
--- a/apps/profiles/views.py
+++ b/apps/profiles/views.py
@@ -9,7 +9,7 @@
 from django.contrib.auth.decorators import login_required
 from django.contrib.auth.models import Group
 from django.core.mail import send_mail
-from django.http import HttpResponse
+from django.http import HttpResponse, Http404
 from django.shortcuts import redirect, render, get_object_or_404
 from django.utils.translation import ugettext as _
 
@@ -185,7 +185,6 @@ def delete_position(request):
     if request.is_ajax():
         if request.method == 'POST':
             position_id = request.POST.get('position_id')
-            print position_id
             position = get_object_or_404(Position, pk=position_id)
             if position.user == request.user:
                 position.delete()
@@ -194,7 +193,7 @@ def delete_position(request):
             else:
                 return_status = json.dumps({'message': _(u"Du prøvde å slette en posisjon som ikke tilhørte deg selv.")})
             return HttpResponse(status=500, content=return_status)
-        return HttpResponse(status=404)
+        raise Http404
 
 
 @login_required
@@ -213,7 +212,7 @@ def update_mark_rules(request):
 
             return HttpResponse(status=212, content=return_status)
         return HttpResponse(status=405)
-    return HttpResponse(status=404)
+    raise Http404
 
 
 @login_required
@@ -292,7 +291,8 @@ def set_primary(request):
             email.save()
 
             return HttpResponse(status=200)
-    return HttpResponse(status=404)
+    raise Http404
+
 
 @login_required
 def verify_email(request):
@@ -317,7 +317,8 @@ def verify_email(request):
             _send_verification_mail(request, email.email)
 
             return HttpResponse(status=200)
-    return HttpResponse(status=404)
+    raise Http404
+
 
 def _send_verification_mail(request, email):
 
@@ -355,7 +356,7 @@ def toggle_infomail(request):
             request.user.save()
 
             return HttpResponse(status=200, content=json.dumps({'state': request.user.infomail}))
-    return HttpResponse(status=404)
+    raise Http404
 
 
 @login_required
@@ -382,7 +383,8 @@ def save_membership_details(request):
                                                     {'message': ", ".join(field_errors)}
                                                 ))
 
-    return HttpResponse(status=404) 
+    raise Http404
+
 
 @login_required
 def user_search(request):


Test patch:
Repository: dotkom/onlineweb4

Issue:
Default all usernames to lowercase
People suck. They can't login cause they don't remember when they be shreddin dat caps all day long yall no wat im saying.



Discussion:

Resolving patch:
diff --git a/apps/authentication/forms.py b/apps/authentication/forms.py
--- a/apps/authentication/forms.py
+++ b/apps/authentication/forms.py
@@ -17,6 +17,8 @@ class LoginForm(forms.Form):
     def clean(self):
         if self._errors:
             return
+
+        self.cleaned_data['username'] = self.cleaned_data['username'].lower()
     
         user = auth.authenticate(username=self.cleaned_data['username'], password=self.cleaned_data['password'])
 
@@ -40,7 +42,7 @@ def login(self, request):
         return False
 
 class RegisterForm(forms.Form):
-    username = forms.CharField(label=_("Brukernavn"), max_length=20, help_text=u'Valgfritt brukernavn')
+    username = forms.CharField(label=_("Brukernavn"), max_length=20, help_text=u'Valgfritt brukernavn. (Konverteres automatisk til små bokstaver.)')
     first_name = forms.CharField(label=_("Fornavn"), max_length=50, help_text=u'Mellomnavn inkluderer du etter fornavnet ditt')
     last_name = forms.CharField(label=_("Etternavn"), max_length=50)
     email = forms.EmailField(label=_("Epost"), max_length=50, help_text=u'Du kan legge til flere epostadresser senere i din profil.')
diff --git a/apps/authentication/models.py b/apps/authentication/models.py
--- a/apps/authentication/models.py
+++ b/apps/authentication/models.py
@@ -160,6 +160,7 @@ def __unicode__(self):
     def save(self, *args, **kwargs):
         if self.ntnu_username == "":
             self.ntnu_username = None
+        self.username = self.username.lower()
         super(OnlineUser, self).save(*args, **kwargs)
 
     def serializable_object(self):


Test patch:
Repository: dotkom/onlineweb4

Issue:
Missing smtplib import in profiles
profiles/views.py is missing `from smtplib import SMTPException`



Discussion:

Resolving patch:
diff --git a/apps/profiles/views.py b/apps/profiles/views.py
--- a/apps/profiles/views.py
+++ b/apps/profiles/views.py
@@ -2,6 +2,7 @@
 import json
 import os
 import uuid
+from smtplib import SMTPException
 
 from django.conf import settings
 from django.contrib import messages


Test patch:
Repository: dotkom/onlineweb4

Issue:
Add appKom to list of committees in dashboard view
AppKom is missing as a committee in the dashboard view. Users can't add a position in that committee.

![screen shot 2014-09-30 at 02 33 48](https://cloud.githubusercontent.com/assets/582580/4451680/c20b1420-4839-11e4-8dfc-b52969d8481c.png)



Discussion:
AppKom should also be in the "about" me section on the front page and other places where the comitees are listed. 


Resolving patch:
diff --git a/apps/authentication/models.py b/apps/authentication/models.py
--- a/apps/authentication/models.py
+++ b/apps/authentication/models.py
@@ -51,6 +51,7 @@
     ('prokom', _(u'Profil-og aviskomiteen')),
     ('trikom', _(u'Trivselskomiteen')),
     ('velkom', _(u'Velkomstkomiteen')),
+    ('appkom', _(u'Applikasjonskomiteen')),
 ]
 
 POSITIONS = [


Test patch:
Repository: dotkom/onlineweb4

Issue:
Committee positions is not sorted alphabetically
Appkom should be above arrKom, not on the bottom of the list.

Should be as simple as editing `apps/authentication/models.py`



Discussion:

Resolving patch:
diff --git a/apps/authentication/models.py b/apps/authentication/models.py
--- a/apps/authentication/models.py
+++ b/apps/authentication/models.py
@@ -40,6 +40,7 @@
 
 COMMITTEES = [
     ('hs', _(u'Hovedstyret')),
+    ('appkom', _(u'Applikasjonskomiteen')),
     ('arrkom', _(u'Arrangementskomiteen')),
     ('bankom', _(u'Bank- og økonomikomiteen')),
     ('bedkom', _(u'Bedriftskomiteen')),
@@ -51,7 +52,6 @@
     ('prokom', _(u'Profil-og aviskomiteen')),
     ('trikom', _(u'Trivselskomiteen')),
     ('velkom', _(u'Velkomstkomiteen')),
-    ('appkom', _(u'Applikasjonskomiteen')),
 ]
 
 POSITIONS = [


Test patch:
Repository: dotkom/onlineweb4

Issue:
(User) Trying to add studmail to two accounts leads to errors
When one account has been registered with a studmail, the ntnu_username will be stored to one account. If the user deletes the studmail from his profile, it could technically be registered with another user.

If this is done, the user will get a 500 error, caused by the fact that verifying the mail will attempt to store the ntnu_username from that email in another user. The error is because ntnu_username is unique.

Fixing this can be done by checking if a user exists with the ntnu_username when the user tries to add it to his profile, before verification mails are sent and so on, and just display an error to the user and explain that they have to contact dotkom@online.ntnu.no to get it fixed.

This can either result from the fact that they are trying to cheat, or that they are geniunly stupid.



Discussion:

Resolving patch:
diff --git a/apps/authentication/forms.py b/apps/authentication/forms.py
--- a/apps/authentication/forms.py
+++ b/apps/authentication/forms.py
@@ -68,6 +68,13 @@ def clean(self):
             if Email.objects.filter(email=email).count() > 0:
                 self._errors['email'] = self.error_class([_(u"Det fins allerede en bruker med denne epostadressen.")])
 
+            # Check if it's studmail and if someone else already has it in their profile
+            if re.match(r'[^@]+@stud\.ntnu\.no', email):
+                ntnu_username = email.split("@")[0]
+                user = User.objects.filter(ntnu_username = ntnu_username)
+                if user.count() == 1:
+                    self._errors['email'] = self.error_class([_(u"En bruker med dette NTNU-brukernavnet fins allerede.")])
+
             # ZIP code digits only
             zip_code = cleaned_data['zip_code']
             if len(zip_code) != 0:
diff --git a/apps/profiles/views.py b/apps/profiles/views.py
--- a/apps/profiles/views.py
+++ b/apps/profiles/views.py
@@ -1,6 +1,7 @@
 #-*- coding: utf-8 -*-
 import json
 import os
+import re
 import uuid
 from smtplib import SMTPException
 
@@ -239,6 +240,15 @@ def add_email(request):
                 messages.error(request, _(u"Eposten %s er allerede registrert.") % email_string)
                 return redirect('profiles')
 
+            # Check if it's studmail and if someone else already has it in their profile
+            if re.match(r'[^@]+@stud\.ntnu\.no', email_string):
+                ntnu_username = email_string.split("@")[0]
+                user = User.objects.filter(ntnu_username = ntnu_username)
+                if user.count() == 1:
+                    if user != request.user:
+                        messages.error(request, _(u"En bruker med dette NTNU-brukernavnet fins allerede."))
+                        return redirect('profiles')
+
             # Create the email
             email = Email(email=email_string, user=request.user)
             email.save()


Test patch:
Repository: dotkom/onlineweb4

Issue:
Add redirect to newly created item after creating it in dashboard inventory
As title states.



Discussion:

Resolving patch:
diff --git a/apps/inventory/dashboard/views.py b/apps/inventory/dashboard/views.py
--- a/apps/inventory/dashboard/views.py
+++ b/apps/inventory/dashboard/views.py
@@ -47,9 +47,9 @@ def new(request):
         if not inventory_form.is_valid():
             messages.error(request, u'Noen av de påkrevde feltene inneholder feil.')
         else:
-            inventory_form.save()
+            item = inventory_form.save()
             messages.success(request, u'Varen ble opprettet')
-            return redirect(index)
+            return redirect(details, item.id)
 
         context['form'] = inventory_form
 
@@ -99,11 +99,15 @@ def item_delete(request, item_pk):
 
     item = get_object_or_404(Item, pk=item_pk)
 
-    item.delete()
+    if request.method == 'POST':
+
+        item.delete()
+
+        messages.success(request, u'Varen %s ble slettet.' % item.name)
 
-    messages.success(request, u'Varen %s ble slettet.' % item.name)
+        return redirect(index)
 
-    return redirect(index)
+    raise PermissionDenied
 
 @login_required
 @permission_required('inventory.add_batch', return_403=True)
@@ -111,18 +115,27 @@ def batch_new(request, item_pk):
     if not has_access(request):
         raise PermissionDenied
 
-    # Get base context
+    # Field mapper
+    fieldmap = {
+        'amount': u'Mengde',
+        'expiration_date': u'Utløpsdato',
+    }
 
     item = get_object_or_404(Item, pk=item_pk)
 
     if request.method == 'POST':
         batch_form = BatchForm(request.POST)
-        batch = batch_form.save(commit=False)
-        batch.item = item
 
         if not batch_form.is_valid():
-            messages.error(request, u'Noen av de påkrevde feltene inneholder feil.')
+            # Dirty hack to display errors since the form is not passed in redirect context
+            error_reply = u"Feil i felt:"
+            for field, error in batch_form.errors.items():
+                error_reply += ' ' + fieldmap[field] + ' (' + batch_form.error_class.as_text(error) + '),'
+
+            messages.error(request, error_reply.rstrip(','))
         else:
+            batch = batch_form.save(commit=False)
+            batch.item = item
             batch.save()
             messages.success(request, u'Batchen ble lagt til.')
 
@@ -163,9 +176,12 @@ def batch_delete(request, item_pk, batch_pk):
 
     batch = get_object_or_404(Batch, pk=batch_pk)
 
-    batch.delete()
+    if request.method == 'POST':
 
-    messages.success(request, u'Batchen ble slettet.')
+        batch.delete()
+        messages.success(request, u'Batchen ble slettet.')
 
-    return redirect(details, item_pk=item_pk)
+        return redirect(details, item_pk=item_pk)
+
+    raise PermissionDenied
 


Test patch:
Repository: dotkom/onlineweb4

Issue:
Extra field in rating results
Feedback rating results display the extra blank field after it was changed in #1129 



Discussion:

Resolving patch:
diff --git a/apps/feedback/views.py b/apps/feedback/views.py
--- a/apps/feedback/views.py
+++ b/apps/feedback/views.py
@@ -109,7 +109,7 @@ def get_chart_data(request, applabel, appmodel, object_id, feedback_id, token=Fa
     rating_titles = []
     answer_collection = dict()
     answer_collection['replies'] = dict()
-    answer_length = int(len(RATING_CHOICES) +1)
+    answer_length = int(len(RATING_CHOICES))
     for question in fbr.ratingquestion:
         if question.display or not token:
             rating_titles.append(str(question))


Test patch:
Repository: dotkom/onlineweb4

Issue:
Payment deadline in email differs from deadline on ow4
![image](https://cloud.githubusercontent.com/assets/5422571/9561120/ed6275d6-4e38-11e5-81cb-6aaf76476473.png)

![image](https://cloud.githubusercontent.com/assets/5422571/9561122/f86afcd2-4e38-11e5-81c7-a240b4fdc31b.png)

https://github.com/dotKom/onlineweb4/pull/1156/files#diff-ecf5ad0447e0a96d3ebddf6499c32b55R208



Discussion:

Resolving patch:
diff --git a/apps/payment/mommy.py b/apps/payment/mommy.py
--- a/apps/payment/mommy.py
+++ b/apps/payment/mommy.py
@@ -2,6 +2,7 @@
 
 import locale
 import logging
+from pytz import timezone as tz
 
 from django.utils import timezone
 from django.core.mail import EmailMessage
@@ -204,8 +205,10 @@ def send_notification_mail(payment_delay, unattend_deadline_passed):
         payment = payment_delay.payment
         subject = _(u"Husk betaling for ") + payment.description()
 
+        valid_to = payment_delay.valid_to.astimezone(tz('Europe/Oslo'))
+
         message = _(u"Hei, du er påmeldt men har ikke betalt for ") + payment.description()
-        message += _(u"\nDu har frem til ") + unicode(payment_delay.valid_to.strftime("%-d %B %Y kl: %H:%M"))
+        message += _(u"\nDu har frem til ") + unicode(valid_to.strftime("%-d %B %Y kl: %H:%M"))
 
 
         #If event unattend deadline has not passed when payment deadline passes, then the user will be automatically unattended, and given a mark.


Test patch:
Repository: dotkom/onlineweb4

Issue:
Payment: Some users did not get unnatended when the deadline passed.
4 users got marks for not paying in time but did not get unattended from the event.

Might have something to do with the guest/ +1 functionality.



Discussion:

Resolving patch:
diff --git a/apps/payment/mommy.py b/apps/payment/mommy.py
--- a/apps/payment/mommy.py
+++ b/apps/payment/mommy.py
@@ -154,7 +154,7 @@ def run():
         payment_delays = PaymentDelay.objects.filter(active=True)
 
         for payment_delay in payment_delays:
-            unattend_deadline_passed = payment_delay.payment.content_object.unattend_deadline > payment_delay.valid_to
+            unattend_deadline_passed = payment_delay.payment.content_object.unattend_deadline < payment_delay.valid_to
             if payment_delay.valid_to < timezone.now():
                 PaymentDelayHandler.handle_deadline_passed(payment_delay, unattend_deadline_passed)
                 logger.info("Deadline passed: " + unicode(payment_delay))


Test patch:
Repository: dotkom/onlineweb4

Issue:
Field of Study text labels are out of date
Needs update to reflect the name changes



Discussion:

Resolving patch:
diff --git a/apps/authentication/models.py b/apps/authentication/models.py
--- a/apps/authentication/models.py
+++ b/apps/authentication/models.py
@@ -21,11 +21,11 @@
     (0, _(u'Gjest')),
     (1, _(u'Bachelor i Informatikk (BIT)')),
     # master degrees take up the interval [10,30]
-    (10, _(u'Software (SW)')),
-    (11, _(u'Informasjonsforvaltning (DIF)')),
-    (12, _(u'Komplekse Datasystemer (KDS)')),
-    (13, _(u'Spillteknologi (SPT)')),
-    (14, _(u'Intelligente Systemer (IRS)')),
+    (10, _(u'Programvaresystemer (P)')),
+    (11, _(u'Databaser og søk (DS)')),
+    (12, _(u'Algoritmer og datamaskiner (AD)')),
+    (13, _(u'Spillteknologi (S)')),
+    (14, _(u'Kunstig intelligens (KI)')),
     (15, _(u'Helseinformatikk (MSMEDTEK)')),
     (30, _(u'Annen mastergrad')),
     (80, _(u'PhD')),


Test patch:
Repository: dotkom/onlineweb4

Issue:
Tags with a '.' will crash
Ref. http://moonshine.online.ntnu.no/article/10/online-far-ny-nettside



Discussion:
Should be stripped


Resolving patch:
diff --git a/apps/article/admin.py b/apps/article/admin.py
--- a/apps/article/admin.py
+++ b/apps/article/admin.py
@@ -18,6 +18,7 @@ class TagAdmin(admin.ModelAdmin):
     def save_model(self, request, obj, form, change):
         obj.changed_by = request.user
         if not change:
+            obj.name = obj.name.replace('.', '')
             obj.created_by = request.user
         obj.save()
 


Test patch:
Repository: dotkom/onlineweb4

Issue:
Field of Study text labels are out of date
Needs update to reflect the name changes



Discussion:

Resolving patch:
diff --git a/apps/authentication/migrations/0008_auto_20151014_2156.py b/apps/authentication/migrations/0008_auto_20151014_2156.py
new file mode 100644
--- /dev/null
+++ b/apps/authentication/migrations/0008_auto_20151014_2156.py
@@ -0,0 +1,20 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import models, migrations
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('authentication', '0007_onlineuser_bio'),
+    ]
+
+    operations = [
+        migrations.AlterField(
+            model_name='onlineuser',
+            name='field_of_study',
+            field=models.SmallIntegerField(default=0, verbose_name='studieretning', choices=[(0, 'Gjest'), (1, 'Bachelor i Informatikk (BIT)'), (10, 'Programvaresystemer (P)'), (11, 'Databaser og s\xf8k (DS)'), (12, 'Algoritmer og datamaskiner (AD)'), (13, 'Spillteknologi (S)'), (14, 'Kunstig intelligens (KI)'), (15, 'Helseinformatikk (MSMEDTEK)'), (30, 'Annen mastergrad'), (80, 'PhD'), (90, 'International'), (100, 'Annet Onlinemedlem')]),
+            preserve_default=True,
+        ),
+    ]


Test patch: