Exemplo n.º 1
0
def register(request):
    register_exception = None
    try:
        # Python 2.7
        backend = "registration.backends.default.DefaultBackend"	# Sends e-mail?
#        backend = "django.contrib.auth.backends.RemoteUserBackend"	# Method "registration_allowed" does not exist
#        backend = settings.AUTHENTICATION_BACKENDS[0]			# Method "registration_allowed" does not exist
        return registration_views.register(
            request, backend,
            form_class=FullRegistrationForm)
    # Detect exception for unsent e-mail
    except smtplib.SMTPException as e:
        register_exception = e
        print "[ERROR] Exception at 'expedient.clearinghouse.users.views'. User '%s' (%s) may have not been registered as it was not possible to send e-mail. Exception: %s" % (request.POST['username'], request.POST['email'], str(e))
    except Exception as e:
        try:
            # Python 2.6
            return registration_views.register(
	        request,
                form_class=FullRegistrationForm)
        except Exception as e:
            register_exception = e
            print "[ERROR] Exception at 'expedient.clearinghouse.users.views': user '%s' (%s) could not fully register. RegistrationForm module returned: %s" % (request.POST['username'], request.POST['email'], str(e))
    # If there was an exception during the registration process, show this on the GUI
    if register_exception:
        return simple.direct_to_template(
            request,
            template="registration/registration_incomplete.html",
                extra_context={
                    "exception": e,
                    "root_email": settings.ROOT_EMAIL,
                    "failed_username": request.POST["username"],
                    "failed_email": request.POST["email"],
                },
            )
Exemplo n.º 2
0
def custom_register (request, *args, **kwargs):
    """
    Wrap the django-registration register view in a custom view, so that we can
    use reCAPTCHA.
    """
    if request.method == "POST":
        # Check the captcha
        check_captcha = captcha.submit(\
            request.POST["recaptcha_challenge_field"],
            request.POST["recaptcha_response_field"],
            settings.RECAPTCHA_PRIVATE_KEY,
            request.META["REMOTE_ADDR"])
        
        if not check_captcha.is_valid:
            # If the captcha is wrong, error
            form    = kwargs["form_class"](request.POST)
            context = {"form": form, "recaptcha_failed": True}
            
            if "extra_context" in kwargs:
                context.update(kwargs["extra_context"])
            
            return render_to_response("registration/registration_form.html",
                context, context_instance=RequestContext(request))
        
    return register(request, *args, **kwargs)
Exemplo n.º 3
0
def register(request):
    if not request.user.is_authenticated():
        from registration.views import register
        return register(request, backend='registration.backends.default.DefaultBackend', form_class=HackerRegistrationForm, success_url=reverse('registration_complete'), template_name='registration/registration_form.html')
    else:
        #if logged in
        return redirect(reverse('landing_page'))
Exemplo n.º 4
0
def p_signup(request,backend):
    template_var = {}

    # print "work as patient"
    return register(request,backend,
                      identity="P",
                      template_name = "registration/p_signup.html",extra_context = template_var) 
Exemplo n.º 5
0
def register_view(request, form_class=None, template_name=None,
                         backend=None, language=None):
        if language:
            request.session['django_language'] = language
            activate(language)
        return register(request, backend, form_class=form_class,
             template_name=template_name)
Exemplo n.º 6
0
def register(request, form_class=RegistrationForm):

    if request.user.is_authenticated():
        # They are logged in, redirect to user account page
        return HttpResponseRedirect( reverse('profiles_create_profile'))

    return reg_views.register(request, form_class=form_class)
Exemplo n.º 7
0
def invitation_detail(request, token):
    """
    Returns a sign up form via the django-registration app if the URL is valid.
    """
    invitation = Invitation.objects.get_invitation(token)
    if not invitation:
        return invitation_error(request, "This invitation is no longer valid.")

    backend = getattr(settings, 'REGISTRATION_BACKEND', 'registration.backends.default.DefaultBackend')
    return register(request, backend)
