コード例 #1
0
ファイル: views.py プロジェクト: simensma/sherpa
def login(request):
    if 'authenticated_users' in request.session:
        del request.session['authenticated_users']

    context = {
        'user_password_length': settings.USER_PASSWORD_LENGTH,
        'memberid_lookups_limit': settings.MEMBERID_LOOKUPS_LIMIT,
        'countries': FocusCountry.get_sorted(),
    }

    if request.method == 'GET':
        if request.user.is_authenticated():
            # User is already authenticated, skip login
            return redirect(request.GET.get('next', reverse('user.views.home')))

        if 'registreringsnokkel' in request.GET:
            try:
                user = User.get_users(include_pending=True).get(pending_registration_key=request.GET['registreringsnokkel'])
                context['prefilled_user'] = user
            except User.DoesNotExist:
                pass

        context['next'] = request.GET.get('next')
        return render(request, 'common/user/login/login.html', context)

    elif request.method == 'POST':
        matches, message = attempt_login(request)

        if len(matches) == 1:
            return redirect(request.GET.get('next', reverse('user.views.home')))

        elif len(matches) > 1:
            # Multiple matches, offer a choice between all matches
            request.session['authenticated_users'] = [u.id for u in matches]
            if 'next' in request.GET:
                return redirect("%s?next=%s" %
                    (reverse('user.login.views.choose_authenticated_user'), request.GET['next']))
            else:
                return redirect('user.login.views.choose_authenticated_user')

        else:
            messages.error(request, message)
            context['next'] = request.GET.get('next')
            context['email'] = request.POST['email']
            return render(request, 'common/user/login/login.html', context)

    else:
        return redirect('user.login.views.login')
コード例 #2
0
def family(request):
    if 'user.family.enrollment_form' in request.session:
        enrollment_form = FamilyEnrollmentForm(
            request.user,
            json.loads(request.session.pop('user.family.enrollment_form')),
        )
    else:
        enrollment_form = FamilyEnrollmentForm(request.user)

    context = {
        'main_member_min_age': settings.MEMBERSHIP['MAIN_MEMBER_MIN_AGE'],
        'adult_age': settings.MEMBERSHIP['AGES']['MAIN'],
        'countries': FocusCountry.get_sorted(),
        'enrollment_form': enrollment_form,
    }
    return render(request, 'common/user/account/family/index.html', context)
コード例 #3
0
ファイル: views.py プロジェクト: Turistforeningen/sherpa
def signon_login(request):
    if not 'dntconnect' in request.session:
        # Use a friendlier error message here?
        raise PermissionDenied

    if request.user.is_authenticated():
        # Shouldn't happen, but handle it just in case.
        add_signon_session_value(request, 'logget_inn')
        return redirect('connect:signon_complete')
    else:
        context = {
            'user_password_length': settings.USER_PASSWORD_LENGTH,
            'countries': FocusCountry.get_sorted(),
        }
        if 'registreringsnokkel' in request.GET:
            try:
                user = User.get_users(include_pending=True).get(pending_registration_key=request.GET['registreringsnokkel'])
                context['prefilled_user'] = user
            except User.DoesNotExist:
                pass

        if request.method == 'GET':
            return render(request, 'central/connect/%s/signon.html' % request.session['dntconnect']['client_id'], context)
        elif request.method == 'POST':
            matches, message = attempt_login(request)

            if len(matches) == 1:
                add_signon_session_value(request, 'logget_inn')
                return redirect('connect:signon_complete')

            elif len(matches) > 1:
                # Multiple matches, offer a choice between all matches
                request.session['authenticated_users'] = [u.id for u in matches]
                return redirect('connect:signon_choose_authenticated_user')

            else:
                messages.error(request, message)
                context['email'] = request.POST['email']
                return render(request, 'central/connect/%s/signon.html' % request.session['dntconnect']['client_id'], context)
        else:
            raise PermissionDenied
コード例 #4
0
ファイル: member.py プロジェクト: Turistforeningen/sherpa
    def __init__(self, address):
        # Add fields, replacing NULL values with the empty string
        self.field1 = address.a1.strip() if address.a1 is not None else ''
        self.field2 = address.a2.strip() if address.a2 is not None else ''
        self.field3 = address.a3.strip() if address.a3 is not None else ''

        # Set the actual country object
        # Uppercase the country code (just in case - you never know with Focus)
        self.country = FocusCountry.get_by_code(code=address.country_code.upper())

        if self.country.code == 'NO':
            # Norwegians - set the actual zipcode object
            try:
                self.zipcode = Zipcode.get_by_zipcode(zipcode=address.zipcode_id)
            except Zipcode.DoesNotExist:
                # Some addresses have NULL in the zipcode field for some reason.
                # Use a zipcode object with empty fields.
                self.zipcode = Zipcode()

            # Set the actual County object based on the zipcode
            if self.zipcode.zipcode != '':
                county_code = address.zipcode.county_code
                if county_code == INTERNATIONAL_ADDRESS_COUNTY_CODE:
                    # International address; define the county as None for now.
                    self.county = None
                else:
                    self.county = County.get_by_code(code=county_code)
            else:
                self.county = None

        else:
            # Foreigners - ignore zipcode/area
            # Remove country code prefixes
            if self.field1.lower().startswith("%s-" % self.country.code.lower()):
                self.field1 = self.field1[len(self.country.code) + 1:].strip()
            if self.field2.lower().startswith("%s-" % self.country.code.lower()):
                self.field2 = self.field2[len(self.country.code) + 1:].strip()
            if self.field3.lower().startswith("%s-" % self.country.code.lower()):
                self.field3 = self.field3[len(self.country.code) + 1:].strip()
