Beispiel #1
0
def _accommodate_legacy_pre_V1_1_0_users(access_token, amazon_user_email,
                                         amazon_user_id):

    # Check if there is a UserProfile (old workflow) for this amazon id
    if not UserProfile.objects.filter(amazon_id=amazon_user_id):
        return

    # If there was a user profile then we need to convert and scrub the user
    UserProfile.objects.get(amazon_id=amazon_user_id).delete()

    try:
        # This is a legacy condition covering users that were created before V1.1.0
        user = User.objects.get(username=amazon_user_email)
        student = Student.objects.get(user=user).id

        role_controller = RoleController(user)
        user_role = role_controller.role_by_entity_type_and_entity_id(
            RoleController.ENTITY_STUDENT, student,
            RoleBase.RoleWrapperByEntityType(RoleController.ENTITY_STUDENT))
        create_linked_authentication_service(
            user_role, LinkedServiceController.SERVICE_AMAZON, amazon_user_id,
            {
                'amazon_user_email': amazon_user_email,
                'amazon_user_id': amazon_user_id,
                'amazon_access_token': access_token
            })
    except ObjectDoesNotExist:
        # It is possible that previously accommodation went wrong and not all objects are currently available
        # If that situation occurs - just leave it as that, it should happen only for sponsors
        pass
Beispiel #2
0
def _accommodate_legacy_pre_V1_1_0_users(access_token, amazon_user_email, amazon_user_id):

    # Check if there is a UserProfile (old workflow) for this amazon id
    if not UserProfile.objects.filter(amazon_id=amazon_user_id):
        return

    # If there was a user profile then we need to convert and scrub the user
    UserProfile.objects.get(amazon_id=amazon_user_id).delete()

    try:
        # This is a legacy condition covering users that were created before V1.1.0
        user = User.objects.get(username=amazon_user_email)
        student = Student.objects.get(user=user).id

        role_controller = RoleController(user)
        user_role = role_controller.role_by_entity_type_and_entity_id(
            RoleController.ENTITY_STUDENT,
            student,
            RoleBase.RoleWrapperByEntityType(RoleController.ENTITY_STUDENT))
        create_linked_authentication_service(
            user_role,
            LinkedServiceController.SERVICE_AMAZON,
            amazon_user_id,
            {
                'amazon_user_email': amazon_user_email,
                'amazon_user_id': amazon_user_id,
                'amazon_access_token': access_token
            })
    except ObjectDoesNotExist:
        # It is possible that previously accommodation went wrong and not all objects are currently available
        # If that situation occurs - just leave it as that, it should happen only for sponsors
        pass
Beispiel #3
0
def migrate_from_amazon(request):
    """
    Helps student migrate from account using Amazon Login
    :param request: any request
    :return: a form to migrate account (similar to registration)
        or a redirect to CERN dashboard
    """
    form = StudentMigrateForm()

    if request.method == 'POST':
        form = StudentMigrateForm(request.POST)

        if form.is_valid():
            email = (form.cleaned_data.get('email_address') or "").strip().lower()
            password = form.cleaned_data.get('password')

            try:
                stu = form.student
            except AttributeError:
                user = User.objects.get(username=email)
            else:
                user = stu.user
                user.username = email

            user.password = password
            user.save()
            messages.success(request, "<h4><i class='fa fa-check'></i> Your password has been updated.</h4>")

            for s in Student.objects.filter(user=user):
                s.migrated = True

            # Can't use a get_or_create bc don't know required field "username"
            try:
                fan = FanPage.objects.get(fan=user)
            except FanPage.DoesNotExist:
                stu = Student.objects.filter(user=user)[0]
                username = "******" % (user_name(user), "Head " if stu.isHead else "", stu.school.name)
                fan = FanPage(fan=user, username=username)
                fan.save()

                # create fan role
                role_controller = RoleController(user)
                fan_role = role_controller.role_by_entity_type_and_entity_id(
                    RoleController.ENTITY_FAN,
                    fan.id,
                    RoleBase.RoleWrapperByEntityType(RoleController.ENTITY_FAN)
                )

            change_current_role(request, RoleController.ENTITY_FAN, fan.id)

            user.backend = "django.contrib.auth.backends.ModelBackend"
            login(request, user)

            return HttpResponseRedirect('/challenges/students')

    return render(request, 'spuddercern/pages/migrate_from_amazon.html', {'form': form})