Exemplo n.º 8
0
def about(request, template=None):

    if request.POST:
        return register(request, 'applicant.backends.DemoApplicantBackend', template_name=template)

    ctxt = {}
    ctxt['applicant_login_form'] = ApplicantLoginForm()
    ctxt['employer_login_form'] = EmployerLoginForm()
    ctxt['form'] = DemoApplicantRegistrationForm()
    ctxt['settings'] = settings
    return render_to_response(template, ctxt, context_instance = RequestContext(request))
Exemplo n.º 9
0
def invitation_detail(request, token):
    """
    Returns a sign up form via the django-registration app if the URL is valid.
    """
    invitation = Invitation.objects.get_invitation(token)
    if not invitation:
        return invitation_error(request, "This invitation is no longer valid.")

    backend = getattr(settings, 'REGISTRATION_BACKEND',
                      'registration.backends.default.DefaultBackend')
    return register(request, backend)
Exemplo n.º 10
0
def d_signup(request,backend):
    '''
    **参数**
    ``backend``
        backend是函数register所需要的,由urls.py里赋值,传入该函数
    '''
    template_var = {}
    
    # print "work as dentist"
    return register(request,backend,
                      identity="D",
                      template_name = "registration/d_signup.html",extra_context = template_var)
Exemplo n.º 11
0
def register(request):
    response = registration_views.register(
        request,
        backend="registration.backends.default.DefaultBackend",
        form_class=forms.RegistrationForm,
        template_name="users/registration_form.html",
        success_url=reverse("home"),
    )

    if response.status_code == 302:
        messages.success(request, "Check your email for an account activation link.")

    return response
Exemplo n.º 12
0
def homepage (request, template_name , page_template):
    """
    Homepage for logged in user and signin page for other
    """
    if request.user.is_authenticated():
        try:
            user = User.objects.get(username = request.user.username)
        except User.DoesNotExist:
            messages.error(request, "You are not a logged in user.")
            return HttpResponseRedirect(reverse('auth_logout'))
            
        try:
            user_profile = user.get_profile()
        except UserProfile.DoesNotExist:
            messages.error(request, "Profile does not exist.")
            return HttpResponseRedirect(reverse('auth_logout'))

        followers_widget = Felloz.objects.get_followers(user = user)
        followings_widget = Felloz.objects.get_followings(user = user)

        recommendations_widget = UserProfile.objects.filter( tags__in = user_profile.tags.all() ).distinct().exclude(user__in = followings_widget).exclude( user = user )
        if not recommendations_widget:
            recommendations_widget = UserProfile.objects.filter(~Q( user__in = followings_widget ) ).exclude( user = user ).order_by('?')

        tags = []
        tags_string = ''
        for x in Tag.objects.all():
            tag = unicodedata.normalize('NFKD', x.name).encode('ascii','ignore')
            tags.append( tag )

            tags_string = ','.join(tags)

        context = {
            'profile': user_profile,
            'followers_widget': followers_widget,
            'followings_widget': followings_widget,
            'recommendations_widget': recommendations_widget,
            'related_doc_widget': related_doc_widget,
            'page_template': page_template,
            'tags': tags_string,
            'site': Site.objects.get_current(),
            }

        if request.is_ajax():
            template_name = page_template
        return render_to_response(template_name, context, context_instance=RequestContext(request))
    else:
        form = AuthenticationForm(request)
        form_registration = register(request, settings.REGISTRATION_BACKENDS, homepage_referer = True)
        return render_to_response('registration/login_registration_forms.html', {'background': True, 'form': form, 'form_registration': form_registration},
                                  context_instance=RequestContext(request))
Exemplo n.º 13
0
def register(request):
    response = registration_views.register(
        request,
        backend="registration.backends.default.DefaultBackend",
        form_class=forms.RegistrationForm,
        template_name="users/registration_form.html",
        success_url=reverse("home"),
    )

    if response.status_code == 302:
        messages.success(request,
                         "Check your email for an account activation link.")

    return response
