def save(self, **kwargs): user = self.object new_flag = (not user.pk or getattr(user, 'new', False)) user.save() if user._roles_to_save is not None: self.old_roles = set(user.roles.all()) user.roles = user._roles_to_save # Newly created user via API is automatically marked as verified # Creator has to provide correct email, or in user profile set email as not verified (since email is required)! # Email change by user will trigger email with verification code so he can finish profile! # If admin doesnt set phone user is force to set it and when phone is changed sms verification is send if new_flag: user.userprofile.email_verified = True user.userprofile.phone_verified = True user.userprofile.save() # Changing a user email makes the email not verified # (unless request.user is not part of the staff or registration is disabled) if self.old_email and not self.request.user.is_staff and settings.REGISTRATION_ENABLED: user.userprofile.email_verified = False user.userprofile.email_token = user.userprofile.generate_token(6) user.userprofile.save() sendmail(user, 'accounts/user/base/profile_verify_subject.txt', 'accounts/user/base/profile_verify_email.txt', extra_context={ 'email_token': user.userprofile.email_token, })
def callback(request): """ Function that will be called by SMSAPI (former HQSMS) after sms has been send out. SMSAPI: After updating message status in SMSAPI system the update will be sent to callback script (1 to 5 statuses in one request). Parameter will be sent using GET method separated by commas. """ params = request.GET msgs = params['MsgId'].split(',') logger.info( 'Received SMSAPI (former HQSMS) callback for %d message(s): %s', len(msgs), msgs) log_msg = 'SMSAPI (former HQSMS) callback: SMS to %(to)s has status %(status)s at %(donedate)s UTC ' \ 'sent from account: %(username)s with SMSAPI ID %(MsgId)s.' for i, msgid in enumerate(msgs): context = { 'MsgId': msgid, 'to': _get_callback_param( params, 'to', i), # WARNING: this parameter is not officially documented 'username': _get_callback_param(params, 'username', i), } status = _get_callback_param(params, 'status', i) status_is_ok = status in CALLBACK_STATUS_CODES_OK context['status'] = CALLBACK_STATUS_CODES.get(status) try: donedate = float(_get_callback_param(params, 'donedate', i)) except ValueError: donedate = 0 context['donedate'] = datetime.fromtimestamp(donedate) if status_is_ok: logger.info(log_msg % context) else: dc1_settings = DefaultDc().settings logger.error(log_msg % context) sendmail( None, 'smsapi/callback_sms_failed_subject.txt', 'smsapi/callback_sms_failed.txt', from_email=dc1_settings.DEFAULT_FROM_EMAIL, recipient_list=[dc1_settings.SUPPORT_EMAIL], fail_silently=True, extra_context=context, ) return HttpResponse(content='OK', status=200)
def add_ticket_submit(request): """ Ajax submit ticket form. """ ticketform = AddTicketForm(request, request.POST) dc_settings = request.dc.settings if ticketform.is_valid(): # Send mail to SUPPORT_EMAIL sendmail(None, 'gui/support/add_ticket_subject.txt', 'gui/support/add_ticket_email.txt', recipient_list=[dc_settings.SUPPORT_EMAIL], from_email=request.user.email, dc=request.dc, extra_context={ 'first_name': request.user.first_name, 'last_name': request.user.last_name, 'company': request.user.userprofile.company, 'email': request.user.email, 'phone': request.user.userprofile.phone, 'severity': ticketform.cleaned_data['severity'], 'ticket_type': ticketform.cleaned_data['ticket_type'], 'vm': ticketform.cleaned_data['vm'], 'summary': ticketform.cleaned_data['summary'], 'desc': ticketform.cleaned_data['desc'], 'repro': ticketform.cleaned_data['repro'], 'dc': request.dc, }) # Send mail to user if dc_settings.SUPPORT_USER_CONFIRMATION: sendmail(request.user, 'gui/support/add_ticket_user_subject.txt', 'gui/support/add_ticket_user_email.txt', from_email=dc_settings.SUPPORT_EMAIL, dc=request.dc, extra_context={ 'summary': ticketform.cleaned_data['summary'], 'severity': ticketform.cleaned_data['severity'], 'ticket_type': ticketform.cleaned_data['ticket_type'], 'vm': ticketform.cleaned_data['vm'], }) # Notify and redirect messages.success(request, _('Your ticket has been submitted.')) if ticketform.cleaned_data.get('vm', None): return redirect('vm_details', hostname=ticketform.cleaned_data['vm']) else: return redirect('vm_list') else: return render(request, 'gui/support/add_ticket_form.html', { 'ticketform': ticketform, })
def _notify_user(request, user, profile): """ Function that notifies user that he has been registered in the system. Can be overloaded to send different text in the email, or use different method of notification. """ sendmail(user, 'gui/accounts/register_subject.txt', 'gui/accounts/register_email.txt', extra_context={ 'user': user, 'profile': profile, 'token': profile.email_token, 'uid': urlsafe_base64_encode(str(user.id)), }, dc=request.dc)
def _notify_user(self, user, profile): """ Function that notifies user that he has been registered in the system. Can be overloaded to send different text in the email, or use different method of notification. Function can be suppressed not to be called at all by setting self.notify_user = False in child __init__ """ sendmail(user, 'gui/accounts/register_subject.txt', 'gui/accounts/register_email.txt', extra_context={ 'user': user, 'profile': profile, 'token': profile.email_token, 'uid': urlsafe_base64_encode(str(user.id)), }, dc=self.request.dc)
def send_post_register_email(request, user): # Send optional email after successful registration (issue #261) template_path = path.join(settings.PROJECT_DIR, 'gui', 'templates') subject = 'gui/accounts/post_register_subject.txt' subject_path = path.join(template_path, subject) body_file_prefix = 'gui/accounts/post_register_email' body = None if path.exists(subject_path) and path.exists(path.join(template_path, body_file_prefix + '.html')): body = body_file_prefix + '.html' elif path.exists(subject_path) and path.exists(path.join(template_path, body_file_prefix + '.txt')): body = body_file_prefix + '.txt' if body: sendmail(user, subject, body, dc=request.dc) else: logger.info('Post registration email subject template: "%s" or body template: "%s" does not exists.' % (subject_path, path.join(template_path, body_file_prefix + '.[html|txt]')))
def send_email_verification(user): return sendmail( user, 'accounts/user/base/profile_verify_subject.txt', 'accounts/user/base/profile_verify_email.txt', extra_context={ 'email_token': user.userprofile.email_token, } )
def save(self, domain_override=None, subject_template_name='registration/password_reset_subject.txt', email_template_name='registration/password_reset_email.html', use_https=False, token_generator=default_token_generator, **kwargs): # Complete override, because we have to use our sendmail() for user in self.users_cache: # Update verification token profile = user.userprofile profile.email_token = token_generator.make_token(user) profile.save() sendmail(user, subject_template_name, email_template_name, extra_context={ 'user': user, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': profile.email_token, 'protocol': use_https and 'https' or 'http', })
def vm_create_cb(result, task_id, vm_uuid=None): """ A callback function for api.vm.base.views.vm_manage. """ vm = Vm.objects.select_related('dc').get(uuid=vm_uuid) msg = result.get('message', '') if result['returncode'] == 0 and msg.find('Successfully created') >= 0: json = result.pop('json', None) try: # save json from smartos json_active = vm.json.load(json) vm.json_active = json_active vm.json = json_active if result['meta']['apiview']['recreate']: Snapshot.objects.filter(vm=vm).delete() SnapshotDefine.objects.filter(vm=vm).delete() BackupDefine.objects.filter(vm=vm).delete() vm.save_metadata('installed', False, save=False) except Exception as e: logger.error( 'Could not parse json output from POST vm_manage(%s). Error: %s', vm_uuid, e) _vm_error(task_id, vm) logger.exception(e) raise TaskException(result, 'Could not parse json output') else: # save all vm.save(update_node_resources=True, update_storage_resources=True) vm_update_ipaddress_usage(vm) # vm_json_active_changed.send(task_id, vm=vm) # Signal! -> not needed because vm_deployed is called below vm_created.send(task_id, vm=vm) # Signal! if msg.find('Successfully started' ) < 0: # VM was created, but could not be started logger.error( 'VM %s was created, but could not be started! Error: %s', vm_uuid, msg) _vm_error(task_id, vm) raise TaskException(result, 'Initial start failed (%s)' % msg) sendmail(vm.owner, 'vm/base/vm_create_subject.txt', 'vm/base/vm_create_email.txt', extra_context={'vm': vm}, user_i18n=True, dc=vm.dc, fail_silently=True) else: logger.error( 'Found nonzero returncode in result from POST vm_manage(%s). Error: %s', vm_uuid, msg) # Revert status and inform user _vm_create_cb_failed(result, task_id, vm) if result['meta']['apiview']['recreate'] and msg.find( 'Successfully deleted') >= 0: _vm_error(task_id, vm) # Something went terribly wrong # and FAIL this task raise TaskException( result, 'Got bad return code (%s). Error: %s' % (result['returncode'], msg)) # So far so good. Now wait for deploy_over in vm_status_event_cb logger.info('VM %s is waiting for deploy_over...', vm_uuid) timer = 0 repeat = 0 while not vm.has_deploy_finished(): if timer > VMS_VM_DEPLOY_TOOLONG: # 10 minutes is too long if repeat == VMS_VM_DEPLOY_TOOLONG_MAX_CYCLES: # 20 minutes is really too long logger.error('VM %s deploy process has timed out!', vm_uuid) _vm_error(task_id, vm) result['message'] = 'VM %s deploy has timed out' % vm.hostname task_log_cb_error(result, task_id, vm=vm, **result['meta']) return result repeat += 1 timer = 0 logger.error( 'VM %s takes too long to deploy. Sending force stop/start', vm_uuid) # noinspection PyUnusedLocal tid, err = vm_reset(vm) sleep(3.0) timer += 3 logger.info('VM %s is completely deployed!', vm_uuid) internal_metadata = vm.json.get( 'internal_metadata', {}).copy() # save internal_metadata for email vm = Vm.objects.select_related('dc', 'template').get(pk=vm.pk) # Reload vm vm_deployed.send(task_id, vm=vm) # Signal! sendmail(vm.owner, 'vm/base/vm_deploy_subject.txt', 'vm/base/vm_deploy_email.txt', fail_silently=True, extra_context={ 'vm': vm, 'internal_metadata': internal_metadata }, user_i18n=True, dc=vm.dc) try: result['message'] = '\n'.join(result['message'].strip().split('\n') [:-1]) # Remove "started" stuff except Exception as e: logger.exception(e) task_log_cb_success(result, task_id, vm=vm, **result['meta']) try: if vm.template: # Try to create snapshot/backup definitions defined by template vm_define_snapshot, vm_define_backup = vm.template.vm_define_snapshot, vm.template.vm_define_backup if vm_define_snapshot or vm_define_backup: user = User.objects.get(id=user_id_from_task_id(task_id)) request = get_dummy_request(vm.dc, method='POST', user=user) SnapshotDefineView.create_from_template(request, vm, vm_define_snapshot, log=logger) BackupDefineView.create_from_template(request, vm, vm_define_backup, log=logger) except Exception as e: logger.exception(e) return result