def create_and_activate_fan_role(request, user):
    # get or create fan role
    fan, created = FanPage.objects.get_or_create(fan=user)
    fan.save()

    # set new users to follow [email protected] fan
    if feature_is_enabled('all_fans_auto_follow_main_spudder_fan') and created:
        main_account = User.objects.get(
            email=settings.MAIN_SPUDDER_FAN_ACCOUNT_EMAIL)
        main_fan = FanPage.objects.get(fan=main_account)
        current_entity = RoleController.GetRoleForEntityTypeAndID(
            RoleController.ENTITY_FAN, fan.id,
            RoleBase.RoleWrapperByEntityType(RoleController.ENTITY_FAN))
        start_following(current_entity, RoleController.ENTITY_FAN, main_fan.id)

    # activate role
    role_controller = RoleController(user)
    role_controller.role_by_entity_type_and_entity_id(
        RoleController.ENTITY_FAN, fan.id,
        RoleBase.RoleWrapperByEntityType(RoleController.ENTITY_FAN))
    change_current_role(request, RoleController.ENTITY_FAN, fan.id)

    return RoleFan(fan)
Beispiel #5
0
def create_and_activate_fan_role(request, user):
    # get or create fan role
    fan, created = FanPage.objects.get_or_create(fan=user)
    fan.save()

    # set new users to follow [email protected] fan
    if feature_is_enabled('all_fans_auto_follow_main_spudder_fan') and created:
        main_account = User.objects.get(email=settings.MAIN_SPUDDER_FAN_ACCOUNT_EMAIL)
        main_fan = FanPage.objects.get(fan=main_account)
        current_entity = RoleController.GetRoleForEntityTypeAndID(
            RoleController.ENTITY_FAN,
            fan.id,
            RoleBase.RoleWrapperByEntityType(RoleController.ENTITY_FAN))
        start_following(current_entity, RoleController.ENTITY_FAN, main_fan.id)

    # activate role
    role_controller = RoleController(user)
    role_controller.role_by_entity_type_and_entity_id(
        RoleController.ENTITY_FAN,
        fan.id,
        RoleBase.RoleWrapperByEntityType(RoleController.ENTITY_FAN))
    change_current_role(request, RoleController.ENTITY_FAN, fan.id)

    return RoleFan(fan)
def accounts_manage_role(request, entity_type, entity_id):
    role_controller = RoleController(request.user)
    if entity_type == RoleController.ENTITY_STUDENT:
        role = role_controller.role_by_entity_type_and_entity_id(
            entity_type, entity_id,
            RoleBase.RoleWrapperByEntityType(entity_type))
        if not role:
            messages.add_message(request, messages.ERROR,
                                 "There was an error loading that role.")
            return redirect('/users')
        if not role.user_is_owner(request.user):
            messages.add_message(request, messages.WARNING,
                                 "You are not the owner of that role.")
            return redirect('/users')
    return render_to_response('spudderaccounts/pages/role_manage.html',
                              {'role': role},
                              context_instance=RequestContext(request))
Beispiel #7
0
def accounts_manage_role(request, entity_type, entity_id):
    role_controller = RoleController(request.user)
    if entity_type == RoleController.ENTITY_STUDENT:
        role = role_controller.role_by_entity_type_and_entity_id(
            entity_type,
            entity_id,
            RoleBase.RoleWrapperByEntityType(entity_type))
        if not role:
            messages.add_message(request, messages.ERROR, "There was an error loading that role.")
            return redirect('/users')
        if not role.user_is_owner(request.user):
            messages.add_message(request, messages.WARNING, "You are not the owner of that role.")
            return redirect('/users')
    return render_to_response(
        'spudderaccounts/pages/role_manage.html',
        {'role': role},
        context_instance=RequestContext(request))
