def company_signup(request):
    if not request.recaptcha_is_valid:
        return JsonResponse(
            status=400,
            data={
                'error': 'reCAPTCHA authorization failed. Please try again.'
            })
    if request.user.is_authenticated():
        return handle_user_type(request, redirect_request=True)
    f = SignupForm(request.POST)
    f.instance.type = 'CO'
    if f.is_valid():
        user = f.save(user_type='CO')
        user = authenticate(username=f.cleaned_data['username'],
                            password=f.cleaned_data['password2'])
        #		auth_login(request, user)
        send_activation_email_task.delay(user.pk,
                                         get_current_site(request).domain)
        context = {
            'user':
            user,
            'email':
            user.email,
            'profile_creation':
            request.build_absolute_uri(
                reverse(settings.PROFILE_CREATION_URL['CO']))
        }
        html = render(request, 'account/post_signup.html',
                      context).content.decode('utf-8')
        return JsonResponse(data={'success': True, 'render': html})
    else:
        return JsonResponse(status=400,
                            data={'errors': dict(f.errors.items())})
Exemplo n.º 2
0
Arquivo: views.py Projeto: thoas/i386
def _signup(request, username, email, password1, password2, confirmation_key):
    if request.method == 'POST':
        form = SignupForm(request.POST)
        if form.is_valid():
            username, password = form.save()
            user = authenticate(username=username, password=password)
            auth_login(request, user)
            return pyamf_success(user)
        return pyamf_errors(form.errors.values()[0])
    return False
Exemplo n.º 3
0
def signup(request):
    """Sign up using email with password."""
    if request.method == 'POST':
        form = SignupForm(data=request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, _('Thank you for your sign up on Vosae.\nPlease follow the instructions that we\'ve just sent to you by e-mail.'))
            return redirect('signin')
    else:
        form = SignupForm()
    return render_to_response('account/signup.html', {'form': form}, context_instance=RequestContext(request))
Exemplo n.º 4
0
def signup_view(request):
    form = SignupForm()
    if request.method == 'POST':
        form = SignupForm(request.POST, request=request)
        if form.is_valid():
            user = form.save()
            user = authenticate(username=user.username, password=form.data['password'])
            if user:
                login(request, user)

            return HttpResponseRedirect(request.POST.get("next", reverse("account:home")))
    return render_to_response('account/signup.html', locals(), context_instance=RequestContext(request))
Exemplo n.º 5
0
def signup(request):
    if request.user.is_authenticated():
        return redirect('account')

    form = SignupForm(request.POST or None)
    if form.is_valid():
        user = form.save()
        log.info("User '%s' id#%s was signed-up" %(user.get_full_name(), user.id))
        return render_to_response('account/signup_success.html', locals(),
            context_instance=RequestContext(request))
    return render_to_response('account/signup.html', locals(),
        context_instance=RequestContext(request))
Exemplo n.º 6
0
    def test_custom_redirect_field(self):
        request = self.factory.request()
        request.GET = {"next_page": "/profile/"}
        form = SignupForm({
            "username": "******",
            "password": "******",
            "password_confirm": "password",
            "email": "*****@*****.**",
        })
        view = SignupRedirectView(request=request, redirect_field_name="next_page")
        form.is_valid()
	self.assertEqual("/profile/", view.form_valid(form)["Location"])
