Ejemplo n.º 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
Ejemplo n.º 2
0
def account_reset_password(request):
    if request.method == 'GET':
        password_form = ResetPasswordForm(initial=request.GET)
        if not password_form.is_valid_token():
            return HttpResponseNotFound()

    if request.method == 'POST':
        password_form = ResetPasswordForm(request.POST)
        if not password_form.is_valid_token():
            return HttpResponseNotFound()
        if password_form.is_valid():
            role = RoleController.GetRoleForEntityTypeAndID(
                password_form.notification.target_entity_type,
                password_form.notification.target_entity_id,
                RoleBase.RoleWrapperByEntityType(
                    password_form.notification.target_entity_type))
            user = role.user
            user.set_password(password_form.cleaned_data.get('password_1'))
            user.save()
            user.spudder_user.mark_password_as_done()
            messages.success(request, "Your new password was saved!")
            # remove notification
            password_form.notification.delete()
            return redirect('/challenges/signin')
    return render_to_response('spudderaccounts/pages/create_password.html', {
        'password_form': password_form,
        'reset_password': True
    },
                              context_instance=RequestContext(request))
Ejemplo n.º 3
0
def send_message(request, page_id):
    """
    Sends a message to the team manager
    :param request: a POST request with message body
    :param team_id: a valid ID of a TeamPage object
    :return: a blank HttpResponse on success
    """
    if request.method == 'POST':
        team = TeamPage.objects.get(id=page_id)

        admin = TeamAdministrator.objects.filter(team_page=team)[0]

        entity = RoleController.GetRoleForEntityTypeAndID(
            admin.entity_type, admin.entity_id,
            RoleBase.RoleWrapperByEntityType(admin.entity_type))
        email = entity.user.email
        details = team.contact_details
        if details and re.match(r'[\w\.]+\@[\w\.]+\.com$', details):
            email = details

        message = request.POST.get('message', '')
        if message:
            to = ['*****@*****.**', email]
            mail.send_mail(subject='Message from Spudder about Team: %s' %
                           team.name,
                           body=message,
                           sender=settings.SERVER_EMAIL,
                           to=to)
        return HttpResponse()
    else:
        return HttpResponseNotAllowed(['POST'])
Ejemplo n.º 4
0
def accounts_activate_role(request, entity_type, entity_id):
    role = RoleController.GetRoleForEntityTypeAndID(
        entity_type, entity_id, RoleBase.RoleWrapperByEntityType(entity_type))
    change_current_role(request, entity_type, entity_id)

    next_url = request.GET.get('next', None)
    if next_url is None:
        next_url = role.home_page_path
    return redirect(next_url or '/users')
Ejemplo n.º 5
0
def select_role_by_authentication_service(service_type, unique_service_id):
    service_wrapper = LinkedServiceController.LinkedServiceByTypeAndID(
        service_type, unique_service_id,
        AuthenticationServiceBase.RoleWrapperByEntityType(service_type))
    if not service_wrapper:
        return None
    return RoleController.GetRoleForEntityTypeAndID(
        service_wrapper.linked_service.role_type,
        service_wrapper.linked_service.role_id,
        RoleBase.RoleWrapperByEntityType(
            service_wrapper.linked_service.role_type))
Ejemplo n.º 6
0
def select_all_user_roles(role_controller):
    """
    Returns a list of all user roles in the right wrapper
    :param role_controller: spudderdomain.controllers.RoleController instance
    :return: list of wrappers subclassed from apudderaccounts.wrappers.RoleBase
    """
    roles = []
    for entity_type in role_controller.ENTITY_TYPES:
        roles += role_controller.roles_by_entity(
            entity_type, RoleBase.RoleWrapperByEntityType(entity_type))
    roles.sort(key=lambda r: r.meta_data.get('last_accessed', 0), reverse=True)
    return roles
Ejemplo n.º 7
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)
Ejemplo n.º 8
0
def change_current_role(request, entity_type=None, entity_id=None):
    if not entity_type or not entity_id:
        role_controller = RoleController(request.user)
        role = select_most_appropriate_user_role(role_controller)
        entity_type = role.entity_type
        entity_id = role.entity.id
    else:
        role = RoleController.GetRoleForEntityTypeAndID(
            entity_type, entity_id,
            RoleBase.EntityWrapperByEntityType(entity_type))
    request.session['current_role'] = {
        'entity_type': entity_type,
        'entity_id': entity_id
    }
    return role