Beispiel #8
0
 def _add_current_role(self, request):
     current_role = None
     if request.user and request.user.is_authenticated():
         role_controller = RoleController(request.user)
         current_role = request.session.get('current_role', None)
         if not current_role:
             one_ane_only_role = select_most_appropriate_user_role(role_controller)
             if one_ane_only_role:
                 current_role = {
                     'entity_type': one_ane_only_role.entity_type,
                     'entity_id': one_ane_only_role.entity.id}
         if current_role:
             change_current_role(request, current_role['entity_type'], current_role['entity_id'])
             current_role = role_controller.role_by_entity_type_and_entity_id(
                 current_role['entity_type'],
                 current_role['entity_id'],
                 RoleBase.RoleWrapperByEntityType(current_role['entity_type']))
     request.current_role = current_role
Beispiel #9
0
 def _add_current_role(self, request):
     current_role = None
     if request.user and request.user.is_authenticated():
         role_controller = RoleController(request.user)
         current_role = request.session.get('current_role', None)
         if not current_role:
             one_ane_only_role = select_most_appropriate_user_role(
                 role_controller)
             if one_ane_only_role:
                 current_role = {
                     'entity_type': one_ane_only_role.entity_type,
                     'entity_id': one_ane_only_role.entity.id
                 }
         if current_role:
             change_current_role(request, current_role['entity_type'],
                                 current_role['entity_id'])
             current_role = role_controller.role_by_entity_type_and_entity_id(
                 current_role['entity_type'], current_role['entity_id'],
                 RoleBase.RoleWrapperByEntityType(
                     current_role['entity_type']))
     request.current_role = current_role
Beispiel #10
0
def register_school(request, school_id, referral_id=None):
    """
    Renders the signup page for a new student at a certain school

    :param request: request to render page
    :param school_id: the ID of the school which the student will
        register with
    :param referral_id: an optional param which indicates a referral by
        another student
    :return: a simple register form (email + password)
    """
    try:
        school = School.objects.get(id=school_id)
    except ObjectDoesNotExist:
        return HttpResponseRedirect('/cern/register/')
    else:
        referrer = None
        if referral_id:
            try:
                referrer = Student.objects.get(id=referral_id)
            except ObjectDoesNotExist:
                referral_id = None

        form = StudentRegistrationForm()
        if request.method == 'POST':
            form = StudentRegistrationForm(request.POST)
            if form.is_valid():
                # Create and login user
                email = form.cleaned_data.get('email_address')
                password = form.cleaned_data.get('password')
                user = User(username=email, email=email, password=password)
                user.save()

                # Create student
                stu = Student(school=school, referred_id=referral_id, user=user)
                if school.num_students() == 0:
                    stu.isHead = True
                stu.save()

                signed_up(stu)
                if referral_id:
                    referrer = Student.objects.get(id=referral_id)
                    recruited_new_student(referrer, school)

                # Create fan for user
                username = "******" % (user_name(user), "Head " if stu.isHead else "", stu.school.name)
                fan = FanPage(fan=user, username=username)
                fan.save()

                user.backend = "django.contrib.auth.backends.ModelBackend"
                login(request, user)

                role_controller = RoleController(user)
                # create the student role
                student_role = role_controller.role_by_entity_type_and_entity_id(
                    RoleController.ENTITY_STUDENT,
                    stu.id,
                    RoleBase.RoleWrapperByEntityType(RoleController.ENTITY_STUDENT)
                )
                # create fan role
                fan_role = role_controller.role_by_entity_type_and_entity_id(
                    RoleController.ENTITY_FAN,
                    fan.id,
                    RoleBase.RoleWrapperByEntityType(RoleController.ENTITY_FAN)
                )

                # activate highest priority role (fan)
                change_current_role(request)

                return HttpResponseRedirect('/challenges/students')
        return render(request, 'spuddercern/pages/register_login.html', {
            'school': school,
            'referrer': referrer,
            'form': form,
            'base_url': settings.SPUDMART_BASE_URL
        })