Exemplo n.º 7
0
    def post(self, request, *args, **kwargs):
        user_form = SignupForm(request.POST)
        personal_information_form = PersonalInformationForm(request.POST)
        education_formset = self.EducationalBackgroundFormSet(
            request.POST, prefix='education')
        membership_formset = self.MembershipOrganizationFormSet(
            request.POST, prefix='membership')
        activity_formset = self.CommunityActivityFormSet(request.POST,
                                                         prefix='activity')
        if user_form.is_valid() and personal_information_form.is_valid(
        ) and education_formset.is_valid() and membership_formset.is_valid(
        ) and activity_formset.is_valid():
            userform = User.objects.create_user(
                username=user_form.cleaned_data['username'],
                first_name=personal_information_form.
                cleaned_data['first_name'],
                last_name=personal_information_form.cleaned_data['last_name'],
                email=user_form.cleaned_data['email'])
            userform.set_password(user_form.cleaned_data['password1'])
            userform.is_active = False
            userform.save()
            profile = personal_information_form.save(user=userform)
            for education_form in education_formset:
                education_form.save(profile=profile)
            for membership_form in membership_formset:
                membership_form.save(profile=profile)
            for activity_form in activity_formset:
                activity_form.save(profile=profile)

            email_subject = "PYLP Registration Email Confirmation"
            instruction = SignUpInstructions.objects.last()
            content = format_html(instruction.content)
            content_value = strip_tags(content)
            email_body = f"Thank you for registering at PYLP Alumni Association, Inc.\n\n{content_value}"
            email = EmailMessage(
                email_subject,
                email_body,
                '*****@*****.**',
                [user_form.cleaned_data['email']],
            )
            email.send(fail_silently=False)
            profile_pk = urlsafe_base64_encode(force_bytes(profile.pk))
            return redirect(reverse('photo-sig', kwargs={'pk': profile_pk}))
        else:
            return render(
                request, 'signup.html', {
                    'UserForm': user_form,
                    'InformationForm': personal_information_form,
                    'EducationForm': education_formset,
                    'MembershipForm': membership_formset,
                    'CommunityForm': activity_formset
                })
Exemplo n.º 8
0
def signup(request):
    if request.method == 'POST':
        form = SignupForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            Profile.register_user(email=data['email'], password=data['password'], first_name=data['first_name'],
                last_name=data['last_name'], institute=Institute.objects.get(name='University of Waterloo'))
            set_referrer(request, 'signup')
            return HttpResponseRedirect(reverse('login'))
    else:
        form = SignupForm()
    context = RequestContext(request)
    context['form'] = form
    return render_to_response('account/signup.html', context)
Exemplo n.º 9
0
def signup(req):
    form = SignupForm(req.POST)
    if form.is_valid():
        user = form.save()
        username = form.cleaned_data["username"]
        password = form.raw_password
        user = authenticate(username=username, password=password)
        if user is not None and user.is_active:
            login(req, user)
        answer = {
            'status': 200,
            'redirect': '/play',
        }
        return HttpResponse(json.dumps(answer),
                            content_type='application/json')
    status = 401
    answer = {'status': status, 'errors': form.errors}
    return HttpResponse(json.dumps(answer), content_type='application/json')
Exemplo n.º 10
0
def signup(request):
    if request.method == 'POST':
        form = SignupForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            Profile.register_user(
                email=data['email'],
                password=data['password'],
                first_name=data['first_name'],
                last_name=data['last_name'],
                institute=Institute.objects.get(name='University of Waterloo'))
            set_referrer(request, 'signup')
            return HttpResponseRedirect(reverse('login'))
    else:
        form = SignupForm()
    context = RequestContext(request)
    context['form'] = form
    return render_to_response('account/signup.html', context)
Exemplo n.º 11
0
 def get(self, request, *args, **kwargs):
     if request.user.is_authenticated():
         #messages.add_message(request, 50, request.user.username+'會員登入成功', extra_tags='登入成功')
         #messages.success(request, request.user.username+'會員登入成功', extra_tags='登入成功')
         return redirect(reverse('main:main'))
     kwargs['userForm'] = SignupForm()
     kwargs['profileform'] = ProfileForm()
     kwargs['CForm'] = CaptchaForm()
     
     return super(CSignUp, self).get(request, *args, **kwargs)
Exemplo n.º 12
0
def account_login(request):

    d = {
        "login_form": LoginEmailForm(),
        "signup_form": SignupForm(),
        "signup_open": getattr(settings, "ACCOUNT_OPEN_SIGNUP", True),
    }

    print d["signup_open"], settings.ACCOUNT_OPEN_SIGNUP
    return render(request, "account_login.html", d)
