Esempio n. 1
0
    def register(self, form):
        RegistrationView.SEND_ACTIVATION_EMAIL = not preferences.SitePreferences.disable_mail_verification

        user = super(RegistrationView, self).register(form)
        profile, _ = Profile.objects.get_or_create(user=user,
                                                   defaults={
                                                       'language':
                                                       Language.get_python3(),
                                                   })

        if preferences.SitePreferences.disable_mail_verification:
            user.is_active = True
            user.save()

        cleaned_data = form.cleaned_data
        profile.timezone = cleaned_data['timezone']
        profile.language = cleaned_data['language']

        profile.save()

        if newsletter_id is not None and cleaned_data['newsletter']:
            Subscription(user=user,
                         newsletter_id=newsletter_id,
                         subscribed=True).save()
        return user
Esempio n. 2
0
    def ready(self):
        # WARNING: AS THIS IS NOT A FUNCTIONAL PROGRAMMING LANGUAGE,
        #          OPERATIONS MAY HAVE SIDE EFFECTS.
        #          DO NOT REMOVE THINKING THE IMPORT IS UNUSED.
        # noinspection PyUnresolvedReferences
        from . import signals, jinja2  # noqa: F401, imported for side effects

        from django.contrib.flatpages.models import FlatPage
        from django.contrib.flatpages.admin import FlatPageAdmin
        from django.contrib import admin

        admin.site.unregister(FlatPage)
        admin.site.register(FlatPage, FlatPageAdmin)

        from judge.models import Language, Profile
        from django.contrib.auth.models import User

        try:
            lang = Language.get_python3()
            for user in User.objects.filter(profile=None):
                # These poor profileless users
                profile = Profile(user=user, language=lang)
                profile.save()
        except DatabaseError:
            pass
Esempio n. 3
0
def make_profile(backend, user, response, is_new=False, *args, **kwargs):
    if is_new:
        if not hasattr(user, 'profile'):
            profile = Profile(user=user)
            profile.language = Language.get_python2()
            if backend.name == 'google-oauth2':
                profile.name = response['displayName']
            elif backend.name in ('github', 'facebook') and 'name' in response:
                profile.name = response['name']
            else:
                logger.info('Info from %s: %s', backend.name, response)
            profile.save()
            form = ProfileForm(instance=profile, user=user)
        else:
            data = backend.strategy.request_data()
            logger.info(data)
            form = ProfileForm(data, instance=user.profile, user=user)
            if form.is_valid():
                with transaction.atomic(), revisions.create_revision():
                    form.save()
                    revisions.set_user(user)
                    revisions.set_comment('Updated on registration')
                    return
        return render(backend.strategy.request,
                      'registration/profile_creation.jade', {
                          'title': 'Create your profile',
                          'form': form
                      })
Esempio n. 4
0
 def __init__(self):
     lang = Language.get_python2()
     for user in User.objects.filter(profile=None):
         # These poor profileless users
         profile = Profile(user=user, language=lang)
         profile.save()
     raise MiddlewareNotUsed
Esempio n. 5
0
def make_profile(backend, user, response, is_new=False, *args, **kwargs):
    if is_new:
        if not hasattr(user, "profile"):
            profile = Profile(user=user)
            profile.language = Language.get_python2()
            if backend.name == "google-oauth2":
                profile.name = response["displayName"]
            elif backend.name in ("github", "facebook") and "name" in response:
                profile.name = response["name"]
            else:
                logger.info("Info from %s: %s", backend.name, response)
            profile.save()
            form = ProfileForm(instance=profile, user=user)
        else:
            data = backend.strategy.request_data()
            logger.info(data)
            form = ProfileForm(data, instance=user.profile, user=user)
            if form.is_valid():
                with transaction.atomic(), revisions.create_revision():
                    form.save()
                    revisions.set_user(user)
                    revisions.set_comment("Updated on registration")
                    return
        return render(
            backend.strategy.request,
            "registration/profile_creation.jade",
            {"title": "Create your profile", "form": form},
        )
Esempio n. 6
0
    def setUpTestData(self):
        super().setUpTestData()

        create_problem_type(name='type')

        self.basic_problem = create_problem(
            code='basic',
            allowed_languages=Language.objects.values_list('key', flat=True),
            types=('type',),
            authors=('normal',),
            testers=('staff_problem_edit_public',),
        )

        limits = []
        for lang in Language.objects.filter(common_name=Language.get_python3().common_name):
            limits.append(
                LanguageLimit(
                    problem=self.basic_problem,
                    language=lang,
                    time_limit=100,
                    memory_limit=131072,
                ),
            )
        LanguageLimit.objects.bulk_create(limits)

        self.organization_private_problem = create_problem(
            code='organization_private',
            time_limit=2,
            is_public=True,
            is_organization_private=True,
            curators=('staff_problem_edit_own', 'staff_problem_edit_own_no_staff'),
        )
