Esempio n. 1
0
    def save(self):
        #   Reset user's offers
        if self.cleaned_data['user']:
            user = ESPUser.objects.get(id=self.cleaned_data['user'])
            user.volunteeroffer_set.all().delete()

        #   Create user if one doesn't already exist, otherwise associate a user.
        #   Note that this will create a new user account if they enter an e-mail
        #   address different from the one on file.
        if not self.cleaned_data['user']:
            user_data = {
                'first_name': self.cleaned_data['name'].split()[0],
                'last_name': ' '.join(self.cleaned_data['name'].split()[1:]),
                'email': self.cleaned_data['email'],
            }
            existing_users = ESPUser.objects.filter(
                **user_data).order_by('-id')
            if existing_users.exists():
                #   Arbitrarily pick the most recent account
                #   This is not too important, we just need a link to an e-mail address.
                user = existing_users[0]
            else:
                auto_username = ESPUser.get_unused_username(
                    user_data['first_name'], user_data['last_name'])
                user = ESPUser(
                    User.objects.create_user(auto_username,
                                             user_data['email']))
                user.__dict__.update(user_data)
                user.save()

        #   Record this user account as a volunteer
        user.makeVolunteer()

        #   Remove offers with the same exact contact info
        VolunteerOffer.objects.filter(email=self.cleaned_data['email'],
                                      phone=self.cleaned_data['phone'],
                                      name=self.cleaned_data['name']).delete()

        offer_list = []
        for req in self.cleaned_data['requests']:
            o = VolunteerOffer()
            o.user_id = user.id
            o.email = self.cleaned_data['email']
            o.phone = self.cleaned_data['phone']
            o.name = self.cleaned_data['name']
            o.confirmed = self.cleaned_data['confirm']
            if 'shirt_size' in self.cleaned_data:
                o.shirt_size = self.cleaned_data['shirt_size']
            if 'shirt_type' in self.cleaned_data:
                o.shirt_type = self.cleaned_data['shirt_type']
            if 'comments' in self.cleaned_data:
                o.comments = self.cleaned_data['comments']
            o.request_id = req
            o.save()
            offer_list.append(o)
        return offer_list
Esempio n. 2
0
def user_registration_validate(request):    
    """Handle the account creation logic when the form is submitted

This function is overloaded to handle either one or two phase reg"""

    if not Tag.getBooleanTag("ask_about_duplicate_accounts",default=False):
        form = SinglePhaseUserRegForm(request.POST)
    else:
        form = UserRegForm(request.POST)

    if form.is_valid():         
        try:
            #there is an email-only account with that email address to upgrade
            user = ESPUser.objects.get(email=form.cleaned_data['email'],
                                       password = '******')
        except ESPUser.DoesNotExist:
            try:
                #there is an inactive account with that username
                user = ESPUser.objects.filter(
                    username = form.cleaned_data['username'],
                    is_active = False).latest('date_joined')

            except ESPUser.DoesNotExist:
                user = ESPUser(email = form.cleaned_data['email'])

        user.username   = form.cleaned_data['username']
        user.last_name  = form.cleaned_data['last_name']
        user.first_name = form.cleaned_data['first_name']
        user.set_password(form.cleaned_data['password'])
            
        #   Append key to password and disable until activation if desired
        if Tag.getBooleanTag('require_email_validation', default=False):
            userkey = random.randint(0,2**31 - 1)
            user.password += "_%d" % userkey
            user.is_active = False

        user.save()
        ESPUser_Profile.objects.get_or_create(user = user)

        user.groups.add(Group.objects.get(name=form.cleaned_data['initial_role']))

        if not Tag.getBooleanTag('require_email_validation', default=False):
            user = authenticate(username=form.cleaned_data['username'],
                                    password=form.cleaned_data['password'])
                
            login(request, user)
            return HttpResponseRedirect('/myesp/profile/')
        else:
            send_activation_email(user,userkey)
            return render_to_response('registration/account_created_activation_required.html', request,
                                      {'user': user, 'site': Site.objects.get_current()})
    else:
        return render_to_response('registration/newuser.html',
                                  request, {'form':form})