Exemplo n.º 13
0
def auth(request):
    if request.user.is_authenticated():
        return handle_user_type(request, redirect_request=True)
    context = {
        'login_form': LoginForm(prefix='l'),
        'signup_form': SignupForm(prefix='s'),
        'student_login_form': StudentLoginForm(prefix='sl'),
        'student_signup_form': StudentSignupForm(prefix='ss')
    }
    return render(request, 'account/auth.html', context)
Exemplo n.º 14
0
def Signup(request):
    if request.method == 'POST':
        form = SignupForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            email = form.cleaned_data.get('email')
            password = form.cleaned_data.get('password')
            User.objects.create_user(username=username,
                                     email=email,
                                     password=password)
            return redirect('edit-profile')
    else:
        form = SignupForm()

    context = {
        'form': form,
    }

    return render(request, 'account/signup.html', context)
Exemplo n.º 15
0
    def post(request):
        form = SignupForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            email = form.cleaned_data.get('email')
            user.email = email
            user.is_active = False
            user.save()

            phone = form.cleaned_data.get('phone')
            account = Account.objects.create(user=user, phone=phone)
            account.activation_token = account.generate_random_token()
            account.save()

            activation_link = "{}{}?token={}".format(
                settings.HOST_NAME, reverse('account:activate'),
                account.activation_token)
            send_activation_email(to=email, activation_link=activation_link)

            return redirect(reverse('home'))
        return render(request, 'account/register.html', {'form': form})
Exemplo n.º 16
0
 def test_custom_redirect_field(self):
     request = self.factory.request()
     request.GET = {"next_page": "/profile/"}
     form = SignupForm({
         "username": "******",
         "password": "******",
         "password_confirm": "password",
         "email": "*****@*****.**",
     })
     view = SignupRedirectView(request=request,
                               redirect_field_name="next_page")
     self.assertEqual("/profile/", view.form_valid(form)["Location"])
Exemplo n.º 17
0
def direct(request):
    site = Site.objects.get_current()
    # The visitor has hit the main webpage, so redirect to /mypage/
    if request.user.is_authenticated():
        return render_to_response('js-remote/index.html', {},
                                  context_instance=RequestContext(request))
    else:
        return render_to_response('home/unauthenticated.html', {
            "login_form": LoginForm(),
            "signup_form": SignupForm()
        },
                                  context_instance=RequestContext(request))
Exemplo n.º 18
0
def signup(request):
    """Sign up using email with password."""
    if request.method == 'POST':
        form = SignupForm(data=request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, _('Thank you for your sign up on Vosae.\nPlease follow the instructions that we\'ve just sent to you by e-mail.'))
            return redirect('signin')
    else:
        form = SignupForm()
    return render_to_response('account/signup.html', {'form': form}, context_instance=RequestContext(request))
Exemplo n.º 19
0
def sign_up(request):
    if request.method == 'POST':
        form = SignupForm(request.POST)

        if form.is_valid():
            form.save()
            send_email_task.delay(request.POST['email'], request.POST['name'])

            return redirect('root')
    else:
        form = SignupForm()
    return render(request, 'account/signup.html', {'form': form})
Exemplo n.º 20
0
    def post(self, request, *args, **kwargs):
        userForm = SignupForm(request.POST)
        profileform = ProfileForm(request.POST)
        CForm = CaptchaForm(request.POST)
        if not (CForm.is_valid() and userForm.is_valid() and profileform.is_valid()):
            kwargs["userForm"] = userForm
            kwargs["profileform"] = profileform
            kwargs["CForm"] = CForm
            return super(CSignUp, self).get(request, *args, **kwargs)

        user = userForm.save()
        password = user.password
        user.set_password(password)
        user.save()
        userProfile = profileform.save(commit=False)
        userProfile.user = user
        userProfile.username = user.username
        userProfile.ip = get_client_ip(request)
        userProfile.save()
        log = authenticate(username=user.username, password=password)
        login(request, log)
        messages.add_message(request, 50, request.user.username + "會員 謝謝您的註冊", extra_tags="註冊成功")
        # messages.success(request, '歡迎註冊')
        return redirect(reverse("main:main"))
