def handle(self, *args, **options): db_users = seaserv.get_emailusers('DB', -1, -1) ldpa_imported_users = seaserv.get_emailusers('LDAPImport', -1, -1) admins = [] for user in db_users + ldpa_imported_users: if user.is_staff: admins.append(user) for u in admins: # save current language cur_language = translation.get_language() # get and active user language user_language = self.get_user_language(u.email) translation.activate(user_language) send_html_email_with_dj_template( u.email, dj_template='notifications/notify_virus.html', subject=_('Virus detected on %s') % settings.SITE_NAME, priority=MAIL_PRIORITY.now ) # restore current language translation.activate(cur_language)
def handle(self, *args, **options): db_users = seaserv.get_emailusers('DB', -1, -1) ldpa_imported_users = seaserv.get_emailusers('LDAPImport', -1, -1) admins = [] for user in db_users + ldpa_imported_users: if user.is_staff: admins.append(user) for u in admins: # save current language cur_language = translation.get_language() # get and active user language user_language = self.get_user_language(u.email) translation.activate(user_language) send_html_email_with_dj_template( u.email, dj_template='notifications/notify_virus.html', subject=_('Virus detected on %s') % settings.SITE_NAME, backend='post_office') # restore current language translation.activate(cur_language)
def email_admins(self): db_users = seaserv.get_emailusers('DB', -1, -1) ldpa_imported_users = seaserv.get_emailusers('LDAPImport', -1, -1) admins = [] for user in db_users + ldpa_imported_users: if user.is_staff: admins.append(user) for u in admins: # save current language cur_language = translation.get_language() # get and active user language user_language = self.get_user_language(u.email) translation.activate(user_language) send_html_email_with_dj_template( u.email, dj_template='notifications/notify_virus.html', subject=_('Virus detected on %s') % settings.SITE_NAME, priority=MAIL_PRIORITY.now ) # restore current language translation.activate(cur_language)
def freeze_user(self, notify_admins=False): self.is_active = False self.save() if notify_admins: admins = get_system_admins() for u in admins: # save current language cur_language = translation.get_language() # get and active user language user_language = Profile.objects.get_user_language(u.email) translation.activate(user_language) send_html_email_with_dj_template( u.email, dj_template='sysadmin/user_freeze_email.html', subject=_('Account %(account)s froze on %(site)s.') % { "account": self.email, "site": settings.SITE_NAME, }, context={'user': self.email}, priority=MAIL_PRIORITY.now ) # restore current language translation.activate(cur_language)
def freeze_user(self, notify_admins=False): self.is_active = False self.save() if notify_admins: admins = get_system_admins() for u in admins: # save current language cur_language = translation.get_language() # get and active user language user_language = Profile.objects.get_user_language(u.email) translation.activate(user_language) send_html_email_with_dj_template( u.email, dj_template='sysadmin/user_freeze_email.html', subject=_('Account %(account)s froze on %(site)s.') % { "account": self.email, "site": settings.SITE_NAME, }, context={'user': self.email}, priority=MAIL_PRIORITY.now) # restore current language translation.activate(cur_language)
def email_repo_owner(self, repo_file): repo_id, file_path = repo_file.split(':', 1) owner = seafile_api.get_repo_owner(repo_id) if not owner: return # save current language cur_language = translation.get_language() # get and active user language user_language = self.get_user_language(owner) translation.activate(user_language) contact_email = Profile.objects.get_contact_email_by_user(owner) send_html_email_with_dj_template( contact_email, dj_template='notifications/notify_virus.html', context={'owner': owner, 'file_url': reverse('view_lib_file', args=[repo_id, file_path]), 'file_name': os.path.basename(file_path), }, subject=_('Virus detected on %s') % get_site_name(), priority=MAIL_PRIORITY.now ) # restore current language translation.activate(cur_language)
def email_repo_owner(self, repo_file): repo_id, file_path = repo_file.split(':', 1) owner = seafile_api.get_repo_owner(repo_id) if not owner: return # save current language cur_language = translation.get_language() # get and active user language user_language = self.get_user_language(owner) translation.activate(user_language) contact_email = Profile.objects.get_contact_email_by_user(owner) send_html_email_with_dj_template( contact_email, subject=_('Virus detected on %s') % get_site_name(), dj_template='notifications/notify_virus.html', context={ 'owner': owner, 'file_url': reverse('view_lib_file', args=[repo_id, file_path]), 'file_name': os.path.basename(file_path) }) # restore current language translation.activate(cur_language)
def ajax_get_link_audit_code(request): """ Generate a token, and record that token with email in cache, expires in one hour, send token to that email address. User provide token and email at share link page, if the token and email are valid, record that email in session. """ content_type = 'application/json; charset=utf-8' token = request.POST.get('token') email = request.POST.get('email') if not is_valid_email(email): return HttpResponse(json.dumps( {'error': _('Email address is not valid')}), status=400, content_type=content_type) dfs = FileShare.objects.get_valid_file_link_by_token(token) ufs = UploadLinkShare.objects.get_valid_upload_link_by_token(token) fs = dfs if dfs else ufs if fs is None: return HttpResponse(json.dumps({'error': _('Share link is not found')}), status=400, content_type=content_type) cache_key = normalize_cache_key(email, 'share_link_audit_') timeout = 60 * 60 # one hour code = gen_token(max_length=6) cache.set(cache_key, code, timeout) # send code to user via email subject = _("Verification code for visiting share links") c = { 'code': code, } try: send_html_email_with_dj_template( email, dj_template='share/audit_code_email.html', context=c, subject=subject, priority=MAIL_PRIORITY.now) return HttpResponse(json.dumps({'success': True}), status=200, content_type=content_type) except Exception as e: logger.error('Failed to send audit code via email to %s') logger.error(e) return HttpResponse(json.dumps({ "error": _("Failed to send a verification code, please try again later.") }), status=500, content_type=content_type)
def email_mail_list(self): try: notify_list = dj_settings.VIRUS_SCAN_NOTIFY_LIST except AttributeError: return for mail in notify_list: send_html_email_with_dj_template( mail, subject=_('Virus detected on %s') % get_site_name(), dj_template='notifications/notify_virus.html')
def email_mail_list(self): try: notify_list = dj_settings.VIRUS_SCAN_NOTIFY_LIST except AttributeError: return for mail in notify_list: send_html_email_with_dj_template( mail, dj_template='notifications/notify_virus.html', subject=_('Virus detected on %s') % settings.SITE_NAME, priority=MAIL_PRIORITY.now )
def email_mail_list(self): try: notify_list = dj_settings.VIRUS_SCAN_NOTIFY_LIST except AttributeError: return for mail in notify_list: send_html_email_with_dj_template( mail, dj_template='notifications/notify_virus.html', subject=_('Virus detected on %s') % get_site_name(), priority=MAIL_PRIORITY.now )
def ajax_get_link_audit_code(request): """ Generate a token, and record that token with email in cache, expires in one hour, send token to that email address. User provide token and email at share link page, if the token and email are valid, record that email in session. """ content_type = 'application/json; charset=utf-8' token = request.POST.get('token') email = request.POST.get('email') if not is_valid_email(email): return HttpResponse(json.dumps({ 'error': _('Email address is not valid') }), status=400, content_type=content_type) dfs = FileShare.objects.get_valid_file_link_by_token(token) ufs = UploadLinkShare.objects.get_valid_upload_link_by_token(token) fs = dfs if dfs else ufs if fs is None: return HttpResponse(json.dumps({ 'error': _('Share link is not found') }), status=400, content_type=content_type) cache_key = normalize_cache_key(email, 'share_link_audit_') timeout = 60 * 60 # one hour code = gen_token(max_length=6) cache.set(cache_key, code, timeout) # send code to user via email subject = _("Verification code for visiting share links") c = { 'code': code, } try: send_html_email_with_dj_template( email, dj_template='share/audit_code_email.html', context=c, subject=subject, priority=MAIL_PRIORITY.now ) return HttpResponse(json.dumps({'success': True}), status=200, content_type=content_type) except Exception as e: logger.error('Failed to send audit code via email to %s') logger.error(e) return HttpResponse(json.dumps({ "error": _("Failed to send a verification code, please try again later.") }), status=500, content_type=content_type)
def post(self, request, token, format=None): """Revoke invitation when the accepter successfully creates an account. And set the account to inactive. """ # recourse check invitation = Invitation.objects.get_by_token(token) if not invitation: error_msg = "Invitation not found." return api_error(status.HTTP_404_NOT_FOUND, error_msg) # permission check if request.user.username != invitation.inviter: error_msg = "Permission denied." return api_error(status.HTTP_403_FORBIDDEN, error_msg) if invitation.accept_time is None: error_msg = "The email address didn't accept the invitation." return api_error(status.HTTP_400_BAD_REQUEST, error_msg) email = invitation.accepter inviter = invitation.inviter try: user = User.objects.get(email) except User.DoesNotExist: error_msg = 'User %s not found.' % email return api_error(status.HTTP_404_NOT_FOUND, error_msg) # set the account to inactive. user.freeze_user() # delete the invitation. invitation.delete() # send email site_name = get_site_name() subject = _('%(user)s revoked your access to %(site_name)s.') % { 'user': email2nickname(inviter), 'site_name': site_name } context = { 'inviter': email2nickname(inviter), 'site_name': site_name, } send_success = send_html_email_with_dj_template( email, subject=subject, dj_template='invitations/invitation_revoke_email.html', context=context) if not send_success: logger.warning('send revoke access email to %s failed') return Response({'success': True})
def send_to(self, email=None): """ Send an invitation email to ``email``. """ if not email: email = self.accepter context = { 'inviter': self.inviter, 'site_name': SITE_NAME, 'token': self.token, } subject = render_to_string('invitations/invitation_email_subject.txt', context).rstrip() send_html_email_with_dj_template( email, dj_template='invitations/invitation_email.html', context=context, subject=subject, priority=MAIL_PRIORITY.now )
def send_to(self, email=None): """ Send an invitation email to ``email``. """ if not email: email = self.accepter context = self.to_dict() context['site_name'] = SITE_NAME # subject = render_to_string('invitations/invitation_email_subject.txt', # context).rstrip() subject = _('%(user)s invited you to join %(site_name)s.') % { 'user': self.inviter, 'site_name': SITE_NAME} send_html_email_with_dj_template( email, dj_template='invitations/invitation_email.html', context=context, subject=subject, priority=MAIL_PRIORITY.now )
def send_to(self, email=None): """ Send an invitation email to ``email``. """ if not email: email = self.accepter context = { 'inviter': self.inviter, 'site_name': SITE_NAME, 'token': self.token, } subject = render_to_string('invitations/invitation_email_subject.txt', context) send_html_email_with_dj_template( email, dj_template='invitations/invitation_email.html', context=context, subject=subject, priority=MAIL_PRIORITY.now)
def send_to(self, email=None): """ Send an invitation email to ``email``. """ if not email: email = self.accepter context = self.to_dict() context['site_name'] = get_site_name() subject = _('You are invited to join %(site_name)s.') % {'site_name': get_site_name()} return send_html_email_with_dj_template(email, subject=subject, dj_template='invitations/invitation_email.html', context=context)
def send_to(self, email=None): """ Send an invitation email to ``email``. """ if not email: email = self.accepter context = self.to_dict() context['site_name'] = get_site_name() # subject = render_to_string('invitations/invitation_email_subject.txt', # context).rstrip() subject = _('%(user)s invited you to join %(site_name)s.') % { 'user': self.inviter, 'site_name': get_site_name()} return send_html_email_with_dj_template( email, dj_template='invitations/invitation_email.html', context=context, subject=subject, priority=MAIL_PRIORITY.now )
def post(self, request): """ Import users from xlsx file Permission checking: 1. admin user. """ xlsx_file = request.FILES.get('file', None) if not xlsx_file: error_msg = 'file can not be found.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) file_type, ext = get_file_type_and_ext(xlsx_file.name) if ext != 'xlsx': error_msg = file_type_error_msg(ext, 'xlsx') return api_error(status.HTTP_400_BAD_REQUEST, error_msg) content = xlsx_file.read() try: fs = BytesIO(content) wb = load_workbook(filename=fs, read_only=True) except Exception as e: logger.error(e) # example file is like: # Email Password Name(Optional) Role(Optional) Space Quota(MB, Optional) # [email protected] a a default 1024 # [email protected] b b default 2048 rows = wb.worksheets[0].rows records = [] # skip first row(head field). next(rows) for row in rows: records.append([col.value for col in row]) if user_number_over_limit(new_users=len(records)): error_msg = 'The number of users exceeds the limit.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) result = {} result['failed'] = [] result['success'] = [] for record in records: if record[0]: email = record[0].strip() if not is_valid_username(email): result['failed'].append({ 'email': email, 'error_msg': 'email %s invalid.' % email }) continue else: result['failed'].append({ 'email': '', 'error_msg': 'email invalid.' }) continue if record[1]: password = str(record[1]).strip() if not password: result['failed'].append({ 'email': email, 'error_msg': 'password invalid.' }) continue else: result['failed'].append({ 'email': email, 'error_msg': 'password invalid.' }) continue vid = get_virtual_id_by_email(email) try: User.objects.get(email=vid) result['failed'].append({ 'email': email, 'error_msg': 'user %s exists.' % email }) continue except User.DoesNotExist: pass user = User.objects.create_user(email, password, is_staff=False, is_active=True) virtual_id = get_virtual_id_by_email(email) if config.FORCE_PASSWORD_CHANGE: UserOptions.objects.set_force_passwd_change(virtual_id) # update the user's optional info # update nikename nickname = email.split('@')[0] try: if record[2]: input_nickname = str(record[2]).strip() if len(input_nickname) <= 64 and '/' not in input_nickname: nickname = input_nickname Profile.objects.add_or_update(virtual_id, nickname, '') except Exception as e: logger.error(e) # update role if record[3]: try: role = record[3].strip() if is_pro_version() and role in get_available_roles(): User.objects.update_role(virtual_id, role) except Exception as e: logger.error(e) # update quota if record[4]: try: space_quota_mb = int(record[4]) if space_quota_mb >= 0: space_quota = int(space_quota_mb) * get_file_size_unit('MB') seafile_api.set_user_quota(virtual_id, space_quota) except Exception as e: logger.error(e) try: send_html_email_with_dj_template( email, dj_template='sysadmin/user_batch_add_email.html', subject=_('You are invited to join %s') % get_site_name(), context={ 'user': email2nickname(request.user.username), 'email': email, 'password': password, }) except Exception as e: logger.error(e) user_info = get_user_info(virtual_id) result['success'].append(user_info) # send admin operation log signal admin_op_detail = { "email": email, } admin_operation.send(sender=None, admin_name=request.user.username, operation=USER_ADD, detail=admin_op_detail) return Response(result)
def do_emails(self, args_str): args = args_str.split('|', 6) if args[0] == 'ERROR': # notify admins db_users = seaserv.get_emailusers('DB', -1, -1) admins = [] for user in db_users: if user.is_staff: admins.append(user) for u in admins: send_html_email_with_dj_template( u.email, dj_template='notifications/notify_admins_on_archiving_error.html', context = { 'archive_id': args[2], 'error_msg': args[5], }, subject="Error on keeper archiving, archive id: {}".format(args[2]), priority=MAIL_PRIORITY.now ) # notify owner cur_language = translation.get_language() user_language = get_user_language(args[1]) translation.activate(user_language) send_html_email_with_dj_template( args[1], dj_template='notifications/notify_user_on_archiving_error.html', context = { 'email': get_user_name(args[1]), 'repo_id': args[3], 'repo_name': args[4], }, subject="Error on keeper archiving, library id: {}".format(args[3]), priority=MAIL_PRIORITY.now ) translation.activate(cur_language) elif args[0] == 'DONE': # notify owner cur_language = translation.get_language() user_language = get_user_language(args[1]) translation.activate(user_language) md = json.loads(base64.b64decode(args[6])) send_html_email_with_dj_template( args[1], dj_template='notifications/notify_user_on_successfull_archiving.html', context = { 'email': get_user_name(args[1]), 'repo_id': args[2], 'repo_name': args[3], 'version': args[4], 'archive_id': args[5], 'md': md, }, subject="Your library has been successfully archived", priority=MAIL_PRIORITY.now ) translation.activate(cur_language) else: logger.warning("Cannot send email on archiving: unknown status: {}".format(args[0]))