Beispiel #11
0
def _process_amazon_login(access_token, amazon_user_email, amazon_user_id, request, amazon_user_name=None):

    # Check to see if we need to accomodate pre V1.1.0 accounts
    _accommodate_legacy_pre_V1_1_0_users(access_token, amazon_user_email, amazon_user_id)

    # Check to see if these credential are tied to a user role via an authentication service
    user_role = select_role_by_authentication_service(LinkedServiceController.SERVICE_AMAZON, amazon_user_id)

    next_url = None

    # If there is a role then get the user, else get the currently authenticate user else create a new user
    if user_role and user_role.user:
        # Case - Amazon Login to existing account
        user = user_role.user

        # Get the role controller for this user
        role_controller = RoleController(user)
    else:
        # First get the user or create one
        if request.user.is_authenticated():
            # Case - Add new amazon login based role to existing account
            user = request.user

            # Make a note on the spudder users that as there are multiple roles a password needs to be set for this user
            user.spudder_user.mark_as_password_required()

        else:
            # Case - first time registration
            user = User.objects.create_user(amazon_user_email, amazon_user_email, amazon_user_id)
            user.save()

        # If there is a school id then this is a student registration
        school_id = request.GET.get('school_id', None)
        if school_id:
            # Create the student
            student = create_student(user, school_id, request.GET.get('referrer', None))

            # Get the Role controller for the current user
            role_controller = RoleController(user)

            # Get the user_role for this user/student combo
            user_role = role_controller.role_by_entity_type_and_entity_id(
                RoleController.ENTITY_STUDENT,
                student.id,
                RoleBase.RoleWrapperByEntityType(RoleController.ENTITY_STUDENT))

            # Store the amazon linked authentication service details
            create_linked_authentication_service(
                user_role,
                LinkedServiceController.SERVICE_AMAZON,
                amazon_user_id,
                {
                    'amazon_user_email': amazon_user_email,
                    'amazon_user_id': amazon_user_id,
                    'amazon_access_token': access_token
                })

        # If the account_type is sponsor, create a SponsorPage
        account_type = get_request_param(request, 'account_type')
        if account_type == 'sponsor':
            # Create sponsor
            sponsor = SponsorPage(sponsor=user)
            sponsor.save()

            # Get the Role controller for the current user
            role_controller = RoleController(user)

            # Get the user_role for this user/student combo
            user_role = role_controller.role_by_entity_type_and_entity_id(
                RoleController.ENTITY_SPONSOR,
                sponsor.id,
                RoleBase.RoleWrapperByEntityType(RoleController.ENTITY_SPONSOR))

            # Store the amazon linked authentication service details
            create_linked_authentication_service(
                user_role,
                LinkedServiceController.SERVICE_AMAZON,
                amazon_user_id,
                {
                    'amazon_user_email': amazon_user_email,
                    'amazon_user_id': amazon_user_id,
                    'amazon_access_token': access_token
                })
            
        # If the account_type is fan, create a FanPage
        if account_type == 'fan':
            # Create fan
            fan, _ = FanPage.objects.get_or_create(fan=user)
            fan.save()

            # Get the Role controller for the current user
            role_controller = RoleController(user)

            # Get the user_role for this user/student combo
            user_role = role_controller.role_by_entity_type_and_entity_id(
                RoleController.ENTITY_FAN,
                fan.id,
                RoleBase.RoleWrapperByEntityType(RoleController.ENTITY_FAN))

            # Store the amazon linked authentication service details
            create_linked_authentication_service(
                user_role,
                LinkedServiceController.SERVICE_AMAZON,
                amazon_user_id,
                {
                    'amazon_user_email': amazon_user_email,
                    'amazon_user_id': amazon_user_id,
                    'amazon_access_token': access_token
                })

        # If the account_type is club, create a Club entity in first stage (before registration as recipient)
        if account_type == 'club':
            inv = None
            if request.session['invitation_id']:
                inv = Invitation.objects.get(id=request.session['invitation_id'])
                if str(amazon_user_name) != str(TempClub.objects.get(id=inv.target_entity_id).name):
                    return HttpResponseRedirect('/spudderaffiliates/invitation/%s/incorrect_name' % inv.id)

            club, _ = Club.objects.get_or_create(
                name=amazon_user_name,
                amazon_email=amazon_user_email,
                amazon_id=amazon_user_id
            )
            if inv:
                club.affiliate = Affiliate.objects.get(name=inv.extras['affiliate_name'])
            club.save()

            club_admin, _ = ClubAdministrator.objects.get_or_create(admin=user, club=club)
            club_admin.save()

            # Get the Role controller for the current user
            role_controller = RoleController(user)

            # Get the user_role for this user/student combo
            user_role = role_controller.role_by_entity_type_and_entity_id(
                RoleController.ENTITY_CLUB_ADMIN,
                club_admin.id,
                RoleBase.RoleWrapperByEntityType(RoleController.ENTITY_CLUB_ADMIN))

            # Store the amazon linked authentication service details
            create_linked_authentication_service(
                user_role,
                LinkedServiceController.SERVICE_AMAZON,
                amazon_user_id,
                {
                    'amazon_user_email': amazon_user_email,
                    'amazon_user_id': amazon_user_id,
                    'amazon_access_token': access_token
                })

            next_url = '/club/register/recipient'

    # Get and update the amazon auth record with the latest access token
    # Note that we don't use this at the moment but will in future - MG:20140708
    amazon_auth = get_authentication_wrapper(user_role, LinkedServiceController.SERVICE_AMAZON, amazon_user_id)
    amazon_auth.update_amazon_access_token(access_token)

    if not next_url:
        next_url = request.GET.get('next', None) or user_role.home_page_path

    if not request.user.is_authenticated():
        if user.spudder_user.has_set_password:
            return redirect('/users/account/signin/%s?next=%s' % (user.id, next_url))
        user = authenticate(
            username=user_role.user.username,
            password=amazon_auth.user_password)
        if user:
            django.contrib.auth.login(request, user)
        else:
            raise Http404
    logging.info('%s?next=%s',change_role_url(user_role),next_url)

    return redirect('%s?next=%s' % (
        change_role_url(user_role),
        next_url))
