예제 #1
0
파일: views.py 프로젝트: neutrinog/Comperio
def user_account(request, username):
    """display user account details page"""
    mm = MessageManager(request)
    # must be an authenticated user and own the profile in order to get the form.
    if request.user.is_authenticated() and request.user.username == username:
        # must also be of type cUser. since the super is default to a User.
        if request.user.__class__ == cUser:
            if request.POST:
                # collect form
                form = SettingsForm(request.POST)
                if form.is_valid():
                    s = request.user.settings
                    s.public_comments = form.cleaned_data['public_comments']
                    s.code_pkg_updates = form.cleaned_data['code_pkg_updates']
                    s.save()
                    mm.set_success("Your settings have been saved")
                    return render(request, 'accounts/user/account.html', {'form':form}, mm.messages())
                else:
                    mm.set_error("Sorry! We encountered an error and were unable to save your settings")
                    form = SettingsForm(instance=request.user.settings)
                    return render(request, 'accounts/user/account.html', {'form':form}, mm.messages())
            else:
                # prepare form
                form = SettingsForm(instance=request.user.settings)
                return render(request, 'accounts/user/account.html', {'form':form}, mm.messages())
    return render(request, 'accounts/user/account.html', mm.messages())
예제 #2
0
파일: views.py 프로젝트: neutrinog/Comperio
def delete(request, username):
    """delete a user account"""
    # prepare messages
    mm = MessageManager(request)
    
    if request.user.is_active and request.user.username == username:
        if request.user.is_superuser:
            mm.set_error("um... you can't delete a super user silly.")
            return redirect(request.META.get('HTTP_REFERER','/'))
        
        # Build the removal key for account                                                                                                                    
        salt = sha.new(str(random.random())).hexdigest()[:5]
        removal_key = sha.new(salt+username).hexdigest()
        key_expires = datetime.datetime.today() + datetime.timedelta(2)
        
        request.user.removal_key = removal_key
        request.user.key_expires = key_expires
        request.user.save()
        
        # prepare email
        email_subject = 'Confirm account deletion'
        email_body =\
"We just received a request to delete your Comperio account.\
\n\nTo delete your account, click this link within 48 hours:\
\n%s/users/delete/confirm/%s" % (
            SITE_URL,
            request.user.removal_key)
        send_mail(email_subject,
                  email_body,
                  '*****@*****.**',
                  [request.user.email])
        mm.set_success("We just sent you an email to verify your account removal.")
        return redirect(request.META.get('HTTP_REFERER','/')) 
예제 #3
0
파일: views.py 프로젝트: neutrinog/Comperio
def contact(request):
    """contact page"""
    # prepare messages
    mm = MessageManager(request)
    if request.POST:
        form = ContactForm(request.POST)
        if form.is_valid():
            data = request.POST.copy()
            
            # make sure we have a human
            if not form.isValidHuman(data):
                mm.set_error('Sorry only humans can contact us. Try reloading the page.')
                return render(request, 'main/contact.html', mm.messages(), {'form':form})
            
            # prepare email
            email_subject = 'Comperio Form Submission'
            email_body =\
"Form submission from %s\n\nName: %s\nEmail: %s\n\n%s" % (
            SITE_URL,
            data['name'],
            data['email'],
            data['message'])
            emails = [x[1] for x in ADMINS]
            send_mail(email_subject,
                  email_body,
                  '*****@*****.**',
                  emails)
            mm.set_success("Thank you! We received your message.")
            return redirect('/')
        
        else:
            return render(request, 'main/contact.html', {'form':form}, mm.messages())
    else:
        form = ContactForm()
    return render(request, 'main/contact.html', {'form':form}, mm.messages())
