Revision d7d60147

b/pithos/aai/fixtures/auth_test_data.json
1
[
2
    {
3
        "model": "aai.PithosUser",
4
        "pk": 1,
5
        "fields": {
6
            "uniq": "test",
7
            "auth_token": "0000",
8
            "auth_token_created": "2011-04-07 09:17:14",
9
            "auth_token_expires": "2015-04-07 09:17:14",
10
            "created": "2011-02-06"
11
   	    }
12
    },
13
    {
14
        "model": "aai.PithosUser",
15
        "pk": 2,
16
        "fields": {
17
            "uniq": "verigak",
18
            "auth_token": "0001",
19
            "auth_token_created": "2011-04-07 09:17:14",
20
            "auth_token_expires": "2015-04-07 09:17:14",
21
            "created": "2011-02-06"
22
   	    }
23
    },
24
    {
25
        "model": "aai.PithosUser",
26
        "pk": 3,
27
        "fields": {
28
            "uniq": "chazapis",
29
            "auth_token": "0002",
30
            "auth_token_created": "2011-04-07 09:17:14",
31
            "auth_token_expires": "2015-04-07 09:17:14",
32
            "created": "2011-02-06"
33
   	    }
34
    },
35
    {
36
        "model": "aai.PithosUser",
37
        "pk": 4,
38
        "fields": {
39
            "uniq": "gtsouk",
40
            "auth_token": "0003",
41
            "auth_token_created": "2011-04-07 09:17:14",
42
            "auth_token_expires": "2015-04-07 09:17:14",
43
            "created": "2011-02-06"
44
   	    }
45
    },
46
    {
47
        "model": "aai.PithosUser",
48
        "pk": 5,
49
        "fields": {
50
            "uniq": "papagian",
51
            "auth_token": "0004",
52
            "auth_token_created": "2011-04-07 09:17:14",
53
            "auth_token_expires": "2015-04-07 09:17:14",
54
            "created": "2011-02-06"
55
   	    }
56
    },
57
    {
58
        "model": "aai.PithosUser",
59
        "pk": 6,
60
        "fields": {
61
            "uniq": "louridas",
62
            "auth_token": "0005",
63
            "auth_token_created": "2011-04-07 09:17:14",
64
            "auth_token_expires": "2015-04-07 09:17:14",
65
            "created": "2011-02-06"
66
   	    }
67
    },
68
    {
69
        "model": "aai.PithosUser",
70
        "pk": 7,
71
        "fields": {
72
            "uniq": "chstath",
73
            "auth_token": "0006",
74
            "auth_token_created": "2011-04-07 09:17:14",
75
            "auth_token_expires": "2015-04-07 09:17:14",
76
            "created": "2011-02-06"
77
   	    }
78
    },
79
    {
80
        "model": "aai.PithosUser",
81
        "pk": 8,
82
        "fields": {
83
            "uniq": "pkanavos",
84
            "auth_token": "0007",
85
            "auth_token_created": "2011-04-07 09:17:14",
86
            "auth_token_expires": "2015-04-07 09:17:14",
87
            "created": "2011-02-06"
88
   	    }
89
    },
90
    {
91
        "model": "aai.PithosUser",
92
        "pk": 9,
93
        "fields": {
94
            "uniq": "mvasilak",
95
            "auth_token": "0008",
96
            "auth_token_created": "2011-04-07 09:17:14",
97
            "auth_token_expires": "2015-04-07 09:17:14",
98
            "created": "2011-02-06"
99
   	    }
100
    }
101
]
b/pithos/aai/functions.py
1
# Copyright 2011 GRNET S.A. All rights reserved.
2
# 
3
# Redistribution and use in source and binary forms, with or
4
# without modification, are permitted provided that the following
5
# conditions are met:
6
# 
7
#   1. Redistributions of source code must retain the above
8
#      copyright notice, this list of conditions and the following
9
#      disclaimer.
10
# 
11
#   2. Redistributions in binary form must reproduce the above
12
#      copyright notice, this list of conditions and the following
13
#      disclaimer in the documentation and/or other materials
14
#      provided with the distribution.
15
# 
16
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
# POSSIBILITY OF SUCH DAMAGE.
28
# 
29
# The views and conclusions contained in the software and
30
# documentation are those of the authors and should not be
31
# interpreted as representing official policies, either expressed
32
# or implied, of GRNET S.A.
33

  
34
from time import time, mktime
35

  
36
from django.conf import settings
37
from django.http import HttpResponse, HttpResponseRedirect
38
from django.utils.cache import patch_vary_headers
39

  
40
from models import PithosUser
41
from shibboleth import Tokens, register_shibboleth_user
42

  
43

  
44
def login(request):
45
    return HttpResponse('login')