def register_school(request, school_id, referral_id=None):
    """
    Renders the signup page for a new student at a certain school

    :param request: request to render page
    :param school_id: the ID of the school which the student will
        register with
    :param referral_id: an optional param which indicates a referral by
        another student
    :return: a simple register form (email + password)
    """
    try:
        school = School.objects.get(id=school_id)
    except ObjectDoesNotExist:
        return HttpResponseRedirect('/cern/register/')
    else:
        referrer = None
        if referral_id:
            try:
                referrer = Student.objects.get(id=referral_id)
            except ObjectDoesNotExist:
                referral_id = None

        form = StudentRegistrationForm()
        if request.method == 'POST':
            form = StudentRegistrationForm(request.POST)
            if form.is_valid():
                # Create and login user
                email = form.cleaned_data.get('email_address')
                password = form.cleaned_data.get('password')
                user = User(username=email, email=email, password=password)
                user.save()

                # Create student
                stu = Student(school=school,
                              referred_id=referral_id,
                              user=user)
                if school.num_students() == 0:
                    stu.isHead = True
                stu.save()

                signed_up(stu)
                if referral_id:
                    referrer = Student.objects.get(id=referral_id)
                    recruited_new_student(referrer, school)

                # Create fan for user
                username = "******" % (user_name(
                    user), "Head " if stu.isHead else "", stu.school.name)
                fan = FanPage(fan=user, username=username)
                fan.save()

                user.backend = "django.contrib.auth.backends.ModelBackend"
                login(request, user)

                role_controller = RoleController(user)
                # create the student role
                student_role = role_controller.role_by_entity_type_and_entity_id(
                    RoleController.ENTITY_STUDENT, stu.id,
                    RoleBase.RoleWrapperByEntityType(
                        RoleController.ENTITY_STUDENT))
                # create fan role
                fan_role = role_controller.role_by_entity_type_and_entity_id(
                    RoleController.ENTITY_FAN, fan.id,
                    RoleBase.RoleWrapperByEntityType(
                        RoleController.ENTITY_FAN))

                # activate highest priority role (fan)
                change_current_role(request)

                return HttpResponseRedirect('/challenges/students')
        return render(
            request, 'spuddercern/pages/register_login.html', {
                'school': school,
                'referrer': referrer,
                'form': form,
                'base_url': settings.SPUDMART_BASE_URL
            })