예제 #4
0
파일: views.py 프로젝트: neutrinog/Comperio
def list_user_code(request):
    """return a list of code packages uploaded by a user"""
    mm = MessageManager(request)
    if request.GET:
        form = LoginForm(request.GET)
        if form.is_valid():
            e = form.cleaned_data['username']
            p = form.cleaned_data['password']
            try:
                user = authenticate(username=e, password=p)
            except NameError:
                user = None
                
            if user is not None:
                if user.is_active:
                    packages = CodePackage.objects.filter(user=user)
                    results = ''
                    for p in packages:
                        results += p.title + "\n"
                    return render_to_response('api/serve.html', {'result':results.rstrip('\n')})
                else:
                    # account is disabled
                    mm.set_error('This account has been disabled, or has not been activated.')
            else:
                # invalid login
                mm.set_error('Invalid credentials.')
                
            return render(request, 'api/list_user_code.html', {'form':form}, mm.messages())
        else:
            # return form errors to user
            return render(request, 'api/list_user_code.html', {'form':form}, mm.messages())
    else:
        form = DeleteCodePackageForm()
        return render(request, 'api/list_user_code.html', {'form':form}, mm.messages())
예제 #5
0
파일: views.py 프로젝트: neutrinog/Comperio
def edit_task(request, id):
    """edit and existing task"""
    mm = MessageManager(request)
    t = get_object_or_404(Task, pk=id)
    if request.user.is_authenticated() and request.user.username == t.user.username:
        if request.POST:
    #        receive sent form
            form = NewTaskForm(request.POST)
            if form.is_valid():
                mm.set_success("task updated")
                t.due_date = form.cleaned_data['due_date']
                t.description = form.cleaned_data['description']
                notify = form.cleaned_data['notify']
                if notify is False:
                    t.notify = False
                else:
                    t.notify = True
                t.save()
                return redirect(t.get_absolute_url())
            else:
                mm.set_error("error")
    #            error
                pass
        else:
    #        setup new form
            form = NewTaskForm(initial={'due_date':t.due_date, 'description':t.description, 'notify':t.notify})
        return render(request, 'tasks/edit.html', {'form':form, 'task':t}, mm.messages())
    else:
        mm.set_notice("you are not authorized to edit that task.")
        return redirect(request.META.get('HTTP_REFERER','/'))
예제 #6
0
파일: views.py 프로젝트: neutrinog/Comperio
def manage_group(request, gid):
    """manage a group"""
    mm = MessageManager(request)
    g = get_object_or_404(cGroup, pk=gid)
    if request.user.is_authenticated() and request.user.is_group_manager(g):
        return render(request, 'accounts/groups/manage.html', mm.messages(), {'group':g})
    else:
        mm.set_error("you are not allowed to manage this group")
        return redirect(g.get_absolute_url())
예제 #7
0
파일: views.py 프로젝트: neutrinog/Comperio
def delete_group(request, gid):
    """delete a group"""
    mm = MessageManager(request)
    g = get_object_or_404(cGroup, pk=gid)
    if request.user.is_authenticated() and request.user.is_group_manager(g):
        # TODO: do we need to remove group reference from users?
        g.delete()
        return redirect(request.user.get_absolute_url() + "#groups")
    else:
        mm.set_error("you are not allowed to delete this group")
        return redirect(request.META.get('HTTP_REFERER','/'))
예제 #8
0
파일: views.py 프로젝트: neutrinog/Comperio
def delete_group_invitation(request, gid):
    """delete the current group invitation key so that it cannot be used"""
    mm = MessageManager(request)
    g = get_object_or_404(cGroup, pk=gid)
    if request.user.is_authenticated() and request.user.is_group_manager(g):
        g.invitation_key = None
        g.key_expires = None
        g.save()
        return redirect(g.get_absolute_url() + "/manage")
    else:
        mm.set_error("you are not authorized to perform this action")
        return redirect(g.get_absolute_url())
예제 #9
0
파일: views.py 프로젝트: neutrinog/Comperio
def group_invitation(request, gid):
    """generate an invitation url for a group"""
    mm = MessageManager(request)
    g = get_object_or_404(cGroup, pk=gid)
    if request.user.is_authenticated() and request.user.is_group_manager(g):
        # Build the invitation key                                                                                                                    
        salt = sha.new(str(random.random())).hexdigest()[:5]
        g.invitation_key = sha.new(salt+g.name).hexdigest()[:13]
        g.key_expires = datetime.datetime.today() + datetime.timedelta(2)
        g.save()
        return redirect(g.get_absolute_url() + "/manage")
    else:
        mm.set_error("you are not authorized to perform this action")
        return redirect(g.get_absolute_url())