Esempio n. 3
0
def profile_editor(request, prog_input=None, responseuponCompletion = True, role=''):
    """ Display the registration profile page, the page that contains the contact information for a student, as attached to a particular program """

    from esp.users.models import K12School
    from esp.web.views.main import registration_redirect
    
    STUDREP_VERB = GetNode('V/Flags/UserRole/StudentRep')
    STUDREP_QSC  = GetNode('Q')


    if prog_input is None:
        prog = None
        navnode = GetNode('Q/Web/myesp')
    else:
        prog = prog_input
        navnode = prog.anchor

    curUser = request.user
    context = {'logged_in': request.user.is_authenticated() }
    context['user'] = request.user
    context['program'] = prog

    curUser = ESPUser(curUser)
    curUser.updateOnsite(request)

    #   Get the profile form from the user's type, although we need to handle 
    #   a couple of extra possibilities for the 'role' variable.
    user_types = ESPUser.getAllUserTypes()
    additional_types = [['',  {'label': 'Not specified', 'profile_form': 'UserContactForm'}],
                        ['Administrator', {'label': 'Administrator', 'profile_form': 'UserContactForm'}],
                       ]
    additional_type_labels = [x[0] for x in additional_types]
    #   Handle all-lowercase versions of role being passed in by calling title()
    user_type_labels = [x[0] for x in user_types]
    if role.title() in user_type_labels:
        target_type = user_types[user_type_labels.index(role.title())][1]
    else:
        target_type = additional_types[additional_type_labels.index(role.title())][1]
    mod = __import__('esp.users.forms.user_profile', (), (), target_type['profile_form'])
    FormClass = getattr(mod, target_type['profile_form'])

    context['profiletype'] = role

    if request.method == 'POST' and request.POST.has_key('profile_page'):
        form = FormClass(curUser, request.POST)

        # Don't suddenly demand an explanation from people who are already student reps
        if UserBit.objects.UserHasPerms(curUser, STUDREP_QSC, STUDREP_VERB):
            if hasattr(form, 'repress_studentrep_expl_error'):
                form.repress_studentrep_expl_error()

        if form.is_valid():
            new_data = form.cleaned_data

            regProf = RegistrationProfile.getLastForProgram(curUser, prog)

            if regProf.id is None:
                old_regProf = RegistrationProfile.getLastProfile(curUser)
            else:
                old_regProf = regProf

            for field_name in ['address_zip','address_city','address_street','address_state']:
                if field_name in new_data and new_data[field_name] != getattr(old_regProf.contact_user,field_name,False):
                    new_data['address_postal'] = ''

            if new_data['address_postal'] == '':
                new_data['address_postal'] = False

            regProf.contact_user = ContactInfo.addOrUpdate(regProf, new_data, regProf.contact_user, '', curUser)
            regProf.contact_emergency = ContactInfo.addOrUpdate(regProf, new_data, regProf.contact_emergency, 'emerg_')

            if new_data.has_key('dietary_restrictions') and new_data['dietary_restrictions']:
                regProf.dietary_restrictions = new_data['dietary_restrictions']

            if role == 'student':
                regProf.student_info = StudentInfo.addOrUpdate(curUser, regProf, new_data)
                regProf.contact_guardian = ContactInfo.addOrUpdate(regProf, new_data, regProf.contact_guardian, 'guard_')
            elif role == 'teacher':
                regProf.teacher_info = TeacherInfo.addOrUpdate(curUser, regProf, new_data)
            elif role == 'guardian':
                regProf.guardian_info = GuardianInfo.addOrUpdate(curUser, regProf, new_data)
            elif role == 'educator':
                regProf.educator_info = EducatorInfo.addOrUpdate(curUser, regProf, new_data)
            blah = regProf.__dict__
            regProf.save()

            curUser.first_name = new_data['first_name']
            curUser.last_name  = new_data['last_name']
            curUser.email     = new_data['e_mail']
            curUser.save()
            if responseuponCompletion == True:
                return registration_redirect(request)
            else:
                return True
        else:
            #   Force loading the school back in if possible...
            replacement_data = form.data.copy()
            try:
                replacement_data['k12school'] = form.fields['k12school'].clean(form.data['k12school']).id
            except:
                pass
            form = FormClass(curUser, replacement_data)

    else:
        if prog_input is None:
            regProf = RegistrationProfile.getLastProfile(curUser)
        else:
            regProf = RegistrationProfile.getLastForProgram(curUser, prog)
        if regProf.id is None:
            regProf = RegistrationProfile.getLastProfile(curUser)
        new_data = {}
        if curUser.isStudent():
            new_data['studentrep'] = (UserBit.objects.filter(user = curUser,
                                     verb = STUDREP_VERB,
                                     qsc  = STUDREP_QSC).count() > 0)
        new_data['first_name'] = curUser.first_name
        new_data['last_name']  = curUser.last_name
        new_data['e_mail']     = curUser.email
        new_data = regProf.updateForm(new_data, role)
        if request.session.has_key('birth_month') and request.session.has_key('birth_day'):
            new_data['dob'] = datetime.date(1994, int(request.session['birth_month']), int(request.session['birth_day']))
        if request.session.has_key('school_id'):
            new_data['k12school'] = request.session['school_id']

        #   Set default values for state fields
        state_fields = ['address_state', 'emerg_address_state']
        state_tag_map = {}
        for field in state_fields:
            state_tag_map[field] = 'local_state'
        form = FormClass(curUser, initial=new_data, tag_map=state_tag_map)

    context['request'] = request
    context['form'] = form
    return render_to_response('users/profile.html', request, navnode, context)
    def satprep_create(self, request, tl, one, two, module, extra, prog):
        if request.method == 'POST':
            form = OnSiteSATPrepRegForm(request.POST)

            if form.is_valid():
                new_data = form.cleaned_data
                username = base_uname = (new_data['first_name'][0]+ \
                                         new_data['last_name']).lower()
                if ESPUser.objects.filter(username=username).count() > 0:
                    i = 2
                    username = base_uname + str(i)
                    while ESPUser.objects.filter(
                            username=username).count() > 0:
                        i += 1
                        username = base_uname + str(i)
                new_user = ESPUser(username=username,
                                   first_name=new_data['first_name'],
                                   last_name=new_data['last_name'],
                                   email=new_data['email'],
                                   is_staff=False,
                                   is_superuser=False)
                new_user.save()
                self.student = new_user
                new_user.recoverPassword()

                #update satprep information
                satprep = SATPrepRegInfo.getLastForProgram(
                    new_user, self.program)
                satprep.old_math_score = new_data['old_math_score']
                satprep.old_verb_score = new_data['old_verb_score']
                satprep.old_writ_score = new_data['old_writ_score']
                satprep.save()

                if new_data['paid']:
                    self.createBit('Paid')

                self.createBit('Attended')

                if new_data['medical']:
                    self.createBit('MedicalFiled')

                if new_data['liability']:
                    self.createBit('LiabilityFiled')

                self.createBit('OnSite')

                v = GetNode('V/Flags/UserRole/Student')
                ub = UserBit()
                ub.user = new_user
                ub.recursive = False
                ub.qsc = GetNode('Q')
                ub.verb = v
                ub.save()

                new_user = ESPUser(new_user)

                return render_to_response(self.baseDir() + 'reg_success.html',
                                          request, (prog, tl),
                                          {'user': new_user})

        else:
            form = OnSiteSATPrepRegForm()

        return render_to_response(self.baseDir() + 'reg_info.html', request,
                                  (prog, tl), {'form': form})
