diff --git a/server/src/uds/REST/methods/accountsusage.py b/server/src/uds/REST/methods/accountsusage.py new file mode 100644 index 000000000..58e65ca97 --- /dev/null +++ b/server/src/uds/REST/methods/accountsusage.py @@ -0,0 +1,156 @@ +# -*- coding: utf-8 -*- + +# +# Copyright (c) 2017 Virtual Cable S.L. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +''' +@author: Adolfo Gómez, dkmaster at dkmon dot com +''' +from __future__ import unicode_literals + +from django.utils.translation import ugettext as _ + + +from uds.models.CalendarRule import freqs, CalendarRule +from uds.models.Util import getSqlDatetime + +from uds.core.util import log +from uds.core.util import permissions +from uds.core.util.model import processUuid +from uds.core.Environment import Environment +from uds.REST.model import DetailHandler +from uds.REST import NotFound, ResponseError, RequestError +from django.db import IntegrityError + +import six +import logging +import datetime + +logger = logging.getLogger(__name__) + + +class AccountsUsage(DetailHandler): # pylint: disable=too-many-public-methods + ''' + Detail handler for Services, whose parent is a Provider + ''' + + @staticmethod + def usageToDict(item, perm): + ''' + Convert a calRule db item to a dict for a rest response + :param item: Service item (db) + :param full: If full is requested, add "extra" fields to complete information + ''' + retVal = { + 'id': item.uuid, + 'name': item.name, + 'comments': item.comments, + 'start': item.start, + 'end': item.end, + 'frequency': item.frequency, + 'interval': item.interval, + 'duration': item.duration, + 'duration_unit': item.duration_unit, + 'permission': perm + } + + return retVal + + def getItems(self, parent, item): + # Check what kind of access do we have to parent provider + perm = permissions.getEffectivePermission(self._user, parent) + try: + if item is None: + return [CalendarRules.usageToDict(k, perm) for k in parent.rules.all()] + else: + k = parent.rules.get(uuid=processUuid(item)) + return CalendarRules.usageToDict(k, perm) + except Exception: + logger.exception('itemId {}'.format(item)) + self.invalidItemException() + + def getFields(self, parent): + return [ + {'name': {'title': _('Rule name')}}, + {'start': {'title': _('Starts'), 'type': 'datetime'}}, + {'end': {'title': _('Ends'), 'type': 'date'}}, + {'frequency': {'title': _('Repeats'), 'type': 'dict', 'dict': dict((v[0], six.text_type(v[1])) for v in freqs) }}, + {'interval': {'title': _('Every'), 'type': 'callback'}}, + {'duration': {'title': _('Duration'), 'type': 'callback'}}, + {'comments': {'title': _('Comments')}}, + ] + + def saveItem(self, parent, item): + # Extract item db fields + # We need this fields for all + logger.debug('Saving rule {0} / {1}'.format(parent, item)) + fields = self.readFieldsFromParams(['name', 'comments', 'frequency', 'start', 'end', 'interval', 'duration', 'duration_unit']) + + if int(fields['interval']) < 1: + self.invalidItemException('Repeat must be greater than zero') + + # Convert timestamps to datetimes + fields['start'] = datetime.datetime.fromtimestamp(fields['start']) + if fields['end'] != None: + fields['end'] = datetime.datetime.fromtimestamp(fields['end']) + + calRule = None + try: + if item is None: # Create new + calRule = parent.rules.create(**fields) + else: + calRule = parent.rules.get(uuid=processUuid(item)) + calRule.__dict__.update(fields) + calRule.save() + except CalendarRule.DoesNotExist: + self.invalidItemException() + except IntegrityError: # Duplicate key probably + raise RequestError(_('Element already exists (duplicate key error)')) + except Exception as e: + logger.exception('Saving calendar') + raise RequestError('incorrect invocation to PUT: {0}'.format(e)) + + return self.getItems(parent, calRule.uuid) + + def deleteItem(self, parent, item): + logger.debug('Deleting rule {} from {}'.format(item, parent)) + try: + calRule = parent.rules.get(uuid=processUuid(item)) + calRule.calendar.modified = getSqlDatetime() + calRule.calendar.save() + calRule.delete() + except Exception: + logger.exception('Exception') + self.invalidItemException() + + return 'deleted' + + def getTitle(self, parent): + try: + return _('Rules of {0}').format(parent.name) + except Exception: + return _('Current rules') diff --git a/server/src/uds/templates/uds/admin/tmpl/accounts.html b/server/src/uds/templates/uds/admin/tmpl/accounts.html new file mode 100644 index 000000000..d13bad986 --- /dev/null +++ b/server/src/uds/templates/uds/admin/tmpl/accounts.html @@ -0,0 +1,39 @@ +{% load i18n %} +
+
+