Esempio n. 7
0
    def ready(self):
        # WARNING: AS THIS IS NOT A FUNCTIONAL PROGRAMMING LANGUAGE,
        #          OPERATIONS MAY HAVE SIDE EFFECTS.
        #          DO NOT REMOVE THINKING THE IMPORT IS UNUSED.
        # noinspection PyUnresolvedReferences
        from . import signals, jinja2

        from django.contrib.flatpages.models import FlatPage
        from django.contrib.flatpages.admin import FlatPageAdmin
        from django.contrib import admin
        from django.contrib.auth.models import User
        from admin.user import MyUserAdmin
        from reversion.admin import VersionAdmin

        class FlatPageVersionAdmin(VersionAdmin, FlatPageAdmin):
            suit_form_size = {
                'fields': {
                    'content': apps.SUIT_FORM_SIZE_FULL
                },
            }

        admin.site.unregister(FlatPage)
        admin.site.register(FlatPage, FlatPageVersionAdmin)
        admin.site.unregister(User)
        admin.site.register(User, MyUserAdmin)
        from judge.models import Language, Profile

        try:
            lang = Language.get_python2()
            for user in User.objects.filter(profile=None):
                # These poor profileless users
                profile = Profile(user=user, language=lang)
                profile.save()
        except DatabaseError:
            pass
Esempio n. 8
0
File: apps.py Progetto: DMOJ/site
    def ready(self):
        # WARNING: AS THIS IS NOT A FUNCTIONAL PROGRAMMING LANGUAGE,
        #          OPERATIONS MAY HAVE SIDE EFFECTS.
        #          DO NOT REMOVE THINKING THE IMPORT IS UNUSED.
        # noinspection PyUnresolvedReferences
        from . import signals, jinja2

        from django.contrib.flatpages.models import FlatPage
        from django.contrib.flatpages.admin import FlatPageAdmin
        from django.contrib import admin

        from reversion.admin import VersionAdmin

        class FlatPageVersionAdmin(VersionAdmin, FlatPageAdmin):
            pass

        admin.site.unregister(FlatPage)
        admin.site.register(FlatPage, FlatPageVersionAdmin)

        from judge.models import Language, Profile
        from django.contrib.auth.models import User

        try:
            lang = Language.get_python2()
            for user in User.objects.filter(profile=None):
                # These poor profileless users
                profile = Profile(user=user, language=lang)
                profile.save()
        except DatabaseError:
            pass
Esempio n. 9
0
def import_users(users):
    log = ''
    for i, row in enumerate(users):
        cur_log = str(i + 1) + '. '

        username = row['username']
        cur_log += username + ': '

        pwd = row['password']
        
        user, created = User.objects.get_or_create(username=username, defaults={
            'is_active': True,
        })

        profile, _ = Profile.objects.get_or_create(user=user, defaults={
            'language': Language.get_python3(),
            'timezone': settings.DEFAULT_USER_TIME_ZONE,
        })

        if created:
            cur_log += 'Create new - '
        else:
            cur_log += 'Edit - '

        if pwd:
            user.set_password(pwd)
        elif created:
            user.set_password('lqdoj')
            cur_log += 'Missing password, set password = lqdoj - '

        if 'name' in row.keys() and row['name']:
            user.first_name = row['name']

        if 'school' in row.keys() and row['school']:
            user.last_name = row['school']

        if row['organizations']:
            orgs = row['organizations'].split('&')
            added_orgs = []
            for o in orgs:
                try:
                    org = Organization.objects.get(slug=o)
                    profile.organizations.add(org)
                    added_orgs.append(org.name)
                except Organization.DoesNotExist:
                    continue
            if added_orgs:
                cur_log += 'Added to ' + ', '.join(added_orgs) + ' - '

        if row['email']:
            user.email = row['email']
            
        user.save()
        profile.save()
        cur_log += 'Saved\n'
        log += cur_log
    log += 'FINISH'

    return log