46

  
47
#     # Special case for testing purposes, delivers the cookie for the
48
#     # test user on first access
49
#     if settings.BYPASS_AUTHENTICATION and \
50
#        request.GET.get('test') is not None:
51
#         u = PithosUser.objects.get(
52
#             auth_token='46e427d657b20defe352804f0eb6f8a2')
53
#         return _redirect_shib_auth_user(user = u)
54
# 
55
#     token = None
56
# 
57
#     # Try to find token in a cookie
58
#     token = request.COOKIES.get('X-Auth-Token', None)
59
# 
60
#     # Try to find token in request header
61
#     if not token:
62
#         token = request.META.get('HTTP_X_AUTH_TOKEN', None)
63
# 
64
#     if token:
65
#         # token was found, retrieve user from backing store
66
#         try:
67
#             user = PithosUser.objects.get(auth_token=token)
68
# 
69
#         except PithosUser.DoesNotExist:
70
#             return HttpResponseRedirect(settings.LOGIN_URL)
71
#         # check user's auth token validity
72
#         if (time() - mktime(user.auth_token_expires.timetuple())) > 0:
73
#             # the user's token has expired, prompt to re-login
74
#             return HttpResponseRedirect(settings.LOGIN_URL)
75
# 
76
#         request.user = user
77
#         return
78
# 
79
#     # token was not found but user authenticated by Shibboleth
80
#     if Tokens.SHIB_EPPN in request.META and \
81
#        Tokens.SHIB_SESSION_ID in request.META:
82
#         try:
83
#             user = PithosUser.objects.get(uniq=request.META[Tokens.SHIB_EPPN])
84
#             return _redirect_shib_auth_user(user)
85
#         except PithosUser.DoesNotExist:
86
#             if register_shibboleth_user(request.META):
87
#                 user = PithosUser.objects.get(uniq=request.META[Tokens.SHIB_EPPN])
88
#                 return _redirect_shib_auth_user(user)
89
#             else:
90
#                 return HttpResponseRedirect(settings.LOGIN_URL)
91
# 
92
#     if settings.TEST and 'TEST-AAI' in request.META:
93
#         return HttpResponseRedirect(settings.LOGIN_URL)
94
# 
95
#     if request.path.endswith(settings.LOGIN_URL):
96
#         # avoid redirect loops
97
#         return
98
#     else:
99
#         # no authentication info found in headers, redirect back
100
#         return HttpResponseRedirect(settings.LOGIN_URL)
101
# 
102
# def process_response(request, response):
103
#     # Tell proxies and other interested parties that the request varies
104
#     # based on X-Auth-Token, to avoid caching of results
105
#     patch_vary_headers(response, ('X-Auth-Token',))
106
#     return response
107
# 
108
# def _redirect_shib_auth_user(user):
109
#     expire_fmt = user.auth_token_expires.strftime('%a, %d-%b-%Y %H:%M:%S %Z')
110
# 
111
#     response = HttpResponse()
112
#     response.set_cookie('X-Auth-Token', value=user.auth_token,
113
#                         expires=expire_fmt, path='/')
114
#     response['X-Auth-Token'] = user.auth_token
115
#     response['Location'] = settings.APP_INSTALL_URL
116
#     response.status_code = 302
117
#     return response
b/pithos/aai/models.py
1
# Copyright 2011 GRNET S.A. All rights reserved.
2
# 
3
# Redistribution and use in source and binary forms, with or
4
# without modification, are permitted provided that the following
5
# conditions are met:
6
# 
7
#   1. Redistributions of source code must retain the above
8
#      copyright notice, this list of conditions and the following
9
#      disclaimer.
10
# 
11
#   2. Redistributions in binary form must reproduce the above
12
#      copyright notice, this list of conditions and the following
13
#      disclaimer in the documentation and/or other materials
14
#      provided with the distribution.
15
# 
16
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
# POSSIBILITY OF SUCH DAMAGE.
28
# 
29
# The views and conclusions contained in the software and
30
# documentation are those of the authors and should not be
31
# interpreted as representing official policies, either expressed
32
# or implied, of GRNET S.A.
33

  
34
from django.db import models
35

  
36
from pithos import settings
37

  
38

  
39
class PithosUser(models.Model):
40
    uniq = models.CharField('Unique ID', max_length=255, null=True)