{% trans 'Accounts' %}

+
+
+{% if messages %} +
+
+ {% for message in messages %} +
+ + {{ message }} +
+ {% endfor %} +
+
+{% endif %} +{% verbatim %} +
+
+
+ + +{% endverbatim %} diff --git a/udsProxy/.gitignore b/udsProxy/.gitignore new file mode 100644 index 000000000..4d1be1f26 --- /dev/null +++ b/udsProxy/.gitignore @@ -0,0 +1,4 @@ +bin +pkg +vars +src/gopkg.in diff --git a/udsProxy/.project b/udsProxy/.project deleted file mode 100644 index bffa0486d..000000000 --- a/udsProxy/.project +++ /dev/null @@ -1,17 +0,0 @@ - - - udsProxy - - - - - - org.python.pydev.PyDevBuilder - - - - - - org.python.pydev.pythonNature - - diff --git a/udsProxy/.pydevproject b/udsProxy/.pydevproject deleted file mode 100644 index 0ebadbb20..000000000 --- a/udsProxy/.pydevproject +++ /dev/null @@ -1,8 +0,0 @@ - - - -/${PROJECT_DIR_NAME}/src - -python 2.7 -Default - diff --git a/udsProxy/src/uds/udsProxy/udsProxy.go b/udsProxy/src/uds/udsProxy/udsProxy.go new file mode 100644 index 000000000..c1654f25c --- /dev/null +++ b/udsProxy/src/uds/udsProxy/udsProxy.go @@ -0,0 +1,84 @@ +package main + +import ( + "fmt" + "log" + "net" + "net/http" + "strconv" + "strings" + "time" + + ini "gopkg.in/ini.v1" +) + +const configFilename = "/etc/UDSProxy.cfg" + +var config struct { + Broker string `ini:"broker"` // Broker address +} + +// Test service +func testService(w http.ResponseWriter, r *http.Request) { + if strings.Split(r.RemoteAddr, ":")[0] != config.Broker { + w.WriteHeader(http.StatusForbidden) + fmt.Fprintf(w, "Access denied") + } + r.ParseForm() + ip, port, timeOutStr := r.FormValue("ip"), r.FormValue("port"), r.FormValue("timeout") + if ip == "" || port == "" { + w.WriteHeader(http.StatusBadRequest) + fmt.Fprintf(w, "Invalid arguments") + return + } + if timeOutStr == "" { + timeOutStr = "4" + } + + timeOut, _ := strconv.Atoi(timeOutStr) + + fmt.Println("Args: ", ip, port) + con, err := net.DialTimeout("tcp", ip+":"+port, time.Duration(timeOut)*time.Second) + + if err == nil { + con.Close() + w.WriteHeader(http.StatusFound) + fmt.Fprint(w, "ok") + } else { + w.WriteHeader(http.StatusNotFound) + fmt.Fprint(w, err) + } +} + +func actor(w http.ResponseWriter, r *http.Request) { + // Get Request as received and forward it to UDS, withouch changing anything... + // We will net params, body, etc... + + r.ParseForm() // parse arguments, you have to call this by yourself + fmt.Println(r.Form) // print form information in server side + fmt.Println("path", r.URL.Path) + fmt.Println("scheme", r.URL.Scheme) + fmt.Println(r.Form["url_long"]) + for k, v := range r.Form { + fmt.Println("key:", k) + fmt.Println("val:", strings.Join(v, "")) + } + fmt.Fprintf(w, "Hello astaxie!") // send data to client side +} + +func main() { + + cfg, err := ini.Load(configFilename) + if err != nil { + log.Fatal(err) + } + cfg.MapTo(&config) + + fmt.Println("Broker address: ", config.Broker) + http.HandleFunc("/actor", actor) // set router + http.HandleFunc("/testService", testService) + err = http.ListenAndServe(":9090", nil) // set listen port + if err != nil { + log.Fatal("ListenAndServe: ", err) + } +} diff --git a/udsProxy/src/udsProxy.py b/udsProxy/src/udsProxy.py deleted file mode 100644 index 6d06c2c4a..000000000 --- a/udsProxy/src/udsProxy.py +++ /dev/null @@ -1,40 +0,0 @@ -# -*- coding: utf-8 -*- - -# -# Copyright (c) 2017 Virtual Cable S.L. -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without modification, -# are permitted provided that the following conditions are met: -# -# * Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# * Neither the name of Virtual Cable S.L. nor the names of its contributors -# may be used to endorse or promote products derived from this software -# without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -import SimpleHTTPServer -import SocketServer - -PORT = 9090 - -if __name__ == "__main__": - Handler = SimpleHTTPServer.SimpleHTTPRequestHandler - httpd = SocketServer.TCPServer(("", PORT), Handler) - - print "Serving at port ", PORT - httpd.serve_forever()