Ejemplo n.º 1
0
def amazon_login(request):
    error = get_request_param(request, 'error', None)
    return_url = get_return_url(request)

    if error is not None:
        if error == 'access_denied':
            return HttpResponseRedirect('/accounts/amazon_required/')
        error_message = request.GET.get('error_description') + \
                        '<br><a href="' + request.GET.get('error_uri') + \
                        '">Learn more</a>'
        return render(request, 'old/accounts/login.html', {
            'next': return_url,
            'error': error_message
        })

    access_token = get_request_param(request, 'access_token')
    query_parameters = urllib.urlencode({'access_token': access_token})

    token_request = urllib2.urlopen(
        'https://api.amazon.com/auth/O2/tokeninfo?%s' % query_parameters)
    json_data = json.load(token_request)
    if token_request.getcode() == 200:
        is_verified = json_data['aud'] == settings.AMAZON_LOGIN_CLIENT_ID
        if not is_verified:
            return render(
                request, 'old/accounts/login.html', {
                    'next': return_url,
                    'error':
                    'Verification failed! Please contact administrators'
                })

        profile_request = urllib2.urlopen(
            'https://api.amazon.com/user/profile?%s' % query_parameters)
        profile_json_data = json.load(profile_request)

        if profile_request.getcode() == 200:

            # Extract the values we need from the Amazon profile
            amazon_user_id = profile_json_data['user_id']
            amazon_user_name = profile_json_data['name']
            amazon_user_email = profile_json_data['email']

            # Process the login as an amazon login, creating and adding roles to the user as needed
            return _process_amazon_login(access_token, amazon_user_email,
                                         amazon_user_id, request,
                                         amazon_user_name)

        else:
            return _handle_amazon_conn_error(request, profile_json_data)
    else:
        return _handle_amazon_conn_error(request, json_data)
Ejemplo n.º 2
0
def amazon_login(request):
    error = get_request_param(request, 'error', None)
    return_url = get_return_url(request)

    if error is not None:
        if error == 'access_denied':
            return HttpResponseRedirect('/accounts/amazon_required/')
        error_message = request.GET.get('error_description') + \
                        '<br><a href="' + request.GET.get('error_uri') + \
                        '">Learn more</a>'
        return render(request, 'old/accounts/login.html', {
            'next': return_url,
            'error': error_message
        })

    access_token = get_request_param(request, 'access_token')
    query_parameters = urllib.urlencode({'access_token': access_token})

    token_request = urllib2.urlopen('https://api.amazon.com/auth/O2/tokeninfo?%s' % query_parameters)
    json_data = json.load(token_request)
    if token_request.getcode() == 200:
        is_verified = json_data['aud'] == settings.AMAZON_LOGIN_CLIENT_ID
        if not is_verified:
            return render(request, 'old/accounts/login.html', {
                'next': return_url,
                'error': 'Verification failed! Please contact administrators'
            })

        profile_request = urllib2.urlopen('https://api.amazon.com/user/profile?%s' % query_parameters)
        profile_json_data = json.load(profile_request)

        if profile_request.getcode() == 200:

            # Extract the values we need from the Amazon profile
            amazon_user_id = profile_json_data['user_id']
            amazon_user_name = profile_json_data['name']
            amazon_user_email = profile_json_data['email']

            # Process the login as an amazon login, creating and adding roles to the user as needed
            return _process_amazon_login(access_token, amazon_user_email, amazon_user_id, request, amazon_user_name)

        else:
            return _handle_amazon_conn_error(request, profile_json_data)
    else:
        return _handle_amazon_conn_error(request, json_data)