Esempio n. 10
0
 def register(self, request, **cleaned_data):
     user = super(RegistrationView, self).register(request, **cleaned_data)
     profile, _ = Profile.objects.get_or_create(
         user=user, defaults={'language': Language.get_python2()})
     profile.name = cleaned_data['display_name']
     profile.timezone = cleaned_data['timezone']
     profile.language = cleaned_data['language']
     profile.organization = cleaned_data['organization']
     if profile.organization is not None:
         profile.organization_join_time = timezone.now()
     profile.save()
     return user
Esempio n. 11
0
    def register(self, form):
        user = super(RegistrationView, self).register(form)
        profile, _ = Profile.objects.get_or_create(user=user, defaults={
            'language': Language.get_python2()
        })

        cleaned_data = form.cleaned_data
        profile.name = cleaned_data['display_name']
        profile.language = cleaned_data['language']
        profile.save()

        return user
Esempio n. 12
0
 def register(self, request, **cleaned_data):
     user = super(RegistrationView, self).register(request, **cleaned_data)
     profile, _ = Profile.objects.get_or_create(user=user, defaults={
         'language': Language.get_python2()
     })
     profile.name = cleaned_data['display_name']
     profile.timezone = cleaned_data['timezone']
     profile.language = cleaned_data['language']
     profile.organization = cleaned_data['organization']
     if profile.organization is not None:
         profile.organization_join_time = timezone.now()
     profile.save()
     return user
Esempio n. 13
0
 def register(self, request, form=None, **cleaned_data):
     user = super(RegistrationView, self).register(request, form=form, **cleaned_data)
     profile, _ = Profile.objects.get_or_create(user=user, defaults={
         'language': Language.get_python2()
     })
     if form is not None:
         cleaned_data = form.cleaned_data
     profile.name = cleaned_data['display_name']
     profile.timezone = cleaned_data['timezone']
     profile.language = cleaned_data['language']
     profile.organizations.add(*cleaned_data['organizations'])
     profile.save()
     return user
Esempio n. 14
0
def import_users(csv_file):
    # 1st row: username, password, name, organization
    # ... row: a_username, passhere, my_name, organ
    try:
        f = open(csv_file, 'r')
    except OSError:
        print("Could not open csv file", csv_file)
        return

    with f:
        reader = csv.DictReader(f)

        for row in reader:
            try:
                username = row['username']
                pwd = row['password']
            except Exception:
                print('username and/or password column missing')
                print(
                    'Make sure your columns are: username, password, name, organization'
                )

            user, created = User.objects.get_or_create(username=username,
                                                       defaults={
                                                           'is_active': True,
                                                       })

            profile, _ = Profile.objects.get_or_create(
                user=user,
                defaults={
                    'language': Language.get_python3(),
                    'timezone': settings.DEFAULT_USER_TIME_ZONE,
                })
            if created:
                print('Created user', username)

            if pwd:
                user.set_password(pwd)
            elif created:
                user.set_password('lqdoj')
                print('User', username, 'missing password, default=lqdoj')

            if 'name' in row.keys() and row['name']:
                user.first_name = row['name']

            if 'organization' in row.keys() and row['organization']:
                org = Organization.objects.get(name=row['organization'])
                profile.organizations.add(org)

            user.save()
            profile.save()
Esempio n. 15
0
    def register(self, form):
        user = super(RegistrationView, self).register(form)
        profile, _ = Profile.objects.get_or_create(user=user, defaults={
            'language': Language.get_python2()
        })

        cleaned_data = form.cleaned_data
        profile.timezone = cleaned_data['timezone']
        profile.language = cleaned_data['language']
        profile.organizations.add(*cleaned_data['organizations'])
        profile.save()

        if newsletter_id is not None and cleaned_data['newsletter']:
            Subscription(user=user, newsletter_id=newsletter_id, subscribed=True).save()
        return user
Esempio n. 16
0
    def register(self, form):
        user = super(RegistrationView, self).register(form)
        profile, _ = Profile.objects.get_or_create(user=user, defaults={
            'language': Language.get_default_language(),
        })

        cleaned_data = form.cleaned_data
        profile.timezone = cleaned_data['timezone']
        profile.language = cleaned_data['language']
        profile.organizations.add(*cleaned_data['organizations'])
        profile.save()

        if newsletter_id is not None and cleaned_data['newsletter']:
            Subscription(user=user, newsletter_id=newsletter_id, subscribed=True).save()
        return user