Esempio n. 5
0
    def onsite_create(self, request, tl, one, two, module, extra, prog):
        if request.method == 'POST':
            form = OnSiteRegForm(request.POST)

            if form.is_valid():
                new_data = form.cleaned_data
                username = ESPUser.get_unused_username(new_data['first_name'],
                                                       new_data['last_name'])
                new_user = ESPUser(username=username,
                                   first_name=new_data['first_name'],
                                   last_name=new_data['last_name'],
                                   email=new_data['email'],
                                   is_staff=False,
                                   is_superuser=False)
                new_user.save()

                self.student = new_user

                regProf = RegistrationProfile.getLastForProgram(
                    new_user, self.program)
                contact_user = ContactInfo(first_name=new_user.first_name,
                                           last_name=new_user.last_name,
                                           e_mail=new_user.email,
                                           user=new_user)
                contact_user.save()
                regProf.contact_user = contact_user

                student_info = StudentInfo(
                    user=new_user,
                    graduation_year=ESPUser.YOGFromGrade(new_data['grade']))

                try:
                    if isinstance(new_data['k12school'], K12School):
                        student_info.k12school = new_data['k12school']
                    else:
                        if isinstance(new_data['k12school'], int):
                            student_info.k12school = K12School.objects.get(
                                id=int(new_data['k12school']))
                        else:
                            student_info.k12school = K12School.objects.filter(
                                name__icontains=new_data['k12school'])[0]
                except:
                    student_info.k12school = None
                student_info.school = new_data[
                    'school'] if not student_info.k12school else student_info.k12school.name

                student_info.save()
                regProf.student_info = student_info

                regProf.save()

                if new_data['paid']:
                    self.createBit('paid')
                    self.updatePaid(True)
                else:
                    self.updatePaid(False)

                self.createBit('Attended')

                if new_data['medical']:
                    self.createBit('Med')

                if new_data['liability']:
                    self.createBit('Liab')

                self.createBit('OnSite')

                new_user.groups.add(Group.objects.get(name="Student"))

                new_user.recoverPassword()

                return render_to_response(
                    self.baseDir() + 'reg_success.html', request, {
                        'student':
                        new_user,
                        'retUrl':
                        '/onsite/%s/classchange_grid?student_id=%s' %
                        (self.program.getUrlBase(), new_user.id)
                    })

        else:
            form = OnSiteRegForm()

        return render_to_response(self.baseDir() + 'reg_info.html', request, {
            'form': form,
            'current_year': ESPUser.current_schoolyear()
        })
