def validate_name(name):
    try:
        validate_unicode_slug(name)
    except ValidationError:
        return False
    else:
        return True
Ejemplo n.º 2
0
def create_library_block(library_key, block_type, definition_id):
    """
    Create a new XBlock in this library of the specified type (e.g. "html").

    The 'definition_id' value (which should be a string like "problem1") will be
    used as both the definition_id and the usage_id.
    """
    assert isinstance(library_key, LibraryLocatorV2)
    ref = ContentLibrary.objects.get_by_key(library_key)
    # Make sure the proposed ID will be valid:
    validate_unicode_slug(definition_id)
    # Ensure the XBlock type is valid and installed:
    XBlock.load_class(block_type)  # Will raise an exception if invalid
    # Make sure the new ID is not taken already:
    new_usage_id = definition_id  # Since this is a top level XBlock, usage_id == definition_id
    usage_key = LibraryUsageLocatorV2(
        library_org=library_key.org,
        library_slug=library_key.slug,
        block_type=block_type,
        usage_id=new_usage_id,
    )
    library_context = get_learning_context_impl(usage_key)
    if library_context.definition_for_usage(usage_key) is not None:
        raise LibraryBlockAlreadyExists("An XBlock with ID '{}' already exists".format(new_usage_id))

    new_definition_xml = '<{}/>'.format(block_type)  # xss-lint: disable=python-wrap-html
    path = "{}/{}/definition.xml".format(block_type, definition_id)
    # Write the new XML/OLX file into the library bundle's draft
    draft = get_or_create_bundle_draft(ref.bundle_uuid, DRAFT_NAME)
    write_draft_file(draft.uuid, path, new_definition_xml)
    # Clear the bundle cache so everyone sees the new block immediately:
    BundleCache(ref.bundle_uuid, draft_name=DRAFT_NAME).clear()
    # Now return the metadata about the new block:
    return get_library_block(usage_key)
Ejemplo n.º 3
0
def create_library(
    collection_uuid, library_type, org, slug, title, description, allow_public_learning, allow_public_read,
    library_license,
):
    """
    Create a new content library.

    org: an organizations.models.Organization instance

    slug: a slug for this library like 'physics-problems'

    title: title for this library

    description: description of this library

    allow_public_learning: Allow anyone to read/learn from blocks in the LMS

    allow_public_read: Allow anyone to view blocks (including source) in Studio?

    Returns a ContentLibraryMetadata instance.
    """
    assert isinstance(collection_uuid, UUID)
    assert isinstance(org, Organization)
    validate_unicode_slug(slug)
    # First, create the blockstore bundle:
    bundle = create_bundle(
        collection_uuid,
        slug=slug,
        title=title,
        description=description,
    )
    # Now create the library reference in our database:
    try:
        ref = ContentLibrary.objects.create(
            org=org,
            slug=slug,
            type=library_type,
            bundle_uuid=bundle.uuid,
            allow_public_learning=allow_public_learning,
            allow_public_read=allow_public_read,
            license=library_license,
        )
    except IntegrityError:
        delete_bundle(bundle.uuid)
        raise LibraryAlreadyExists(slug)
    CONTENT_LIBRARY_CREATED.send(sender=None, library_key=ref.library_key)
    return ContentLibraryMetadata(
        key=ref.library_key,
        bundle_uuid=bundle.uuid,
        title=title,
        type=library_type,
        description=description,
        num_blocks=0,
        version=0,
        last_published=None,
        allow_public_learning=ref.allow_public_learning,
        allow_public_read=ref.allow_public_read,
        license=library_license,
    )
Ejemplo n.º 4
0
def create_library_block(library_key, block_type, definition_id):
    """
    Create a new XBlock in this library of the specified type (e.g. "html").

    The 'definition_id' value (which should be a string like "problem1") will be
    used as both the definition_id and the usage_id.
    """
    assert isinstance(library_key, LibraryLocatorV2)
    ref = ContentLibrary.objects.get_by_key(library_key)
    if ref.type != COMPLEX:
        if block_type != ref.type:
            raise IncompatibleTypesError(
                _('Block type "{block_type}" is not compatible with library type "{library_type}".'
                  ).format(
                      block_type=block_type,
                      library_type=ref.type,
                  ))
    lib_bundle = LibraryBundle(library_key,
                               ref.bundle_uuid,
                               draft_name=DRAFT_NAME)
    # Total number of blocks should not exceed the maximum allowed
    total_blocks = len(lib_bundle.get_top_level_usages())
    if total_blocks + 1 > settings.MAX_BLOCKS_PER_CONTENT_LIBRARY:
        raise BlockLimitReachedError(
            _(u"Library cannot have more than {} XBlocks").format(
                settings.MAX_BLOCKS_PER_CONTENT_LIBRARY))
    # Make sure the proposed ID will be valid:
    validate_unicode_slug(definition_id)
    # Ensure the XBlock type is valid and installed:
    XBlock.load_class(block_type)  # Will raise an exception if invalid
    # Make sure the new ID is not taken already:
    new_usage_id = definition_id  # Since this is a top level XBlock, usage_id == definition_id
    usage_key = LibraryUsageLocatorV2(
        lib_key=library_key,
        block_type=block_type,
        usage_id=new_usage_id,
    )
    library_context = get_learning_context_impl(usage_key)
    if library_context.definition_for_usage(usage_key) is not None:
        raise LibraryBlockAlreadyExists(
            "An XBlock with ID '{}' already exists".format(new_usage_id))

    new_definition_xml = '<{}/>'.format(
        block_type)  # xss-lint: disable=python-wrap-html
    path = "{}/{}/definition.xml".format(block_type, definition_id)
    # Write the new XML/OLX file into the library bundle's draft
    draft = get_or_create_bundle_draft(ref.bundle_uuid, DRAFT_NAME)
    write_draft_file(draft.uuid, path, new_definition_xml.encode('utf-8'))
    # Clear the bundle cache so everyone sees the new block immediately:
    BundleCache(ref.bundle_uuid, draft_name=DRAFT_NAME).clear()
    # Now return the metadata about the new block:
    LIBRARY_BLOCK_CREATED.send(sender=None,
                               library_key=ref.library_key,
                               usage_key=usage_key)
    return get_library_block(usage_key)