예제 #10
0
파일: views.py 프로젝트: neutrinog/Comperio
def reject_from_group(request, gid, uid):
    """reject a pending membership request"""
    mm = MessageManager(request)
    g = get_object_or_404(cGroup, pk=gid)
    u = get_object_or_404(cUser, pk=uid)
    if request.user.is_authenticated() and request.user.is_group_manager(g):
        if u in g.pending_users.all():
            mm.set_success("membership refused for %s" % u.username)
            g.pending_users.remove(u)
            g.save()
        else:
            mm.set_error("you can't just reject whomever you want!")
        return redirect(reverse('manage-group', None, (), {'gid':g.pk}))
    return redirect(g.get_absolute_url())
예제 #11
0
파일: views.py 프로젝트: neutrinog/Comperio
def create_curriculum(request):
    """create a new curriculum container"""
    mm = MessageManager(request)
    if request.POST:
        form = CreateCurriculumForm(request.POST)
        if form.is_valid():
            # save it
            c = form.save(request)
            mm.set_success("the curriculum was saved")
            return redirect(c.get_absolute_url())
        else:
            mm.set_error("the form has errors")
            pass
    else:
        form = CreateCurriculumForm()
    return render(request, 'curricula/create_curriculum.html', {'form':form}, mm.messages())
예제 #12
0
파일: views.py 프로젝트: neutrinog/Comperio
def admit_to_group(request, gid, uid):
    """admit a user into a group"""
    mm = MessageManager(request)
    g = get_object_or_404(cGroup, pk=gid)
    u = get_object_or_404(cUser, pk=uid)
    if request.user.is_authenticated() and request.user.is_group_manager(g):
        if u in g.pending_users.all():
            mm.set_success("%s has been admitted" % u.username)
            g.pending_users.remove(u)
            u.groups.add(g)
            g.members.add(u)
            u.save()
            g.save()
        else:
            mm.set_error("you can't just add whomever you want to your group!")
        return redirect(reverse('manage-group', None, (), {'gid':g.pk}))
    return redirect(g.get_absolute_url())
예제 #13
0
파일: views.py 프로젝트: neutrinog/Comperio
def create_group(request):
    """create a new user group"""
    mm = MessageManager(request)
    if request.user.is_authenticated() and request.user.__class__ is cUser:
        if request.POST:
            form = CreateGroupForm(request.POST)
            if form.is_valid():
                data = request.POST.copy()
                # make sure the group name is unique
                try:
                    cGroup.objects.get(name=data["title"])
                    mm.set_error("that group name is already taken")
                    return render(request,'accounts/groups/create.html', mm.messages(), {'form':form})
                except cGroup.DoesNotExist:
                    # create group
                    g = cGroup()
                    g.name = data["title"]
                    g.description = data["description"]
                    g.type = data["type"]
                    g.visibility = data["visibility"]
                    g.open_registration = data.has_key("open_registration")
                    g.save()
                    
                    # add user to group
                    request.user.groups.add(g)
                    g.managers.add(request.user)
                    
                    # Build the invitation key                                                                                                                    
                    salt = sha.new(str(random.random())).hexdigest()[:5]
                    g.invitation_key = sha.new(salt+g.name).hexdigest()[:13]
                    g.key_expires = datetime.datetime.today() + datetime.timedelta(2)
                    g.save()
                    manage_url = reverse('manage-group', None, (), {'gid':g.pk})
                    invite_url = "%s%s/%s" % (SITE_URL, reverse('join-group', None, (), {'gid':g.pk}), g.invitation_key)
                    mm.set_success("Successfully Created Group \"%s\"!<p> We automatically generated an invitation url that you can share with your friends. For more information check out the <a href=\"%s\">Administration Page</a>.</p><p>Invitation Url: <a href=\"%s\">%s</a></p>" % (g.name, manage_url, invite_url, invite_url))
                    # TODO: take to new group page
                    return redirect(g.get_absolute_url())
            else:
                return render(request,'accounts/groups/create.html', mm.messages(), {'form':form})
        else:
            # prepare new form for user
            form = CreateGroupForm(initial={'open_registration':True})
            return render(request,'accounts/groups/create.html', mm.messages(), {'form':form})
    else:
        mm.set_error("you are not allowed to create a group")
        return redirect(request.META.get('HTTP_REFERER','/'))
