示例#1
0
def bulk_add(request):
    """
    Bulk-add users to the system (Originally used for the CSC2012)
    """
    if not _user_is_logged(request):
        msg_error(request, "You are not authenticated!")
        return redirect("dashboard")
    if not request.user.is_staff:
        msg_error(
            request, "You do not have permission to access this resource!")
        return redirect("dashboard")

    # Display bulk add screen
    mem_data = get_memory(request, "data", "")
    return render(
        request, "user/users_bulkadd.html", {"data": mem_data}
    )
示例#2
0
def revoke(request, context_id):

    # Try to find the context
    try:
        entry = MarketplaceContextEntry.objects.get(context__id=context_id)
    except:
        msg_error(request, "Context with id " +
                  context_id + " is not in the market!")
        return redirect("dashboard")

    # Check if context belongs to calling user
    if request.user.id != entry.context.owner.id:
        msg_error(request, "Context with id " +
                  context_id + " does not belong to you!")
        return redirect("dashboard")

    # Is it confirmed?
    if ("confirm" in request.GET) and (request.GET["confirm"] == "yes"):

        # Delete icon if we have the last reference
        if get_icon_usage(entry.icon) == 1:
            try:
                entry.icon.delete()
            except:
                pass

        # The context is also not public any more
        entry.context.public = False
        entry.context.save()

        # Delete the specified contextualization entry
        entry.delete()

        # Go to dashboard
        msg_confirm(request, "Context removed successfully!")
        return redirect("dashboard")

    else:
        # Show the confirmation screen
        return render_confirm(
            request, "Revoke context",
            "Are you sure you want to remove this entry from the marketplace?",
            reverse("market_revoke", kwargs={"context_id": context_id})
            + "?confirm=yes",
            reverse("dashboard")
        )
示例#3
0
def revoke(request, context_id):

    # Try to find the context
    try:
        entry = MarketplaceContextEntry.objects.get(context__id=context_id)
    except:
        msg_error(request,
                  "Context with id " + context_id + " is not in the market!")
        return redirect("dashboard")

    # Check if context belongs to calling user
    if request.user.id != entry.context.owner.id:
        msg_error(request,
                  "Context with id " + context_id + " does not belong to you!")
        return redirect("dashboard")

    # Is it confirmed?
    if ("confirm" in request.GET) and (request.GET["confirm"] == "yes"):

        # Delete icon if we have the last reference
        if get_icon_usage(entry.icon) == 1:
            try:
                entry.icon.delete()
            except:
                pass

        # The context is also not public any more
        entry.context.public = False
        entry.context.save()

        # Delete the specified contextualization entry
        entry.delete()

        # Go to dashboard
        msg_confirm(request, "Context removed successfully!")
        return redirect("dashboard")

    else:
        # Show the confirmation screen
        return render_confirm(
            request, "Revoke context",
            "Are you sure you want to remove this entry from the marketplace?",
            reverse("market_revoke", kwargs={"context_id": context_id}) +
            "?confirm=yes", reverse("dashboard"))
示例#4
0
def publish(request, context_id):

    # Try to find the context
    try:
        context = ContextDefinition.objects.get(id=context_id)
    except:
        msg_error(request, "Context with id " +
                  context_id + " is not defined!")
        return redirect("dashboard")

    # Check if context belongs to calling user
    if request.user.id != context.owner.id:
        msg_error(request, "Context with id " +
                  context_id + " does not belong to you!")
        return redirect("dashboard")

    # Check if this entry is already there
    if MarketplaceContextEntry.objects.filter(context=context).exists():
        msg_info(request, "This context already exists in the marketplace!")
        return redirect("dashboard")

    # Render values
    return uncache_response(
        render(
            request,
            "market/marketplace_publish_ctx.html",
            {
                "groups": MarketplaceGroup.objects.all(),
                "context": context,
                "icons": get_icons(request.user),

                # For redirection with memory
                "values": {
                    "group": get_memory(request, "group"),
                    "instructions": get_memory(request, "instructions"),
                    "tags": get_memory(request, "tags")
                }
            }
        )
    )
