예제 #1
0
def classselect(request):
    """ Defines the registration view for first-time users.
        Note: the user will not be registered if they enter
        a username that already exists in our database.
    """
    con = Context()

    user = request.session['user']

    if "chooseclass" in request.POST:
        # Try clause checks if all fields are filled out.
        try:
            nickname=request.POST['chartstringname']
            chartstring = request.POST['chartstring']
            groupname = request.POST['groupname']
            if chartstring != '':
                userobj = User.objects.get(name=user)
                userobj.user_type = 'MANAGER'
		userobj.save()
                new_chartstring = Chartstring(
                    nickname=request.POST['chartstringname'],
                    chartstring=request.POST['chartstring'],
                    budget=request.POST['chartstringamount'],
                    remaining=request.POST['chartstringamount'],
                    manager=userobj)
                if groupname != '':
                    try:
                        add_group = Group.objects.get(name=groupname)
                    except ObjectDoesNotExist:
                        add_group = Group.objects.create(name=groupname)
                else:
                    try:
                        add_group = Group.objects.get(name=nickname)
                    except ObjectDoesNotExist:
                        add_group = Group.objects.create(name=nickname)
                userobj.groups.add(add_group)
                new_chartstring.group = add_group
                new_chartstring.save()
            else:
                if groupname != '':
                    try:
                        userobj = User.objects.get(name=user)
                        add_group = Group.objects.get(name=groupname)
                        userobj.groups.add(add_group)
                    except ObjectDoesNotExist:
                        con['does_not_exist'] = True
                        con.update(csrf(request))
                        return render_to_response('classselect.html', con)
                    else:
                        managers = User.objects.filter(
                            groups=add_group,
                            user_type="MANAGER")
                        for manager in managers:
                            add_Notification(
                                user=manager,
                                code="new_user",
                                info={'group': add_group, 'requestor': userobj})
        except (MultiValueDictKeyError, ObjectDoesNotExist):
            con['empty_fields'] = True
            con.update(csrf(request))
            return render_to_response('classselect.html', con)
	# Resets request.method, so that POST data is no longer stored.
        request.method = None

        if User.objects.get(name=user).user_type == 'GENERAL':
            return HttpResponseRedirect('/browse/')
        elif User.objects.get(name=user).user_type == 'ADMIN':
            return HttpResponseRedirect('/admin/')
        else:
            return HttpResponseRedirect('/manage/')
    elif "cancel" in request.POST:
        return HttpResponseRedirect('/')
    con.update(csrf(request))
    return render_to_response('classselect.html', con)
예제 #2
0
def browse(request):
    """ Defines the view to browse and request applications.
        Users not logged in are redirected to the login page.
    """
    if 'user' not in request.session:
        return HttpResponseRedirect('/')

    # if User.objects.get(name=request.session['user']).user_type == 'MANAGER':
    #     return HttpResponseRedirect('/manage/')

    elif User.objects.get(name=request.session['user']).user_type == 'ADMIN':
        return HttpResponseRedirect('/admin/')

    user = User.objects.get(name=request.session['user'])

    # Form handling; for POST requests to this view.
    apps = App.objects.all()
    if request.method == 'POST':
        app = request.POST['app']
        app_object = App.objects.get(href_name=app)

        # Write change to database.
        try:
            new_app = User_Apps.objects.get(app=app_object, user=user)
        except ObjectDoesNotExist:
            new_app = User_Apps.objects.create(
                user=user,
                app=app_object,
                status='AVAILABLE')

        if new_app.status == 'APPROVED':
            return HttpResponseRedirect('/media/'+ app +'.zip')
        else:
            new_app.status = 'REQUESTED'
            new_app.group = Group.objects.get(name=request.POST['mygroup'])
            new_app.save()

            managers = User.objects.filter(
                        groups=new_app.group,
                        user_type="MANAGER")
            for manager in managers:
                add_Notification(
                    user=manager,
                    code="request",
                    info={'app': app_object, 'requestor': user})

        # Resets request.method, so that POST data is no longer stored.
        request.method = None

    app_states = []
    for app in apps:
        href_name = app.href_name
        try:
            status = User_Apps.objects.get(app=app, user=user).status
            if status.lower() == 'available':
                app_states.append("app-btn-" + href_name)
            elif status.lower() == 'requested':
                app_states.append('requested-btn-' + href_name)
            elif status.lower() == 'approved':
                app_states.append('downloadable-btn-' + href_name)
        except ObjectDoesNotExist:
            app_states.append("app-btn-" + href_name)

    # Dictionary for displaying applications and their statuses
    # app_display: key = app's href name
    #              value = 'available' or 'requested'
    # app_info: key = app's href name
    #           value = the app object from App.objects.all()
    app_display = dict([(apps[x].href_name, app_states[x])
        for x in range(len(apps))])
    app_info = dict([(apps[x].href_name, apps[x])
        for x in range(len(apps))])

    messages = get_Notifications(user)

    # Context and set-up
    con = Context({
            'username': request.session['user'],
            'usertype': user.user_type,
            'sid': request.session['sid'],
            'app_display': app_display,
            'app_info': app_info,
            'messages': messages,
            'notifications': len(messages),
            'groups': sorted(user.groups.all(), key=lambda group: group.name),
        })

    """
    for message in messages:
        message.delete()
    user.notifications = 0
    user.save()"""

    # Update context with Security token for html form
    con.update(csrf(request))

    return render_to_response('browse.html', con)