예제 #14
0
파일: views.py 프로젝트: neutrinog/Comperio
def create_lesson(request, c_id):
    """create a new lesson"""
    c = get_object_or_404(Curriculum, pk=c_id)
    mm = MessageManager(request)
    if request.POST:
        form = CreateLessonForm(request.POST)
        if form.is_valid():
            # save it
            l = form.save(request, c)
            mm.set_success("the lesson was saved")
            return redirect(c.get_absolute_url())
        else:
            mm.set_error("the form has errors")
            pass
    else:
        form = CreateLessonForm()
    return render(request, 'curricula/create_lesson.html', {'form':form, 'curriculum':c}, mm.messages())
예제 #15
0
파일: views.py 프로젝트: neutrinog/Comperio
def kick_from_group(request, gid, uid):
    """kick a user out of a group"""
    mm = MessageManager(request)
    g = get_object_or_404(cGroup, pk=gid)
    u = get_object_or_404(cUser, pk=uid)
    if request.user.is_authenticated() and request.user.is_group_manager(g):
        # can only kick normal users, not managers
        if u in g.users():
            u.groups.remove(g)
            g.members.remove(u)
            u.save()
            g.save()
            
            mm.set_success("%s has been kicked" % u.username)
        else:
            mm.set_error("you can only kick existing members")
        return redirect(reverse('manage-group', None, (), {'gid':g.pk}))
    return redirect(g.get_absolute_url())
예제 #16
0
파일: views.py 프로젝트: neutrinog/Comperio
def edit_group(request, gid):
    """edit a group"""
    mm = MessageManager(request)
    g = get_object_or_404(cGroup, pk=gid)
    if request.user.is_authenticated() and request.user.is_group_manager(g):
        if request.POST:
            form = CreateGroupForm(request.POST)
            if form.is_valid():
                data = request.POST.copy()
                # make sure the group name is unique
                #try:
                #    cGroup.objects.get(name=data["title"])
                #    mm.set_error("that group name is already taken")
                #    return render(request,'accounts/groups/create.html', mm.messages(), {'form':form})
                #except cGroup.DoesNotExist:
                    # create group
                #g = cGroup()
                g.name = data["title"]
                g.description = data["description"]
                g.type = data["type"]
                g.visibility = data["visibility"]
                g.open_registration = data.has_key("open_registration")
                g.save()
                
                # add user to group
                #request.user.groups.add(g)
                
                #g.managers.add(request.user)   
                #g.save()
                
                mm.set_success("edits were successfull")
                # TODO: take to new group page
                return redirect(g.get_absolute_url())
            else:
                return render(request,'accounts/groups/edit.html', mm.messages(), {'form':form, 'group':g})
        else:
            # prepare new form for user
            form = CreateGroupForm(initial={'title': g.name, 'description':g.description, 'type':g.type, 'open_registration':g.open_registration})
            return render(request,'accounts/groups/edit.html', mm.messages(), {'form':form, 'group':g})
    else:
        mm.set_error("you are not allowed to edit this group")
        return redirect(g.get_absolute-url())
예제 #17
0
파일: views.py 프로젝트: neutrinog/Comperio
def edit_curriculum(request, id):
    """edit a curriculum"""
    mm = MessageManager(request)
    c = get_object_or_404(Curriculum, pk=id)
    if request.user.is_authenticated() and request.user.username == c.user.username:
        if request.POST:
            form = CreateCurriculumForm(request.POST)
            if form.is_valid():
                # update it
                c = form.update(request, c)
                mm.set_success('"%s" has been updated' % c.title)
                return redirect(c.get_absolute_url())
            else:
                mm.set_error("the form has errors")
                pass
        else:
            form = CreateCurriculumForm(initial={'title':c.title, 'description':c.description})
        return render(request, 'curricula/edit_curriculum.html', {'form':form, 'curriculum':c}, mm.messages())
    else:
        mm.set_notice('You are not authorized to edit that curriculum')
        return redirect(request.META.get('HTTP_REFERER','/'))
