Example #1
0
def process_callback(
    request: http.HttpRequest,
    payload: SessionPayload,
) -> Optional[str]:
    """Extract the token and store for future calls.

    :param request: Http Request received
    :param payload: Session payload with dictionary with additional info.
    :return: Error message or None if everything has gone correctly.
    """
    # Correct response from a previous request. Obtain the access token,
    # the refresh token, and the expiration date.
    # Verify if the state is the one expected (stored in the session)
    if request.GET.get('state') != request.session[oauth_hash_key]:
        # This call back does not match the appropriate request. Something
        # went wrong.
        return _('Inconsistent OAuth response. Unable to authorize')

    oauth_instance = payload.get('target_url')
    if not oauth_instance:
        return _('Internal error. Empty OAuth Instance name')

    oauth_info = settings.CANVAS_INFO_DICT.get(oauth_instance)
    if not oauth_info:
        return _('Internal error. Invalid OAuth Dict element')

    domain = oauth_info['domain_port']
    response = requests.post(
        oauth_info['access_token_url'].format(domain),
        {
            'grant_type': 'authorization_code',
            'client_id': oauth_info['client_id'],
            'client_secret': oauth_info['client_secret'],
            'redirect_uri': request.session[callback_url_key],
            'code': request.GET.get('code')})

    if response.status_code != status.HTTP_200_OK:
        return _('Unable to obtain access token from OAuth')

    # Response is correct. Parse and extract elements
    response_data = response.json()

    # Create the new token for the user
    utoken = models.OAuthUserToken(
        user=request.user,
        instance_name=oauth_instance,
        access_token=response_data['access_token'],
        refresh_token=response_data.get('refresh_token'),
        valid_until=timezone.now() + timedelta(
            seconds=response_data.get('expires_in', 0)),
    )
    utoken.save()

    return None
Example #2
0
def finish_scheduling(
    request: http.HttpRequest,
    workflow: Optional[models.Workflow] = None,
) -> http.HttpResponse:
    """Finish the create/edit operation of a scheduled operation."""
    del workflow
    payload = SessionPayload(request.session)
    if payload is None:
        # Something is wrong with this execution. Return to action table.
        messages.error(request, _('Incorrect action scheduling invocation.'))
        return redirect('action:index')

    return services.schedule_crud_factory.crud_finish(
        payload.get('operation_type'), request=request, payload=payload)
Example #3
0
File: zip.py Project: ubc/ontask_b
def create_and_send_zip(
    session: SessionBase,
    action: models.Action,
    item_column: models.Column,
    user_fname_column: Optional[models.Column],
    payload: SessionPayload,
) -> http.HttpResponse:
    """Process the list of tuples in files and create the ZIP BytesIO object.

    :param session: Session object while creating a zip (need it to flush it)
    :param action: Action being used for ZIP
    :param item_column: Column used to itemize the zip
    :param user_fname_column: Optional column to create file name
    :param payload: Dictionary with additional parameters to create the ZIP
    :return: HttpResponse to send back with the ZIP download header
    """
    files = _create_eval_data_tuple(action, item_column,
                                    payload.get('exclude_values', []),
                                    user_fname_column)
    file_name_template = _create_filename_template(payload, user_fname_column)

    # Create the ZIP and return it for download
    sbuf = BytesIO()
    zip_file_obj = zipfile.ZipFile(sbuf, 'w')
    for user_fname, part_id, msg_body in files:
        if payload['zip_for_moodle']:
            # If a zip for Moodle, field is Participant [number]. Take the
            # number only
            part_id = part_id.split()[1]

        zip_file_obj.writestr(
            file_name_template.format(user_fname=user_fname, part_id=part_id),
            str(msg_body),
        )
    zip_file_obj.close()

    SessionPayload.flush(session)

    suffix = datetime.now().strftime('%y%m%d_%H%M%S')
    # Attach the compressed value to the response and send
    compressed_content = sbuf.getvalue()
    response = http.HttpResponse(compressed_content)
    response['Content-Type'] = 'application/x-zip-compressed'
    response['Content-Transfer-Encoding'] = 'binary'
    response['Content-Disposition'] = (
        'attachment; filename="ontask_zip_action_{0}.zip"'.format(suffix))
    response['Content-Length'] = str(len(compressed_content))

    return response
Example #4
0
def run_done(
    request: http.HttpRequest,
    workflow: Optional[models.Workflow] = None,
) -> http.HttpResponse:
    """Finish the create/edit operation of a scheduled operation."""
    payload = SessionPayload(request.session)
    if payload is None:
        # Something is wrong with this execution. Return to action table.
        messages.error(request, _('Incorrect action run invocation.'))
        return redirect('action:index')

    return services.ACTION_PROCESS_FACTORY.process_run_request_done(
        payload.get('operation_type'),
        request=request,
        workflow=workflow,
        payload=payload)
    def process_post(
        self,
        request: http.HttpRequest,
        schedule_item: models.ScheduledOperation,
        op_payload: SessionPayload,
    ) -> http.HttpResponse:
        """Process the valid form."""
        if op_payload.get('confirm_items'):
            # Update information to carry to the filtering stage
            op_payload['button_label'] = ugettext('Schedule')
            op_payload['valuerange'] = 2
            op_payload['step'] = 2
            op_payload.store_in_session(request.session)

            return redirect('action:item_filter')

        # Go straight to the final step
        return self.finish(request, op_payload, schedule_item)
Example #6
0
    def process_run_post(
        self,
        request: http.HttpRequest,
        action: models.Action,
        payload: SessionPayload,
    ) -> http.HttpResponse:
        """Process the VALID POST request."""
        if payload.get('confirm_items'):
            # Add information to the session object to execute the next pages
            payload['button_label'] = ugettext('Send')
            payload['valuerange'] = 2
            payload['step'] = 2
            payload.store_in_session(request.session)

            return redirect('action:item_filter')

        # Go straight to the final step.
        return self.process_run_request_done(request,
                                             workflow=action.workflow,
                                             payload=payload,
                                             action=action)
Example #7
0
    def process_run_post(
        self,
        request: http.HttpRequest,
        action: models.Action,
        payload: SessionPayload,
    ) -> http.HttpResponse:
        """Process the VALID POST request."""
        if payload.get('confirm_items'):
            # Create a dictionary in the session to carry over all the
            # information to execute the next pages
            payload['button_label'] = ugettext('Send')
            payload['valuerange'] = 2
            payload['step'] = 2
            continue_url = 'action:item_filter'
        else:
            continue_url = 'action:run_done'

        payload.store_in_session(request.session)

        # Check for the CANVAS token and proceed to the continue_url
        return _canvas_get_or_set_oauth_token(request, payload['target_url'],
                                              continue_url)