コード例 #5
0
ファイル: views.py プロジェクト: Turistforeningen/sherpa
def household(request):
    enrollment = get_or_create_enrollment(request)

    if enrollment.state == 'payment':
        # Payment has been initiated but the user goes back here - why?
        # Reset the state and let them reinitiate payment when they're ready.
        enrollment.state = 'registration'
        enrollment.save()
    elif enrollment.state == 'complete':
        # A previous registration has been completed, so why would the user come directly here?
        # Just redirect them back to registration which will restart a new registration.
        return redirect("enrollment:registration")

    errors = invalid_location in request.GET
    if request.method == 'POST':
        enrollment.country = request.POST['country']
        enrollment.address1 = polite_title(request.POST['address1'])
        enrollment.address2 = polite_title(request.POST['address2'])
        enrollment.address3 = polite_title(request.POST['address3'])
        enrollment.zipcode = request.POST['zipcode']
        enrollment.area = request.POST.get('area', '')
        enrollment.existing_memberid = request.POST.get('existing', '')[:50]
        enrollment.wants_yearbook = enrollment.country != 'NO' and 'yearbook' in request.POST
        enrollment.attempted_yearbook = False
        if enrollment.wants_yearbook:
            if enrollment.existing_memberid != '' or not enrollment.has_potential_main_member():
                enrollment.wants_yearbook = False
                enrollment.attempted_yearbook = True
        enrollment.save()

        if enrollment.validate_location():
            if enrollment.country != 'NO':
                return redirect('enrollment:verification')
            else:
                try:
                    focus_zipcode = FocusZipcode.objects.get(zipcode=enrollment.zipcode)
                    Forening.objects.get(focus_id=focus_zipcode.main_forening_id) # Verify that the Forening exists
                    return redirect('enrollment:verification')
                except FocusZipcode.DoesNotExist:
                    # We know that this zipcode exists in Zipcode, because validate_location validated, and it checks
                    # for that
                    logger.warning(
                        "Postnummer finnes i Zipcode, men ikke i Focus!",
                        exc_info=sys.exc_info(),
                        extra={
                            'request': request,
                            'postnummer': enrollment.zipcode
                        }
                    )
                    messages.error(request, 'focus_zipcode_missing')
                except Forening.DoesNotExist:
                    logger.warning(
                        "Focus-postnummer mangler foreningstilknytning!",
                        exc_info=sys.exc_info(),
                        extra={'request': request}
                    )
                    messages.error(request, 'focus_zipcode_missing')
        else:
            errors = True

    context = {
        'enrollment': enrollment,
        'invalid_existing': invalid_existing in request.GET,
        'countries': FocusCountry.get_sorted(),
        'foreign_shipment_price': FOREIGN_SHIPMENT_PRICE,
        'errors': errors,
    }
    context.update(current_template_layout(request))
    return render(request, 'central/enrollment/household.html', context)