示例#5
0
def publish(request, context_id):

    # Try to find the context
    try:
        context = ContextDefinition.objects.get(id=context_id)
    except:
        msg_error(request,
                  "Context with id " + context_id + " is not defined!")
        return redirect("dashboard")

    # Check if context belongs to calling user
    if request.user.id != context.owner.id:
        msg_error(request,
                  "Context with id " + context_id + " does not belong to you!")
        return redirect("dashboard")

    # Check if this entry is already there
    if MarketplaceContextEntry.objects.filter(context=context).exists():
        msg_info(request, "This context already exists in the marketplace!")
        return redirect("dashboard")

    # Render values
    return uncache_response(
        render(
            request,
            "market/marketplace_publish_ctx.html",
            {
                "groups": MarketplaceGroup.objects.all(),
                "context": context,
                "icons": get_icons(request.user),

                # For redirection with memory
                "values": {
                    "group": get_memory(request, "group"),
                    "instructions": get_memory(request, "instructions"),
                    "tags": get_memory(request, "tags")
                }
            }))
示例#6
0
def bulk_add_commit(request):
    """
    Commit the bulky-added users
    """
    if not _user_is_logged(request):
        msg_error(request, "You are not authenticated!")
        return redirect("dashboard")
    if not request.user.is_staff:
        msg_error(
            request, "You do not have permission to access this resource!")
        return redirect("dashboard")

    # Parse the users
    data = request.POST.get("data", "")
    users = re.split(r"\r?\n", data)
    line = 0
    for u in users:
        u = u.strip()
        line += 1

        # Skip empty lines
        if (u == ""):
            continue

        # Process line
        data = u.split(",")
        if len(data) < 2:
            msg_warning(
                request, "Expected <strong>user,password, ...</strong> syntax\
 on line " + str(line))
            return redirect_memory("user__bulk_add", request)

        # Add user
        try:
            u = User(username=data[0])
            u.set_password(data[1])

            # Setup optional fields
            if len(data) >= 3:
                u.first_name = data[2]
            if len(data) >= 4:
                u.last_name = data[3]
            if len(data) >= 5:
                u.email = data[4]

            # Add user
            u.save()
            msg_confirm(request, "User " + data[0] + " added!")

        except Exception as ex:
            msg_error(
                request, "Error while adding user " + data[0] + ": " + str(ex))
            return redirect_memory("user__bulk_add", request)

    # Go to dashboard
    return redirect("dashboard")
示例#7
0
def publish_action(request):

    # Fetch entries
    fContext = request.POST["context"]
    fInstructions = request.POST["instructions"]
    fTags = request.POST["tags"]
    fGroup = request.POST["group"]

    # Validate entries
    if not fInstructions:
        msg_error(request, "Please enter some instructions!")
        return redirect_memory(
            reverse("market_publish", kwargs={"context_id": fContext}),
            request
        )

    # Sanitize tags
    tagParts = fTags.split(",")
    tagString = ""
    for t in tagParts:
        t = t.strip()
        if t != "":
            if tagString != "":
                tagString += "|"
            tagString += t.replace(" ", "_").lower()
    tagString = "|" + tagString + "|"

    # Prepare entry
    e = MarketplaceContextEntry()
    e.tags = tagString
    e.details = fInstructions
    e.context = ContextDefinition.objects.get(id=fContext)
    e.group = MarketplaceGroup.objects.get(id=fGroup)

    # Upload image
    if "icon" in request.FILES:
        icon = request.FILES["icon"]
        n = icon.name.lower()
        if not (n.endswith(".jpg") or n.endswith(".jpeg")
                or n.endswith(".png") or n.endswith(".gif")
                or n.endswith(".bmp")):
            msg_error(request, "The uploaded icon file is not an image!")
            return redirect_memory(
                reverse("market_publish", kwargs={"context_id": fContext}),
                request
            )

        e.icon = request.FILES["icon"]

    # Or if we already have a previous icon, reuse that
    elif "prev_icon" in request.POST:
        req_icon = request.POST["prev_icon"]
        if user_owns_icon(req_icon, request.user):
            e.icon = req_icon
        else:
            msg_error(request, "You do not have permission to use this icon!")
            return redirect_memory(
                reverse("market_publish", kwargs={"context_id": fContext}),
                request
            )

    else:
        msg_error(request, "No icon was selected!")
        return redirect_memory(
            reverse("market_publish", kwargs={"context_id": fContext}),
            request
        )

    # Save entry (This also stores the uploaded image)
    e.save()

    # The context is also public now
    e.context.public = True
    e.context.save()

    # Now rescale the uploaded icon within 64x64 pixels
    if "icon" in request.FILES:
        if ((e.icon.width > 84) or (e.icon.height > 84)):
            im = Image.open(e.icon.path)
            im.thumbnail((84, 84), Image.ANTIALIAS)
            im.save(e.icon.path)

    # Go to dashboard
    msg_confirm(request, "Context published successfully!")
    return redirect("dashboard")