Exemplo n.º 14
0
def register_volunteer(request, *args, **kwargs):
    """Override of default django-registration register, adding
    NonUserProfile data to profile
    """
    if 'nonuser_profile' in request.session:
        nonuser_profile = request.session['nonuser_profile']
    else:
        nonuser_profile = {}
    prerendered_select = USStateSelect(attrs={
        'required': 'required',
        'id': 'state'
    }).render('state', nonuser_profile.get('state', ''))
    resp = register(request,
                    backend='registration.backends.default.DefaultBackend',
                    form_class=BetterRegistrationFormUniqueEmail,
                    extra_context={
                        'nonuser_profile': nonuser_profile,
                        'prerendered_select': prerendered_select
                    })

    if request.method == 'POST':

        try:

            user = User.objects.get(username=request.POST['username'])
            user.first_name = nonuser_profile.get(
                'first_name', request.POST.get('first_name', ''))
            user.last_name = nonuser_profile.get(
                'last_name', request.POST.get('last_name', ''))
            user.save()
            user.get_profile()

        except User.DoesNotExist:
            pass

        except Profile.DoesNotExist:
            profile = Profile(
                user=user,
                phone=nonuser_profile.get('phone',
                                          request.POST.get('phone', '')),
                city=nonuser_profile.get('city', request.POST.get('city', '')),
                state=nonuser_profile.get('state',
                                          request.POST.get('state', '')),
                zipcode=nonuser_profile.get('zipcode',
                                            request.POST.get('zipcode', '')),
                is_a=nonuser_profile.get('is_a', request.POST.get('is_a', '')))
            profile.save()

    return resp
Exemplo n.º 15
0
def register(request):
    register_exception = None
    try:
        # Python 2.7
        backend = "registration.backends.default.DefaultBackend"  # Sends e-mail?
        #        backend = "django.contrib.auth.backends.RemoteUserBackend"	# Method "registration_allowed" does not exist
        #        backend = settings.AUTHENTICATION_BACKENDS[0]			# Method "registration_allowed" does not exist
        return registration_views.register(request,
                                           backend,
                                           form_class=FullRegistrationForm)
    # Detect exception for unsent e-mail
    except smtplib.SMTPException as e:
        register_exception = e
        print "[ERROR] Exception at 'expedient.clearinghouse.users.views'. User '%s' (%s) may have not been registered as it was not possible to send e-mail. Exception: %s" % (
            request.POST['username'], request.POST['email'], str(e))
    except Exception as e:
        try:
            # Python 2.6
            return registration_views.register(request,
                                               form_class=FullRegistrationForm)
        except Exception as e:
            register_exception = e
            print "[ERROR] Exception at 'expedient.clearinghouse.users.views': user '%s' (%s) could not fully register. RegistrationForm module returned: %s" % (
                request.POST['username'], request.POST['email'], str(e))
    # If there was an exception during the registration process, show this on the GUI
    if register_exception:
        return simple.direct_to_template(
            request,
            template="registration/registration_incomplete.html",
            extra_context={
                "exception": e,
                "root_email": settings.ROOT_EMAIL,
                "failed_username": request.POST["username"],
                "failed_email": request.POST["email"],
            },
        )
Exemplo n.º 16
0
def register_with_token(request, token, backend):
    extra_context={'token': token}
    if request.method == 'POST': # delegate to the registration app
        return register(request, backend, form_class=InvitedUserProfileRegistrationForm, extra_context=extra_context, success_url='root')
    else:
        try:
            invite = UserInvite.objects.get(token=token)
        except UserInvite.DoesNotExist:
            form = InvitedUserProfileRegistrationForm(initial={'token': token})
        else:
            form = InvitedUserProfileRegistrationForm(initial={'token': token, 'email':invite.email})
            extra_context['email'] = invite.email
    
    extra_context['form'] = form
    return direct_to_template(request, template='registration/registration_form.html', extra_context=extra_context)
