Example #1
0
def modal_login(request, **kwargs):
    
   # redirect_field_name = kwargs.pop("next")
    if request.method == "POST":
        login_form = LoginForm(request.POST)
        if login_form.is_valid():
            next = request.POST.get("next","/food/")
            login_form.login(request, redirect_url=next)
            return HttpResponse(next)
        redirect_field_name, redirect_field_value = "next", request.referer
        response = render(request,"login_error.html",locals())
        response.status_code = 400 
        return response
Example #2
0
def mf_login(request):
    form = LoginForm()
    if request.method == "POST":
        form = LoginForm(request.POST)
        if form.is_valid():
            form.login(request)
            return redirect('mf-index')
    ctx = {
        "page": "login",
        "form": form,
        "registration_open": settings.REGISTRATION_OPEN,
    }
    return render(request, "accounts/login.html", ctx)
Example #3
0
def video_login(request, slug):
    if not request.method == 'POST':
        raise Exception('This view is meant to be called via a POST request.')

    video, created = get_or_create_video(slug)
    login_success = False
    outbound_message = dict()
    outbound_message[DATA_KEY] = {}
    form = LoginForm(data=json.loads(request.raw_post_data))

    if form.is_valid():
        user = form.user
        form.login(request)
        login_success = True

        action.send(user, verb='viewed video', action_object=video)

        userSerializer = UserSerializer(user)
        userSerialized = JSONRenderer().render(userSerializer.data)
        outbound_message[DATA_KEY]['user'] = json.loads(userSerialized)
        outbound_message[DATA_KEY]['share_url'] = reverse('profiles-share',
                                                          args=[
                                                              user.username,
                                                              slug,
                                                          ])
    else:
        outbound_message[DATA_KEY]['errors'] = \
            json.loads(errors_to_json(form.errors))

    outbound_message[EVENT_TYPE_KEY] = 'FB_LOGIN'
    outbound_message[CHANNEL_KEY] = \
        '/framebuzz/session/%s' % request.session.session_key
    outbound_message[DATA_KEY]['login_success'] = login_success

    return HttpResponse(json.dumps(outbound_message),
                        content_type="application/json")
Example #4
0
def login(request, **kwargs):
    success_url = kwargs.pop("success_url", None)

    if success_url is None:
        success_url = "/"

    if request.method == "POST":
        form = LoginForm(request.POST)
        if form.is_valid():
            return form.login(request, redirect_url=success_url)
    else:
        form = LoginForm()

    registerform = SignupForm()

    ctx = {
        "form": form,
        "registerform": registerform,
        "redirect_field_name": "next",
        "redirect_field_value": request.REQUEST.get("next"),
        "apps": SocialApp.objects.all(),
    }
    return render_to_response('users/login.html', RequestContext(request, ctx))
Example #5
0
def login(request, **kwargs):
    success_url = kwargs.pop("success_url", None)

    if success_url is None:
        success_url = "/"

    if request.method == "POST":
        form = LoginForm(request.POST)
        if form.is_valid():
            return form.login(request, redirect_url=success_url)
    else:
        form = LoginForm()

    registerform = SignupForm()

    ctx = {
        "form": form,
        "registerform": registerform,
        "redirect_field_name": "next",
        "redirect_field_value": request.REQUEST.get("next"),
        "apps": SocialApp.objects.all(),
    }
    return render_to_response("users/login.html", RequestContext(request, ctx))
Example #6
0
    def post(self, request):
        serializer = LoginInputSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        login_field = 'email'
        form_login = serializer.validated_data.get('email', '')
        if not form_login:
            form_login = serializer.validated_data.get('username', '')
            if form_login:
                login_field = 'username'

        login_data = {
            'login': form_login,
            'password': serializer.validated_data.get('password')
        }

        with transaction.atomic(), clear_messages(request):
            form = LoginForm(request=request, data=login_data)
            form_valid_or_raise(form, {'login': login_field})
            allauth_response = form.login(request)
            # commit transaction here because an implicit EmailConfirmation object may be created
            # as part of the allauth login process, and we want it to be saved

        with transaction.atomic(), clear_messages(request):
            user = getattr(form, 'user', None)
            token = handle_login_response(allauth_response,
                                          user,
                                          allow_disabled=False)
            profile = getattr(getattr(token, 'user', None), 'profile', None)
            response_serializer = UserTokenResponseSerializer({
                'token':
                token,
                'profile':
                profile
            })
            response = Response(response_serializer.data)
            return response