예제 #18
0
파일: views.py 프로젝트: neutrinog/Comperio
def upload(request):
    """upload a code package to a user profile"""
    mm = MessageManager(request)
    if request.POST:
        form = UploadCodePackageForm(request.POST, request.FILES)
        if form.is_valid():
            e = form.cleaned_data['username']
            p = form.cleaned_data['password']
            try:
                user = authenticate(username=e, password=p)
            except NameError:
                user = None
                
            if user is not None:
                if user.is_active:
                    if form.save(request, user):
                        mm.set_success("package uploaded")
                        form = UploadCodePackageForm()
                    else:
                        mm.set_error("package could not be uploaded")
                else:
                    # account is disabled
                    mm.set_error('This account has been disabled, or has not been activated.')
            else:
                # invalid login
                mm.set_error('Invalid credentials.')
                
            return render(request, 'api/upload.html', {'form':form}, mm.messages())
        else:
            # return form errors to user
            return render(request, 'api/upload.html', {'form':form}, mm.messages())
    else:
        form = UploadCodePackageForm()
        return render(request, 'api/upload.html', {'form':form}, mm.messages())
예제 #19
0
파일: views.py 프로젝트: neutrinog/Comperio
def edit_lesson(request, c_id, l_id):
    """edit a lesson"""
    mm = MessageManager(request)
    c = get_object_or_404(Curriculum, pk=c_id) # we don't need both curriculum and lesson id because we are moving towards just using the custom lesson model
    l = get_object_or_404(Lesson, pk=l_id)
    if request.user.is_authenticated() and request.user.username == l.user.username:
        if request.POST:
            form = CreateLessonForm(request.POST)
            if form.is_valid():
                # update it
                l = form.update(request, l)
                mm.set_success('"%s" has been updated' % l.title)
                return redirect(l.get_absolute_url())
            else:
                mm.set_error("the form has errors")
                pass
        else:
            form = CreateLessonForm(initial={'title':l.title, 'description':l.description, 'body':l.body})
        return render(request, 'curricula/edit_lesson.html', {'form':form, 'lesson':l, 'curriculum':c}, mm.messages())
    else:
        mm.set_notice('You are not authorized to edit that curriculum')
        return redirect(request.META.get('HTTP_REFERER','/'))
예제 #20
0
파일: views.py 프로젝트: neutrinog/Comperio
def delete_code_package(request):
    """delete a code package from a user account"""
    mm = MessageManager(request)
    if request.POST:
        form = DeleteCodePackageForm(request.POST, request.FILES)
        if form.is_valid():
            e = form.cleaned_data['username']
            p = form.cleaned_data['password']
            try:
                user = authenticate(username=e, password=p)
            except NameError:
                user = None
                
            if user is not None:
                if user.is_active:
                    p = form.cleaned_data['packageName']
                    try:
                        # TODO: can we match the package field instead?
                        # TODO: catch multiple items returned
                        p = CodePackage.objects.get(user=user, title=p)
                        p.delete()
                        mm.set_success("package deleted")
                        form = DeleteCodePackageForm()  
                    except CodePackage.DoesNotExist:
                        mm.set_notice('package could not be found')
                else:
                    # account is disabled
                    mm.set_error('This account has been disabled, or has not been activated.')
            else:
                # invalid login
                mm.set_error('Invalid credentials.')
                
            return render(request, 'api/delete_code_package.html', {'form':form}, mm.messages())
        else:
            # return form errors to user
            return render(request, 'api/delete_code_package.html', {'form':form}, mm.messages())
    else:
        form = DeleteCodePackageForm()
        return render(request, 'api/delete_code_package.html', {'form':form}, mm.messages())
예제 #21
0
파일: views.py 프로젝트: neutrinog/Comperio
def add_task(request):
    """add a new task"""
    mm = MessageManager(request)
    if request.POST:
#        receive sent form
        form = NewTaskForm(request.POST)
        if form.is_valid():
            mm.set_success("task created")
            dd = form.cleaned_data['due_date']
            desc = form.cleaned_data['description']
            note = form.cleaned_data['notify']
            task = Task(due_date=dd, description=desc, notify=note, author=request.user, status=0)
            task.set_object(request.user)
            task.save()
            return redirect(request.user.get_absolute_url())
        else:
            mm.set_error("error")