Exemplo n.º 17
0
def register(request):
    try:
        return registration_views.register(request,
                                           form_class=FullRegistrationForm)
    except Exception as e:
        print "[ERROR] Exception at 'expedient.clearinghouse.users.views': user '%s' (%s) could not fully register. RegistrationForm module returned: %s" % (
            request.POST['username'], request.POST['email'], str(e))
        return simple.direct_to_template(
            request,
            template='registration/registration_incomplete.html',
            extra_context={
                'exception': e,
                'root_email': settings.ROOT_EMAIL,
                'failed_username': request.POST['username'],
                'failed_email': request.POST['email'],
            },
        )
Exemplo n.º 18
0
def register(request):
    try:
	return registration_views.register(
	    request,
            form_class=FullRegistrationForm)
    except Exception as e:
        print "[ERROR] Exception at 'expedient.clearinghouse.users.views': user '%s' (%s) could not fully register. RegistrationForm module returned: %s" % (request.POST['username'], request.POST['email'], str(e))
        return simple.direct_to_template(
            request,
            template='registration/registration_incomplete.html',
            extra_context={
                'exception': e,
                'root_email': settings.ROOT_EMAIL,
                'failed_username': request.POST['username'],
                'failed_email': request.POST['email'],
            },
        )
Exemplo n.º 19
0
def splash(request, template=None):

    if request.user.is_authenticated():
        try:
            profile = ApplicantProfile.objects.get(user=request.user)
            return redirect(reverse('applicant_dashboard'))
        except ApplicantProfile.DoesNotExist:
            return redirect(reverse('employer_dashboard'))

    if request.POST:
        return register(request, 'applicant.backends.DemoApplicantBackend', template_name=template)

    ctxt = {}
    ctxt['applicant_login_form'] = ApplicantLoginForm()
    ctxt['employer_login_form'] = EmployerLoginForm()
    ctxt['form'] = DemoApplicantRegistrationForm()
    ctxt['settings'] = settings
    return render_to_response(template, ctxt, context_instance = RequestContext(request))
Exemplo n.º 20
0
def custom_register(request, **kwargs):
    """Registers users and redirects those who are already authenticated."""
    if request.user.is_authenticated():
        return HttpResponseRedirect(LOGIN_REDIRECT_URL)
    else:
        site_config_error, email_config_error = False, False
        if Site.objects.get_current().domain == "example.com"\
        or Site.objects.get_current().name == "example.com":
            site_config_error = True
        if project_settings.EMAIL_HOST_USER == "*****@*****.**":
            email_config_error = True

        return registration_views.register(request,
            backend='registration.backends.default.DefaultBackend',
            template_name='registration/registration_form.html',
            extra_context={
                'site_config_error' : site_config_error,
                'email_config_error': email_config_error},
            **kwargs)
Exemplo n.º 21
0
def custom_register(request, **kwargs):
    """Registers users and redirects those who are already authenticated."""
    if request.user.is_authenticated():
        return HttpResponseRedirect(LOGIN_REDIRECT_URL)
    else:
        site_config_error, email_config_error = False, False
        if Site.objects.get_current().domain == "example.com"\
        or Site.objects.get_current().name == "example.com":
            site_config_error = True
        if project_settings.EMAIL_HOST_USER == "*****@*****.**":
            email_config_error = True

        return registration_views.register(
            request,
            backend='registration.backends.default.DefaultBackend',
            template_name='registration/registration_form.html',
            extra_context={
                'site_config_error': site_config_error,
                'email_config_error': email_config_error
            },
            **kwargs)
Exemplo n.º 22
0
 def post(self, request, *args, **kwargs):
     cookie = facebook.get_user_from_cookie(request.COOKIES,
                                            settings.FACEBOOK_APP_ID,
                                            settings.FACEBOOK_API_SECRET)
     
     if cookie:
         uid = cookie['uid']
         facebook_api = facebook.GraphAPI(cookie['access_token']);
         try:
             profile = facebook_api.get_object('me')
         
             post_req = request.POST.copy()
             post_req["username"] = profile["name"]
             post_req["email"] = profile["email"]
             password = rand1(8)
             post_req["password1"]=post_req["password2"]=password
             request.POST = post_req
         
         except URLError:
             pass
     else:
             profile = {}
         
     http_response = register(request, form_class=RegistrationFormExpandedUsername, *args, **kwargs) 
     
     if "email" in profile and isinstance(http_response, HttpResponseRedirect):
         try:
             new_user = User.objects.get(email=profile["email"])
             UserSocialAuth.objects.create(user=new_user, 
                                           uid=uid,
                                           provider="facebook",
                                           extra_data=simplejson.dumps({u'access_token': cookie['access_token'], 
                                                                         u'expires': None, 
                                                                         u'id': uid,
                                                                         u'public_profile_url':'https://graph.facebook.com/%s' % (profile["username"])
                                                                       })
                                           )
         except User.DoesNotExist:
             pass
     return http_response