def migrate_from_amazon(request):
    """
    Helps student migrate from account using Amazon Login
    :param request: any request
    :return: a form to migrate account (similar to registration)
        or a redirect to CERN dashboard
    """
    form = StudentMigrateForm()

    if request.method == 'POST':
        form = StudentMigrateForm(request.POST)

        if form.is_valid():
            email = (form.cleaned_data.get('email_address')
                     or "").strip().lower()
            password = form.cleaned_data.get('password')

            try:
                stu = form.student
            except AttributeError:
                user = User.objects.get(username=email)
            else:
                user = stu.user
                user.username = email

            user.password = password
            user.save()
            messages.success(
                request,
                "<h4><i class='fa fa-check'></i> Your password has been updated.</h4>"
            )

            for s in Student.objects.filter(user=user):
                s.migrated = True

            # Can't use a get_or_create bc don't know required field "username"
            try:
                fan = FanPage.objects.get(fan=user)
            except FanPage.DoesNotExist:
                stu = Student.objects.filter(user=user)[0]
                username = "******" % (user_name(
                    user), "Head " if stu.isHead else "", stu.school.name)
                fan = FanPage(fan=user, username=username)
                fan.save()

                # create fan role
                role_controller = RoleController(user)
                fan_role = role_controller.role_by_entity_type_and_entity_id(
                    RoleController.ENTITY_FAN, fan.id,
                    RoleBase.RoleWrapperByEntityType(
                        RoleController.ENTITY_FAN))

            change_current_role(request, RoleController.ENTITY_FAN, fan.id)

            user.backend = "django.contrib.auth.backends.ModelBackend"
            login(request, user)

            return HttpResponseRedirect('/challenges/students')

    return render(request, 'spuddercern/pages/migrate_from_amazon.html',
                  {'form': form})
