Commit 28bdf6fe authored by Olga Brani's avatar Olga Brani
Browse files

fixing conflicts

parents 6a9985b0 f3697f66
......@@ -40,7 +40,7 @@ from django.utils import simplejson as json
from django.conf import settings
from django.core.urlresolvers import reverse
from astakos.im.models import AstakosUser, GroupKind, Service, Resource
from astakos.im.models import AstakosUser, Service, Resource
from astakos.im.api.faults import Fault, ItemNotFound, InternalServerError, BadRequest
from astakos.im.settings import (
INVITATIONS_ENABLED, COOKIE_NAME, EMAILCHANGE_ENABLED, QUOTAHOLDER_URL)
......@@ -86,58 +86,6 @@ def api_method(http_method=None):
return decorator
def _get_user_by_username(user_id):
try:
user = AstakosUser.objects.get(username=user_id)
except AstakosUser.DoesNotExist:
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__iexact=email)
except AstakosUser.DoesNotExist:
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
@api_method(http_method='GET')
def get_services(request):
callback = request.GET.get('callback', None)
......@@ -170,10 +118,6 @@ def get_menu(request, with_extra_links=False, with_signout=True):
append(item(url=absolute(request, reverse('edit_profile')),
name="My account"))
if with_extra_links:
# if user.has_usable_password() and user.provider in ('local', ''):
# append(item(
# url=absolute(request, reverse('password_change')),
# name="Change password"))
if EMAILCHANGE_ENABLED:
append(item(
url=absolute(request, reverse('email_change')),
......@@ -184,24 +128,6 @@ def get_menu(request, with_extra_links=False, with_signout=True):
name="Invitations"))
if QUOTAHOLDER_URL:
# append(item(
# url=absolute(request, reverse('group_list')),
# name="Projects",
# # submenu=(item(
# # url=absolute(request,
# # reverse('group_list')),
# # name="Overview"),
# # item(
# # url=absolute(request,
# # reverse('group_create_list')),
# # name="Create"),
# # item(
# # url=absolute(request,
# # reverse('group_search')),
# # name="Join"),
# # )
# )
# )
append(item(
url=absolute(request, reverse('project_list')),
name="Projects"))
......@@ -211,12 +137,6 @@ def get_menu(request, with_extra_links=False, with_signout=True):
append(item(
url=absolute(request, reverse('feedback')),
name="Contact"))
# append(item(
# url=absolute(request, reverse('billing')),
# name="Billing"))
# append(item(
# url=absolute(request, reverse('timeline')),
# name="Timeline"))
if with_signout:
append(item(
url=absolute(request, reverse('logout')),
......
......@@ -40,9 +40,8 @@ from smtplib import SMTPException
from astakos.im.models import (
AstakosUser,
# AstakosGroup, GroupKind,
Resource, Service, RESOURCE_SEPARATOR,
Project, ProjectApplication, ProjectMembership, filter_queryset_by_property)
Project, ProjectApplication, ProjectMembership)
from astakos.im.api.backends.base import (
BaseBackend, SuccessResult, FailureResult)
from astakos.im.api.backends.errors import (
......@@ -303,19 +302,4 @@ class DjangoBackend(BaseBackend):
# TODO return information for unknown ids
q = Resource.objects.filter(service__id=service_id,
id__in=ids)
q.delete()
# @safe
# def create_group(self, **kwargs):
# policies = kwargs.pop('policies', ())
# permissions = kwargs.pop('permissions', ())
# members = kwargs.pop('members', ())
# owners = kwargs.pop('owners', ())
#
# g = self._create_object(AstakosGroup, **kwargs)
#
# g.permissions = permissions
# g.policies = policies
# # g.members = members
# g.owners = owners
# return self._details(g)
\ No newline at end of file
q.delete()
\ No newline at end of file
......@@ -38,9 +38,11 @@ from time import time, mktime
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.utils import simplejson as json
from astakos.im.api.faults import Fault, Unauthorized, InternalServerError, BadRequest
from astakos.im.api import render_fault, _get_user_by_email, _get_user_by_username
from . import render_fault
from .faults import (
Fault, Unauthorized, InternalServerError, BadRequest, ItemNotFound)
from astakos.im.models import AstakosUser, Service
from astakos.im.forms import FeedbackForm
from astakos.im.functions import send_feedback as send_feedback_func
......@@ -64,8 +66,9 @@ def api_method(http_method=None, token_required=False):
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')
if service.auth_token_expires:
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)
......@@ -81,26 +84,40 @@ def api_method(http_method=None, token_required=False):
@api_method(http_method='GET', token_required=True)
def get_user_by_email(request, user=None):
def get_user_info(request):
# 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)
username = request.META.get('HTTP_X_USER_USERNAME')
uuid = request.META.get('HTTP_X_USER_UUID')
if not username and not uuid:
raise BadRequest('Either username or uuid is required.')
query = AstakosUser.objects.all()
user_info = None
if username:
try:
user = query.get(username__iexact=username)
except AstakosUser.DoesNotExist:
raise ItemNotFound('Invalid username: %s' % username)
else:
user_info = {'uuid': user.uuid}
else:
try:
user = query.get(uuid=uuid)
except AstakosUser.DoesNotExist:
raise ItemNotFound('Invalid uuid: %s' % uuid)
else:
user_info = {'username': user.username}
response = HttpResponse()
response.status = 200
response.content = json.dumps(user_info)
response['Content-Type'] = 'application/json; charset=UTF-8'
response['Content-Length'] = len(response.content)
return response
@csrf_exempt
......
......@@ -40,11 +40,6 @@ class Boolean(Integer):
Boolean = Boolean()
# class GroupKind(Integer):
# def init(self):
# self.opts.update({'minimum': 1, 'maximum': 5})
# GroupKind = GroupKind()
Timepoint = Text(classname='Timepoint', maxlen=24)
......
......@@ -39,10 +39,9 @@ from time import time, mktime
from django.http import HttpResponse
from django.utils import simplejson as json
from astakos.im.api.faults import (
Fault, Unauthorized, InternalServerError, BadRequest,
Forbidden)
from astakos.im.api import render_fault, _get_user_by_email, _get_user_by_username
from .faults import (
Fault, Unauthorized, InternalServerError, BadRequest, Forbidden)
from . import render_fault
from astakos.im.models import AstakosUser
from astakos.im.util import epoch
......@@ -84,45 +83,6 @@ def api_method(http_method=None, token_required=False, perms=None):
return decorator
@api_method(http_method='GET', token_required=True)
def authenticate_old(request, user=None):
# Normal Response Codes: 204
# Error Response Codes: internalServerError (500)
# badRequest (400)
# unauthorised (401)
if not user:
raise BadRequest('No user')
# Check if the is active.
if not user.is_active:
raise Unauthorized('User inactive')
# Check if the token has expired.
if (time() - mktime(user.auth_token_expires.timetuple())) > 0:
raise Unauthorized('Authentication expired')
if not user.signed_terms:
raise Unauthorized('Pending approval terms')
response = HttpResponse()
response.status = 204
user_info = {
'id': user.id,
'username': user.username,
'uuid': user.uuid,
'uniq': user.email,
'auth_token': user.auth_token,
'auth_token_created': user.auth_token_created.isoformat(),
'auth_token_expires': user.auth_token_expires.isoformat(),
'has_credits': user.has_credits,
'has_signed_terms': user.signed_terms,
'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
@api_method(http_method='GET', token_required=True)
def authenticate(request, user=None):
# Normal Response Codes: 204
......@@ -147,40 +107,14 @@ def authenticate(request, user=None):
response.status = 204
user_info = {
'id': user.id,
'userid': user.username,
'username': user.username,
'uuid': user.uuid,
'email': [user.email],
'name': user.realname,
'auth_token': user.auth_token,
'auth_token_created': epoch(user.auth_token_created),
'auth_token_expires': epoch(user.auth_token_expires),
'has_credits': user.has_credits,
'is_active': user.is_active,
'groups': [g.name for g in user.groups.all()]}
'has_credits': user.has_credits}
response.content = json.dumps(user_info)
response['Content-Type'] = 'application/json; charset=UTF-8'
response['Content-Length'] = len(response.content)
return response
@api_method(http_method='GET', token_required=True, perms=['im.can_access_userinfo'])
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, perms=['im.can_access_userinfo'])
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)
......@@ -42,6 +42,7 @@ from astakos.im import settings as astakos_settings
from astakos.im import messages as astakos_messages
import logging
import urllib
logger = logging.getLogger(__name__)
......@@ -87,8 +88,17 @@ class AuthProvider(object):
msg = 'AUTH_PROVIDER_%s' % msg
return override_msg or getattr(astakos_messages, msg, msg) % params
@property
def add_url(self):
return reverse(self.login_view)
def __init__(self, user=None):
self.user = user
for tpl in ['login_prompt', 'login', 'signup_prompt']:
tpl_name = '%s_%s' % (tpl, 'template')
override = self.get_setting(tpl_name)
if override:
setattr(self, tpl_name, override)
def __getattr__(self, key):
if not key.startswith('get_'):
......@@ -141,11 +151,7 @@ class LocalAuthProvider(AuthProvider):
login_prompt = _('if you already have a username and password')
signup_prompt = _('New to ~okeanos ?')
signup_link_prompt = _('create an account now')
@property
def add_url(self):
return reverse('password_change')
login_view = 'password_change'
one_per_user = True
......@@ -171,13 +177,10 @@ class ShibbolethAuthProvider(AuthProvider):
primary_login_prompt = _('If you are a student/researcher/faculty you can'
' login using your university-credentials in'
' the following page')
@property
def add_url(self):
return reverse('astakos.im.target.shibboleth.login')
login_view = 'astakos.im.target.shibboleth.login'
login_template = 'im/auth/shibboleth_login.html'
login_prompt_template = 'im/auth/shibboleth_login_prompt.html'
login_prompt_template = 'im/auth/third_party_provider_generic_login_prompt.html'
class TwitterAuthProvider(AuthProvider):
......@@ -186,10 +189,7 @@ class TwitterAuthProvider(AuthProvider):
add_prompt = _('Allows you to login to your account using Twitter')
details_tpl = _('Twitter screen name: %(info_screen_name)s')
user_title = _('Twitter (%(info_screen_name)s)')
@property
def add_url(self):
return reverse('astakos.im.target.twitter.login')
login_view = 'astakos.im.target.twitter.login'
login_template = 'im/auth/third_party_provider_generic_login.html'
login_prompt_template = 'im/auth/third_party_provider_generic_login_prompt.html'
......@@ -201,10 +201,7 @@ class GoogleAuthProvider(AuthProvider):
add_prompt = _('Allows you to login to your account using Google')
details_tpl = _('Google account: %(info_email)s')
user_title = _('Google (%(info_email)s)')
@property
def add_url(self):
return reverse('astakos.im.target.google.login')
login_view = 'astakos.im.target.google.login'
login_template = 'im/auth/third_party_provider_generic_login.html'
login_prompt_template = 'im/auth/third_party_provider_generic_login_prompt.html'
......@@ -216,10 +213,7 @@ class LinkedInAuthProvider(AuthProvider):
add_prompt = _('Allows you to login to your account using LinkedIn')
user_title = _('LinkedIn (%(info_emailAddress)s)')
details_tpl = _('LinkedIn account: %(info_emailAddress)s')
@property
def add_url(self):
return reverse('astakos.im.target.linkedin.login')
login_view = 'astakos.im.target.linkedin.login'
login_template = 'im/auth/third_party_provider_generic_login.html'
login_prompt_template = 'im/auth/third_party_provider_generic_login_prompt.html'
......
......@@ -37,7 +37,6 @@ from astakos.im.settings import (
GLOBAL_MESSAGES, PROFILE_EXTRA_LINKS)
from astakos.im.api import get_menu
from astakos.im.util import get_query
from astakos.im.models import GroupKind
from astakos.im.auth_providers import PROVIDERS as AUTH_PROVIDERS
from django.utils import simplejson as json
......@@ -108,8 +107,3 @@ def menu(request):
return {}
else:
return {'menu': menu_items}
def group_kinds(request):
return {'group_kinds': GroupKind.objects.exclude(
name='default').values_list('name', flat=True)}
# 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
......@@ -25,7 +25,7 @@
# 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
......@@ -53,29 +53,29 @@ class Cookie():
self.uuid, sep, self.auth_token = cookie.partition('|')
self.request = request
self.response = response
@property
def uuid(self):
return getattr(self, 'uuid', '')
@property
def auth_token(self):
return getattr(self, 'auth_token', '')
@property
def is_set(self):
no_token = not self.auth_token
return not no_token
@property
def is_valid(self):
return self.uuid == getattr(self.user, 'uuid', '') and \
self.auth_token == getattr(self.user, 'auth_token', '')
@property
def user(self):
return getattr(self.request, 'user', AnonymousUser())
def __set(self):
if not self.response:
raise ValueError(_(astakos_messages.NO_RESPONSE))
......@@ -86,16 +86,16 @@ class Cookie():
COOKIE_NAME, value=cookie_value, expires=expire_fmt, path='/',
domain=COOKIE_DOMAIN, secure=COOKIE_SECURE
)
msg = 'Cookie [expiring %(auth_token_expires)s] set for %(email)s' % user.__dict__
msg = 'Cookie [expiring %(auth_token_expires)s] set for %(uuid)s' % user.__dict__
logger._log(LOGGING_LEVEL, msg, [])
def __delete(self):
if not self.response:
raise ValueError(_(astakos_messages.NO_RESPONSE))
self.response.delete_cookie(COOKIE_NAME, path='/', domain=COOKIE_DOMAIN)
msg = 'Cookie deleted for %(email)s' % self.__dict__
msg = 'Cookie deleted for %(uuid)s' % self.__dict__
logger._log(LOGGING_LEVEL, msg, [])
def fix(self, response=None):
self.response = response or self.response
try:
......
......@@ -65,60 +65,102 @@ def get_client():
_client = QuotaholderClient(QUOTAHOLDER_URL, token=QUOTAHOLDER_TOKEN)
return _client
def call(func_name):
"""Decorator function for Quotaholder client calls."""
def decorator(payload_func):
@wraps(payload_func)
def wrapper(entities=(), **kwargs):
if not entities:
return ()
if not QUOTAHOLDER_URL:
return ()
c = get_client()
func = c.__dict__.get(func_name)
if not func:
return ()
data = payload_func(entities, **kwargs)
if not data:
return data
funcname = func.__name__
kwargs = {'context': {}, funcname: data}
rejected = func(**kwargs)
msg = _('%s: %s - Rejected: %s' % (funcname, data, rejected,))
logger.log(LOGGING_LEVEL, msg)
return rejected
return wrapper
return decorator
@call('set_quota')
def send_quota(users):
data = []
append = data.append
for user in users:
for resource, uplimit in user.quota.iteritems():
key = ENTITY_KEY
quantity = None
capacity = uplimit if uplimit != inf else None
import_limit = None
export_limit = None
flags = 0
args = (
user.uuid, resource, key, quantity, capacity, import_limit,
export_limit, flags)
append(args)
return data
def set_quota(payload):
c = get_client()
if not c:
return
result = c.set_quota(context={}, clientkey=clientkey, set_quota=payload)
logger.info('set_quota: %s rejected: %s' % (payload, result))
return result
def get_quota(user):
c = get_client()
if not c:
return
payload = []
append = payload.append