Ejemplo n.º 3
0
def save_linkedin(request):
    """
    Saves linkedin details so that CERN can post to LinkedIn.

    :param request: response from LinkedIn
    :return: redirect to CERN dashboard
    """
    if request.method == 'GET':
        state = 'aowj3p5ro8a0f9jq23lk4jqlwkejADSE$SDSDFGJJaw'
        returned_state = get_request_param(request, 'state')
        if returned_state == state:
            # Handle case when user does not authorize
            if get_request_param(request, 'error') == 'access_denied':
                pass
            code = get_request_param(request, 'code')

            response = urlopen('https://www.linkedin.com/uas/oauth2/accessToken' +
                               '?grant_type=authorization_code' +
                               '&code=' + code +
                               '&redirect_uri=http://' + request.META['HTTP_HOST'] +
                                '/cern/save_linkedin' +
                                '&client_id=' + settings.LINKEDIN_API_KEY +
                                '&client_secret=' + settings.LINKEDIN_SECRET_KEY,
                                data=" ")

            json = loads(response.read())
            seconds_remaining = int(json['expires_in']) - 86400*3
            expires = datetime.utcnow() + timedelta(seconds=seconds_remaining)
            token = json['access_token']

            student = request.current_role.entity
            student.linkedin_token = token
            student.linkedin_expires = expires
            student.save()

            return HttpResponseRedirect('/cern/')
        elif returned_state == '':
            # the request does not come from the LinkedIn API
            return HttpResponseForbidden()
        else:
            # there was a CSRF error, do something else
            pass
Ejemplo n.º 4
0
def save_linkedin(request):
    """
    Saves linkedin details so that CERN can post to LinkedIn.

    :param request: response from LinkedIn
    :return: redirect to CERN dashboard
    """
    if request.method == 'GET':
        state = 'aowj3p5ro8a0f9jq23lk4jqlwkejADSE$SDSDFGJJaw'
        returned_state = get_request_param(request, 'state')
        if returned_state == state:
            # Handle case when user does not authorize
            if get_request_param(request, 'error') == 'access_denied':
                pass
            code = get_request_param(request, 'code')

            response = urlopen(
                'https://www.linkedin.com/uas/oauth2/accessToken' +
                '?grant_type=authorization_code' + '&code=' + code +
                '&redirect_uri=http://' + request.META['HTTP_HOST'] +
                '/cern/save_linkedin' + '&client_id=' +
                settings.LINKEDIN_API_KEY + '&client_secret=' +
                settings.LINKEDIN_SECRET_KEY,
                data=" ")

            json = loads(response.read())
            seconds_remaining = int(json['expires_in']) - 86400 * 3
            expires = datetime.utcnow() + timedelta(seconds=seconds_remaining)
            token = json['access_token']

            student = request.current_role.entity
            student.linkedin_token = token
            student.linkedin_expires = expires
            student.save()

            return HttpResponseRedirect('/cern/')
        elif returned_state == '':
            # the request does not come from the LinkedIn API
            return HttpResponseForbidden()
        else:
            # there was a CSRF error, do something else
            pass
Ejemplo n.º 5
0
def just_login(request):
    raise DeprecationWarning("This code is deprecated")
    error = get_request_param(request, 'error', None)

    if error is not None:
        error_message = request.GET.get('error_description') + \
                        '<br><a href="' + request.GET.get('error_uri') + \
                        '">Learn more</a>'
        return render(request, 'spuddercern/old/login.html', {
            'error': error_message
        })

    access_token = get_request_param(request, 'access_token')
    query_parameters = urllib.urlencode({'access_token': access_token})

    token_request = urllib2.urlopen(
        'https://api.amazon.com/auth/O2/tokeninfo?%s' % query_parameters)
    json_data = json.load(token_request)
    if token_request.getcode() == 200:
        is_verified = json_data['aud'] == settings.AMAZON_LOGIN_CLIENT_ID
        if not is_verified:
            return render(request, 'spuddercern/old/login.html', {
                'error': 'Verification failed! Please contact administrators'
            })

        profile_request = urllib2.urlopen(
            'https://api.amazon.com/user/profile?%s' % query_parameters)
        profile_json_data = json.load(profile_request)

        if profile_request.getcode() == 200:
            amazon_user_id = profile_json_data['user_id']
            amazon_user_name = profile_json_data['name']
            amazon_user_email = profile_json_data['email']

            profiles = UserProfile.objects.filter(amazon_id=amazon_user_id)
            if profiles.count() == 0:
                users_with_email = User.objects.filter(
                    email=amazon_user_email)

                if len(users_with_email) == 0:
                    return HttpResponseRedirect('/cern/')
                else:  # User exists, but for some reason it's profile
                    # wasn't created
                    user = users_with_email[0]

                user_profile = UserProfile(user=user)
                user_profile.amazon_id = amazon_user_id
                user_profile.amazon_access_token = access_token
                user_profile.username = amazon_user_name
                user_profile.save()

            user = authenticate(username=amazon_user_email,
                                password=amazon_user_id)
            profile = user.get_profile()

            if not profile.amazon_access_token:
                profile.amazon_access_token = access_token
                profile.save()

            try:
                Student.objects.get(user=user)
            except ObjectDoesNotExist:
                if is_sponsor(user):
                    django.contrib.auth.login(request, user)

                    logging.info(request.user.is_authenticated())
                    logging.info(is_sponsor(request.user))

                    return HttpResponseRedirect('/dashboard/')
                else:
                    # Redirect to splash page w/o authentication
                    return HttpResponseRedirect('/cern/register')
            else:
                django.contrib.auth.login(request, user)

                logging.info(request.user.is_authenticated())
                logging.info(is_sponsor(request.user))

                return HttpResponseRedirect('/cern/')
        else:
            return _handle_amazon_conn_error(request, profile_json_data)
    else:
        return _handle_amazon_conn_error(request, json_data)