#            error
            pass
    else:
#        setup new form
        form = NewTaskForm()
    return render(request, 'tasks/new.html', {'form':form}, mm.messages())
예제 #22
0
파일: views.py 프로젝트: neutrinog/Comperio
def login_view(request):
    """Login to a user account and redirect to profile"""
    # TODO: put link on profile page to return to original page
    # prepare messages
    mm = MessageManager(request)
    if request.user.is_authenticated():
        return redirect(request.user.get_absolute_url())
        
    if request.POST:
        if request.session.test_cookie_worked():
            request.session.delete_test_cookie()
            # cookies are enabled
            form = LoginForm(request.POST)
            if not form == None and form.is_valid():
                # log the user in. we extended to backend to allow using email
                # instead of just username
                e = form.cleaned_data['username']
                p = form.cleaned_data['password']
                
                try:
                    user = authenticate(username=e, password=p)
                except NameError:
                    user = None
                    
                if user is not None:
                    if user.is_active:
                        #request.user = user
                        login(request, user)
                        mm.set_success('you are logged in!')
                        return redirect(request.user.get_absolute_url())
                    else:
                        # account is disabled
                        mm.set_error('This account has been disabled, or has not been activated.')
                else:
                    # invalid login
                    mm.set_error('Invalid credentials.')
            else:
                #mm.set_error('The form is invalid')
                pass
        else:
            # cookies are not enabled
            mm.set_error('Please enable cookies and try again.')
    else:
        
        form = LoginForm()
    request.session.set_test_cookie()
    return render(request, 'accounts/login.html', {'form':form}, mm.messages())
예제 #23
0
파일: views.py 프로젝트: neutrinog/Comperio
def register(request):
    """register a new user"""
    # prepare messages
    mm = MessageManager(request)
    if request.user.is_authenticated():
        mm.set_notice('You already have an account')
        return render(request, 'accounts/register.html', mm.messages())
    if request.POST:
        form = RegistrationForm(request.POST)
        new_data = request.POST.copy()
        
        # Validate passwords
        # TODO: put validation in form.
        if not form.isValidHuman(new_data):
            mm.set_error('Sorry only humans can register. Try reloading the page')
            return render(request, 'accounts/register.html', mm.messages(), {'form':form})
        if not form.isValidUsername(new_data):
            mm.set_error('That username is already taken')
            return render(request, 'accounts/register.html', mm.messages(), {'form':form})
        if not form.isValidEmail(new_data):
            mm.set_error('That email is already in use')
            return render(request, 'accounts/register.html', mm.messages(), {'form':form})
        if not form.PasswordsMatch(new_data):
            mm.set_error('Passwords do not match')
            return render(request, 'accounts/register.html', mm.messages(), {'form':form})
        if not form.isValidPassword(new_data):
            mm.set_error('Passwords must be at least 6 characters long')
            return render(request, 'accounts/register.html', mm.messages(), {'form':form})
            
        # validate form data
        if form.is_valid():
            # Save the user
            new_user = form.save(new_data)
            if not new_user is None:
                # TODO: email is not sent for certain emails ([email protected] fails)
                email_subject = 'Your new Comperio account confirmation'
                email_body =\
"You recently signed up for a new Comperio account.\
\n\nTo activate your account, click this link within 48 hours:\
\n%s/users/confirm/%s\
\n\n After your account is activated you can go to your account by clicking the link below\
\n%s/users/%s\
\n\nAccount Details\
\nusername: %s\
\nemail: %s\
\npassword: %s" % (
                    SITE_URL,
                    new_user.activation_key,
                    SITE_URL,
                    new_user.username,
                    new_user.username,
                    form.cleaned_data['email'],
                    form.cleaned_data['password1'])
                send_mail(email_subject,
                          email_body,
                          '*****@*****.**',
                          [new_user.email])
                mm.set_success("You're in! We just emailed you instructions to activate your account")
                return redirect('/')
            else:
                mm.set_error("Could not create user")
        else:
            mm.set_error("Please fill all required fields.")
            return render(request, 'accounts/register.html', mm.messages(), {'form':form})
    form = RegistrationForm()
    return render(request, 'accounts/register.html', mm.messages(), {'form':form})