diff --git a/settings.py b/settings.py index d0922a23da..d6c432f056 100644 --- a/settings.py +++ b/settings.py @@ -214,7 +214,7 @@ LOGGING = { 'disable_existing_loggers': True, 'formatters': { 'standard': { - 'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s' + 'format': '%(asctime)s [%(levelname)s] %(name)s:%(lineno)s %(funcName)s %(message)s' }, }, 'handlers': { @@ -251,6 +251,17 @@ LOGGING = { } } +################# +# Email sending # +################# + +SEND_EMAIL_ON_ADDING_SYSTEM_MEMBER = True # Whether to send email when a system staff adding new member. +SEND_EMAIL_ON_RESETTING_USER_PASSWD = True # Whether to send email when a system staff resetting user's password. + +##################### +# External settings # +##################### + def load_local_settings(module): '''Import any symbols that begin with A-Z. Append to lists any symbols that begin with "EXTRA_". diff --git a/share/views.py b/share/views.py index db004a6b41..eb3954256f 100644 --- a/share/views.py +++ b/share/views.py @@ -26,7 +26,7 @@ from seahub.contacts.signals import mail_sended from seahub.share.models import FileShare from seahub.views import validate_owner, is_registered_user from seahub.utils import render_permission_error, string2list, render_error, \ - gen_token, gen_shared_link + gen_token, gen_shared_link, IS_EMAIL_CONFIGURED try: from seahub.settings import CLOUD_MODE @@ -467,6 +467,10 @@ def send_shared_link(request): result = {} content_type = 'application/json; charset=utf-8' + if not IS_EMAIL_CONFIGURED: + data = json.dumps({'error':_(u'Sending shared link failed. Email service is not properly configured, please contact administrator.')}) + return HttpResponse(data, status=500, content_type=content_type) + from seahub.settings import SITE_NAME form = FileLinkShareForm(request.POST) diff --git a/thirdpart/auth/forms.py b/thirdpart/auth/forms.py index 4f3b998ba0..3b88616ad5 100644 --- a/thirdpart/auth/forms.py +++ b/thirdpart/auth/forms.py @@ -8,6 +8,7 @@ from django.utils.translation import ugettext_lazy as _ from django.utils.http import int_to_base36 from seahub.base.accounts import User +from seahub.utils import IS_EMAIL_CONFIGURED class AuthenticationForm(forms.Form): """ @@ -61,6 +62,9 @@ class PasswordResetForm(forms.Form): """ Validates that a user exists with the given e-mail address. """ + if not IS_EMAIL_CONFIGURED: + raise forms.ValidationError(_(u'Failed to send email, email service is not properly configured, please contact administrator.')) + email = self.cleaned_data["email"] # TODO: add filter method to UserManager diff --git a/thirdpart/auth/views.py b/thirdpart/auth/views.py index bee6a6a8f4..b001692548 100644 --- a/thirdpart/auth/views.py +++ b/thirdpart/auth/views.py @@ -1,8 +1,10 @@ import re +import logging from django.conf import settings # Avoid shadowing the login() view below. from django.views.decorators.csrf import csrf_protect from django.core.urlresolvers import reverse +from django.contrib import messages from django.shortcuts import render_to_response, get_object_or_404 from django.contrib.sites.models import Site, RequestSite from django.http import HttpResponseRedirect, Http404 @@ -20,6 +22,9 @@ from auth.tokens import default_token_generator from seahub.base.accounts import User +# Get an instance of a logger +logger = logging.getLogger(__name__) + @csrf_protect @never_cache def login(request, template_name='registration/login.html', @@ -126,8 +131,16 @@ def password_reset(request, is_admin_site=False, template_name='registration/pas opts['email_template_name'] = email_template_name if not Site._meta.installed: opts['domain_override'] = RequestSite(request).domain - form.save(**opts) - return HttpResponseRedirect(post_reset_redirect) + try: + form.save(**opts) + except Exception, e: + logger.error(str(e)) + messages.error(request, _(u'Failed to send email, please contact administrator.')) + return render_to_response(template_name, { + 'form': form, + }, context_instance=RequestContext(request)) + else: + return HttpResponseRedirect(post_reset_redirect) else: form = password_reset_form() return render_to_response(template_name, { diff --git a/utils/__init__.py b/utils/__init__.py index 54a32cc1e6..4910004210 100644 --- a/utils/__init__.py +++ b/utils/__init__.py @@ -28,6 +28,11 @@ try: from settings import DOCUMENT_CONVERTOR_ROOT except ImportError: DOCUMENT_CONVERTOR_ROOT = None +try: + from settings import EMAIL_HOST + IS_EMAIL_CONFIGURED = True +except ImportError: + IS_EMAIL_CONFIGURED = False import settings @@ -722,3 +727,4 @@ def show_delete_days(request): days = 7 return days + diff --git a/views.py b/views.py index ce219a8aa7..357e14ba17 100644 --- a/views.py +++ b/views.py @@ -8,6 +8,7 @@ import tempfile import sys import urllib import urllib2 +import logging from urllib import quote from django.core.cache import cache from django.core.urlresolvers import reverse @@ -69,7 +70,7 @@ from utils import render_permission_error, render_error, list_to_string, \ calculate_repo_last_modify, valid_previewed_file, \ check_filename_with_rename, get_accessible_repos, EMPTY_SHA1, \ get_file_revision_id_size, get_ccnet_server_addr_port, \ - gen_file_get_url, string2list, MAX_INT, \ + gen_file_get_url, string2list, MAX_INT, IS_EMAIL_CONFIGURED, \ gen_file_upload_url, check_and_get_org_by_repo, \ get_file_contributors, EVENTS_ENABLED, get_user_events, get_org_user_events, \ get_starred_files, star_file, unstar_file, is_file_starred, get_dir_starred_files, \ @@ -80,7 +81,11 @@ try: DOCUMENT_CONVERTOR_ROOT += '/' except ImportError: DOCUMENT_CONVERTOR_ROOT = None -from settings import FILE_PREVIEW_MAX_SIZE, INIT_PASSWD, USE_PDFJS +from settings import FILE_PREVIEW_MAX_SIZE, INIT_PASSWD, USE_PDFJS,\ + SEND_EMAIL_ON_ADDING_SYSTEM_MEMBER, SEND_EMAIL_ON_RESETTING_USER_PASSWD + +# Get an instance of a logger +logger = logging.getLogger(__name__) @login_required def root(request): @@ -1987,17 +1992,9 @@ def send_user_reset_email(request, email, password): 'password': password, 'site_name': settings.SITE_NAME, } - try: - send_mail(_(u'Password Reset'), t.render(Context(c)), - None, [email], fail_silently=False) - msg = _('Successfully resetting password to %(passwd)s, an email has been sent to %(user)s.') % \ - {'passwd': password, 'user': email} - messages.success(request, msg) - except: - msg = _('Successfully resetting password to %(passwd)s, but failed to send email to %(user)s, please check your email configuration.') % \ - {'passwd':password, 'user': email} - messages.error(request, msg) - + send_mail(_(u'Password Reset'), t.render(Context(c)), + None, [email], fail_silently=False) + @login_required @sys_staff_required def user_reset(request, user_id): @@ -2007,10 +2004,24 @@ def user_reset(request, user_id): user.set_password(INIT_PASSWD) user.save() - if hasattr(settings, 'EMAIL_HOST'): - send_user_reset_email(request, user.email, INIT_PASSWD) + if IS_EMAIL_CONFIGURED: + if SEND_EMAIL_ON_RESETTING_USER_PASSWD: + try: + send_user_reset_email(request, user.email, INIT_PASSWD) + msg = _('Successfully resetted password to %(passwd)s, an email has been sent to %(user)s.') % \ + {'passwd': INIT_PASSWD, 'user': user.email} + messages.success(request, msg) + except Exception, e: + logger.error(str(e)) + msg = _('Successfully resetted password to %(passwd)s, but failed to send email to %(user)s, please check your email configuration.') % \ + {'passwd':INIT_PASSWD, 'user': user.email} + messages.success(request, msg) + else: + messages.success(request, _(u'Successfully resetted password to %(passwd)s for user %(user)s.') % \ + {'passwd':INIT_PASSWD,'user': user.email}) else: - messages.success(request, _(u'Successfully resetting password to %s') % INIT_PASSWD) + messages.success(request, _(u'Successfully resetted password to %(passwd)s for user %(user)s. But email notification can not be sent, because Email service is not properly configured.') % \ + {'passwd':INIT_PASSWD,'user': user.email}) except User.DoesNotExist: msg = _(u'Failed to reset password: user does not exist') messages.error(request, msg) @@ -2033,12 +2044,8 @@ def send_user_add_mail(request, email, password): 'protocol': use_https and 'https' or 'http', 'site_name': settings.SITE_NAME, } - try: - send_mail(_(u'Seafile Registration Information'), t.render(Context(c)), - None, [email], fail_silently=False) - messages.success(request, _(u'Successfully sending mail')) - except: - messages.error(request, _(u'Failed to send mail')) + send_mail(_(u'Seafile Registration Information'), t.render(Context(c)), + None, [email], fail_silently=False) @login_required def user_add(request): @@ -2055,8 +2062,7 @@ def user_add(request): email = form.cleaned_data['email'] password = form.cleaned_data['password1'] - user = User.objects.create_user(email, password, - is_staff=False, + user = User.objects.create_user(email, password, is_staff=False, is_active=True) if request.user.org: @@ -2069,9 +2075,19 @@ def user_add(request): return HttpResponseRedirect(reverse('org_useradmin', args=[url_prefix])) else: - if hasattr(settings, 'EMAIL_HOST'): - send_user_add_mail(request, email, password) - + if IS_EMAIL_CONFIGURED: + if SEND_EMAIL_ON_ADDING_SYSTEM_MEMBER: + try: + send_user_add_mail(request, email, password) + messages.success(request, _(u'Successfully added user %s. An email notification has been sent.' % email)) + except Exception, e: + logger.error(str(e)) + messages.success(request, _(u'Successfully added user %s. An error accurs when sending email notification, please check your email configuration.' % email)) + else: + messages.success(request, _(u'Successfully added user %s.' % email)) + else: + messages.success(request, _(u'Successfully added user %s. But email notification can not be sent, because Email service is not properly configured.' % email)) + return HttpResponseRedirect(reverse('sys_useradmin', args=[])) else: form = AddUserForm()