41
    realname = models.CharField('Real Name', max_length=255, default='')
42
    affiliation = models.CharField('Affiliation', max_length=255, default='')
43
    quota = models.IntegerField('Storage Limit', default=settings.DEFAULT_QUOTA)
44
    auth_token = models.CharField('Authentication Token', max_length=32, null=True)
45
    auth_token_created = models.DateTimeField('Time of auth token creation', auto_now_add=True)
46
    auth_token_expires = models.DateTimeField('Time of auth token expiration', auto_now_add=True)
47
    created = models.DateTimeField('Time of creation', auto_now_add=True)
48
    updated = models.DateTimeField('Time of last update', auto_now=True)
49

  
50
    class Meta:
51
        verbose_name = u'Pithos User'
52

  
53
    def __unicode__(self):
54
        return self.uniq
b/pithos/aai/shibboleth.py
1
# Copyright 2011 GRNET S.A. All rights reserved.
2
# 
3
# Redistribution and use in source and binary forms, with or
4
# without modification, are permitted provided that the following
5
# conditions are met:
6
# 
7
#   1. Redistributions of source code must retain the above
8
#      copyright notice, this list of conditions and the following
9
#      disclaimer.
10
# 
11
#   2. Redistributions in binary form must reproduce the above
12
#      copyright notice, this list of conditions and the following
13
#      disclaimer in the documentation and/or other materials
14
#      provided with the distribution.
15
# 
16
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
# POSSIBILITY OF SUCH DAMAGE.
28
# 
29
# The views and conclusions contained in the software and
30
# documentation are those of the authors and should not be
31
# interpreted as representing official policies, either expressed
32
# or implied, of GRNET S.A.
33

  
34
from util import register_user
35

  
36

  
37
class Tokens:
38
    # these are mapped by the Shibboleth SP software
39
    SHIB_EPPN = "eppn" # eduPersonPrincipalName
40
    SHIB_NAME = "Shib-InetOrgPerson-givenName"
41
    SHIB_SURNAME = "Shib-Person-surname"
42
    SHIB_CN = "Shib-Person-commonName"
43
    SHIB_DISPLAYNAME = "Shib-InetOrgPerson-displayName"
44
    SHIB_EP_AFFILIATION = "Shib-EP-Affiliation"
45
    SHIB_SESSION_ID = "Shib-Session-ID"
46

  
47

  
48
class NoUniqueToken(BaseException):
49
    def __init__(self, msg):
50
        self.msg = msg
51

  
52

  
53
class NoRealName(BaseException):
54
    def __init__(self, msg):
55
        self.msg = msg
56

  
57

  
58
def register_shibboleth_user(tokens):
59
    """Registers a Shibboleth user using the input hash as a source for data."""
60

  
61
    try:
62
        eppn = tokens[Tokens.SHIB_EPPN]
63
    except KeyError:
64
        raise NoUniqueToken("Authentication does not return a unique token")
65

  
66
    if Tokens.SHIB_DISPLAYNAME in tokens:
67
        realname = tokens[Tokens.SHIB_DISPLAYNAME]
68
    elif Tokens.SHIB_CN in tokens:
69
        realname = tokens[Tokens.SHIB_CN]
70
    elif Tokens.SHIB_NAME in tokens and Tokens.SHIB_SURNAME in tokens:
71
        realname = tokens[Tokens.SHIB_NAME] + ' ' + tokens[Tokens.SHIB_SURNAME]
72
    else:
73
        raise NoRealName("Authentication does not return the user's name")
74

  
75
    affiliation = tokens.get(Tokens.SHIB_EP_AFFILIATION, '')
76

  
77
    register_user(eppn, realname, affiliation)
78

  
79
    return True
