示例#1
0
def forgot_password(request):
  
  forgot_password_form = ForgotPasswordForm(request.POST, auto_id="id_%s")
  if request.method == 'POST':
    if forgot_password_form.is_valid():	
		data = forgot_password_form.cleaned_data
		try:
			user = User.objects.get(email = data['email'])
		except:
			forgot_password_form = ForgotPasswordForm(auto_id="id_%s")
			return render_to_response('users/forgot_password.html', {
			'forgot_password_form': forgot_password_form
			}, context_instance = RequestContext(request))
		random.seed()
		new_pass = ''.join([choice('qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890') for i in range(8)]) 
		user.set_password(new_pass)
		user.save()
		mailmsg = ("Hello " + user.first_name + ",\n\nAs requested, here is a new  password for you to use to login to Observatory: \n" + new_pass + "\n\n")
		send_mail('New Password for Observatory', mailmsg, MAIL_SENDER, 
		[user.email], fail_silently=False)
		return HttpResponseRedirect(reverse(forgot_password_success)) 
    else:
		return render_to_response('users/forgot_password.html', {
		'forgot_password_form': forgot_password_form
		}, context_instance = RequestContext(request))
  else:
    forgot_password_form = ForgotPasswordForm(auto_id="id_%s")
    
    return render_to_response('users/forgot_password.html', {
      'forgot_password_form': forgot_password_form
    }, context_instance = RequestContext(request))
示例#2
0
def external_add(request):
    """
    Allow users who don't have access to the rest of the ticket system to file a ticket in a specific list.
    This is useful if, for example, a core web team are in a group that can file todos for each other,
    but you also want students to be able to post trouble tickets to a list just for the sysadmin. This
    way we don't have to put all students into a group that gives them access to the whole ticket system.
    """
    if request.POST:
            form = AddExternalItemForm(request.POST)

            if form.is_valid():
                # Don't commit the save until we've added in the fields we need to set
                item = form.save(commit=False)
                item.list_id = 20 # Hate hard-coding in IDs like this.
                item.created_by = request.user
                item.assigned_to = User.objects.get(username='******')
                item.save()
                
                # Send email
                email_subject = render_to_string("todo/email/assigned_subject.txt", { 'task': item.title })                    
                email_body = render_to_string("todo/email/assigned_body.txt", { 'task': item, 'site': current_site, })
                try:
                    send_mail(email_subject, email_body, item.created_by.email, [item.assigned_to.email], fail_silently=False)
                except:
                    messages.error(request, "Task saved but mail not sent. Contact your administrator." )                    

                messages.success(request, "Your trouble ticket has been submitted. We'll get back to you soon." )                    
                
                return HttpResponseRedirect(reverse('intranet_home'))
            
        
    else:
        form = AddExternalItemForm()

    return render_to_response('todo/add_external_task.html', locals(), context_instance=RequestContext(request))
示例#3
0
  def do_warnings(self):
      """
      Send warning emails if either the blog or the repository haven't
      been updated in a week, send warning emails to the mentors if it hasn't 
      been updated in two weeks.
      """

      from dashboard.views.projects import show

      def days_ago(eventset):
          return (datetime.datetime.utcnow() - eventset.most_recent_date).days

      #If they haven't set up their blog yet, ping them and their mentor
      if self.blog.most_recent_date == datetime.datetime(1,1,1):
          blog_days_ago = 14
      else:
          blog_days_ago = days_ago(self.blog)

      if self.repository.most_recent_date == datetime.datetime(1,1,1):
          repo_days_ago = 14
      else:
          repo_days_ago = days_ago(self.repository)

      warning_msg = """You haven't updated <a href="%s"> your projects's </a> %s in the last %s days. If you're having problems please contact the mentors."""
      warning_subj = "%s %s Stagnation"

      if (blog_days_ago >= 8 and self.blog_warn_level < 1) or (blog_days_ago >= 14 and self.blog_warn_level < 2):

          blog_msg = warning_msg % (SITE_ADDRESS + reverse(show, args=(self.url_path,)), "Blog", blog_days_ago)
          blog_subj = warning_subj % (self.title, "Blog")

          blog_to = []
          for author in self.authors.filter(is_active = True):
              blog_to.extend([a.address for a in author.emails.all()])

          if self.mentor and blog_days_ago >= 14 and self.blog_warn_level == 1:
              blog_to.extend([a.address for a in self.mentor.emails.all()])
              for uber in User.objects.filter(info__ubermentor = True):
                  blog_to.extend([a.address for a in uber.emails.all()])

          try:
              send_mail(blog_subj, blog_msg, "*****@*****.**", blog_to)
          except:
              import traceback
              traceback.print_exc()
          self.blog_warn_level += 1

      if blog_days_ago < 8:
          self.blog_warn_level = 0

      if (repo_days_ago >= 8 and self.repo_warn_level < 1) or (repo_days_ago >= 14 and self.repo_warn_level < 2):

          repo_msg = warning_msg % (SITE_ADDRESS + reverse(show, args=(self.url_path,)), "Repository", repo_days_ago)
          repo_subj = warning_subj % (self.title, "Repository")

          repo_to = []
          for author in self.authors.filter(is_active=True):
              repo_to.extend([a.address for a in author.emails.all()])

          if self.mentor and repo_days_ago >= 14 and self.repo_warn_level == 1:
              repo_to.extend([a.address for a in self.mentor.emails.all()])
              for uber in User.objects.filter(info__ubermentor = True):
                  repo_to.extend([a.address for a in uber.emails.all()])

          try:
              send_mail(repo_subj, repo_msg, "*****@*****.**", repo_to)
          except:
              import traceback
              traceback.print_exc()
          self.repo_warn_level += 1

      if repo_days_ago < 8:
          self.repo_warn_level = 0

      self.save()