Exemplo n.º 21
0
 def post(self, request, *args, **kwargs):
     userForm = SignupForm(request.POST)
     profileform = ProfileForm(request.POST)
     CForm = CaptchaForm(request.POST)
     if not (CForm.is_valid() and userForm.is_valid() and profileform.is_valid()):
         kwargs['userForm'] = userForm
         kwargs['profileform'] = profileform
         kwargs['CForm'] = CForm
         return super(CSignUp, self).get(request, *args, **kwargs)
     
     user = userForm.save()
     password = user.password
     user.set_password(password)
     user.save()
     userProfile = profileform.save(commit=False)
     userProfile.user = user
     userProfile.username = user.username
     userProfile.ip = get_client_ip(request)
     userProfile.save()
     log = authenticate(username=user.username, password=password)
     login(request, log)
     messages.add_message(request, 50, request.user.username+'會員 謝謝您的註冊', extra_tags='註冊成功')
     #messages.success(request, '歡迎註冊')
     return redirect(reverse('main:main'))
Exemplo n.º 22
0
def signup(request):
    if request.method == 'POST':
        form = SignupForm(request.POST)
        if form.is_valid():
            user = form.save()
            auth_login(request, user)
            return redirect('home')
    else:
        form = SignupForm()

    return render(request, 'signup.html', {'form': form})
Exemplo n.º 23
0
def signup(request, confirmation_key=None, **kwargs):

    template_name = kwargs.pop("template_name", "account/account_signup.html")
    redirect_field_name = kwargs.pop("redirect_field_name", "next")
    success_url = kwargs.pop("success_url", None)
    ctx = {}

    if success_url is None:
        success_url = get_default_redirect(request, redirect_field_name)

    if request.method == "POST":
        form = SignupForm(request.POST)
        if form.is_valid():
            user = form.save(request=request)
            request.session["new_user"] = True
            form.login(request, user)
            request.session["event"] = 'Registered using non-Facebook form'

            return HttpResponseRedirect(reverse("signup_connect_fb"))
    else:
        form = SignupForm()
        if confirmation_key is not None:
            try:
                join_invitation = JoinInvitationEmail.objects.get(
                    confirmation_key=confirmation_key.lower())
                ctx.update({
                    "email": join_invitation.contact.email,
                    "confirmation_key": join_invitation.confirmation_key
                })
                request.session["source"] = 'email_invite'

            except JoinInvitationEmail.DoesNotExist:
                pass

    ctx.update({
        "form":
        form,
        "redirect_field_name":
        redirect_field_name,
        "redirect_field_value":
        request.REQUEST.get(redirect_field_name),
    })

    return render_to_response(template_name, RequestContext(request, ctx))
Exemplo n.º 24
0
def signup(request):
    context = {}
    if request.method == 'POST':
        form = SignupForm(request.POST)
        if form.is_valid():
            user = form.save()
            user.save()
            return HttpResponse("OK")
    else:
        form = SignupForm()
    context = {'form': form}
    return render(request, 'user/auth/signup.html', context)