Exemplo n.º 23
0
def view_homepage(request):
	if request.user.is_authenticated(): return redirect(settings.LOGIN_REDIRECT_URL)

	if request.method == "POST":
		submit_type = request.POST.get('submit_button')

		if submit_type == "register":
			from registration.views import register
			return register(request, 'registration.backends.default.DefaultBackend')

		elif submit_type == "login":
			from django.contrib.auth.views import login
			return login(request)

		else:
			return redirect("/")

	else:
		register_form = RegistrationForm(auto_id=False)
		login_form = AuthenticationForm(auto_id=False)

	return render_to_response(settings.OPENGIS_TEMPLATE_PREFIX + "homepage.html", {'register_form':register_form, 'login_form':login_form}, context_instance=RequestContext(request))
Exemplo n.º 24
0
def register_volunteer(request, *args, **kwargs):
    """Override of default django-registration register, adding
    NonUserProfile data to profile
    """
    if 'nonuser_profile' in request.session:
        nonuser_profile = request.session['nonuser_profile']
    else:
        nonuser_profile = {}
    prerendered_select = USStateSelect(attrs={'required': 'required', 'id': 'state'}).render('state', nonuser_profile.get('state', ''))
    resp = register(request, backend='registration.backends.default.DefaultBackend',
                    form_class=BetterRegistrationFormUniqueEmail, extra_context={'nonuser_profile': nonuser_profile, 'prerendered_select': prerendered_select})

    if request.method == 'POST':

        try:

            user = User.objects.get(username=request.POST['username'])
            user.first_name = nonuser_profile.get('first_name', request.POST.get('first_name', ''))
            user.last_name = nonuser_profile.get('last_name', request.POST.get('last_name', ''))
            user.save()
            user.get_profile()

        except User.DoesNotExist:
            pass

        except Profile.DoesNotExist:
            profile = Profile(
                user=user,
                phone=nonuser_profile.get('phone', request.POST.get('phone', '')),
                city=nonuser_profile.get('city', request.POST.get('city', '')),
                state=nonuser_profile.get('state', request.POST.get('state', '')),
                zipcode=nonuser_profile.get('zipcode', request.POST.get('zipcode', '')),
                is_a=nonuser_profile.get('is_a', request.POST.get('is_a', ''))
            )
            profile.save()

    return resp
Exemplo n.º 25
0
def register_inline(request, backend, success_url=None, form_class=None,
                    disallowed_url='registration_disallowed',
                    template_name='registration/registration_inline.html',
                    extra_context=None):
    '''
    This view needs signed url in `u` GET parameter
    '''
    try:
        signed_url = request.GET.get('u','not valid :(')
        log.debug('signed url from GET[u]: %s'%signed_url)
        org_url = signing.loads(signed_url)
        log.debug('De-signed url: %s'%org_url)
    except signing.BadSignature:
        messages.error(request, _("Passed URL was invalid. Please try again!"))
        log.error('Invalid signed URL passed to inline registration')
        return redirect('/')

    if not extra_context:
        extra_context={}

    extra_context['url']=org_url[0]

    return register(request, backend, success_url, form_class, 
            disallowed_url, template_name, extra_context)