示例#8
0
def publish_action(request):

    # Fetch entries
    fContext = request.POST["context"]
    fInstructions = request.POST["instructions"]
    fTags = request.POST["tags"]
    fGroup = request.POST["group"]

    # Validate entries
    if not fInstructions:
        msg_error(request, "Please enter some instructions!")
        return redirect_memory(
            reverse("market_publish", kwargs={"context_id": fContext}),
            request)

    # Sanitize tags
    tagParts = fTags.split(",")
    tagString = ""
    for t in tagParts:
        t = t.strip()
        if t != "":
            if tagString != "":
                tagString += "|"
            tagString += t.replace(" ", "_").lower()
    tagString = "|" + tagString + "|"

    # Prepare entry
    e = MarketplaceContextEntry()
    e.tags = tagString
    e.details = fInstructions
    e.context = ContextDefinition.objects.get(id=fContext)
    e.group = MarketplaceGroup.objects.get(id=fGroup)

    # Upload image
    if "icon" in request.FILES:
        icon = request.FILES["icon"]
        n = icon.name.lower()
        if not (n.endswith(".jpg") or n.endswith(".jpeg") or n.endswith(".png")
                or n.endswith(".gif") or n.endswith(".bmp")):
            msg_error(request, "The uploaded icon file is not an image!")
            return redirect_memory(
                reverse("market_publish", kwargs={"context_id": fContext}),
                request)

        e.icon = request.FILES["icon"]

    # Or if we already have a previous icon, reuse that
    elif "prev_icon" in request.POST:
        req_icon = request.POST["prev_icon"]
        if user_owns_icon(req_icon, request.user):
            e.icon = req_icon
        else:
            msg_error(request, "You do not have permission to use this icon!")
            return redirect_memory(
                reverse("market_publish", kwargs={"context_id": fContext}),
                request)

    else:
        msg_error(request, "No icon was selected!")
        return redirect_memory(
            reverse("market_publish", kwargs={"context_id": fContext}),
            request)

    # Save entry (This also stores the uploaded image)
    e.save()

    # The context is also public now
    e.context.public = True
    e.context.save()

    # Now rescale the uploaded icon within 64x64 pixels
    if "icon" in request.FILES:
        if ((e.icon.width > 84) or (e.icon.height > 84)):
            im = Image.open(e.icon.path)
            im.thumbnail((84, 84), Image.ANTIALIAS)
            im.save(e.icon.path)

    # Go to dashboard
    msg_confirm(request, "Context published successfully!")
    return redirect("dashboard")
示例#9
0
def csc_do_login(request):
    """ Login """
    if request.user is not None and request.user.is_authenticated():
        return redirect("dashboard")

    u_name = request.POST.get('username', '')
    if u_name == '':
        msg_error(request, "Please specify a username!")
        return redirect("user_csc_login")

    u_pwd = request.POST.get('password', '')
    if u_pwd == '':
        msg_error(request, "Please specify a password!")
        return redirect("user_csc_login")

    # Open config file
    config = ConfigParser.RawConfigParser()
    config.read(settings.CSC_USER_CONFIG_FILE)

    # Read user parameter
    try:

        # Fetch the salted password
        salted_pwd = config.get('accounts', u_name)
        if not salted_pwd:
            msg_error(request, "Invalid username/password combination!")
            return redirect("user_csc_login")

        # Validate password
        if crypt.crypt(u_pwd, salted_pwd) != salted_pwd:
            msg_error(request, "Invalid username/password combination!")
            return redirect("user_csc_login")

        # Calculate the loginname
        u_loginname = "csc_" + u_name

        # Check if the user exists in the database.
        # Otherwise create it...
        try:
            u = User.objects.get(username=u_loginname)
        except:

            # Create new user
            u = User(username=u_loginname)

            # Setup permissions
            u.set_password(u_pwd)
            u.save()

        # Login user
        try:
            u.backend = 'django.contrib.auth.backends.ModelBackend'
            django_login(request, u)
        except Exception as ex:
            msg_error(request, "An error occured! " + str(ex))
            return redirect("user_csc_login")

    except NoOptionError:
        msg_error(request, "Invalid username/password combination!")
        return redirect("user_csc_login")

    except Exception as e:
        msg_error(request, "An error occured! " + str(e))
        return redirect("user_csc_login")

    # Everything was ok, the user is logged in
    return redirect("dashboard")