Exemplo n.º 25
0
    def test_create_cart(self):
        data = {'create_time': timezone.now(), 'is_payed': False, 'total': 0}
        form = CartForm(data=data)
        self.assertTrue(form.is_valid())

        data = {}
        form = CartForm(data=data)
        self.assertTrue(form.is_valid())
        cart = form.save()

        state = State.objects.create(name='s1')
        city = City.objects.create(name='c1', state=state)

        signup_data = {
            'first_name': 'first name',
            'last_name': 'last name',
            'national_id': '0720500494',
            'email': '*****@*****.**',
            'phone': '09121234567',
            'username': '******',
            'post_code': '0123456789',
            'state': '1',
            'city': '1',
            'address': 'the address',
            'password1': 'password@123',
            'password2': 'password@123'
        }
        form = SignupForm(data=signup_data)
        self.assertTrue(form.is_valid())
        form.save()

        data = {'client': 1}
        form = CartForm(data=data)
        form.is_valid()
        form.save()

        self.assertEqual(
            Cart.objects.get(pk=2).client.first_name, 'first name')
Exemplo n.º 26
0
def signup_view(request):
    if request.method == 'POST':
        form = SignupForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.is_active = False
            user.save()
            send_activation_email(request, user)
            return render(
                request, 'account/message.html', {
                    'title':
                    "Sign Up Successful",
                    'message':
                    "Thank you for signing up. An activation link is sent to your email. Please Activate your "
                    "account using that link",
                })
    else:
        form = SignupForm()
    return render(request, 'account/register.html', {'form': form})
Exemplo n.º 27
0
def signup(request):
	if request.user.is_authenticated:
		return redirect('/')

	context = {}
	if request.method == 'POST':
		form = SignupForm(request.POST)
		if form.is_valid():
			user = form.save()
			login(request, user)

			return redirect('/account/')

	else:
		form = SignupForm()

	context['form'] = form

	return render(request, 'account/auth/signup.html', context)
Exemplo n.º 28
0
Arquivo: views.py Projeto: braskin/pd
def signup(request, confirmation_key=None, **kwargs):

    template_name = kwargs.pop("template_name", "account/account_signup.html")
    redirect_field_name = kwargs.pop("redirect_field_name", "next")
    success_url = kwargs.pop("success_url", None)
    ctx = {}

    if success_url is None:
        success_url = get_default_redirect(request, redirect_field_name)

    if request.method == "POST":
        form = SignupForm(request.POST)
        if form.is_valid():
            user = form.save(request=request)
            request.session["new_user"] = True
            form.login(request, user)
            request.session["event"] = "Registered using non-Facebook form"

            return HttpResponseRedirect(reverse("signup_connect_fb"))
    else:
        form = SignupForm()
        if confirmation_key is not None:
            try:
                join_invitation = JoinInvitationEmail.objects.get(confirmation_key=confirmation_key.lower())
                ctx.update(
                    {"email": join_invitation.contact.email, "confirmation_key": join_invitation.confirmation_key}
                )
                request.session["source"] = "email_invite"

            except JoinInvitationEmail.DoesNotExist:
                pass

    ctx.update(
        {
            "form": form,
            "redirect_field_name": redirect_field_name,
            "redirect_field_value": request.REQUEST.get(redirect_field_name),
        }
    )

    return render_to_response(template_name, RequestContext(request, ctx))
Exemplo n.º 29
0
def signup(request):

    if request.user.is_authenticated:
        return redirect('/account/')

    context = {}
    if request.method == 'POST':
        form = SignupForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.is_active = False
            user.save()
            verify_email(request, user)
            return render(request, 'account/auth/verify.html', {})

    else:
        form = SignupForm()

    context['form'] = form

    return render(request, 'account/auth/signup.html', context)
Exemplo n.º 30
0
def college_signup(request):
	if request.user.is_anonymous:
		return redirect('landing')
	if request.user.is_authenticated():
		return handle_user_type(request, redirect_response=True)
	
	if request.method == 'GET':
		f = SignupForm()
	else:
		f = SignupForm(request.POST)
		f.instance.type = 'C'
		if f.is_valid():
			college = f.save(user_type='C')
			college = authenticate(username=f.cleaned_data['username'], password=f.cleaned_data['password2'])
			context = {}
			if college:
#				auth_login(request, college)
				context['email'] = college.email
				context['profile_creation'] = request.build_absolute_uri(reverse(settings.PROFILE_CREATION_URL['C']))
				send_activation_email_task.delay(college.pk, get_current_site(request).domain)
				return render(request, 'account/post_signup.html', context)
	return render(request, 'college/signup.html', {'college_signup_form': f})
Exemplo n.º 31
0
    def post(self, request):
        form = SignupForm(data=request.data)
        email = request.data.get("email")

        if form.is_valid():
            clear_first_name, clear_last_name = get_clearbit_data(email)

            form_values = request.data.copy()
            form_values["first_name"] = clear_first_name
            form_values["last_name"] = clear_last_name
            form = SignupForm(form_values)

            user = form.save(commit=False)
            user.is_active = True
            user.save()
            current_site = get_current_site(request)
            mail_subject = "Activate your blog account."
            mail_context = {
                "user": user,
                "domain": current_site.domain,
                "uid": urlsafe_base64_encode(force_bytes(user.pk)),
                "token": account_activation_token.make_token(user),
            }
            message = render_to_string("account/rest_email_activation.html",
                                       mail_context)
            to_email = form.cleaned_data.get("email")
            email = EmailMessage(mail_subject, message, to=[to_email])
            email.send()
            return JsonResponse(
                {
                    "status": "success",
                    "message":
                    "confirm your email to complete the registration",
                },
                status=200,
            )
        return Response(form.errors, status=409)
def signup(request):
    form = SignupForm()
    return render(request, "account/signup.html", {"form": form})
Exemplo n.º 33
0
def signup(request):
    context = {}
    if request.method == "POST":
        user_form = SignupForm(request.POST)
        if user_form.is_valid():
            users_email = User.objects.filter(email=user_form.data["email"])
            if len(users_email) != 0:
                messages.error(request,
                               "Пользователь с таким email уже существует.")
                context["form"] = SignupForm(request.POST)
                return render(request, "account/signup.html", context)
            else:
                ok = check_blacklist(user_form.data['email'])
                if ok is not None:
                    messages.error(
                        request,
                        f"Имя пользователя не должно содержать \"{ok}\"")
                    context["form"] = SignupForm(request.POST)
                    return render(request, "account/signup.html", context)
                else:
                    new_user = user_form.save(commit=True)
                    new_user.set_password(user_form.cleaned_data["password1"])
                    new_user.is_active = False
                    new_user.save()
                    profile = Profile(user=new_user, avatar_id=1)
                    profile.save()
                    code_object = Code()
                    code_object.user = new_user
                    code_object.code, code_object.token = utils.generate_codes(
                        new_user, datetime.datetime.now())
                    code_object.save()
                    mail_context = {
                        'token': code_object.token,
                        'code': code_object.code,
                        'user': new_user
                    }
                    utils.send_mail(new_user.email,
                                    'Подтверждение Регистрации',
                                    'mail/confirmation.html', mail_context)
                    messages.warning(
                        request,
                        'На вашу электронную почту было отправлено письмо, для подтверждения.'
                    )
                    return redirect(reverse('account:login'))
        else:
            errors = user_form.errors.as_json()
            errors = json.loads(errors)
            codes = []
            for key, message in errors.items():
                for error in message:
                    codes.append(error['code'])
            print(codes)
            if 'unique' in codes:
                messages.error(request,
                               "Пользователь с таким именем уже существует.")
            if 'password_too_similar' in codes:
                messages.error(request, "Пароль и имя пользователя совпадают.")
            if 'password_mismatch' in codes:
                messages.error(request, "Пароли не совпадают.")
            if ('password_no_symbol'
                    in codes) or ('password_no_lower' in codes) or (
                        'password_no_upper'
                        in codes) or ('password_no_number' in codes) or (
                            'password_too_short'
                            in codes) or ('password_too_common' in codes):
                messages.error(
                    request,
                    "Пароль не соответствует требованиям. (минимум: длина 8 символов, "
                    "1 спец.символ, 1 строчная буква, 1 прописная буква, 1 цифра)"
                )
            context["form"] = SignupForm(request.POST)
    else:
        if request.user.is_authenticated:
            messages.warning(request, "Вы уже вошли в аккаунт.")
            return redirect(reverse('account:view_my'))
        context["form"] = SignupForm()
    return render(request, "account/signup.html", context)