Example #7
0
def homepage(request):
    # Main landing page.

    from allauth.account.forms import SignupForm, LoginForm

    class NewOrgForm(forms.ModelForm):
        class Meta:
            model = Organization
            fields = ['name', 'subdomain']
            labels = {
                "name": "Organization Name",
                "subdomain": "Pick a web address",
            }
            help_texts = {
                "name":
                "",
                "subdomain":
                "Must be all lowercase and can contain letters, digits, and dashes.",
            }
            widgets = {
                "subdomain":
                forms.TextInput(
                    attrs={
                        "placeholder": "orgname",
                        "addon_after": "." +
                        settings.ORGANIZATION_PARENT_DOMAIN
                    })
            }

        def clean_subdomain(self):
            # Not sure why the field validator isn't being run by the ModelForm.
            import re
            from .models import subdomain_regex
            from django.forms import ValidationError
            if not re.match(subdomain_regex, self.cleaned_data['subdomain']):
                raise ValidationError(
                    "The organization address must contain only lowercase letters, digits, and dashes and cannot start or end with a dash."
                )
            return self.cleaned_data['subdomain']

    signup_form = SignupForm()
    neworg_form = NewOrgForm()
    login_form = LoginForm()

    # The allauth forms have 'autofocus' set on their widgets that draw the
    # focus in a way that doesn't make sense here.
    signup_form.fields['username'].widget.attrs.pop("autofocus", None)
    login_form.fields['login'].widget.attrs.pop("autofocus", None)

    if request.POST.get("action") == "neworg":
        signup_form = SignupForm(request.POST)
        neworg_form = NewOrgForm(request.POST)
        if (request.user.is_authenticated
                or signup_form.is_valid()) and neworg_form.is_valid():
            # Perform signup and new org creation, then redirect
            # to that org.
            with transaction.atomic():
                if not request.user.is_authenticated:
                    # Create account.
                    user = signup_form.save(request)

                    # Log them in.
                    from django.contrib.auth import authenticate, login
                    user = authenticate(user_object=user)
                    login(request, user)
                else:
                    user = request.user

                org = Organization.create(admin_user=user,
                                          **neworg_form.cleaned_data)

                # Send a message to site administrators.
                from django.core.mail import mail_admins

                def subvars(s):
                    return s.format(
                        org_subdomain=org.subdomain,
                        org_name=org.name,
                        org_link=settings.SITE_ROOT_URL +
                        "/admin/siteapp/organization/{}/change".format(org.id),
                        username=user.username,
                        email=user.email,
                        user_link=settings.SITE_ROOT_URL +
                        "/admin/siteapp/user/{}/change".format(user.id),
                    )

                mail_admins(
                    subvars(
                        "New organization: {org_name} (created by {email})"),
                    subvars(
                        "A new organization has been registered!\n\nOrganization\n------------\nName: {org_name}\nSubdomain: {org_subdomain}\nAdmin: {org_link}\n\nRegistering User\n----------------\nUsername: {username}\nEmail: {email}\nOrganization: {org_name}\nAdmin: {user_link}"
                    ))

                return HttpResponseRedirect("/welcome/" + org.subdomain)

    elif request.POST.get("action") == "login":
        login_form = LoginForm(request.POST, request=request)
        if login_form.is_valid():
            login_form.login(request)
            return HttpResponseRedirect('/')  # reload

    elif request.POST.get(
            "action") == "logout" and request.user.is_authenticated:
        from django.contrib.auth import logout
        logout(request)
        return HttpResponseRedirect('/')  # reload

    return render(
        request, "landing.html", {
            "domain":
            settings.ORGANIZATION_PARENT_DOMAIN,
            "signup_form":
            signup_form,
            "neworg_form":
            neworg_form,
            "login_form":
            login_form,
            "member_of_orgs":
            Organization.get_all_readable_by(request.user)
            if request.user.is_authenticated else None,
        })