Ejemplo n.º 6
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))
Ejemplo n.º 7
0
def just_login(request):
    raise DeprecationWarning("This code is deprecated")
    error = get_request_param(request, 'error', None)

    if error is not None:
        error_message = request.GET.get('error_description') + \
                        '<br><a href="' + request.GET.get('error_uri') + \
                        '">Learn more</a>'
        return render(request, 'spuddercern/old/login.html',
                      {'error': error_message})

    access_token = get_request_param(request, 'access_token')
    query_parameters = urllib.urlencode({'access_token': access_token})

    token_request = urllib2.urlopen(
        'https://api.amazon.com/auth/O2/tokeninfo?%s' % query_parameters)
    json_data = json.load(token_request)
    if token_request.getcode() == 200:
        is_verified = json_data['aud'] == settings.AMAZON_LOGIN_CLIENT_ID
        if not is_verified:
            return render(request, 'spuddercern/old/login.html', {
                'error':
                'Verification failed! Please contact administrators'
            })

        profile_request = urllib2.urlopen(
            'https://api.amazon.com/user/profile?%s' % query_parameters)
        profile_json_data = json.load(profile_request)

        if profile_request.getcode() == 200:
            amazon_user_id = profile_json_data['user_id']
            amazon_user_name = profile_json_data['name']
            amazon_user_email = profile_json_data['email']

            profiles = UserProfile.objects.filter(amazon_id=amazon_user_id)
            if profiles.count() == 0:
                users_with_email = User.objects.filter(email=amazon_user_email)

                if len(users_with_email) == 0:
                    return HttpResponseRedirect('/cern/')
                else:  # User exists, but for some reason it's profile
                    # wasn't created
                    user = users_with_email[0]

                user_profile = UserProfile(user=user)
                user_profile.amazon_id = amazon_user_id
                user_profile.amazon_access_token = access_token
                user_profile.username = amazon_user_name
                user_profile.save()

            user = authenticate(username=amazon_user_email,
                                password=amazon_user_id)
            profile = user.get_profile()

            if not profile.amazon_access_token:
                profile.amazon_access_token = access_token
                profile.save()

            try:
                Student.objects.get(user=user)
            except ObjectDoesNotExist:
                if is_sponsor(user):
                    django.contrib.auth.login(request, user)

                    logging.info(request.user.is_authenticated())
                    logging.info(is_sponsor(request.user))

                    return HttpResponseRedirect('/dashboard/')
                else:
                    # Redirect to splash page w/o authentication
                    return HttpResponseRedirect('/cern/register')
            else:
                django.contrib.auth.login(request, user)

                logging.info(request.user.is_authenticated())
                logging.info(is_sponsor(request.user))

                return HttpResponseRedirect('/cern/')
        else:
            return _handle_amazon_conn_error(request, profile_json_data)
    else:
        return _handle_amazon_conn_error(request, json_data)
Ejemplo n.º 8
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))