diff --git a/cloud/endagaweb/forms/dashboard_forms.py b/cloud/endagaweb/forms/dashboard_forms.py index 2f9a6ddc..a97b13cb 100644 --- a/cloud/endagaweb/forms/dashboard_forms.py +++ b/cloud/endagaweb/forms/dashboard_forms.py @@ -10,15 +10,16 @@ import datetime +import pytz +from crispy_forms.bootstrap import StrictButton, FieldWithButtons +from crispy_forms.helper import FormHelper +from crispy_forms.layout import Layout, Submit, Field from django import forms +from django.contrib.auth.forms import PasswordChangeForm, PasswordResetForm +from django.contrib.auth.models import User +from django.core import urlresolvers from django.db.models import Value from django.db.models.functions import Coalesce -from django.core import urlresolvers -from crispy_forms.helper import FormHelper -from crispy_forms.layout import Layout, Submit, Field -from crispy_forms.bootstrap import StrictButton, FieldWithButtons -from django.contrib.auth.forms import PasswordChangeForm -import pytz from ccm.common.currency import CURRENCIES from endagaweb import models @@ -190,7 +191,7 @@ def __init__(self, *args, **kwargs): self.helper.form_class = 'profile-form' update_button = StrictButton('Update', css_class='btn-default', type='submit') - self.helper.layout = Layout(FieldWithButtons('notify_numbers', update_button)) + self.helper.layout = Layout(FieldWithButtons('notify_numbers', update_button)) class SubVacuumForm(forms.Form): @@ -368,3 +369,29 @@ def __init__(self, *args, **kwargs): self.helper.form_action = '/dashboard/staff/tower-monitoring' self.helper.add_input(Submit('submit', 'Select')) self.helper.layout = Layout('tower') + + +class UserSearchForm(forms.Form): + """Crispy search form on /dashboard/subscribers.""" + query = forms.CharField(required=False, label="", + widget=forms.TextInput( + attrs={'placeholder': + 'abc@domain.com'})) + + def __init__(self, sender, *args, **kwargs): + self.helper = FormHelper() + self.helper.form_id = 'id-SearchForm' + self.helper.form_method = 'get' + self.helper.form_action = '/dashboard/user/management' + search_button = StrictButton('Search', css_class='btn-default', + type='submit') + self.helper.layout = Layout(FieldWithButtons('query', search_button)) + super(UserSearchForm, self).__init__(*args, **kwargs) + + + +class PasswordResetRequestForm(PasswordResetForm): + email = forms.CharField(label=("Email"), max_length=254) + class Meta: + model = User + fields = ("email") diff --git a/cloud/endagaweb/models.py b/cloud/endagaweb/models.py index 65b0780f..aef6fdb9 100644 --- a/cloud/endagaweb/models.py +++ b/cloud/endagaweb/models.py @@ -59,6 +59,43 @@ 'outside_call', 'outside_sms', 'local_call', 'local_sms', ) +PERMISSIONS = ( + # User Management + ('user_management', 'User Management'), + + # Towers + ('view_bts', 'View Tower'), + ('edit_bts', 'Manage Tower'), + + # Subscriber + ('adjust_credit', 'Adjust Credit(Subscriber)'), + ('view_subscriber', 'View Subscriber'), + ('edit_subscriber', 'Manage Subscriber'), + + # Network + ('view_network', 'View Network'), + ('edit_network', 'Manage Network'), + ('view_notification', 'View Notification(Network)'), + ('edit_notification', 'Manage Notification(Network)'), + ('view_denomination', 'View Denomination(Network)'), + ('edit_denomination', 'Manage Denomination(Network)'), + + # In Tower/Network/Subscriber + ('send_sms', 'Broadcast SMS'), + + # Graphs + ('view_graph', 'View Graph'), + + # Reports + ('view_report', 'View Report'), + ('download_graph', 'Download Report'), + + # Activity + ('view_activity', 'View Activity'), + ('download_activity', 'Download Activity(Report)'), + + ) + class UserProfile(models.Model): """UserProfiles extend the default Django User models. @@ -71,7 +108,7 @@ class UserProfile(models.Model): timezone_choices = [(v, v) for v in pytz.common_timezones] timezone = models.CharField(max_length=50, default='UTC', choices=timezone_choices) - + role = models.CharField(max_length=20, default='Cloud Admin') # A UI kludge indicate which network a user is currently viewing # Important: This is not the only network a User is associated with # because a user may have permissions on other Network instances. @@ -103,7 +140,9 @@ def new_user_hook(sender, instance, created, **kwargs): """ if created and instance.username != settings.ANONYMOUS_USER_NAME: profile = UserProfile.objects.create(user=instance) - network = Network.objects.create() + # Add explicit name to avoid duplicate names when + # running setup_test_db + network = Network.objects.create(name='Network_%s' % (instance.pk,)) network.auth_group.user_set.add(instance) network.save() # Make this the users currently selected network @@ -296,6 +335,9 @@ class BTS(models.Model): #none is unknown or invalid channel = models.IntegerField(null=True, blank=True) + class Meta: + default_permissions = () + def __unicode__(self): return "BTS(%s, %s, last active: %s)" % ( self.uuid, self.inbound_url, self.last_active) @@ -792,6 +834,9 @@ class UsageEvent(models.Model): timespan = models.DecimalField(null=True, max_digits=7, decimal_places=1) date_synced = models.DateTimeField(auto_now_add=True) + class Meta: + default_permissions = () + def voice_sec(self): """Gets the number of seconds for this call. @@ -980,9 +1025,8 @@ class Network(models.Model): environment = models.TextField(default="default") class Meta: - permissions = ( - ('view_network', 'View network'), - ) + default_permissions = () + permissions = PERMISSIONS @property def api_token(self): @@ -1432,14 +1476,14 @@ def create_auth(sender, instance, created, **kwargs): authenticate. """ if not instance.auth_group or not instance.auth_user: - instance.auth_group, created_group = Group.objects.get_or_create(name='network_%s' - % instance.pk) + instance.auth_group, created_group = Group.objects.get_or_create(name='%s_GROUP_%s' % + (instance.name, instance.pk)) if created_group: assign_perm('view_network', instance.auth_group, instance) post_save.disconnect(UserProfile.new_user_hook, sender=User) - instance.auth_user, created_user = User.objects.get_or_create(username='network_%s' - % instance.pk) + instance.auth_user, created_user = User.objects.get_or_create(username='%s_USER_%s' % + (instance.name, instance.pk)) if created_user: Token.objects.create(user=instance.auth_user) instance.auth_group.user_set.add(instance.auth_user) diff --git a/cloud/endagaweb/static/js/dashboard/validator.js b/cloud/endagaweb/static/js/dashboard/validator.js new file mode 100644 index 00000000..6311a22e --- /dev/null +++ b/cloud/endagaweb/static/js/dashboard/validator.js @@ -0,0 +1,414 @@ +/* ======================================================================== + * Bootstrap (plugin): validator.js v0.11.9 + * ======================================================================== + * The MIT License (MIT) + * + * Copyright (c) 2016 Cina Saffary. + * Made by @1000hz in the style of Bootstrap 3 era @fat + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * ======================================================================== */ + + ++function ($) { + 'use strict'; + + // VALIDATOR CLASS DEFINITION + // ========================== + + function getValue($el) { + return $el.is('[type="checkbox"]') ? $el.prop('checked') : + $el.is('[type="radio"]') ? !!$('[name="' + $el.attr('name') + '"]:checked').length : + $el.is('select[multiple]') ? ($el.val() || []).length : + $el.val() + } + + var Validator = function (element, options) { + this.options = options + this.validators = $.extend({}, Validator.VALIDATORS, options.custom) + this.$element = $(element) + this.$btn = $('button[type="submit"], input[type="submit"]') + .filter('[form="' + this.$element.attr('id') + '"]') + .add(this.$element.find('input[type="submit"], button[type="submit"]')) + + this.update() + + this.$element.on('input.bs.validator change.bs.validator focusout.bs.validator', $.proxy(this.onInput, this)) + this.$element.on('submit.bs.validator', $.proxy(this.onSubmit, this)) + this.$element.on('reset.bs.validator', $.proxy(this.reset, this)) + + this.$element.find('[data-match]').each(function () { + var $this = $(this) + var target = $this.attr('data-match') + + $(target).on('input.bs.validator', function (e) { + getValue($this) && $this.trigger('input.bs.validator') + }) + }) + + // run validators for fields with values, but don't clobber server-side errors + this.$inputs.filter(function () { + return getValue($(this)) && !$(this).closest('.has-error').length + }).trigger('focusout') + + this.$element.attr('novalidate', true) // disable automatic native validation + } + + Validator.VERSION = '0.11.9' + + Validator.INPUT_SELECTOR = ':input:not([type="hidden"], [type="submit"], [type="reset"], button)' + + Validator.FOCUS_OFFSET = 20 + + Validator.DEFAULTS = { + delay: 500, + html: false, + disable: true, + focus: true, + custom: {}, + errors: { + match: 'Does not match', + minlength: 'Not long enough' + }, + feedback: { + success: 'glyphicon-ok', + error: 'glyphicon-remove' + } + } + + Validator.VALIDATORS = { + 'native': function ($el) { + var el = $el[0] + if (el.checkValidity) { + return !el.checkValidity() && !el.validity.valid && (el.validationMessage || "error!") + } + }, + 'match': function ($el) { + var target = $el.attr('data-match') + return $el.val() !== $(target).val() && Validator.DEFAULTS.errors.match + }, + 'minlength': function ($el) { + var minlength = $el.attr('data-minlength') + return $el.val().length < minlength && Validator.DEFAULTS.errors.minlength + } + } + + Validator.prototype.update = function () { + var self = this + + this.$inputs = this.$element.find(Validator.INPUT_SELECTOR) + .add(this.$element.find('[data-validate="true"]')) + .not(this.$element.find('[data-validate="false"]') + .each(function () { self.clearErrors($(this)) }) + ) + + this.toggleSubmit() + + return this + } + + Validator.prototype.onInput = function (e) { + var self = this + var $el = $(e.target) + var deferErrors = e.type !== 'focusout' + + if (!this.$inputs.is($el)) return + + this.validateInput($el, deferErrors).done(function () { + self.toggleSubmit() + }) + } + + Validator.prototype.validateInput = function ($el, deferErrors) { + var value = getValue($el) + var prevErrors = $el.data('bs.validator.errors') + + if ($el.is('[type="radio"]')) $el = this.$element.find('input[name="' + $el.attr('name') + '"]') + + var e = $.Event('validate.bs.validator', {relatedTarget: $el[0]}) + this.$element.trigger(e) + if (e.isDefaultPrevented()) return + + var self = this + + return this.runValidators($el).done(function (errors) { + $el.data('bs.validator.errors', errors) + + errors.length + ? deferErrors ? self.defer($el, self.showErrors) : self.showErrors($el) + : self.clearErrors($el) + + if (!prevErrors || errors.toString() !== prevErrors.toString()) { + e = errors.length + ? $.Event('invalid.bs.validator', {relatedTarget: $el[0], detail: errors}) + : $.Event('valid.bs.validator', {relatedTarget: $el[0], detail: prevErrors}) + + self.$element.trigger(e) + } + + self.toggleSubmit() + + self.$element.trigger($.Event('validated.bs.validator', {relatedTarget: $el[0]})) + }) + } + + + Validator.prototype.runValidators = function ($el) { + var errors = [] + var deferred = $.Deferred() + + $el.data('bs.validator.deferred') && $el.data('bs.validator.deferred').reject() + $el.data('bs.validator.deferred', deferred) + + function getValidatorSpecificError(key) { + return $el.attr('data-' + key + '-error') + } + + function getValidityStateError() { + var validity = $el[0].validity + return validity.typeMismatch ? $el.attr('data-type-error') + : validity.patternMismatch ? $el.attr('data-pattern-error') + : validity.stepMismatch ? $el.attr('data-step-error') + : validity.rangeOverflow ? $el.attr('data-max-error') + : validity.rangeUnderflow ? $el.attr('data-min-error') + : validity.valueMissing ? $el.attr('data-required-error') + : null + } + + function getGenericError() { + return $el.attr('data-error') + } + + function getErrorMessage(key) { + return getValidatorSpecificError(key) + || getValidityStateError() + || getGenericError() + } + + $.each(this.validators, $.proxy(function (key, validator) { + var error = null + if ((getValue($el) || $el.attr('required')) && + ($el.attr('data-' + key) !== undefined || key == 'native') && + (error = validator.call(this, $el))) { + error = getErrorMessage(key) || error + !~errors.indexOf(error) && errors.push(error) + } + }, this)) + + if (!errors.length && getValue($el) && $el.attr('data-remote')) { + this.defer($el, function () { + var data = {} + data[$el.attr('name')] = getValue($el) + $.get($el.attr('data-remote'), data) + .fail(function (jqXHR, textStatus, error) { errors.push(getErrorMessage('remote') || error) }) + .always(function () { deferred.resolve(errors)}) + }) + } else deferred.resolve(errors) + + return deferred.promise() + } + + Validator.prototype.validate = function () { + var self = this + + $.when(this.$inputs.map(function (el) { + return self.validateInput($(this), false) + })).then(function () { + self.toggleSubmit() + self.focusError() + }) + + return this + } + + Validator.prototype.focusError = function () { + if (!this.options.focus) return + + var $input = this.$element.find(".has-error :input:first") + if ($input.length === 0) return + + $('html, body').animate({scrollTop: $input.offset().top - Validator.FOCUS_OFFSET}, 250) + $input.focus() + } + + Validator.prototype.showErrors = function ($el) { + var method = this.options.html ? 'html' : 'text' + var errors = $el.data('bs.validator.errors') + var $group = $el.closest('.form-group') + var $block = $group.find('.help-block.with-errors') + var $feedback = $group.find('.form-control-feedback') + + if (!errors.length) return + + errors = $('