Example #8
0
def homepage(request):
    # Main landing page.

    from allauth.account.forms import SignupForm, LoginForm

    portfolio_form = PortfolioSignupForm()
    signup_form = SignupForm()
    login_form = LoginForm()

    # The allauth forms have 'autofocus' set on their widgets that draw the
    # focus in a way that doesn't make sense here.
    signup_form.fields['username'].widget.attrs.pop("autofocus", None)
    login_form.fields['login'].widget.attrs.pop("autofocus", None)

    if request.POST.get("action") == "signup":
        signup_form = SignupForm(request.POST)
        portfolio_form = PortfolioSignupForm(request.POST)
        if (request.user.is_authenticated or signup_form.is_valid()) and portfolio_form.is_valid():
            # Perform signup and new org creation, then redirect to main page
            with transaction.atomic():
                if not request.user.is_authenticated:
                    # Create account.
                    new_user = signup_form.save(request)

                    # Log them in.
                    from django.contrib.auth import authenticate, login
                    user = authenticate(request, username=signup_form.cleaned_data['username'], password=signup_form.cleaned_data['password1'])
                    if user is not None:
                        login(request, user, 'django.contrib.auth.backends.ModelBackend')
                    else:
                        print("[ERROR] new_user '{}' did not authenticate after during account creation.".format(new_user.username))
                        messages.error(request, "[ERROR] new_user '{}' did not authenticate during account creation. Account not created. Report error to System Administrator. {}".format(new_user.username, vars(new_user)))
                        return HttpResponseRedirect("/")
                else:
                    user = request.user
                if portfolio_form.is_valid():
                    portfolio = portfolio_form.save()
                    portfolio.assign_owner_permissions(request.user)

                # Send a message to site administrators.
                from django.core.mail import mail_admins
                def subvars(s):
                    return s.format(
                        portfolio=portfolio.title,
                        username=user.username,
                        email=user.email,
                    )
                mail_admins(
                    subvars("New portfolio: {portfolio} (created by {email})"),
                    subvars("A new portfolio has been registered!\n\nPortfolio\n------------\nName: {portfolio}\nRegistering User\n----------------\nUsername: {username}\nEmail: {email}"))

                return HttpResponseRedirect("/projects")

    elif request.POST.get("action") == "login":
        login_form = LoginForm(request.POST, request=request)
        if login_form.is_valid():
            login_form.login(request)
            return HttpResponseRedirect('/') # reload

    elif request.POST.get("action") == "logout" and request.user.is_authenticated:
        from django.contrib.auth import logout
        logout(request)
        return HttpResponseRedirect('/') # reload

    return render(request, "index.html", {
        "hide_registration": SystemSettings.hide_registration,
        "signup_form": signup_form,
        "portfolio_form": portfolio_form,
        "login_form": login_form,
        "member_of_orgs": Organization.get_all_readable_by(request.user) if request.user.is_authenticated else None,
    })