示例#4
0
def view_list(request,list_id=0,list_slug=None,view_completed=0):
    
    """
    Display and manage items in a task list
    """
    
    # Make sure the accessing user has permission to view this list.
    # Always authorize the "mine" view. Admins can view/edit all lists.

    if list_slug == "mine"  or list_slug == "recent-add" or list_slug == "recent-complete" :
        auth_ok =1
    else: 
        list = get_object_or_404(List, slug=list_slug)
        listid = list.id    
        
        # Check whether current user is a member of the group this list belongs to.
        if list.group in request.user.groups.all() or request.user.mentor or list_slug == "mine" :
            auth_ok = 1   # User is authorized for this view
        else: # User does not belong to the group this list is attached to
            messages.error(request, "You do not have permission to view/edit this list.")                                    

        
    # First check for items in the mark_done POST array. If present, change
    # their status to complete.
    if request.POST.getlist('mark_done'):
        done_items = request.POST.getlist('mark_done')
        # Iterate through array of done items and update its representation in the model
        for thisitem in done_items:
            p = Item.objects.get(id=thisitem)
            p.completed = 1
            p.completed_date = datetime.datetime.now()
            p.save()
            messages.success(request, "Item \"%s\" marked complete." % p.title)                                             


    # Undo: Set completed items back to incomplete
    if request.POST.getlist('undo_completed_task'):
        undone_items = request.POST.getlist('undo_completed_task')
        for thisitem in undone_items:
            p = Item.objects.get(id=thisitem)
            p.completed = 0
            p.save()
            messages.success(request, "Previously completed task \"%s\" marked incomplete." % p.title)


    # And delete any requested items
    if request.POST.getlist('del_task'):
        deleted_items = request.POST.getlist('del_task')
        for thisitem in deleted_items:
            p = Item.objects.get(id=thisitem)
            p.delete()
            messages.success(request, "Item \"%s\" deleted." % p.title)         

    # And delete any *already completed* items
    if request.POST.getlist('del_completed_task'):
        deleted_items = request.POST.getlist('del_completed_task')
        for thisitem in deleted_items:
            p = Item.objects.get(id=thisitem)
            p.delete()
            messages.success(request, "Deleted previously completed item \"%s\"."  % p.title)                       


    thedate = datetime.datetime.now()
    created_date = "%s-%s-%s" % (thedate.year, thedate.month, thedate.day)


    # Get list of items with this list ID, or filter on items assigned to me, or recently added/completed
    if list_slug == "mine":
        task_list = Item.objects.filter(assigned_to=request.user, completed=0)
        completed_list = Item.objects.filter(assigned_to=request.user, completed=1)
        
    elif list_slug == "recent-add":
        # We'll assume this only includes uncompleted items to avoid confusion.
        # Only show items in lists that are in groups that the current user is also in.
        task_list = Item.objects.filter(list__group__in=(request.user.groups.all()),completed=0).order_by('-created_date')[:50]
        # completed_list = Item.objects.filter(assigned_to=request.user, completed=1)   
        
    elif list_slug == "recent-complete":
        # Only show items in lists that are in groups that the current user is also in.
        task_list = Item.objects.filter(list__group__in=request.user.groups.all(),completed=1).order_by('-completed_date')[:50]
        # completed_list = Item.objects.filter(assigned_to=request.user, completed=1)             


    else:
        task_list = Item.objects.filter(list=list.id, completed=0)
        completed_list = Item.objects.filter(list=list.id, completed=1)


    if request.POST.getlist('add_task') :
        form = AddItemForm(list, request.POST,initial={
        'assigned_to':request.user.id,
        'priority':999,
        })
        
        if form.is_valid():
            # Save task first so we have a db object to play with
            new_task = form.save()

            # Send email alert only if the Notify checkbox is checked AND the assignee is not the same as the submittor
            # Email subect and body format are handled by templates
            if "notify" in request.POST :
                if new_task.assigned_to != request.user :
                                        
                    # Send email
                    email_subject = render_to_string("todo/email/assigned_subject.txt", { 'task': new_task })                    
                    email_body = render_to_string("todo/email/assigned_body.txt", { 'task': new_task, 'site': current_site, })
                    try:
                        send_mail(email_subject, email_body, new_task.created_by.email, [new_task.assigned_to.email], fail_silently=False)
                    except:
                        messages.error(request, "Task saved but mail not sent. Contact your administrator.")
                        

            messages.success(request, "New task \"%s\" has been added." % new_task.title)                       
            
            return HttpResponseRedirect(request.path)

    else:
        if list_slug != "mine" and list_slug != "recent-add" and list_slug != "recent-complete" : # We don't allow adding a task on the "mine" view
            form = AddItemForm(list, initial={
                'assigned_to':request.user.id,
                'priority':999,
                } )

    if request.user.mentor :
        can_del = 1

    return render_to_response('todo/view_list.html', locals(), context_instance=RequestContext(request))
