Commit 2e53c348 authored by Sofia Papagiannaki's avatar Sofia Papagiannaki
Browse files

Provide an API call for the service clients to send user feedback

* new model Service
* new management commands for handling the services
* remove ASTAKOS_CLOUD_SERVICES setting
* change get_services API call to return
the Service objects
* separate admin from service API calls
* introduce send_feedback service API call

Refs: #2413
parent 7994aac4
......@@ -59,9 +59,6 @@ ASTAKOS_IM_STATIC_URL /static/im/
ASTAKOS_MODERATION_ENABLED True If False and invitations are not enabled newly created user will be automatically accepted
ASTAKOS_BASEURL \http://pithos.dev.grnet.gr Astakos baseurl
ASTAKOS_SITENAME GRNET Cloud Service name that appears in emails
ASTAKOS_CLOUD_SERVICES ({'icon': 'home-icon.png', 'id': 'cloud', 'name': 'grnet cloud', 'url': '/'}, Cloud services appear in the horizontal bar
{'id': 'okeanos', 'name': 'cyclades', 'url': '/okeanos.html'},
{'id': 'pithos', 'name': 'pithos+', 'url': '/ui/'})
ASTAKOS_RECAPTCHA_ENABLED True Enable recaptcha
ASTAKOS_RECAPTCHA_PUBLIC_KEY Recaptcha public key obtained after registration here: http://recaptcha.net
ASTAKOS_RECAPTCHA_PRIVATE_KEY Recaptcha private key obtained after registration here: http://recaptcha.net
......
# Copyright 2011-2012 GRNET S.A. All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above
# copyright notice, this list of conditions and the following
# disclaimer.
#
# 2. 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.
#
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``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 GRNET S.A 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.
#
# The views and conclusions contained in the software and
# documentation are those of the authors and should not be
# interpreted as representing official policies, either expressed
# or implied, of GRNET S.A.
from django.http import HttpResponse
from django.utils import simplejson as json
from astakos.im.models import AstakosUser
from astakos.im.faults import ItemNotFound
format = ('%a, %d %b %Y %H:%M:%S GMT')
def _get_user_by_username(user_id):
try:
user = AstakosUser.objects.get(username = user_id)
except AstakosUser.DoesNotExist, e:
raise ItemNotFound('Invalid userid')
else:
response = HttpResponse()
response.status=200
user_info = {'id':user.id,
'username':user.username,
'email':[user.email],
'name':user.realname,
'auth_token_created':user.auth_token_created.strftime(format),
'auth_token_expires':user.auth_token_expires.strftime(format),
'has_credits':user.has_credits,
'enabled':user.is_active,
'groups':[g.name for g in user.groups.all()]}
response.content = json.dumps(user_info)
response['Content-Type'] = 'application/json; charset=UTF-8'
response['Content-Length'] = len(response.content)
return response
def _get_user_by_email(email):
if not email:
raise BadRequest('Email missing')
try:
user = AstakosUser.objects.get(email = email)
except AstakosUser.DoesNotExist, e:
raise ItemNotFound('Invalid email')
if not user.is_active:
raise ItemNotFound('Inactive user')
else:
response = HttpResponse()
response.status=200
user_info = {'id':user.id,
'username':user.username,
'email':[user.email],
'enabled':user.is_active,
'name':user.realname,
'auth_token_created':user.auth_token_created.strftime(format),
'auth_token_expires':user.auth_token_expires.strftime(format),
'has_credits':user.has_credits,
'groups':[g.name for g in user.groups.all()],
'user_permissions':[p.codename for p in user.user_permissions.all()]}
response.content = json.dumps(user_info)
response['Content-Type'] = 'application/json; charset=UTF-8'
response['Content-Length'] = len(response.content)
return response
\ No newline at end of file
......@@ -39,18 +39,18 @@ from traceback import format_exc
from time import time, mktime
from urllib import quote
from urlparse import urlparse
from collections import defaultdict
from django.conf import settings
from django.http import HttpResponse
from django.utils import simplejson as json
from django.core.urlresolvers import reverse
from astakos.im.faults import BadRequest, Unauthorized, InternalServerError, \
Fault, ItemNotFound, Forbidden
from astakos.im.models import AstakosUser
from astakos.im.settings import CLOUD_SERVICES, INVITATIONS_ENABLED, COOKIE_NAME, \
EMAILCHANGE_ENABLED
from astakos.im.api.faults import *
from astakos.im.models import AstakosUser, Service
from astakos.im.settings import INVITATIONS_ENABLED, COOKIE_NAME, EMAILCHANGE_ENABLED
from astakos.im.util import epoch
from astakos.im.api import _get_user_by_email, _get_user_by_username
logger = logging.getLogger(__name__)
format = ('%a, %d %b %Y %H:%M:%S GMT')
......@@ -84,6 +84,9 @@ def api_method(http_method=None, token_required=False, perms=None):
raise Unauthorized('Access denied')
try:
user = AstakosUser.objects.get(auth_token=x_auth_token)
## Check if the token has expired.
#if (time() - mktime(user.auth_token_expires.timetuple())) > 0:
# raise Unauthorized('Authentication expired')
if not user.has_perms(perms):
raise Forbidden('Unauthorized request')
except AstakosUser.DoesNotExist, e:
......@@ -173,7 +176,9 @@ def authenticate(request, user=None):
@api_method(http_method='GET')
def get_services(request):
callback = request.GET.get('callback', None)
data = json.dumps(CLOUD_SERVICES)
services = Service.objects.all()
data = tuple({'name':s.name, 'url':s.url, 'icon':s.icon} for s in services)
data = json.dumps(data)
mimetype = 'application/json'
if callback:
......@@ -225,7 +230,7 @@ def get_menu(request, with_extra_links=False, with_signout=True):
return HttpResponse(content=data, mimetype=mimetype)
@api_method(http_method='GET', token_required=True, perms=['im.can_access_userinfo'])
@api_method(http_method='GET', token_required=True)
def get_user_by_email(request, user=None):
# Normal Response Codes: 200
# Error Response Codes: internalServerError (500)
......@@ -234,35 +239,9 @@ def get_user_by_email(request, user=None):
# forbidden (403)
# itemNotFound (404)
email = request.GET.get('name')
if not email:
raise BadRequest('Email missing')
try:
user = AstakosUser.objects.get(email = email)
except AstakosUser.DoesNotExist, e:
raise ItemNotFound('Invalid email')
if not user.is_active:
raise ItemNotFound('Inactive user')
else:
response = HttpResponse()
response.status=200
user_info = {'id':user.id,
'username':user.username,
'email':[user.email],
'enabled':user.is_active,
'name':user.realname,
'auth_token_created':user.auth_token_created.strftime(format),
'auth_token_expires':user.auth_token_expires.strftime(format),
'has_credits':user.has_credits,
'groups':[g.name for g in user.groups.all()],
'user_permissions':[p.codename for p in user.user_permissions.all()],
'group_permissions': list(user.get_group_permissions())}
response.content = json.dumps(user_info)
response['Content-Type'] = 'application/json; charset=UTF-8'
response['Content-Length'] = len(response.content)
return response
return _get_user_by_email(email)
@api_method(http_method='GET', token_required=True, perms=['can_access_userinfo'])
@api_method(http_method='GET', token_required=True)
def get_user_by_username(request, user_id, user=None):
# Normal Response Codes: 200
# Error Response Codes: internalServerError (500)
......@@ -270,23 +249,4 @@ def get_user_by_username(request, user_id, user=None):
# unauthorised (401)
# forbidden (403)
# itemNotFound (404)
try:
user = AstakosUser.objects.get(username = user_id)
except AstakosUser.DoesNotExist, e:
raise ItemNotFound('Invalid userid')
else:
response = HttpResponse()
response.status=200
user_info = {'id':user.id,
'username':user.username,
'email':[user.email],
'name':user.realname,
'auth_token_created':user.auth_token_created.strftime(format),
'auth_token_expires':user.auth_token_expires.strftime(format),
'has_credits':user.has_credits,
'enabled':user.is_active,
'groups':[g.name for g in user.groups.all()]}
response.content = json.dumps(user_info)
response['Content-Type'] = 'application/json; charset=UTF-8'
response['Content-Length'] = len(response.content)
return response
\ No newline at end of file
return _get_user_by_username(user_id)
\ No newline at end of file
# Copyright 2011-2012 GRNET S.A. All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above
# copyright notice, this list of conditions and the following
# disclaimer.
#
# 2. 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.
#
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``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 GRNET S.A 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.
#
# The views and conclusions contained in the software and
# documentation are those of the authors and should not be
# interpreted as representing official policies, either expressed
# or implied, of GRNET S.A.
import logging
import urllib
from functools import wraps
from traceback import format_exc
from time import time, mktime
from urllib import quote
from urlparse import urlparse
from collections import defaultdict
from django.conf import settings
from django.http import HttpResponse
from django.core.urlresolvers import reverse
from django.views.decorators.csrf import csrf_exempt
from astakos.im.api.faults import *
from astakos.im.models import AstakosUser, Service
from astakos.im.settings import INVITATIONS_ENABLED, COOKIE_NAME, EMAILCHANGE_ENABLED
from astakos.im.util import epoch
from astakos.im.forms import FeedbackForm
from astakos.im.functions import send_feedback as send_feedback_func, SendMailError
logger = logging.getLogger(__name__)
def render_fault(request, fault):
if isinstance(fault, InternalServerError) and settings.DEBUG:
fault.details = format_exc(fault)
request.serialization = 'text'
data = fault.message + '\n'
if fault.details:
data += '\n' + fault.details
response = HttpResponse(data, status=fault.code)
response['Content-Length'] = len(response.content)
return response
def api_method(http_method=None, token_required=False):
"""Decorator function for views that implement an API method."""
def decorator(func):
@wraps(func)
def wrapper(request, *args, **kwargs):
try:
if http_method and request.method != http_method:
raise BadRequest('Method not allowed.')
x_auth_token = request.META.get('HTTP_X_AUTH_TOKEN')
if token_required:
if not x_auth_token:
raise Unauthorized('Access denied')
try:
service = Service.objects.get(auth_token=x_auth_token)
# Check if the token has expired.
if (time() - mktime(service.auth_token_expires.timetuple())) > 0:
raise Unauthorized('Authentication expired')
except Service.DoesNotExist, e:
raise Unauthorized('Invalid X-Auth-Token')
response = func(request, *args, **kwargs)
return response
except Fault, fault:
return render_fault(request, fault)
except BaseException, e:
logger.exception('Unexpected error: %s' % e)
fault = InternalServerError('Unexpected error')
return render_fault(request, fault)
return wrapper
return decorator
@api_method(http_method='GET', token_required=True)
def get_user_by_email(request, user=None):
# Normal Response Codes: 200
# Error Response Codes: internalServerError (500)
# badRequest (400)
# unauthorised (401)
# forbidden (403)
# itemNotFound (404)
email = request.GET.get('name')
return _get_user_by_email(email)
@api_method(http_method='GET', token_required=True)
def get_user_by_username(request, user_id, user=None):
# Normal Response Codes: 200
# Error Response Codes: internalServerError (500)
# badRequest (400)
# unauthorised (401)
# forbidden (403)
# itemNotFound (404)
return _get_user_by_username(user_id)
@csrf_exempt
@api_method(http_method='POST', token_required=True)
def send_feedback(request, email_template_name='im/feedback_mail.txt'):
# Normal Response Codes: 200
# Error Response Codes: internalServerError (500)
# badRequest (400)
# unauthorised (401)
auth_token = request.POST.get('auth', '')
if not auth_token:
raise BadRequest('Missing user authentication')
user = None
try:
user = AstakosUser.objects.get(auth_token=auth_token)
except:
pass
if not user:
raise BadRequest('Invalid user authentication')
form = FeedbackForm(request.POST)
if not form.is_valid():
raise BadRequest('Invalid data')
msg = form.cleaned_data['feedback_msg']
data = form.cleaned_data['feedback_data']
send_feedback_func(msg, data, user, email_template_name)
response = HttpResponse(status=200)
response['Content-Length'] = len(response.content)
return response
\ No newline at end of file
......@@ -33,7 +33,7 @@
from astakos.im.settings import IM_MODULES, INVITATIONS_ENABLED, IM_STATIC_URL, \
COOKIE_NAME, LOGIN_MESSAGES, PROFILE_EXTRA_LINKS
from astakos.im.api import get_menu
from astakos.im.api.admin import get_menu
from astakos.im.util import get_query
from django.conf import settings
......
# Copyright 2012 GRNET S.A. All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above
# copyright notice, this list of conditions and the following
# disclaimer.
#
# 2. 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.
#
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``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 GRNET S.A 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.
#
# The views and conclusions contained in the software and
# documentation are those of the authors and should not be
# interpreted as representing official policies, either expressed
# or implied, of GRNET S.A.
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from astakos.im.models import Service
class Command(BaseCommand):
help = "List g"
option_list = BaseCommand.option_list + (
make_option('-c',
action='store_true',
dest='csv',
default=False,
help="Use pipes to separate values"),
)
def handle(self, *args, **options):
if args:
raise CommandError("Command doesn't accept any arguments")
services = Service.objects.all()
labels = ('id', 'name', 'url', 'icon')
columns = (3, 12, 40, 40)
if not options['csv']:
line = ' '.join(l.rjust(w) for l, w in zip(labels, columns))
self.stdout.write(line + '\n')
sep = '-' * len(line)
self.stdout.write(sep + '\n')
for service in services:
fields = (str(service.id), service.name, service.url, service.icon)
if options['csv']:
line = '|'.join(fields)
else:
line = ' '.join(f.rjust(w) for f, w in zip(fields, columns))
self.stdout.write(line.encode('utf8') + '\n')
# Copyright 2012 GRNET S.A. All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above
# copyright notice, this list of conditions and the following
# disclaimer.
#
# 2. 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.
#
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``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 GRNET S.A 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.
#
# The views and conclusions contained in the software and
# documentation are those of the authors and should not be
# interpreted as representing official policies, either expressed
# or implied, of GRNET S.A.
from django.core.management.base import BaseCommand, CommandError
from astakos.im.models import Service
class Command(BaseCommand):
args = "<name> <url> [<icon>]"
help = "Register a service"
def handle(self, *args, **options):
if len(args) < 2:
raise CommandError("Invalid number of arguments")
service = Service(name=args[0], url=args[1])
if len(args) == 3:
service.icon = args[2]
try:
service.save()
self.stdout.write('Service created with token: %s\n' % service.auth_token)
except Exception, e:
raise CommandError(e)
\ No newline at end of file
# Copyright 2012 GRNET S.A. All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above
# copyright notice, this list of conditions and the following
# disclaimer.
#
# 2. 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.
#
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``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 GRNET S.A 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.
#
# The views and conclusions contained in the software and
# documentation are those of the authors and should not be
# interpreted as representing official policies, either expressed
# or implied, of GRNET S.A.
from django.core.management.base import BaseCommand, CommandError
from astakos.im.models import Service
class Command(BaseCommand):
args = "<name>"
help = "Renew service token"
def handle(self, *args, **options):
if len(args) != 1:
raise CommandError("Invalid number of arguments")
try:
service = Service.objects.get(name=args[0])
service.renew_token()
service.save()
self.stdout.write('New service token: %s\n' % service.auth_token)
except Service.DoesNotExist:
raise CommandError("Invalid service name")
except Exception, e:
raise CommandError(e)
\ No newline at end of file
# Copyright 2012 GRNET S.A. All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above
# copyright notice, this list of conditions and the following
# disclaimer.
#
# 2. 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.
#
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``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 GRNET S.A 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