80

  
b/pithos/aai/util.py
1
# Copyright 2011 GRNET S.A. All rights reserved.
2
# 
3
# Redistribution and use in source and binary forms, with or
4
# without modification, are permitted provided that the following
5
# conditions are met:
6
# 
7
#   1. Redistributions of source code must retain the above
8
#      copyright notice, this list of conditions and the following
9
#      disclaimer.
10
# 
11
#   2. Redistributions in binary form must reproduce the above
12
#      copyright notice, this list of conditions and the following
13
#      disclaimer in the documentation and/or other materials
14
#      provided with the distribution.
15
# 
16
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
# POSSIBILITY OF SUCH DAMAGE.
28
# 
29
# The views and conclusions contained in the software and
30
# documentation are those of the authors and should not be
31
# interpreted as representing official policies, either expressed
32
# or implied, of GRNET S.A.
33

  
34
# Business Logic for working with users
35

  
36
from hashlib import md5
37
from time import asctime
38
from datetime import datetime, timedelta
39

  
40
from django.conf import settings
41
from django.db import transaction
42

  
43
from models import PithosUser
44

  
45

  
46
@transaction.commit_on_success
47
def register_user(uniq, realname, affiliation):
48
    user = PithosUser()
49
    user.uniq = uniq
50
    user.realname = realname
51
    user.affiliation = affiliation
52
    user.save()
53
    create_auth_token(user)
54
    return user
55

  
56
@transaction.commit_on_success
57
def delete_user(user):
58
    if user is not None:
59
        user.delete()
60

  
61
@transaction.commit_on_success
62
def create_auth_token(user):
63
    md5 = md5()
64
    md5.update(user.uniq)
65
    md5.update(user.realname.encode('ascii', 'ignore'))
66
    md5.update(asctime())
67

  
68
    user.auth_token = md5.hexdigest()
69
    user.auth_token_created = datetime.now()
70
    user.auth_token_expires = user.auth_token_created + \
71
                              timedelta(hours=settings.AUTH_TOKEN_DURATION)
72
    user.save()
73

  
/dev/null
1
# Copyright 2011 GRNET S.A. All rights reserved.
2
# 
3
# Redistribution and use in source and binary forms, with or
4
# without modification, are permitted provided that the following
5
# conditions are met:
6
# 
7
#   1. Redistributions of source code must retain the above
8
#      copyright notice, this list of conditions and the following
9
#      disclaimer.
10
# 
11
#   2. Redistributions in binary form must reproduce the above
12
#      copyright notice, this list of conditions and the following
13
#      disclaimer in the documentation and/or other materials
14
#      provided with the distribution.
15
# 
16
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
# POSSIBILITY OF SUCH DAMAGE.
28
# 
29
# The views and conclusions contained in the software and
30
# documentation are those of the authors and should not be
31
# interpreted as representing official policies, either expressed
32
# or implied, of GRNET S.A.
33

  
34
from django.conf import settings
35

  
36

  
37
class DummyAuthMiddleware(object):
38
    def process_request(self, request):
39
        token = request.META.get('HTTP_X_AUTH_TOKEN', None)
40
        if token is None:
41
            token = request.REQUEST.get('X-Auth-Token', None)
42
        request.user = settings.AUTH_TOKENS.get(token, None)
b/pithos/middleware/__init__.py
1
# Copyright 2011 GRNET S.A. All rights reserved.
2
# 
3
# Redistribution and use in source and binary forms, with or
4
# without modification, are permitted provided that the following
5
# conditions are met:
6
# 
7
#   1. Redistributions of source code must retain the above
8
#      copyright notice, this list of conditions and the following
9
#      disclaimer.
10
# 
11
#   2. Redistributions in binary form must reproduce the above
12
#      copyright notice, this list of conditions and the following
13
#      disclaimer in the documentation and/or other materials
14
#      provided with the distribution.
15
# 
16
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
# POSSIBILITY OF SUCH DAMAGE.
28
# 
29
# The views and conclusions contained in the software and
30
# documentation are those of the authors and should not be
31
# interpreted as representing official policies, either expressed
32
# or implied, of GRNET S.A.
33

  
34
from django.conf import settings
35
from django.core.exceptions import MiddlewareNotUsed
36

  
37
import logging
38
import logging.handlers
39
import logging.config
40

  
41
__all__ = ('LoggingConfigMiddleware',)
42

  
43
class LoggingConfigMiddleware:
44
    def __init__(self):
45
        '''Initialise the logging setup from settings, called on first request.'''