Beispiel #14
0
def _process_amazon_login(access_token,
                          amazon_user_email,
                          amazon_user_id,
                          request,
                          amazon_user_name=None):

    # Check to see if we need to accomodate pre V1.1.0 accounts
    _accommodate_legacy_pre_V1_1_0_users(access_token, amazon_user_email,
                                         amazon_user_id)

    # Check to see if these credential are tied to a user role via an authentication service
    user_role = select_role_by_authentication_service(
        LinkedServiceController.SERVICE_AMAZON, amazon_user_id)

    next_url = None

    # If there is a role then get the user, else get the currently authenticate user else create a new user
    if user_role and user_role.user:
        # Case - Amazon Login to existing account
        user = user_role.user

        # Get the role controller for this user
        role_controller = RoleController(user)
    else:
        # First get the user or create one
        if request.user.is_authenticated():
            # Case - Add new amazon login based role to existing account
            user = request.user

            # Make a note on the spudder users that as there are multiple roles a password needs to be set for this user
            user.spudder_user.mark_as_password_required()

        else:
            # Case - first time registration
            user = User.objects.create_user(amazon_user_email,
                                            amazon_user_email, amazon_user_id)
            user.save()

        # If there is a school id then this is a student registration
        school_id = request.GET.get('school_id', None)
        if school_id:
            # Create the student
            student = create_student(user, school_id,
                                     request.GET.get('referrer', None))

            # Get the Role controller for the current user
            role_controller = RoleController(user)

            # Get the user_role for this user/student combo
            user_role = role_controller.role_by_entity_type_and_entity_id(
                RoleController.ENTITY_STUDENT, student.id,
                RoleBase.RoleWrapperByEntityType(
                    RoleController.ENTITY_STUDENT))

            # Store the amazon linked authentication service details
            create_linked_authentication_service(
                user_role, LinkedServiceController.SERVICE_AMAZON,
                amazon_user_id, {
                    'amazon_user_email': amazon_user_email,
                    'amazon_user_id': amazon_user_id,
                    'amazon_access_token': access_token
                })

        # If the account_type is sponsor, create a SponsorPage
        account_type = get_request_param(request, 'account_type')
        if account_type == 'sponsor':
            # Create sponsor
            sponsor = SponsorPage(sponsor=user)
            sponsor.save()

            # Get the Role controller for the current user
            role_controller = RoleController(user)

            # Get the user_role for this user/student combo
            user_role = role_controller.role_by_entity_type_and_entity_id(
                RoleController.ENTITY_SPONSOR, sponsor.id,
                RoleBase.RoleWrapperByEntityType(
                    RoleController.ENTITY_SPONSOR))

            # Store the amazon linked authentication service details
            create_linked_authentication_service(
                user_role, LinkedServiceController.SERVICE_AMAZON,
                amazon_user_id, {
                    'amazon_user_email': amazon_user_email,
                    'amazon_user_id': amazon_user_id,
                    'amazon_access_token': access_token
                })

        # If the account_type is fan, create a FanPage
        if account_type == 'fan':
            # Create fan
            fan, _ = FanPage.objects.get_or_create(fan=user)
            fan.save()

            # Get the Role controller for the current user
            role_controller = RoleController(user)

            # Get the user_role for this user/student combo
            user_role = role_controller.role_by_entity_type_and_entity_id(
                RoleController.ENTITY_FAN, fan.id,
                RoleBase.RoleWrapperByEntityType(RoleController.ENTITY_FAN))

            # Store the amazon linked authentication service details
            create_linked_authentication_service(
                user_role, LinkedServiceController.SERVICE_AMAZON,
                amazon_user_id, {
                    'amazon_user_email': amazon_user_email,
                    'amazon_user_id': amazon_user_id,
                    'amazon_access_token': access_token
                })

        # If the account_type is club, create a Club entity in first stage (before registration as recipient)
        if account_type == 'club':
            inv = None
            if request.session['invitation_id']:
                inv = Invitation.objects.get(
                    id=request.session['invitation_id'])
                if str(amazon_user_name) != str(
                        TempClub.objects.get(id=inv.target_entity_id).name):
                    return HttpResponseRedirect(
                        '/spudderaffiliates/invitation/%s/incorrect_name' %
                        inv.id)

            club, _ = Club.objects.get_or_create(
                name=amazon_user_name,
                amazon_email=amazon_user_email,
                amazon_id=amazon_user_id)
            if inv:
                club.affiliate = Affiliate.objects.get(
                    name=inv.extras['affiliate_name'])
            club.save()

            club_admin, _ = ClubAdministrator.objects.get_or_create(admin=user,
                                                                    club=club)
            club_admin.save()

            # Get the Role controller for the current user
            role_controller = RoleController(user)

            # Get the user_role for this user/student combo
            user_role = role_controller.role_by_entity_type_and_entity_id(
                RoleController.ENTITY_CLUB_ADMIN, club_admin.id,
                RoleBase.RoleWrapperByEntityType(
                    RoleController.ENTITY_CLUB_ADMIN))

            # Store the amazon linked authentication service details
            create_linked_authentication_service(
                user_role, LinkedServiceController.SERVICE_AMAZON,
                amazon_user_id, {
                    'amazon_user_email': amazon_user_email,
                    'amazon_user_id': amazon_user_id,
                    'amazon_access_token': access_token
                })

            next_url = '/club/register/recipient'

    # Get and update the amazon auth record with the latest access token
    # Note that we don't use this at the moment but will in future - MG:20140708
    amazon_auth = get_authentication_wrapper(
        user_role, LinkedServiceController.SERVICE_AMAZON, amazon_user_id)
    amazon_auth.update_amazon_access_token(access_token)

    if not next_url:
        next_url = request.GET.get('next', None) or user_role.home_page_path

    if not request.user.is_authenticated():
        if user.spudder_user.has_set_password:
            return redirect('/users/account/signin/%s?next=%s' %
                            (user.id, next_url))
        user = authenticate(username=user_role.user.username,
                            password=amazon_auth.user_password)
        if user:
            django.contrib.auth.login(request, user)
        else:
            raise Http404
    logging.info('%s?next=%s', change_role_url(user_role), next_url)

    return redirect('%s?next=%s' % (change_role_url(user_role), next_url))