Exemplo n.º 26
0
 def get(self, request, *args, **kwargs):
     twitter_cookie = twitter.get_user_from_cookie(request.COOKIES,
                                                   settings.TWITTER_CONSUMER_SECRET)
     if twitter_cookie:
         uid = twitter_cookie['uid']
         post_req = request.POST.copy()
         #post_req["email"] = profile["email"]
         password = rand1(8)
         post_req["password1"]=post_req["password2"]=password
         request.POST = post_req
     else:
         profile = {}
             
     http_response = register(request, form_class=RegistrationFormExpandedUsername, *args, **kwargs) 
     
     if twitter_cookie and isinstance(http_response, HttpResponseRedirect):
         try:
             new_user = User.objects.get(username=profile["username"])
             UserSocialAuth.objects.create(user=new_user, 
                                           uid=uid,
                                           provider="twitter")
         except User.DoesNotExist:
             pass
     return http_response
Exemplo n.º 27
0
 def inner(request, *args, **kwargs):
     if request.user.is_authenticated():
         return view(request, *args, **kwargs)
     from registration.views import register
     return register(request, next=request.path, *args, **kwargs)
Exemplo n.º 28
0
def register(request):
    return registration_views.register(
        request,
        form_class=FullRegistrationForm)
Exemplo n.º 29
0
def main(request):
   if request.user.is_authenticated():
      return redirect('/groups')
   else:
      return register(request,'app.accounts.regbackend.Backend','/',RegistrationFormNoUserName)
Exemplo n.º 30
0
Arquivo: views.py Projeto: HiPiH/life
def registration(req):
    out={}
    if req.user.is_authenticated():
        return HttpResponseRedirect(req.user.get_absolute_url())
    from registration.views import register
    return register(req,form_class=FormUserReg)

    
    # ЕСЛИ УЖЕ АВТОРИЗОВАН ТО НЕЛЬЗЯ РЕГИТЬСЯ

        
    if req.POST:
        out['reg_form'] = reg_form = FormUserReg(req.POST)
        # проверка совпадения пароля
        passworderr = None
        if req.POST['password1'] != req.POST['password2']:
            out['passworderr'] = passworderr = u'Пароли не совпадают'
            
        if reg_form.is_valid() and not passworderr:
            # СОЗДАНИЕ НОВОГО ПОЛЬЗОВАТЕЛЯ

            new_user = User.objects.create_user(reg_form.cleaned_data['username'], reg_form.cleaned_data['email'])
            new_user.first_name, new_user.last_name, new_user.birthday = reg_form.cleaned_data['first_name'], reg_form.cleaned_data['last_name'], reg_form.cleaned_data['birthday']
            new_user.metro, new_user.address, new_user.sex = reg_form.cleaned_data['metro'], reg_form.cleaned_data['address'], reg_form.cleaned_data['sex']
            
            # КОД ВАЛИДАЦИИ
            new_user.validation_code = random.randint(100000,999999)
            # УСТАНОВКА ПАРОЛЯ И СОХРАНЕНИЕ РЕАЛЬНОГО В БД
            new_user.set_password(reg_form.cleaned_data['password1'])

            if config.validation_new_users.getValue():
                new_user.is_active = False

            
            new_user.save()
            
            ###################################
            # НАСТРОИЬТ ПОЧТУ #
            #@todo: what to do
            ###################################
            """
            new_user.email_user(_('New account email confirmation'),
                   render_to_string('registration/checkemail.eml',
                                    {'new_user': reg_formUser.cleaned_data['first_name'], 'new_user_email': new_user.email, 'new_userLogin': new_user.username,
                                     'valCode': validator.code},
                                     context_instance=RequestContext(req)
                                     ),
                   from_email = SEND_FROM_EMAIL
                )
            
            # ОПОВЕЩЕНИЕ АДМИНОВ О НОВОМ ПОЛЬЗОВАТЕЛЕ
            if config.notification_admin.getValue():
            """
            
            
            if config.validation_new_users.getValue():
                return HttpResponseRedirect('/accounts/validation/')
            else:
                user = authenticate(username=reg_form.cleaned_data['username'], password=reg_form.cleaned_data['password1'])
                login(req, user)
                # Редирект юзера после регистрации, если указано NEXT
                if req.GET:
                    if 'next' in req.GET:
                        return HttpResponseRedirect(req.GET['next'])
                else:
                    return HttpResponseRedirect(new_user.get_absolute_url())                
        else:
            return out
    else:
        if req.user.is_authenticated():
            if req.GET:
                if 'next' in req.GET:
                    return HttpResponseRedirect(req.GET['next'])
            return HttpResponseRedirect(req.user.get_absolute_url())
        out['reg_form'] = reg_form = FormUserReg()
        return out