Ejemplo n.º 5
0
def validate_newsletters(newsletters):
    if not newsletters:
        raise ValidationError("No Newsletter Provided")

    newsletters = [n.replace(" ", "") for n in newsletters]
    for newsletter in newsletters:
        try:
            validate_unicode_slug(newsletter)
        except ValidationError:
            raise ValidationError("Invalid newsletter")

    return newsletters
Ejemplo n.º 6
0
def create_library(collection_uuid, org, slug, title, description):
    """
    Create a new content library.

    org: an organizations.models.Organization instance

    slug: a slug for this library like 'physics-problems'

    title: title for this library

    description: description of this library

    Returns a ContentLibraryMetadata instance.
    """
    assert isinstance(collection_uuid, UUID)
    assert isinstance(org, Organization)
    validate_unicode_slug(slug)
    # First, create the blockstore bundle:
    bundle = create_bundle(
        collection_uuid,
        slug=slug,
        title=title,
        description=description,
    )
    # Now create the library reference in our database:
    try:
        ref = ContentLibrary.objects.create(
            org=org,
            slug=slug,
            bundle_uuid=bundle.uuid,
            allow_public_learning=True,
            allow_public_read=True,
        )
    except IntegrityError:
        delete_bundle(bundle.uuid)
        raise LibraryAlreadyExists(slug)
    return ContentLibraryMetadata(
        key=ref.library_key,
        bundle_uuid=bundle.uuid,
        title=title,
        description=description,
        version=0,
    )
def register_user(request):
    """Handles the creation of a new user for authentication
    Method args:
        request -- the full HTTP request object
    """
    errors_found = False

    req_body = json.loads(request.body.decode())

    all_users = User.objects.all()

    username_check = [
        user for user in all_users if user.username == req_body['username']
    ]
    email_check = [
        user for user in all_users if user.email == req_body['email']
    ]

    errors = dict()
    if username_check:
        errors["username"] = "******"
        errors_found = True

    if email_check:
        errors["email"] = "This email is already in use"
        errors_found = True

    try:
        validate_email(req_body['email'])
    except ValidationError:
        errors_found = True
        errors["email"] = "Please enter a valid email address"

    try:
        validate_unicode_slug(req_body['username'])
    except ValidationError:
        errors_found = True
        errors["username"] = "******"

    if errors_found:
        response = json.dumps(errors)
    else:
        # make new user
        new_user = User.objects.create_user(username=req_body['username'],
                                            password=req_body['password'],
                                            email=req_body['email'],
                                            first_name=req_body['first_name'],
                                            last_name=req_body['last_name'],
                                            is_student=req_body['is_student'],
                                            is_teacher=req_body['is_teacher'])
        token = Token.objects.create(user=new_user)

        response = json.dumps({"token": token.key})

        send_mail(
            f"Welcome {req_body['first_name']}",
            "Welcome to lesson Ninja! And thank you for trying this out. If you have any questions, concerns, or comments feel free to reach out to me at [email protected]. Happy Learning!",
            "*****@*****.**", [new_user.email],
            fail_silently=False)

    return HttpResponse(response, content_type='application/json')
Ejemplo n.º 8
0
def register_user(request):
    """Handles the creation of a new user for authentication
    Method args:
        request -- the full HTTP request object
    """
    errors_found = False

    req_body = json.loads(request.body.decode())

    all_users = User.objects.all()

    username_check = [
        user for user in all_users if user.username == req_body['username']
    ]
    email_check = [
        user for user in all_users if user.email == req_body['email']
    ]

    errors = dict()
    if username_check:
        errors["username"] = "******"
        errors_found = True

    if email_check:
        errors["email"] = "This email is already in use"
        errors_found = True

    try:
        validate_email(req_body['email'])
    except ValidationError:
        errors_found = True
        errors["email"] = "Please enter a valid email address"

    try:
        validate_unicode_slug(req_body['username'])
    except ValidationError:
        errors_found = True
        errors["username"] = "******"

    if errors_found:
        response = json.dumps(errors)
    else:
        # make new user
        new_user = User.objects.create_user(
            username=req_body['username'],
            password=req_body['password'],
            email=req_body['email'],
            first_name=req_body['first_name'],
            last_name=req_body['last_name'],
            is_employer=req_body['is_employer'],
            is_crew_member=req_body['is_crew_member'])
        token = Token.objects.create(user=new_user)

        response = json.dumps({"token": token.key})

        send_mail(f"Welcome {req_body['first_name']}",
                  "Welcome to TC Careers!",
                  "*****@*****.**", [new_user.email],
                  fail_silently=False)

    return HttpResponse(response, content_type='application/json')