46
        if getattr(settings, 'DEBUG', False):
47
            logging.basicConfig(level = logging.DEBUG, format = '%(asctime)s [%(levelname)s] %(name)s %(message)s', datefmt = '%Y-%m-%d %H:%M:%S')
48
        else:
49
            logging.basicConfig(level = logging.INFO, format = '%(asctime)s [%(levelname)s] %(name)s %(message)s', datefmt = '%Y-%m-%d %H:%M:%S')
50
        raise MiddlewareNotUsed('Logging setup only.')
1
from log import LoggingConfigMiddleware
2
from auth import AuthMiddleware
b/pithos/middleware/auth.py
1
# Copyright 2011 GRNET S.A. All rights reserved.
2
# 
3
# Redistribution and use in source and binary forms, with or
4
# without modification, are permitted provided that the following
5
# conditions are met:
6
# 
7
#   1. Redistributions of source code must retain the above
8
#      copyright notice, this list of conditions and the following
9
#      disclaimer.
10
# 
11
#   2. Redistributions in binary form must reproduce the above
12
#      copyright notice, this list of conditions and the following
13
#      disclaimer in the documentation and/or other materials
14
#      provided with the distribution.
15
# 
16
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
# POSSIBILITY OF SUCH DAMAGE.
28
# 
29
# The views and conclusions contained in the software and
30
# documentation are those of the authors and should not be
31
# interpreted as representing official policies, either expressed
32
# or implied, of GRNET S.A.
33

  
34
from time import time, mktime
35

  
36
from django.conf import settings
37

  
38
from pithos.aai.models import PithosUser
39

  
40

  
41
class AuthMiddleware(object):
42
    def process_request(self, request):
43
        request.user = None
44
        
45
        # Try to find token in a cookie, in a request header, or as a parameter.
46
        token = request.COOKIES.get('X-Auth-Token', None)
47
        if not token:
48
            token = request.META.get('HTTP_X_AUTH_TOKEN', None)
49
        if not token:
50
            token = request.REQUEST.get('X-Auth-Token', None)
51
        if not token:
52
            return
53
        
54
        # Token was found, retrieve user from backing store.
55
        try:
56
            user = PithosUser.objects.get(auth_token=token)
57
        except:
58
            return
59
        
60
        # Check if the token has expired.
61
        if (time() - mktime(user.auth_token_expires.timetuple())) > 0:
62
            return
63
            
64
        request.user = user.uniq
b/pithos/middleware/log.py
1
# Copyright 2011 GRNET S.A. All rights reserved.
2
# 
3
# Redistribution and use in source and binary forms, with or
4
# without modification, are permitted provided that the following
5
# conditions are met:
6
# 
7
#   1. Redistributions of source code must retain the above
8
#      copyright notice, this list of conditions and the following
9
#      disclaimer.
10
# 
11
#   2. Redistributions in binary form must reproduce the above
12
#      copyright notice, this list of conditions and the following
13
#      disclaimer in the documentation and/or other materials
14
#      provided with the distribution.
15
# 
16
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
# POSSIBILITY OF SUCH DAMAGE.
28
# 
29
# The views and conclusions contained in the software and
30
# documentation are those of the authors and should not be
31
# interpreted as representing official policies, either expressed
32
# or implied, of GRNET S.A.
33

  
34
from django.conf import settings
35
from django.core.exceptions import MiddlewareNotUsed
36

  
37
import logging
38

  
39

  
40
class LoggingConfigMiddleware:
41
    def __init__(self):
42
        '''Initialise the logging setup from settings, called on first request.'''
43
        if getattr(settings, 'DEBUG', False):
44
            logging.basicConfig(level = logging.DEBUG, format = '%(asctime)s [%(levelname)s] %(name)s %(message)s', datefmt = '%Y-%m-%d %H:%M:%S')
45
        else:
46
            logging.basicConfig(level = logging.INFO, format = '%(asctime)s [%(levelname)s] %(name)s %(message)s', datefmt = '%Y-%m-%d %H:%M:%S')
47
        raise MiddlewareNotUsed('Logging setup only.')
/dev/null
1
"""
2
This file demonstrates two different styles of tests (one doctest and one
3
unittest). These will both pass when you run "manage.py test".
4

  
5
Replace these with more appropriate tests for your application.
6
"""
7

  
8
from django.test import TestCase
9

  
10
class SimpleTest(TestCase):
11
    def test_basic_addition(self):