예제 #3
0
def manage(request):
    """ Defines the manager view for BearApps. PIs and RSOs are
        directed to this view to manage their user requests and
        chartstrings/budgets.
    """
    # Setup sockets to notify license servers
    context = zmq.Context()
    socket = context.socket(zmq.PUB)
    socket.connect("tcp://127.0.0.1:23272")

    if 'user' not in request.session:
        return HttpResponseRedirect('/')

    user = User.objects.get(name=request.session['user'])
    if user.user_type != "MANAGER":
        if user.user_type == "GENERAL":
            return HttpResponseRedirect('/browse/')
        return HttpResponseRedirect('/admin/')
    # Sorts all groups & all users in alphabetical order.
    groups = sorted(user.groups.all(), key=lambda group: group.name)
    all_users = sorted(User.objects.all(), key=lambda user: user.name)
    # all_users.remove(user)

    # groups contains all of the manager's groups
    # all_users contains all of the users in the manager's groups excluding the manager
    if request.method == 'POST':
        if "approve" in request.POST:
            app = request.POST['app']
            price = App.objects.get(href_name=app).price
            chartstring = Chartstring.objects.get(
                chartstring=request.POST['chartstring'])
            user_requested = User.objects.get(SID=request.POST['user'])

            # Write change to database.
            app_object = App.objects.get(href_name=app)
            app = user_requested.user_apps_set.get(app=app_object)
            app.chartstring = chartstring
            chartstring.remaining = chartstring.remaining - price
            chartstring.save()
            app.date = date.today()
            app.status = 'APPROVED'
            app.save()

            add_Notification(user=user_requested,
                            info={'app': app_object},
                            code='approve')

            # Notify any subscribed servers of database change.
            socket.send_unicode(request.POST['app'])

        elif "revoke" in request.POST:
            app = request.POST['app']
            user_requested = User.objects.get(SID=request.POST['user'])
            # Write change to database.
            app_object = App.objects.get(href_name=app)
            app = user_requested.user_apps_set.get(app=app_object)
            app.delete()

            add_Notification(user=user_requested,
                            info={'app': app_object},
                            code='revoke')

            # Notify any subscribed servers of database change.
            socket.send_unicode(request.POST['app'])

        elif "reject" in request.POST:
            app = request.POST['app']
            app_object = App.objects.get(href_name=app)
            user_requested = User.objects.get(SID=request.POST['user'])
            app = user_requested.user_apps_set.get(app=app_object)
            app.delete()
            add_Notification(user=user_requested,
                            info={'app': app_object},
                            code='reject')

        elif "new" in request.POST:
            new_chartstring = Chartstring(
                nickname=request.POST['nickname'],
                chartstring=request.POST['chartstring'],
                budget=request.POST['amount'],
                remaining=request.POST['amount'],
                manager=user)
            new_chartstring.group = Group.objects.get(
                                    name=request.POST['group'])
            new_chartstring.save()
        elif "newgroup" in request.POST:
            try:
                new_group = Group(name=request.POST['groupname'])
                new_group.save()
                user.groups.add(new_group)
                user.save()
            except:
                new_group = Group.objects.get(name=request.POST['groupname'])
                user.groups.add(new_group)
                user.save()

        return HttpResponseRedirect('manage')

    chart_history = {chartstring: chartstring.user_apps_set.all() for chartstring in Chartstring.objects.all()}

    members = filter(lambda member: len(set(member.groups.all()).intersection(set(groups))) > 0, all_users)

    users_of_app = {}
    for member in members:
        chartstrings = filter(lambda chartstring: chartstring.group in user.groups.all() and chartstring.group in member.groups.all(), Chartstring.objects.all())
        user_apps = filter(lambda user_app: user_app.group in user.groups.all(), member.user_apps_set.all())

        for user_app in user_apps:
            if user_app.app in users_of_app:
                users_of_app[user_app.app].append((member, user_app.status, chartstrings))
            else:
                users_of_app[user_app.app] = [(member, user_app.status, chartstrings)]

    temp_chartstrings = []
    chartstrings = []

    for group in groups:
        temp_chartstrings = sorted(Chartstring.objects.filter(group=group),
                        key=lambda chartstring: chartstring.nickname.lower())
        for chartstring in temp_chartstrings:
            [chartstrings.append(chartstring) for chartstring in temp_chartstrings if not chartstrings.count(chartstring)]

    members_by_group = {group: [member for member in
                        User.objects.filter(groups=group)
                        if member != user] for group in groups}

    messages = get_Notifications(user)

    con = Context({
        'username': request.session['user'],
        'groups': groups,
        'users_of_app': users_of_app,
        'members_by_group': members_by_group,
        'chartstrings': chartstrings,
        'chart_history': chart_history,
        'messages': messages,
        'notifications': len(messages),
        })

    con.update(csrf(request))

    return render_to_response('manage.html', con)