コード例 #6
0
ファイル: views.py プロジェクト: Turistforeningen/sherpa
def login(request):
    if 'authenticated_users' in request.session:
        del request.session['authenticated_users']

    context = {
        'user_password_length': settings.USER_PASSWORD_LENGTH,
        'memberid_lookups_limit': settings.MEMBERID_LOOKUPS_LIMIT,
        'countries': FocusCountry.get_sorted(),
    }

    if request.method == 'GET':
        # If the user is already authenticated, send them straight forwards
        if request.user.is_authenticated():
            return redirect(request.GET.get('next', reverse('user:home')))

        # If logging in on a non-central site, first send the user to the
        # central site to try automatic login. Except if 'sso_checked' is set in
        # session, in which case they've already tried and failed.
        if not request.site.is_central() \
                and 'sso_checked' not in request.session:
            return_address = 'https://%s%s?next=%s' % (
                request.site.domain,
                reverse('user:login.single_signon_return'),
                request.GET.get('next', reverse('user:home')),
            )
            return redirect('https://%s%s?next=%s' % (
                Site.get_central().domain,
                reverse('user:login.single_signon_check'),
                urlquote(return_address),
            ))

        if 'registreringsnokkel' in request.GET:
            try:
                user = User.get_users(include_pending=True).get(
                    pending_registration_key=request.GET['registreringsnokkel']
                )
                context['prefilled_user'] = user
            except User.DoesNotExist:
                pass

        if 'next' in request.GET:
            context['next'] = urlquote(request.GET['next'])
        if request.session.get('OAuth-authorization'):
            context['stripped_layout'] = True

        return render(request, 'common/user/login/login.html', context)

    elif request.method == 'POST':
        matches, message = attempt_login(request)

        if len(matches) == 1:
            if request.session.get('OAuth-authorization'):
                try:
                    o = urlparse(request.GET.get('next', None))
                    client_id = [a[1] for a in parse_qsl(o.query) if a[0] == 'client_id'][0]
                    request.user.last_login_oauth_date = datetime.now()
                    request.user.save()
                    log, created = UserOauthActiveLog.objects.get_or_create(
                        user=request.user,
                        oauth_client_id=client_id,
                        defaults={
                            'first_date': request.user.last_login_oauth_date,
                            'last_date': request.user.last_login_oauth_date
                        })
                    if not created:
                        log.last_date = request.user.last_login_oauth_date
                        log.save()
                except:
                    pass
            else:
                request.user.last_login_site_date = datetime.now()
                request.user.save()

            if request.site.is_central():
                return redirect(request.GET.get('next', reverse('user:home')))
            else:
                if 'sso_checked' in request.session:
                    del request.session['sso_checked']
                return redirect(sso_login_url(
                    request.site,
                    request.user,
                    request.GET.get('next', reverse('user:home')),
                ))

        elif len(matches) > 1:
            # Multiple matches, offer a choice between all matches
            request.session['authenticated_users'] = [u.id for u in matches]
            if 'next' in request.GET:
                return redirect(
                    "%s?next=%s" % (
                        reverse('user:login.choose_authenticated_user'),
                        urlquote(request.GET['next']),
                    )
                )
            else:
                return redirect('user:login.choose_authenticated_user')

        else:
            messages.error(request, message)
            if 'next' in request.GET:
                context['next'] = urlquote(request.GET['next'])
            context['email'] = request.POST['email']
            if request.session.get('OAuth-authorization'):
                context['stripped_layout'] = True
            return render(request, 'common/user/login/login.html', context)

    else:
        return redirect('user:login.login')
コード例 #7
0
def register_membership(request):
    """This view should reuse the standard registration logic in user/login/util and still merge the user objects
    instead of reimplementing the logic."""
    if request.user.is_member():
        return redirect('user:home')

    if request.method == 'GET':
        context = {
            'memberid_lookups_limit': settings.MEMBERID_LOOKUPS_LIMIT,
            'countries': FocusCountry.get_sorted()
        }
        return render(request, 'common/user/account/register_membership.html', context)
    elif request.method == 'POST':
        try:
            user = request.user
            verified_user = verify_memberid(
                ip_address=request.META['REMOTE_ADDR'],
                memberid=request.POST['memberid'],
                country_code=request.POST['country'],
                zipcode=request.POST['zipcode'],
            )

            if request.POST['email-equal'] == 'true':
                # Focus-email is empty, or equal to this email, so just use it
                chosen_email = user.get_email()
            elif request.POST['email-choice'] == 'sherpa':
                chosen_email = user.get_email()
            elif request.POST['email-choice'] == 'focus':
                chosen_email = verified_user.get_email()
            elif request.POST['email-choice'] == 'custom':
                # Check that the email address is valid
                if not validator.email(request.POST['email']):
                    messages.error(request, 'invalid_email')
                    return redirect('user:register_membership')
                chosen_email = request.POST['email']
            else:
                raise Exception("Missing email-equal / email-choise-parameters")

            # Check that the user doesn't already have an account
            if not verified_user.is_inactive:
                messages.error(request, 'user_exists')
                return redirect('user:register_membership')

            # Ok, registration successful, update the user

            # The verified user might be pending. The merge method only merges related objects, so if that's the case,
            # set the new user's state to pending.
            if verified_user.is_pending:
                user.is_pending = True
                user.save()

            # The verification lookup will ensure there's already an inactive user, pending or not, so merge them
            user.merge_with(verified_user, move_password=True) # This will delete the other user

            # Point the user to its corresponding memberid and clear other personal information
            user.identifier = request.POST['memberid']
            user.memberid = request.POST['memberid']
            user.first_name = ''
            user.last_name = ''
            user.email = ''
            user.save()

            # Save the chosen email in Focus
            user.set_contact_info({'email': chosen_email})

            return redirect('user:home')

        except MemberidLookupsExceeded:
            messages.error(request, 'memberid_lookups_exceeded')
            return redirect('user:register_membership')

        except CountryDoesNotExist:
            raise PermissionDenied

        except (NoMatchingMemberid, ActorIsNotPersonalMember, ValueError):
            messages.error(request, 'invalid_memberid')
            return redirect('user:register_membership')
コード例 #8
0
 def get_country(self):
     return FocusCountry.get_by_code(code=self.country)