Exemplo n.º 31
0
def registration(req):
    out = {}
    if req.user.is_authenticated():
        return HttpResponseRedirect(req.user.get_absolute_url())
    from registration.views import register
    return register(req, form_class=FormUserReg)

    # ЕСЛИ УЖЕ АВТОРИЗОВАН ТО НЕЛЬЗЯ РЕГИТЬСЯ

    if req.POST:
        out['reg_form'] = reg_form = FormUserReg(req.POST)
        # проверка совпадения пароля
        passworderr = None
        if req.POST['password1'] != req.POST['password2']:
            out['passworderr'] = passworderr = u'Пароли не совпадают'

        if reg_form.is_valid() and not passworderr:
            # СОЗДАНИЕ НОВОГО ПОЛЬЗОВАТЕЛЯ

            new_user = User.objects.create_user(
                reg_form.cleaned_data['username'],
                reg_form.cleaned_data['email'])
            new_user.first_name, new_user.last_name, new_user.birthday = reg_form.cleaned_data[
                'first_name'], reg_form.cleaned_data[
                    'last_name'], reg_form.cleaned_data['birthday']
            new_user.metro, new_user.address, new_user.sex = reg_form.cleaned_data[
                'metro'], reg_form.cleaned_data[
                    'address'], reg_form.cleaned_data['sex']

            # КОД ВАЛИДАЦИИ
            new_user.validation_code = random.randint(100000, 999999)
            # УСТАНОВКА ПАРОЛЯ И СОХРАНЕНИЕ РЕАЛЬНОГО В БД
            new_user.set_password(reg_form.cleaned_data['password1'])

            if config.validation_new_users.getValue():
                new_user.is_active = False

            new_user.save()

            ###################################
            # НАСТРОИЬТ ПОЧТУ #
            #@todo: what to do
            ###################################
            """
            new_user.email_user(_('New account email confirmation'),
                   render_to_string('registration/checkemail.eml',
                                    {'new_user': reg_formUser.cleaned_data['first_name'], 'new_user_email': new_user.email, 'new_userLogin': new_user.username,
                                     'valCode': validator.code},
                                     context_instance=RequestContext(req)
                                     ),
                   from_email = SEND_FROM_EMAIL
                )
            
            # ОПОВЕЩЕНИЕ АДМИНОВ О НОВОМ ПОЛЬЗОВАТЕЛЕ
            if config.notification_admin.getValue():
            """

            if config.validation_new_users.getValue():
                return HttpResponseRedirect('/accounts/validation/')
            else:
                user = authenticate(
                    username=reg_form.cleaned_data['username'],
                    password=reg_form.cleaned_data['password1'])
                login(req, user)
                # Редирект юзера после регистрации, если указано NEXT
                if req.GET:
                    if 'next' in req.GET:
                        return HttpResponseRedirect(req.GET['next'])
                else:
                    return HttpResponseRedirect(new_user.get_absolute_url())
        else:
            return out
    else:
        if req.user.is_authenticated():
            if req.GET:
                if 'next' in req.GET:
                    return HttpResponseRedirect(req.GET['next'])
            return HttpResponseRedirect(req.user.get_absolute_url())
        out['reg_form'] = reg_form = FormUserReg()
        return out
Exemplo n.º 32
0
def register(request, *args, **kwargs):
    if request.user.is_authenticated():
        return HttpResponseRedirect('/dashboard/')
    return registration_views.register(request, *args, **kwargs)
Exemplo n.º 33
0
 def get(self, request, *args, **kwargs):
     return register(request, form_class=RegistrationFormExpandedUsername, *args, **kwargs)