Esempio n. 6
0
    def onsite_create(self, request, tl, one, two, module, extra, prog):
        if request.method == 'POST':
            form = OnSiteRegForm(request.POST)
            
            if form.is_valid():
                new_data = form.cleaned_data
                username = ESPUser.get_unused_username(new_data['first_name'], new_data['last_name'])
                new_user = ESPUser(username = username,
                                first_name = new_data['first_name'],
                                last_name  = new_data['last_name'],
                                email      = new_data['email'],
                                is_staff   = False,
                                is_superuser = False)
                new_user.save()

                self.student = new_user

                regProf = RegistrationProfile.getLastForProgram(new_user,
                                                                self.program)
                contact_user = ContactInfo(first_name = new_user.first_name,
                                           last_name  = new_user.last_name,
                                           e_mail     = new_user.email,
                                           user       = new_user)
                contact_user.save()
                regProf.contact_user = contact_user

                student_info = StudentInfo(user = new_user, graduation_year = ESPUser.YOGFromGrade(new_data['grade']))
                student_info.save()
                regProf.student_info = student_info

                regProf.save()
                
                if new_data['paid']:
                    self.createBit('Paid')
                    self.updatePaid(True)
                else:
                    self.updatePaid(False)

                self.createBit('Attended')

                if new_data['medical']:
                    self.createBit('MedicalFiled')

                if new_data['liability']:
                    self.createBit('LiabilityFiled')

                self.createBit('OnSite')

                v = GetNode( 'V/Flags/UserRole/Student')
                ub = UserBit()
                ub.user = new_user
                ub.recursive = False
                ub.qsc = GetNode('Q')
                ub.verb = v
                ub.save()

                new_user.recoverPassword()
                
                return render_to_response(self.baseDir()+'reg_success.html', request, (prog, tl), {
                    'student': new_user, 
                    'retUrl': '/onsite/%s/classchange_grid?student_id=%s' % (self.program.getUrlBase(), new_user.id)
                    })

        else:
            form = OnSiteRegForm()

	return render_to_response(self.baseDir()+'reg_info.html', request, (prog, tl), {'form':form, 'current_year':ESPUser.current_schoolyear()})