12
        """
13
        Tests that 1 + 1 always equals 2.
14
        """
15
        self.failUnlessEqual(1 + 1, 2)
16

  
17
__test__ = {"doctest": """
18
Another way to test that 1 + 1 is equal to 2.
19

  
20
>>> 1 + 1 == 2
21
True
22
"""}
23

  
b/pithos/settings.py.dist
119 119

  
120 120
MIDDLEWARE_CLASSES = (
121 121
    'django.middleware.common.CommonMiddleware',
122
    'django.contrib.sessions.middleware.SessionMiddleware',
122
#    'django.contrib.sessions.middleware.SessionMiddleware',
123 123
#    'django.middleware.csrf.CsrfViewMiddleware',
124
    'django.contrib.auth.middleware.AuthenticationMiddleware',
125
    'django.contrib.messages.middleware.MessageMiddleware',
124
#    'django.contrib.auth.middleware.AuthenticationMiddleware',
125
#    'django.contrib.messages.middleware.MessageMiddleware',
126 126
    'pithos.middleware.LoggingConfigMiddleware',
127
    'pithos.api.auth.DummyAuthMiddleware'
127
    'pithos.middleware.AuthMiddleware'
128 128
)
129 129

  
130 130
ROOT_URLCONF = 'pithos.urls'
......
136 136
)
137 137

  
138 138
INSTALLED_APPS = (
139
    'django.contrib.auth',
140
    'django.contrib.contenttypes',
141
    'django.contrib.sessions',
142
    'django.contrib.sites',
143
    'django.contrib.messages',
139
#    'django.contrib.auth',
140
#    'django.contrib.contenttypes',
141
#    'django.contrib.sessions',
142
#    'django.contrib.sites',
143
#    'django.contrib.messages',
144 144
#    'django.contrib.admin',
145 145
#    'django.contrib.admindocs',
146
    'pithos.aai',
146 147
    'pithos.api',
147 148
    'pithos.public'
148 149
)
149 150

  
150
AUTH_TOKENS = {
151
    '0000': 'test',
152
    '0001': 'verigak',
153
    '0002': 'chazapis',
154
    '0003': 'gtsouk',
155
    '0004': 'papagian',
156
    '0005': 'louridas',
157
    '0006': 'chstath',
158
    '0007': 'pkanavos',
159
    '0008': 'mvasilak'}
151
# Set the expiration time of newly created auth tokens
152
# to be this many hours after their creation time.
153
AUTH_TOKEN_DURATION = 30 * 24
154

  
155
# Default quota for new users.
156
DEFAULT_QUOTA = 10 * 1024 * 1024 * 1024
157

  
/dev/null
1
#coding=utf8
2

  
3
# Copyright 2011 GRNET S.A. All rights reserved.
4
# 
5
# Redistribution and use in source and binary forms, with or
6
# without modification, are permitted provided that the following
7
# conditions are met:
8
# 
9
#   1. Redistributions of source code must retain the above
10
#      copyright notice, this list of conditions and the following
11
#      disclaimer.
12
# 
13
#   2. Redistributions in binary form must reproduce the above
14
#      copyright notice, this list of conditions and the following
15
#      disclaimer in the documentation and/or other materials
16
#      provided with the distribution.
17
# 
18
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
19
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
21
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
22
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
25
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
26
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
28
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29
# POSSIBILITY OF SUCH DAMAGE.
30
# 
31
# The views and conclusions contained in the software and
32
# documentation are those of the authors and should not be
33
# interpreted as representing official policies, either expressed
34
# or implied, of GRNET S.A.
35

  
36
# Django settings for pithos project.
37
import os
38

  
39
PROJECT_PATH = os.path.dirname(os.path.abspath(__file__)) + '/'
40

  
41
DEBUG = True
42
TEMPLATE_DEBUG = DEBUG
43

  
44
TEST = True
45

  
46
ADMINS = (
47
    # ('Your Name', 'your_email@domain.com'),
48
)
49

  
50
MANAGERS = ADMINS
51

  
52
DATABASES = {
53
    'default': {
54
        'ENGINE': 'sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
55
        'NAME': PROJECT_PATH + 'pithos.db',		# Or path to database file if using sqlite3.
56
        'USER': '',                      # Not used with sqlite3.
57
        'PASSWORD': '',                  # Not used with sqlite3.
58
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
59
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
60
    }
61
}
62

  
63
# The backend to use and its initilization options.
64
if TEST:
65
    BACKEND = ('SimpleBackend', (os.path.join(PROJECT_PATH, 'data/test/'),))
