示例#1
0
def create_offering(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = CreateOfferingForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            unit = form.save(commit=False)
            # Get provider ID and set it to unit
            post_data = request.POST.copy()
            provider = post_data.pop("provider")[0]
            app = ClientApp.objects.get(provider=provider)
            unit.lrs_provider = app
            # Start & end date
            start_date = post_data.pop("start_date")[0]
            end_date = post_data.pop("end_date")[0]

            from datetime import datetime as dt
            client_format = '%d / %m / %Y'
            database_format = '%Y-%m-%d'

            # Create a Date object
            start_date = dt.strptime(start_date, client_format)
            end_date = dt.strptime(end_date, client_format)
            # Get formatted date string
            start_date = start_date.strftime(database_format)
            end_date = end_date.strftime(database_format)
            # Create a Date object whose format suits database column format
            start_date = dt.strptime(start_date, database_format)
            end_date = dt.strptime(end_date, database_format)

            unit.start_date = start_date
            unit.end_date = end_date

            unit.save()

            m = UnitOfferingMembership(user=request.user,
                                       unit=unit,
                                       admin=True)
            m.save()

            return render(request, 'clatoolkit/createoffering_success.html', {
                'verb': 'created',
                'unit': unit
            })

    # if a GET (or any other method) we'll create a blank form
    else:
        form = CreateOfferingForm(initial={'provider': 'default_lrs'})

    return render(request, 'clatoolkit/createoffering.html', {
        'verb': 'Create',
        'form': form
    })
示例#2
0
def register_existing(request, unit_id):
    try:
        unit = UnitOffering.objects.get(id=unit_id)
    except UnitOffering.DoesNotExist:
        raise Http404

    if not unit.users.filter(id=request.user.id).exists():
        membership = UnitOfferingMembership(user=request.user,
                                            unit=unit,
                                            admin=False)
        membership.save()

    return redirect("myunits")
示例#3
0
def register(request, unit_id):
    import requests
    # Like before, get the request's context.
    context = RequestContext(request)

    # A boolean value for telling the template whether the registration was successful.
    # Set to False initially. Code changes value to True when registration succeeds.
    registered = False

    try:
        unit = UnitOffering.objects.get(id=unit_id)
    except UnitOffering.DoesNotExist:
        raise Http404

    platforms = unit.get_required_platforms()

    u = None

    if request.user.is_authenticated():
        u = request.user

    # If it's a HTTP POST, we're interested in processing form data.
    if request.method == 'POST':
        # Attempt to grab information from the raw form information.
        # Note that we make use of both UserForm and UserProfileForm.
        user_form = UserForm(data=request.POST)
        profile_form = UserProfileForm(data=request.POST)

        # If the two forms are valid...
        if user_form.is_valid() and profile_form.is_valid():
            # Generate LRS Account
            user = user_form.cleaned_data['username']
            email = user_form.cleaned_data['email']
            lrs = unit.get_lrs()

            # Create a signature to authorise lrs account creation.
            # We don't want randoms creating accounts arbitrarly!
            hash = hmac.new(str(lrs.get_secret()), lrs.get_key(), sha1)

            # Return ascii formatted signature in base64
            signature = binascii.b2a_base64(hash.digest())[:-1]

            payload = {
                "user": user,
                "mailbox": email,
                "client": lrs.app_name,
                "signature": signature
            }

            # TODO: Remove hardwired url (probs from client app model?)
            # print lrs.get_reg_lrs_account_url()
            r = requests.post(lrs.get_reg_lrs_account_url(), data=payload)

            if not (str(r.status_code) == '200' and r.content == 'success'):
                print 'Error: LRS account could not be created.'
                return HttpResponse(r.content)

            ### When an LRS account has been created, create the toolkit account.
            # Save the user's form data to the database.
            user = user_form.save()

            # Now we hash the password with the set_password method.
            # Once hashed, we can update the user object.
            user.set_password(user.password)
            user.save()

            m = UnitOfferingMembership(user=user, unit=unit, admin=False)
            m.save()

            # Now sort out the UserProfile instance.
            # Since we need to set the user attribute ourselves, we set commit=False.
            # This delays saving the model until we're ready to avoid integrity problems.
            profile = profile_form.save(commit=False)
            profile.user = user
            profile.role = "Student"

            # Now we save the UserProfile model instance.
            profile.save()

            # Log in as the newly signed up user
            u = authenticate(username=user_form.cleaned_data["username"],
                             password=user_form.cleaned_data["password"])
            login(request, u)

            return HttpResponseRedirect("/")

    # Not a HTTP POST, so we render our form using two ModelForm instances.
    # These forms will be blank, ready for user input.
    else:
        user_form = UserForm()
        profile_form = UserProfileForm()

    # Render the template depending on the context.
    return render_to_response(
        'clatoolkit/register.html', {
            'user_form': user_form,
            'profile_form': profile_form,
            'registered': registered,
            "course": unit,
            "req_platforms": platforms,
            "user": u
        }, context)