Example #9
0
File: views.py Project: mfrlin/TPO
def reservation(request, id):
    service = get_object_or_404(Service, id=id)

    chosen_employee = None
    emp_size = 0
    if not service.is_active():
        raise Http404
    minTime, maxTime = getMinMaxTime(service.service_provider)

    #step2 = request.session['_step'] if '_step' in request.session
    step2 = request.GET.get('step', None)

    # POST
    step = request.POST.get('step', None)

    data = None
    if step:
        try:
            data = pickle.loads(base64.b64decode(request.POST.get('data')))  # Serializes an object from request
        except:
            raise Http404
    elif step2:
        step = step2
        if 'reservation_data' in request.session:
            data = request.session['reservation_data']
        else:
            step = None

    if (request.method != 'POST' and data is None) or step is None:
        #form = ReservationForm(request, workingHours=None, service=None)
        form = ReservationForm(request, workingHours=None, service=service)
        data = {'service_provider_id': service.service_provider_id, 'service_id': service.id}
        return render_to_response('reservations/reservation.html', locals(), context_instance=RequestContext(request))

    workingHours = WorkingHours.objects.filter(service_provider_id=service.service_provider_id)

    #formNonRegisteredUser = NonRegisteredUserForm(prefix='nonRegBtn')
    formNonRegisteredUser = NonRegisteredUserForm(provider=service.service_provider)
    loginForm = LoginForm(prefix='loginBtn')
    signupForm = SignupForm(prefix='signupBtn')

    if step == '1':
        # Service, date, time
        # form = ReservationForm(request.POST, workingHours='gergerre')
        form = ReservationForm(request, request.POST, workingHours=workingHours, service=service)
        if form.is_valid():
            chosen_employee = form.cleaned_data['employees']
            data['date'] = form.cleaned_data['date']
            data['time'] = form.cleaned_data['time']
            data['number'] = form.cleaned_data['number']
            data['employees'] = form.cleaned_data['employees']

            if request.user.is_authenticated():
                data['user_id'] = request.user.id
                data['name'] = request.user.get_full_name()
                data['phone'] = request.user.phone
                data['email'] = request.user.email
                return render_to_response('reservations/confirmation.html', locals(),
                                          context_instance=RequestContext(request))

            return render_to_response('reservations/userinfo.html', locals(), context_instance=RequestContext(request))

        return render_to_response('reservations/reservation.html', locals(), context_instance=RequestContext(request))

    if step == '2':
        if data.get('date') is None or data.get('time') is None:
            raise Http404

        if 'signupBtn' in request.POST:
            signupForm = SignupForm(request.POST, prefix='signupBtn')

            if signupForm.is_valid():
                userr = signupForm.save(request)

                data['user_id'] = userr.id
                data['name'] = userr.get_full_name()
                data['phone'] = userr.phone
                data['email'] = userr.email

                return render_to_response('reservations/confirmation.html', locals(),
                                          context_instance=RequestContext(request))

        if 'loginBtn' in request.POST:
            loginForm = LoginForm(request.POST, prefix='loginBtn')

            if loginForm.is_valid():
                data['user_id'] = loginForm.user.id
                data['name'] = loginForm.user.get_full_name()
                data['phone'] = loginForm.user.phone
                data['email'] = loginForm.user.email

                request.session['reservation_data'] = data
                return loginForm.login(request, redirect_url=reverse('reservation', args=[service.id]) + "?step=2a")

        if 'nonRegBtn' in request.POST:

            formNonRegisteredUser = NonRegisteredUserForm(request.POST, provider=service.service_provider)
            if formNonRegisteredUser.is_valid():
                data['name'] = formNonRegisteredUser.cleaned_data['name']
                data['phone'] = formNonRegisteredUser.cleaned_data['phone']
                data['email'] = formNonRegisteredUser.cleaned_data['email']
                return render_to_response('reservations/confirmation.html', locals(),
                                          context_instance=RequestContext(request))
        return render_to_response('reservations/userinfo.html', locals(), context_instance=RequestContext(request))

    if step == '2a':
        if request.user.is_authenticated():
            return render_to_response('reservations/confirmation.html', locals(),
                                      context_instance=RequestContext(request))

    if step == '3':
        # Confirmation
        if data.get('date') is None or data.get('time') is None:  # or data.get('user_id') is None:
            raise Http404
        if data.get('user_id') is not None:
            ruser = get_object_or_404(User, id=data.get('user_id'))
        else:
            ruser = None

        sync(service.service_provider)

        # Checking again if form for reservation is valid
        chosen_employee = data.get('employees')
        emp_id = None
        if chosen_employee is not None and chosen_employee != '':
            emp_id = chosen_employee.id

        form = ReservationForm(request,
                               {'date': data.get('date'), 'time': data.get('time'), 'employees': emp_id},
                               workingHours=workingHours, service=service)

        if form.is_valid():
            form_emp = None
            if chosen_employee != '':
                form_emp = chosen_employee
            reserve = Reservation(user=ruser, service=service, date=data['date'], time=data['time'],
                                  employee=form_emp)
            # Add backup fields
            reserve.user_fullname = data.get('name')
            reserve.user_phone = data.get('phone')
            reserve.user_email = data.get('email')
            reserve.service_provider = service.service_provider
            reserve.service_name = service.name
            reserve.service_duration = service.duration
            reserve.service_price = service.discounted_price()
            reserve.show_up = False
            if chosen_employee is not None and chosen_employee != '':
                reserve.employee = chosen_employee
            else:
                # if employees assigned to service, randomly choose one who is free
                if service.employees.all().__len__() > 0:
                    today_r = Reservation.objects.filter(employee__in=service.employees.all(), date=reserve.date)
                    # find free employees
                    reserveDt = datetime.datetime.combine(reserve.date, reserve.time)
                    free_emp = list(service.employees.all())
                    free_emp_editable = list(service.employees.all())
                    for emp in free_emp:
                        emp_time = EmployeeWorkingHours.objects.filter(employee=emp.id)[0].get_for_day(emp,
                                                                                                       reserve.date.weekday())
                        if not EmployeeWorkingHours.objects.filter(employee=emp.id)[0].get_for_day(emp,
                                                                                                   reserve.date.weekday()):
                            free_emp_editable.remove(emp)
                        if reserve.time < emp_time.time_from or reserveDt + datetime.timedelta(
                                minutes=reserve.service_duration) > datetime.datetime.combine(reserve.date,
                                                                                              emp_time.time_to):
                            free_emp_editable.remove(emp)
                    for r in today_r:
                        rDt = datetime.datetime.combine(r.date, r.time)
                        if r.active_during(reserveDt):
                            if r.employee in free_emp:
                                free_emp_editable.remove(r.employee)
                                # choose random employee
                    if free_emp_editable:
                        random_employee = free_emp_editable[random.randint(0, len(free_emp_editable) - 1)]
                        reserve.employee = random_employee

            # Save
            reserve.user.notification_type = 'email'
            reserve.save()
            # saving coupon is_valid
            coupons = Coupon.objects.filter(service=service.id)
            coupon_is_used = False
            for coup in coupons:
                if data['number'] == coup.number:
                    coup.is_used = True
                    coup.save()
                    coupon_is_used = True
                    # Validation checking in form

            user_page_link = '%s/u/%s' % (settings.BASE_URL, reserve.service_provider.userpage_link)
            email_to1 = data.get('email')
            email_to2 = service.service_provider.user.email
            if service.service_provider.reservation_confirmation_needed:
                subject = _('Confirmation of service reservation')
                renderedToCustomer = render_to_string('emails/reservation_customer.html',
                                                      {'reservation': reserve, 'link': user_page_link})
                renderedToProvider = render_to_string('emails/reservation_provider.html',
                                                      {'reservation': reserve, 'link': user_page_link})
                message1 = (subject, renderedToCustomer, None, [email_to1])
                message2 = (subject, renderedToProvider, None, [email_to2])
                send_mass_mail((message1, message2), fail_silently=True)
            else:
                subject = _('Confirmation of service reservation')
                renderedToCustomer = render_to_string('emails/reservation_customer.html',
                                                      {'reservation': reserve, 'link': user_page_link})
                send_mail(subject, renderedToCustomer, email_to2, [email_to1],
                          fail_silently=False)

            start = datetime.datetime.combine(reserve.date, reserve.time)
            gcal_params = urllib.urlencode({
                'action': 'TEMPLATE',
                'text': reserve.service_name.encode('utf8'),
                'dates': '%s/%s' % (datetime_to_url_format(start),
                                    datetime_to_url_format(
                                        start + datetime.timedelta(minutes=reserve.service_duration))),
                'details': reserve.service.description.encode('utf8'),
                'location': reserve.service_provider.full_address().encode('utf8'),
                'trp': 'true',
                'sprop': 'E-Narocanje',
                'sprop': 'name:%s' % settings.BASE_URL,
            })
            url_service = settings.BASE_URL + reverse('service', args=(service.id,))

            sync(service.service_provider)

            return render_to_response('reservations/done.html', locals(), context_instance=RequestContext(request))

        # Someone else has made a reservation in the meantime
        return render_to_response('reservations/alreadyreserved.html', locals(),
                                  context_instance=RequestContext(request))
    raise Http404