66
else:
67
    BACKEND = ('SimpleBackend', (os.path.join(PROJECT_PATH, 'data/pithos/'),))
68

  
69
# Local time zone for this installation. Choices can be found here:
70
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
71
# although not all choices may be available on all operating systems.
72
# On Unix systems, a value of None will cause Django to use the same
73
# timezone as the operating system.
74
# If running in a Windows environment this must be set to the same as your
75
# system time zone.
76
TIME_ZONE = 'UTC'
77

  
78
# Language code for this installation. All choices can be found here:
79
# http://www.i18nguy.com/unicode/language-identifiers.html
80
LANGUAGE_CODE = 'en-us'
81

  
82
SITE_ID = 1
83

  
84
# If you set this to False, Django will make some optimizations so as not
85
# to load the internationalization machinery.
86
USE_I18N = True
87

  
88
# If you set this to False, Django will not format dates, numbers and
89
# calendars according to the current locale
90
USE_L10N = True
91

  
92
# Absolute filesystem path to the directory that will hold user-uploaded files.
93
# Example: "/home/media/media.lawrence.com/"
94
MEDIA_ROOT = ''
95

  
96
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
97
# trailing slash if there is a path component (optional in other cases).
98
# Examples: "http://media.lawrence.com", "http://example.com/media/"
99
MEDIA_URL = ''
100

  
101
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
102
# trailing slash.
103
# Examples: "http://foo.com/media/", "/media/".
104
ADMIN_MEDIA_PREFIX = '/media/'
105

  
106
# Make this unique, and don't share it with anybody.
107
SECRET_KEY = '$j0cdrfm*0sc2j+e@@2f-&3-_@2=^!z#+b-8o4_i10@2%ev7si'
108

  
109
# List of callables that know how to import templates from various sources.
110
TEMPLATE_LOADERS = (
111
    'django.template.loaders.filesystem.Loader',
112
    'django.template.loaders.app_directories.Loader',
113
#     'django.template.loaders.eggs.Loader',
114
)
115

  
116
MIDDLEWARE_CLASSES = (
117
    'django.middleware.common.CommonMiddleware',
118
    'django.contrib.sessions.middleware.SessionMiddleware',
119
#    'django.middleware.csrf.CsrfViewMiddleware',
120
    'django.contrib.auth.middleware.AuthenticationMiddleware',
121
    'django.contrib.messages.middleware.MessageMiddleware',
122
    'pithos.middleware.LoggingConfigMiddleware',
123
    'pithos.api.auth.DummyAuthMiddleware'
124
)
125

  
126
ROOT_URLCONF = 'pithos.urls'
127

  
128
TEMPLATE_DIRS = (
129
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
130
    # Always use forward slashes, even on Windows.
131
    # Don't forget to use absolute paths, not relative paths.
132
)
133

  
134
INSTALLED_APPS = (
135
    'django.contrib.auth',
136
    'django.contrib.contenttypes',
137
    'django.contrib.sessions',
138
    'django.contrib.sites',
139
    'django.contrib.messages',
140
#    'django.contrib.admin',
141
#    'django.contrib.admindocs',
142
    'api',
143
	'public'
144
)
145

  
146
AUTH_TOKENS = {
147
    '0000': 'test',
148
    '0001': 'verigak',
149
    '0002': 'chazapis',
150
    '0003': 'gtsouk',
151
    '0004': 'papagian',
152
    '0005': 'louridas',
153
    '0006': 'chstath',
154
    '0007': 'pkanavos',
155
    '0008': 'mvasilak',
156
    '0009': 'διογένης'}
b/pithos/urls.py
37 37
    (r'^v1(?:$|/)', include('pithos.api.urls')),
38 38
    (r'^v1\.0(?:$|/)', include('pithos.api.urls')),
39 39
    (r'^public(?:$|/)', include('pithos.public.urls')),
40
    (r'^login(?:$|/)', 'pithos.aai.functions.login')
40 41
)

Also available in: Unified diff