Esempio n. 17
0
    def save(self, request):
        user = super(MySignupForm, self).save(request)
        profile, _ = Profile.objects.get_or_create(
            user=user, defaults={'language': Language.get_python2()})

        profile.name = self.cleaned_data.get('display_name')
        profile.timezone = self.cleaned_data.get('timezone')
        profile.language = self.cleaned_data.get('language')
        profile.organizations.add(*self.cleaned_data.get('organizations'))
        profile.save()

        if newsletter_id is not None and self.cleaned_data.get('newsletter'):
            Subscription(user=user,
                         newsletter_id=newsletter_id,
                         subscribed=True).save()
        return user
Esempio n. 18
0
    def ready(self):
        # WARNING: AS THIS IS NOT A FUNCTIONAL PROGRAMMING LANGUAGE,
        #          OPERATIONS MAY HAVE SIDE EFFECTS.
        #          DO NOT REMOVE THINKING THE IMPORT IS UNUSED.
        # noinspection PyUnresolvedReferences
        from . import signals, jinja2

        from judge.models import Language, Profile
        from django.contrib.auth.models import User

        try:
            lang = Language.get_python2()
            for user in User.objects.filter(profile=None):
                # These poor profileless users
                profile = Profile(user=user, language=lang)
                profile.save()
        except DatabaseError:
            pass
Esempio n. 19
0
    def register(self, request, form=None, **cleaned_data):
        user = super(RegistrationView, self).register(request,
                                                      form=form,
                                                      **cleaned_data)
        profile, _ = Profile.objects.get_or_create(
            user=user, defaults={'language': Language.get_python2()})
        if form is not None:
            cleaned_data = form.cleaned_data
        profile.name = cleaned_data['display_name']
        profile.timezone = cleaned_data['timezone']
        profile.language = cleaned_data['language']
        profile.organizations.add(*cleaned_data['organizations'])
        profile.save()

        if newsletter_id is not None and cleaned_data['newsletter']:
            Subscription(user=user,
                         newsletter_id=newsletter_id,
                         subscribed=True).save()
        return user
Esempio n. 20
0
def make_profile(backend, user, response, is_new=False, *args, **kwargs):
    if is_new:
        if not hasattr(user, 'profile'):
            profile = Profile(user=user)
            profile.language = Language.get_python2()
            logger.info('Info from %s: %s', backend.name, response)
            profile.save()
            return
#            form = ProfileForm(instance=profile, user=user)
        else:
            data = backend.strategy.request_data()
            logger.info(data)
            return
            form = ProfileForm(data, instance=user.profile, user=user)
            if form.is_valid():
                with transaction.atomic(), revisions.create_revision():
                    form.save()
                    revisions.set_user(user)
                    revisions.set_comment('Updated on registration')
                    return
Esempio n. 21
0
def make_profile(backend, user, response, is_new=False, *args, **kwargs):
    if is_new:
        if not hasattr(user, 'profile'):
            profile = Profile(user=user)
            profile.language = Language.get_python2()
            logger.info('Info from %s: %s', backend.name, response)
            profile.save()
            form = ProfileForm(instance=profile, user=user)
        else:
            data = backend.strategy.request_data()
            logger.info(data)
            form = ProfileForm(data, instance=user.profile, user=user)
            if form.is_valid():
                with transaction.atomic(), revisions.create_revision():
                    form.save()
                    revisions.set_user(user)
                    revisions.set_comment('Updated on registration')
                    return
        return render(backend.strategy.request, 'registration/profile_creation.html', {
            'title': 'Create your profile', 'form': form
        })
Esempio n. 22
0
def make_profile(backend, user, response, is_new=False, *args, **kwargs):
    if is_new:
        if not hasattr(user, 'profile'):
            profile = Profile(user=user)
            profile.language = Language.get_python3()
            logger.info('Info from %s: %s', backend.name, response)
            profile.save()
            form = ProfileForm(instance=profile, user=user)
        else:
            data = backend.strategy.request_data()
            logger.info(data)
            form = ProfileForm(data, instance=user.profile, user=user)
            if form.is_valid():
                with transaction.atomic():
                    form.save()
                    return

        return render(backend.strategy.request,
                      'registration/profile_creation.html', {
                          'title': 'Create your profile',
                          'form': form,
                      })