Exemplo n.º 34
0
 def get(request):
     form = SignupForm()
     return render(request, 'account/register.html', {'form': form})
Exemplo n.º 35
0
from django.conf.urls import url, include

from account.forms import LoginUsernameForm, SignupForm, ChangePasswordForm, SettingsForm, PasswordResetForm, PasswordResetTokenForm

from .base import ViewConfig

patch = "http://pinaxproject.com/pinax-design/patches/django-user-accounts.svg"
label = "dua"
title = "Django User Accounts"
views = [
    ViewConfig(pattern=r"^account/signup/$",
               template="account/signup.html",
               name="account_signup",
               pattern_kwargs={},
               form=SignupForm()),
    ViewConfig(pattern=r"^account/login/$",
               template="account/login.html",
               name="account_login",
               pattern_kwargs={},
               form=LoginUsernameForm(),
               ACCOUNT_OPEN_SIGNUP=True),
    ViewConfig(pattern=r"^account/logout/$",
               template="account/logout.html",
               name="account_logout",
               pattern_kwargs={}),
    ViewConfig(pattern=r"^account/confirm_email/(?P<key>\w+)/$",
               template="account/email_confirm.html",
               name="account_confirm_email",
               pattern_kwargs={"key": "abc"},
               confirmation={
                   "key": "foo",
Exemplo n.º 36
0
def createUser(request):
    """
    Creates a new user and a profile

    Params:
    - emailaddress1
    - emailaddress2
    - username
    - password1
    - password2
    - dash
    - type

    Returns a user_dict on success, 500 with message on error.
    """
    
    param = simplejson.loads(request.body)
    dash = param.get('dash', False)
    user_type = param.get('type', 'fishers')

    form = SignupForm(param)

    if form.is_valid():
        user = form.save()
        if user_type in ['staff', 'intern'] and dash_can_create:
            user.is_staff = True
            user.save()

        user.profile.registration = '{}'
        user.profile.tags.add('usvi')
        if user_type in ['intern'] and dash_can_create:
            user.profile.is_intern = True
        user.profile.save()


        if dash is False:
            user = authenticate(username=user.username, password=param.get('password'))
            login(request, user)
        api_key, created = ApiKey.objects.get_or_create(user=user)
        api_key.key = api_key.generate_key()
        api_key.save()
        
        user_dict = {
            'username': user.username,
            'name': ' '.join([user.first_name, user.last_name]),
            'email': user.email,
            'is_staff': user.is_staff,
            'registration': user.profile.registration,
            'is_intern': user.profile.is_intern,
            'api_key': user.api_key.key
        }
        return HttpResponse(simplejson.dumps({'success': True, 'user': user_dict}))
    else:
        # Something is went wrong
        if 'username' in form.errors:
            return HttpResponse("duplicate-user", status=500)
        
        # if 'emailaddress1' in form.errors:
        #     return HttpResponse("invalid-email", status=500)
        
        if 'emailaddress1' in form.errors:
            return HttpResponse("duplicate-email", status=500)
        
        if 'password1' in form.errors:
            return HttpResponse("invalid-password", status=500)
        else:
            return HttpResponse("unknown-error", status=500)
Exemplo n.º 37
0
def index(request):
    total_in_game_currency = None
    if request.user.is_authenticated:
        total_in_game_currency = request.user.get_bank_account().get_in_game_currency()

    return render(request, 'bithumb/index.html', {'signup_form': SignupForm(), 'login_form': LoginForm(), 'total_score': total_in_game_currency})