Ejemplo n.º 9
0
def challenge_view(request, challenge_id):
    challenge = get_object_or_404(Challenge, id=challenge_id)
    template = challenge.template
    template_data = {
        'challenge':
        challenge,
        'template':
        template,
        'owner':
        RoleController.GetRoleForEntityTypeAndID(
            challenge.creator_entity_type, challenge.creator_entity_id,
            RoleBase.EntityWrapperByEntityType(challenge.creator_entity_type))
    }
    return render(request, 'spudderspuds/challenges/pages/challenge_view.html',
                  template_data)
Ejemplo n.º 10
0
def get_entity_base_instanse_by_id_and_type(entity_id, entity_type):
    from spudderaccounts.wrappers import RoleBase
    from spudderdomain.controllers import RoleController, EntityController
    from spudderdomain.wrappers import EntityBase
    if entity_type in RoleController.ENTITY_TYPES:
        entity = RoleController.GetRoleForEntityTypeAndID(
            entity_type, entity_id,
            RoleBase.RoleWrapperByEntityType(entity_type))
    elif entity_type in EntityController.ENTITY_TYPES:
        entity = EntityController.GetWrappedEntityByTypeAndId(
            entity_type, entity_id,
            EntityBase.EntityWrapperByEntityType(entity_type))
    else:
        raise NotImplementedError("Entity type %s is not supported" %
                                  entity_type)
    return entity
Ejemplo n.º 11
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))
Ejemplo n.º 12
0
 def creator(self):
     attribute_key = '_creator'
     try:
         creator = getattr(self, attribute_key)
         if not creator:
             raise AttributeError
     except AttributeError:
         from spudderaccounts.controllers import RoleController
         from spudderaccounts.wrappers import RoleBase
         creator = None
         for entity_type in RoleController.ENTITY_TYPES:
             if self.creator_entity_type == entity_type:
                 creator = RoleController.GetRoleForEntityTypeAndID(
                     entity_type, self.creator_entity_id,
                     RoleBase.EntityWrapperByEntityType(entity_type))
         setattr(self, attribute_key, creator)
     return creator
Ejemplo n.º 13
0
    def NotifyEntity(cls,
                     target_entity_id,
                     target_entity_type,
                     notification_type,
                     extras={},
                     notification_channels=[NOTIFY_BY_EMAIL]):

        notifications = Notification.objects.filter(
            target_entity_id=target_entity_id,
            target_entity_type=target_entity_type,
            notification_type=notification_type)
        created = False
        notify_after = extras.get('notify_after')
        for notification in notifications:
            if notification.extras.get('notify_after') == notify_after:
                created = True
                break

        if not created:
            notification = Notification(target_entity_id=target_entity_id,
                                        target_entity_type=target_entity_type,
                                        notification_type=notification_type,
                                        extras=extras)
            notification.save()

        for notification_channel in notification_channels:
            if notification_channel in cls.NOTIFICATION_CHANNELS:
                if notification_channel == cls.NOTIFY_BY_EMAIL:
                    if notification_type == Notification.COMPLETE_CHALLENGE_NOTIFICATION and not created:
                        entity = RoleController.GetRoleForEntityTypeAndID(
                            target_entity_type, target_entity_id,
                            RoleBase.RoleWrapperByEntityType(
                                target_entity_type))
                        kwargs = {'notification': notification}
                        CommunicationController.CommunicateWithEmail(
                            emails=entity.contact_emails, **kwargs)
                else:
                    raise NotImplementedError(
                        'Notification channel %s not implemented' %
                        notification_channel)
            else:
                raise NotImplementedError(
                    'Notification channel %s not supported' %
                    notification_channel)
Ejemplo n.º 14
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
Ejemplo n.º 15
0
def challenge_challenge_thanks(request, participation_id):
    participation = get_object_or_404(ChallengeChallengeParticipation,
                                      id=participation_id)
    creator = RoleController.GetRoleForEntityTypeAndID(
        participation.participating_entity_type,
        participation.participating_entity_id,
        RoleBase.EntityWrapperByEntityType(
            participation.participating_entity_type))
    beneficiary = EntityController.GetWrappedEntityByTypeAndId(
        participation.recipient_entity_type, participation.recipient_entity_id,
        EntityBase.EntityWrapperByEntityType(
            participation.recipient_entity_type))
    template_data = {
        'participation': participation,
        'creator': creator,
        'beneficiary': beneficiary,
        'just_submitted': request.GET.get('just_submitted')
    }
    return render(
        request,
        'spudderspuds/challenges/pages/challenge_challenge_thanks.html',
        template_data)
Ejemplo n.º 16
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})
Ejemplo n.º 17
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.º 18
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
            })