Esempio n. 23
0
    def authenticate(self, username=None, password=None):
        # Telerik Academy Authentication

        r = requests.post(
            self.get_login_url(settings.API_KEY, username, password))
        result = json.loads(r.content)

        if result['IsValid']:
            try:
                user = User.objects.get(username=username)
            except User.DoesNotExist:
                user = User(username=username)

                user.save()

                profile, _ = Profile.objects.get_or_create(
                    user=user,
                    defaults={
                        'language': Language.get_python2(),
                        'timezone': 'Europe/Sofia',
                    })

                profile.name = username
                profile.save()

            import pdb
            pdb.set_trace()

            if result['IsAdmin']:
                user.is_staff = True
                user.is_superuser = True
            else:
                user.is_staff = False
                user.is_superuser = False
            user.save()

            return user

        return None
Esempio n. 24
0
import hmac
import re
import struct

from django.conf import settings
from django.contrib.auth.models import User
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import Resolver404, resolve, reverse
from django.utils.encoding import force_bytes
from django.utils.http import urlquote
from requests.exceptions import HTTPError
from judge.models import Profile, Language
from django.contrib.auth.models import User

admin_change_re = re.compile(r"/admin/auth/user/(\d+)/change/")
admin_change_default_lang = lang = Language.get_python3()

class ShortCircuitMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        try:
            callback, args, kwargs = resolve(request.path_info, getattr(request, 'urlconf', None))
        except Resolver404:
            callback, args, kwargs = None, None, None

        if getattr(callback, 'short_circuit_middleware', False):
            return callback(request, *args, **kwargs)
        return self.get_response(request)
Esempio n. 25
0
 def get_initial(self, request=None):
     initial = super(RegistrationView, self).get_initial(request)
     initial['timezone'] = 'America/Toronto'
     initial['language'] = Language.get_python2()
     return initial
Esempio n. 26
0
    def setUpTestData(self):
        super().setUpTestData()

        self.users.update({
            'staff_submission_view_all':
            create_user(
                username='******',
                is_staff=True,
                user_permissions=('view_all_submission', ),
            ),
        })

        self.basic_submission = Submission.objects.create(
            user=self.users['normal'].profile,
            problem=create_problem(code='basic'),
            language=Language.get_python3(),
            result='AC',
            status='D',
            case_points=99,
            case_total=100,
            memory=20,
            locked_after=None,
        )

        self.full_ac_submission = Submission.objects.create(
            user=self.users['normal'].profile,
            problem=create_problem(code='full_ac'),
            language=Language.get_python3(),
            result='AC',
            status='D',
            case_points=1,
            case_total=1,
        )
        self.full_ac_submission_source = SubmissionSource.objects.create(
            submission=self.full_ac_submission,
            source='',
        )

        self.locked_submission = Submission.objects.create(
            user=self.users['normal'].profile,
            problem=create_problem(code='locked'),
            language=Language.get_python3(),
            result='WA',
            status='D',
            case_points=1,
            case_total=1,
            locked_after=timezone.now() - timezone.timedelta(days=100),
        )

        self.future_locked_submission = Submission.objects.create(
            user=self.users['normal'].profile,
            problem=create_problem(code='future_locked'),
            language=Language.get_python3(),
            result='WA',
            status='D',
            case_points=1,
            case_total=1,
            locked_after=timezone.now() + timezone.timedelta(days=100),
        )

        self.ie_submission = Submission.objects.create(
            user=self.users['superuser'].profile,
            problem=create_problem(
                code='ie',
                is_public=True,
            ),
            language=Language.get_python3(),
            result='IE',
            status='IE',
            memory=None,
        )

        # jump down the rabbit hole to attach a contest submission
        problem = create_problem(code='queued')
        contest = create_contest(key='queued')
        self.queued_submission = Submission.objects.create(
            user=self.users['superuser'].profile,
            problem=problem,
            language=Language.get_python3(),
            contest_object=contest,
            case_points=50,
            case_total=100,
        )
        self.queued_contest_submission = ContestSubmission.objects.create(
            submission=self.queued_submission,
            problem=create_contest_problem(problem=problem,
                                           contest=contest,
                                           partial=False),
            participation=create_contest_participation(contest=contest,
                                                       user='******'),
        )
Esempio n. 27
0
 def get_initial(self, request=None):
     initial = super(RegistrationView, self).get_initial(request)
     initial['timezone'] = getattr(settings, 'DEFAULT_USER_TIME_ZONE', 'America/Toronto')
     initial['language'] = Language.get_python2()
     return initial
Esempio n. 28
0
 def get_initial(self, request=None):
     initial = super(RegistrationView, self).get_initial(request)
     initial['timezone'] = getattr(settings, 'DEFAULT_USER_TIME_ZONE',
                                   'America/Toronto')
     initial['language'] = Language.get_python2()
     return initial