예제 #4
0
def register(request):
    """ Defines the registration view for first-time users.
        Note: the user will not be registered if they enter
        a username that already exists in our database.
    """
    con = Context()
    con['groups'] = Group.objects.all()

    if "register" in request.POST:
        # Try clause checks if all fields are filled out.
        try:
            username = request.POST['username']
            studentid = request.POST['SID']
            password = request.POST['password']
            verify = request.POST['verify-password']
            status = request.POST['status']
            group_count = int(request.POST['group_count'])
            groups = []
            for i in range(1, group_count + 1):
                groups.append(request.POST['groups-' + str(i)])
        except (MultiValueDictKeyError, ObjectDoesNotExist):
            con['empty_fields'] = True
            con.update(csrf(request))
            return render_to_response('register.html', con)

        # Checks if passwords match.
        if password != verify:
            con['not_match'] = True
            con.update(csrf(request))
            return render_to_response('register.html', con)

        # Checks if username is already taken.
        for user in User.objects.all():
            if user.name == username:
                con['user_taken'] = True
                con.update(csrf(request))
                return render_to_response('register.html', con)
            if user.SID == studentid:
                con['sid_taken'] = True
                con.update(csrf(request))
                return render_to_response('register.html', con)

        # Creates admin functionality if professor or rso is selected.
        user_type = 'GENERAL'
        # if (status == 'professor') or (status == 'rso'):
        if (status == 'chartstring'):
            user_type = 'MANAGER'
        elif (status == 'admin'):
            user_type = 'ADMIN'

        # Initializes the new user.
        new_user = User.objects.create(
            name=username,
            SID=studentid,
            password=password,
            user_type=user_type,
            )

        # Adds the new user to selected groups.
        # If group exists, gets Group object, otherwise, creates a new group.
        for group in groups:
            try:
                add_group = Group.objects.get(name=group)
                new_user.groups.add(add_group)
            except ObjectDoesNotExist:
                if user_type == "GENERAL":
                    new_user.delete()
                    con['does_not_exist'] = True
                    con.update(csrf(request))
                    return render_to_response('register.html', con)
                    # if group == '':
                    #     con['blank_group'] = True
                    #     new_user.delete()
                    #     con.update(csrf(request))
                    #     return render_to_response('register.html', con)
                if user_type == "MANAGER" and group != '':
                    add_group = Group.objects.create(name=group)
                    new_user.groups.add(add_group)

            if new_user.user_type == "GENERAL" and add_group != None:
                managers = User.objects.filter(
                    groups=add_group,
                    user_type="MANAGER")
                for manager in managers:
                    add_Notification(
                        user=manager,
                        code="new_user",
                        info={'group': add_group, 'requestor': new_user})

        # Resets request.method, so that POST data is no longer stored.
        request.method = None
        # if len(new_user.groups.filter(name='')) > 0:
        new_user.groups.filter(name='').delete()
        if len(new_user.groups.all()) == 0:
            con['empty_fields'] = True
            new_user.delete()
            con.update(csrf(request))
            return render_to_response('register.html', con)
        # Redirects user to the log in page.
        return HttpResponseRedirect('/')
    elif "cancel" in request.POST:
        return HttpResponseRedirect('/')
    con.update(csrf(request))
    return render_to_response('register.html', con)