示例#5
0
def view_task(request,task_id):

    """
    View task details. Allow task details to be edited.
    """

    task = get_object_or_404(Item, pk=task_id)
    comment_list = Comment.objects.filter(task=task_id)
        
    # Before doing anything, make sure the accessing user has permission to view this item.
    # Determine the group this task belongs to, and check whether current user is a member of that group.
    # Admins can edit all tasks.

    if task.list.group in request.user.groups.all() or request.user.mentor:
        
        auth_ok = 1
        if request.POST:
             form = EditItemForm(request.POST,instance=task)

             if form.is_valid():
                 form.save()
                 
                 # Also save submitted comment, if non-empty
                 if request.POST['comment-body']:
                     c = Comment(
                         author=request.user, 
                         task=task,
                         body=request.POST['comment-body'],
                     )
                     c.save()
                    
                     # And email comment to all people who have participated in this thread.
                     email_subject = render_to_string("todo/email/assigned_subject.txt", { 'task': task })                    
                     email_body = render_to_string("todo/email/newcomment_body.txt", { 'task': task, 'body':request.POST['comment-body'], 'site': current_site, 'user':request.user })

                     # Get list of all thread participants - task creator plus everyone who has commented on it.
                     recip_list = []
                     recip_list.append(task.created_by.email)
                     commenters = Comment.objects.filter(task=task)
                     for c in commenters:
                         recip_list.append(c.author.email)
                     # Eliminate duplicate emails with the Python set() function
                     recip_list = set(recip_list)     
                     
                     # Send message
                     try:
                        send_mail(email_subject, email_body, task.created_by.email, recip_list, fail_silently=False)
                        messages.success(request, "Comment sent to thread participants.")                       
                        
                     except:
                        messages.error(request, "Comment saved but mail not sent. Contact your administrator.")
                    
                 
                 messages.success(request, "The task has been edited.")
                 
                 return HttpResponseRedirect(reverse('todo-incomplete_tasks', args=[task.list.id, task.list.slug]))
                 
        else:
            form = EditItemForm(instance=task)
            if task.due_date:
                thedate = task.due_date
            else:
                thedate = datetime.datetime.now()
            

    else:
        messages.info(request, "You do not have permission to view/edit this task.")
        

    return render_to_response('todo/view_task.html', locals(), context_instance=RequestContext(request))