Exemplo n.º 34
0
def index(request, backend, success_url=None, 
        form_class=EmailRegistrationForm, profile_callback=None,
        #authentication_form = EmailLoginForm,
        template_name='landing.html',
        page_template = 'entry_index_page.html',
        extra_context=None, invitation_key=None):

    # Show landing page with registration 
    if not request.user.is_authenticated():
        # Check invite mode 
        if hasattr(settings, 'INVITE_MODE') and settings.INVITE_MODE:
            is_key_valid = InvitationKey.objects.is_key_valid
            # check key with email and pull email.


            #### HANDLE INVITATION PROCESS ####
                ## For prefilling email registration, go to registration/views.py
            # User enters site 
            if invitation_key and is_key_valid(invitation_key): 
                # has valid key

                # grab associated object with key
                str_invitation = '"'+invitation_key+'"'
                invitee_object = InvitationKey.objects.get(key=invitation_key)

                # save email and album_no in session to pass into registration
                request.session['email'] = invitee_object.to_user_email
                request.session['invited_album'] = invitee_object.from_user_album
                request.session['invite_key'] = invitation_key

                # show registration landing w/ prefilled
                return register(request, backend, success_url, form_class, profile_callback, template_name, extra_context={'invitation_key': invitation_key, 'invitee_object': invitee_object})

            else:
                if invitation_key == None:
                    #1 User enters website normally (uninvited)
                    #form_auth = EmailLoginForm() # for login form
                    return register(request, backend, success_url, form_class, profile_callback, template_name, extra_context=None)
                            #extra_context={'form_auth': form_auth})
                else:
                    # User entered invalid key
                    template = 'invitation/wrong_invitation_key.html'
                    return render_to_response(template, {'invitation_key': invitation_key }, RequestContext(request))

        else: 
            # norm registration mode (not used unless invite mode off)
            return register(request, backend, success_url, form_class, profile_callback, template_name, extra_context)
        
    ## SHOW PROFILE PAGE with SCHOOL FEED ##
    else:


        ### TEMP ###
        berkeley = 0 
        dartmouth = 0 
        ## end ##




        ###### BRING UP SCHOOL FEED ######
        # Find College Meme user w/ school memes
        college_meme_obj = User.objects.get(username = '******')

        user_school = request.user.get_profile().school
        if user_school == 'Berkeley':
            drag_list_experience = Experiences.objects.get(title = settings.SCHOOL_UCB_ALBUM, creator = college_meme_obj) 

            #temp
            berkeley = drag_list_experience
        elif user_school == 'Dartmouth': 
            drag_list_experience = Experiences.objects.get(title = settings.SCHOOL_DARTMOUTH_ALBUM, creator = college_meme_obj) 


            #temp
            dartmouth = drag_list_experience
        else:
            drag_list_experience = Experiences.objects.get(title = 'General', creator = college_meme_obj) # if nothing, default to General

        school_feed_memes = drag_list_experience.meme_set.all().order_by('-id')

        # grabs user's albums from the database
        experiences = Experiences.objects.filter(creator = request.user)

        # form to create new experience/album
        addexperienceform = AddExperienceForm()

        # form to upload meme
        imageform = ImageUploadForm()

        if request.is_ajax():
            template = page_template
        else:
            template = 'profile.html'

        return render_to_response(
                template,
                {'memes': school_feed_memes, 'experiences': experiences,
                    'page_template': page_template, 
                    'addexperienceform': addexperienceform,
                    'imageform' : imageform,
                    'user_school': user_school,

                    # temp
                    'dartmouth': dartmouth,
                    'berkeley': berkeley,
                },
                # is_uncat is 0 (user on feed not uncat page)
                RequestContext(request))
Exemplo n.º 35
0
def create_account(request):
    if request.user.is_anonymous():
        #return register(request, 'registration.backends.default.DefaultBackend', success_url='login.html')
        return register(request, 'registration.backends.simple.SimpleBackend', success_url='/login/')
    else:
        return HttpResponseRedirect('/movie/feed_rec/')