Merge remote-tracking branch 'origin/newstyles' into newstyles
authorOlga Brani <olgabrani@grnet.gr>
Fri, 15 Jun 2012 14:39:32 +0000 (17:39 +0300)
committerOlga Brani <olgabrani@grnet.gr>
Fri, 15 Jun 2012 14:39:32 +0000 (17:39 +0300)
82 files changed:
astakos/im/queue.py [deleted file]
docs/build/README [deleted file]
docs/source/backends.rst [deleted file]
docs/source/conf.py [deleted file]
docs/source/devguide.rst [deleted file]
docs/source/forms.rst [deleted file]
docs/source/images/login.jpg [deleted file]
docs/source/images/signup.jpg [deleted file]
docs/source/images/~okeanos.jpg [deleted file]
docs/source/index.rst [deleted file]
docs/source/models.rst [deleted file]
docs/source/views.rst [deleted file]
snf-astakos-app/Changelog
snf-astakos-app/README
snf-astakos-app/astakos/im/activation_backends.py
snf-astakos-app/astakos/im/api/__init__.py [new file with mode: 0644]
snf-astakos-app/astakos/im/api/admin.py [moved from snf-astakos-app/astakos/im/api.py with 81% similarity]
snf-astakos-app/astakos/im/api/faults.py [moved from snf-astakos-app/astakos/im/faults.py with 96% similarity]
snf-astakos-app/astakos/im/api/service.py [new file with mode: 0644]
snf-astakos-app/astakos/im/auth_backends.py
snf-astakos-app/astakos/im/context_processors.py
snf-astakos-app/astakos/im/fixtures/admin_user.json [deleted file]
snf-astakos-app/astakos/im/fixtures/auth_test_data.json [deleted file]
snf-astakos-app/astakos/im/fixtures/groups.json
snf-astakos-app/astakos/im/fixtures/test_user.json [deleted file]
snf-astakos-app/astakos/im/forms.py
snf-astakos-app/astakos/im/functions.py
snf-astakos-app/astakos/im/management/commands/_common.py
snf-astakos-app/astakos/im/management/commands/addgroup.py
snf-astakos-app/astakos/im/management/commands/addgrouppermissions.py [new file with mode: 0644]
snf-astakos-app/astakos/im/management/commands/createuser.py
snf-astakos-app/astakos/im/management/commands/inviteuser.py
snf-astakos-app/astakos/im/management/commands/listgroups.py
snf-astakos-app/astakos/im/management/commands/listinvitations.py
snf-astakos-app/astakos/im/management/commands/listservices.py [new file with mode: 0644]
snf-astakos-app/astakos/im/management/commands/listusers.py
snf-astakos-app/astakos/im/management/commands/modifyuser.py
snf-astakos-app/astakos/im/management/commands/registerservice.py [moved from astakos/im/rabbitmq/queue.py with 70% similarity]
snf-astakos-app/astakos/im/management/commands/removegrouppermissions.py [new file with mode: 0644]
snf-astakos-app/astakos/im/management/commands/renewservicetoken.py [new file with mode: 0644]
snf-astakos-app/astakos/im/management/commands/sendactivation.py
snf-astakos-app/astakos/im/management/commands/showinvitation.py
snf-astakos-app/astakos/im/management/commands/showuser.py
snf-astakos-app/astakos/im/management/commands/unregisterservice.py [moved from astakos/im/rabbitmq/__init__.py with 75% similarity]
snf-astakos-app/astakos/im/middleware.py [new file with mode: 0644]
snf-astakos-app/astakos/im/migrations/0007_auto__chg_field_astakosuser_email_verified__chg_field_astakosuser_has_.py [new file with mode: 0644]
snf-astakos-app/astakos/im/migrations/0007_auto__del_field_invitation_accepted__del_field_invitation_is_accepted.py [new file with mode: 0644]
snf-astakos-app/astakos/im/migrations/0008_auto__add_emailchange.py [new file with mode: 0644]
snf-astakos-app/astakos/im/migrations/0009_auto__add_service.py [new file with mode: 0644]
snf-astakos-app/astakos/im/migrations/0010_auto__add_field_astakosuser_activation_sent__chg_field_service_url.py [new file with mode: 0644]
snf-astakos-app/astakos/im/migrations/0011_set_old_activation_sent.py [new file with mode: 0644]
snf-astakos-app/astakos/im/migrations/0012_auto__add_additionalmail.py [new file with mode: 0644]
snf-astakos-app/astakos/im/models.py
snf-astakos-app/astakos/im/queue/userevent.py
snf-astakos-app/astakos/im/settings.py
snf-astakos-app/astakos/im/static/im/cloudbar/cloudbar.js
snf-astakos-app/astakos/im/static/im/css/custom.css
snf-astakos-app/astakos/im/static/im/js/jquery.infieldlabel.js
snf-astakos-app/astakos/im/synnefo_settings.py
snf-astakos-app/astakos/im/target/local.py
snf-astakos-app/astakos/im/target/redirect.py
snf-astakos-app/astakos/im/target/shibboleth.py
snf-astakos-app/astakos/im/templates/im/account_base.html
snf-astakos-app/astakos/im/templates/im/base.html
snf-astakos-app/astakos/im/templates/im/feedback_mail.txt
snf-astakos-app/astakos/im/templates/im/login_base.html
snf-astakos-app/astakos/im/templates/im/signup.html
snf-astakos-app/astakos/im/templates/im/switch_accounts_email.txt
snf-astakos-app/astakos/im/templates/registration/email_change_confirm.html [new file with mode: 0644]
snf-astakos-app/astakos/im/templates/registration/email_change_done.html [new file with mode: 0644]
snf-astakos-app/astakos/im/templates/registration/email_change_email.txt [new file with mode: 0644]
snf-astakos-app/astakos/im/templates/registration/email_change_form.html [new file with mode: 0644]
snf-astakos-app/astakos/im/templates/registration/logged_out.html
snf-astakos-app/astakos/im/templates/registration/password_reset_complete.html
snf-astakos-app/astakos/im/templates/registration/password_reset_confirm.html
snf-astakos-app/astakos/im/templates/registration/password_reset_done.html
snf-astakos-app/astakos/im/templates/registration/password_reset_form.html
snf-astakos-app/astakos/im/urls.py
snf-astakos-app/astakos/im/util.py
snf-astakos-app/astakos/im/views.py
snf-astakos-app/conf/20-snf-astakos-app-cloudbar.conf
snf-astakos-app/conf/20-snf-astakos-app-settings.conf

diff --git a/astakos/im/queue.py b/astakos/im/queue.py
deleted file mode 100755 (executable)
index a1c08b8..0000000
+++ /dev/null
@@ -1,108 +0,0 @@
-# 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.
-
-import pika
-import json
-import uuid
-
-from urlparse import urlparse
-from time import time
-
-
-def exchange_connect(exchange, vhost='/'):
-    """Format exchange as a URI: rabbitmq://user:pass@host:port/exchange"""
-    parts = urlparse(exchange)
-    if parts.scheme != 'rabbitmq':
-        return None
-    if len(parts.path) < 2 or not parts.path.startswith('/'):
-        return None
-    exchange = parts.path[1:]
-    connection = pika.BlockingConnection(pika.ConnectionParameters(
-                    host=parts.hostname, port=parts.port, virtual_host=vhost,
-                    credentials=pika.PlainCredentials(parts.username, parts.password)))
-    channel = connection.channel()
-    channel.exchange_declare(exchange=exchange, type='topic', durable=True)
-    return (connection, channel, exchange)
-
-def exchange_close(conn):
-    connection, channel, exchange = conn
-    connection.close()
-
-def exchange_send(conn, key, value):
-    """Messages are sent to exchanges at a key."""
-    connection, channel, exchange = conn
-    channel.basic_publish(exchange=exchange,
-                          routing_key=key,
-                          body=json.dumps(value))
-
-    
-def exchange_route(conn, key, queue):
-    """Set up routing of keys to queue."""
-    connection, channel, exchange = conn
-    channel.queue_declare(queue=queue, durable=True,
-                          exclusive=False, auto_delete=False)
-    channel.queue_bind(exchange=exchange,
-                       queue=queue,
-                       routing_key=key)
-
-def queue_callback(conn, queue, cb):
-    
-    def handle_delivery(channel, method_frame, header_frame, body):
-        #print 'Basic.Deliver %s delivery-tag %i: %s' % (header_frame.content_type,
-        #                                                method_frame.delivery_tag,
-        #                                                body)
-        if cb:
-            cb(json.loads(body))
-        channel.basic_ack(delivery_tag=method_frame.delivery_tag)
-    
-    connection, channel, exchange = conn
-    channel.basic_consume(handle_delivery, queue=queue)
-
-def queue_start(conn):
-    connection, channel, exchange = conn
-    channel.start_consuming()
-
-class Receipt(object):
-    def __init__(self, client, user, resource, value, details=None):
-        self.eventVersion = 1
-        self.id = str(uuid.uuid4())
-        self.timestamp = int(time() * 1000)
-        self.clientId = client
-        self.userId = user
-        self.resource = resource
-        self.value = value
-        if details:
-            self.details = details
-    
-    def format(self):
-        return self.__dict__
diff --git a/docs/build/README b/docs/build/README
deleted file mode 100644 (file)
index fc0215c..0000000
+++ /dev/null
@@ -1 +0,0 @@
-This is where the docs will be built.
diff --git a/docs/source/backends.rst b/docs/source/backends.rst
deleted file mode 100644 (file)
index f103e87..0000000
+++ /dev/null
@@ -1,7 +0,0 @@
-Backends
-==============
-
-.. automodule:: astakos.im.backends
-   :show-inheritance:
-   :members:
-   :undoc-members:
diff --git a/docs/source/conf.py b/docs/source/conf.py
deleted file mode 100644 (file)
index 8714897..0000000
+++ /dev/null
@@ -1,223 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# Astakos documentation build configuration file, created by
-# sphinx-quickstart on Wed May 18 12:42:48 2011.
-#
-# This file is execfile()d with the current directory set to its containing dir.
-#
-# Note that not all possible configuration values are present in this
-# autogenerated file.
-#
-# All configuration values have a default; values that are commented out
-# serve to show the default.
-
-import sys, os
-
-# If extensions (or modules to document with autodoc) are in another directory,
-# add these directories to sys.path here. If the directory is relative to the
-# documentation root, use os.path.abspath to make it absolute, like shown here.
-sys.path.insert(0, os.path.abspath('../..'))
-
-from synnefo import settings
-from django.core.management import setup_environ
-setup_environ(settings)
-
-# -- General configuration -----------------------------------------------------
-
-# If your documentation needs a minimal Sphinx version, state it here.
-#needs_sphinx = '1.0'
-
-# Add any Sphinx extension module names here, as strings. They can be extensions
-# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
-extensions = ['sphinx.ext.autodoc', 'sphinx.ext.todo']
-
-# Add any paths that contain templates here, relative to this directory.
-templates_path = ['_templates']
-
-# The suffix of source filenames.
-source_suffix = '.rst'
-
-# The encoding of source files.
-#source_encoding = 'utf-8-sig'
-
-# The master toctree document.
-master_doc = 'index'
-
-# General information about the project.
-project = u'Astakos'
-copyright = u'2011, Astakos Team'
-
-# The version info for the project you're documenting, acts as replacement for
-# |version| and |release|, also used in various other places throughout the
-# built documents.
-#
-# The short X.Y version.
-version = '1'
-# The full version, including alpha/beta/rc tags.
-release = '1'
-
-# The language for content autogenerated by Sphinx. Refer to documentation
-# for a list of supported languages.
-#language = None
-
-# There are two options for replacing |today|: either, you set today to some
-# non-false value, then it is used:
-#today = ''
-# Else, today_fmt is used as the format for a strftime call.
-#today_fmt = '%B %d, %Y'
-
-# List of patterns, relative to source directory, that match files and
-# directories to ignore when looking for source files.
-exclude_patterns = ['_build']
-
-# The reST default role (used for this markup: `text`) to use for all documents.
-#default_role = None
-
-# If true, '()' will be appended to :func: etc. cross-reference text.
-#add_function_parentheses = True
-
-# If true, the current module name will be prepended to all description
-# unit titles (such as .. function::).
-#add_module_names = True
-
-# If true, sectionauthor and moduleauthor directives will be shown in the
-# output. They are ignored by default.
-#show_authors = False
-
-# The name of the Pygments (syntax highlighting) style to use.
-pygments_style = 'sphinx'
-
-# A list of ignored prefixes for module index sorting.
-#modindex_common_prefix = []
-
-
-# -- Options for HTML output ---------------------------------------------------
-
-# The theme to use for HTML and HTML Help pages.  See the documentation for
-# a list of builtin themes.
-html_theme = 'default'
-
-# Theme options are theme-specific and customize the look and feel of a theme
-# further.  For a list of options available for each theme, see the
-# documentation.
-#html_theme_options = {}
-
-# Add any paths that contain custom themes here, relative to this directory.
-#html_theme_path = []
-
-# The name for this set of Sphinx documents.  If None, it defaults to
-# "<project> v<release> documentation".
-#html_title = None
-
-# A shorter title for the navigation bar.  Default is the same as html_title.
-#html_short_title = None
-
-# The name of an image file (relative to this directory) to place at the top
-# of the sidebar.
-#html_logo = None
-
-# The name of an image file (within the static path) to use as favicon of the
-# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
-# pixels large.
-#html_favicon = None
-
-# Add any paths that contain custom static files (such as style sheets) here,
-# relative to this directory. They are copied after the builtin static files,
-# so a file named "default.css" will overwrite the builtin "default.css".
-#html_static_path = ['_static']
-
-# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
-# using the given strftime format.
-#html_last_updated_fmt = '%b %d, %Y'
-
-# If true, SmartyPants will be used to convert quotes and dashes to
-# typographically correct entities.
-#html_use_smartypants = True
-
-# Custom sidebar templates, maps document names to template names.
-#html_sidebars = {}
-
-# Additional templates that should be rendered to pages, maps page names to
-# template names.
-#html_additional_pages = {}
-
-# If false, no module index is generated.
-#html_domain_indices = True
-
-# If false, no index is generated.
-#html_use_index = True
-
-# If true, the index is split into individual pages for each letter.
-#html_split_index = False
-
-# If true, links to the reST sources are added to the pages.
-#html_show_sourcelink = True
-
-# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
-#html_show_sphinx = True
-
-# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
-#html_show_copyright = True
-
-# If true, an OpenSearch description file will be output, and all pages will
-# contain a <link> tag referring to it.  The value of this option must be the
-# base URL from which the finished HTML is served.
-#html_use_opensearch = ''
-
-# This is the file name suffix for HTML files (e.g. ".xhtml").
-#html_file_suffix = None
-
-# Output file base name for HTML help builder.
-htmlhelp_basename = 'Astakosdoc'
-
-
-# -- Options for LaTeX output --------------------------------------------------
-
-# The paper size ('letter' or 'a4').
-#latex_paper_size = 'letter'
-
-# The font size ('10pt', '11pt' or '12pt').
-#latex_font_size = '10pt'
-
-# Grouping the document tree into LaTeX files. List of tuples
-# (source start file, target name, title, author, documentclass [howto/manual]).
-latex_documents = [
-  ('index', 'Astakos.tex', u'Astakos Documentation',
-   u'Astakos Team', 'manual'),
-]
-
-# The name of an image file (relative to this directory) to place at the top of
-# the title page.
-#latex_logo = None
-
-# For "manual" documents, if this is true, then toplevel headings are parts,
-# not chapters.
-#latex_use_parts = False
-
-# If true, show page references after internal links.
-#latex_show_pagerefs = False
-
-# If true, show URL addresses after external links.
-#latex_show_urls = False
-
-# Additional stuff for the LaTeX preamble.
-#latex_preamble = ''
-
-# Documents to append as an appendix to all manuals.
-#latex_appendices = []
-
-# If false, no module index is generated.
-#latex_domain_indices = True
-
-
-# -- Options for manual page output --------------------------------------------
-
-# One entry per manual page. List of tuples
-# (source start file, name, description, authors, manual section).
-man_pages = [
-    ('index', 'astakos', u'Astakos Documentation',
-     [u'Astakos Team'], 1)
-]
-
-
-autodoc_default_flags = ['members']
diff --git a/docs/source/devguide.rst b/docs/source/devguide.rst
deleted file mode 100644 (file)
index d6de4a3..0000000
+++ /dev/null
@@ -1,241 +0,0 @@
-Astakos Developer Guide
-=======================
-
-Introduction
-------------
-
-Astakos serves as the point of authentication for GRNET (http://www.grnet.gr) services. It is a platform-wide service, allowing users to register, login, and keep track of permissions.
-
-Users in astakos can be authenticated via several identity providers:
-
-* Local
-* Shibboleth
-
-It provides also a command line tool for managing user accounts.
-
-It is build over django and extends its authentication mechanism.
-
-This document's goals are:
-
-* present the overall architectural design.
-* provide basic use cases.
-* describe the APIs to the outer world.
-* document the views and provide guidelines for a developer to extend them.
-
-The present document is meant to be read alongside the Django documentation (https://www.djangoproject.com/). Thus, it is suggested that the reader is familiar with associated technologies.
-
-Document Revisions
-^^^^^^^^^^^^^^^^^^
-
-=========================  ================================
-Revision                   Description
-=========================  ================================
-0.1 (Feb 10, 2012)         Initial release.
-=========================  ================================
-
-Overview
---------
-
-Astakos service co-ordinates the access to resources (and the subsequent permission model) and acts as the single point of registry and entry to the GRNET cloud offering, comprising of Cyclades and Pithos subsystems.
-
-It also propagates the user state to the Aquarium pricing subsystem.
-
-.. image:: images/~okeanos.jpg
-
-Registration Use Cases
-----------------------
-
-The following subsections describe two basic registration use cases. All the registration cases are covered in :ref:`registration-flow-label`
-
-Invited user
-^^^^^^^^^^^^
-
-A registered ~okeanos user, invites student Alice to subscribe to ~okeanos services. Alice receives an email and through a link is navigated to Astakos's signup page. The system prompts her to select one of the available authentication mechanisms (Shibboleth or local authentication) in order to register to the system. Alice already has a Shibboleth account so chooses that and then she is redirected to her institution's login page. Upon successful login, her account is created.
-
-Since she is invited his account is automaticaly activated and she is redirected to Astakos's login page. As this is the first time Alice has accessed the system she is redirected to her profile page where she can edit or provide more information.
-
-Not invited user
-^^^^^^^^^^^^^^^^
-
-Tony while browsing in the internet finds out about ~okeanos services. He visits the signup page and since his has not a shibboleth account selects the local authentication mechanism. Upon successful signup the account is created.
-
-Since his not an invited user his account has to be activated from an administrator first, in order to be able to login. Upon the account's activation he receives an email and through a link he is redirected to the login page.
-
-Authentication Use Cases
-------------------------
-
-Cloud service user
-^^^^^^^^^^^^^^^^^^
-
-Alice requests a specific resource from a cloud service ex. Pithos. In the request supplies the `X-Auth-Token`` to identify whether she is eligible to perform the specific task. The service contacts Astakos through its ``/im/authenticate`` api call (see :ref:`authenticate-api-label`) providing the specific ``X-Auth-Token``. Astakos checkes whether the token belongs to an active user and it has not expired and returns a dictionary containing user related information. Finally the service uses the ``uniq`` field included in the dictionary as the account string to identify the user accessible resources. 
-
-.. _registration-flow-label:
-
-Registration Flow
------------------
-
-.. image:: images/signup.jpg
-    :scale: 100%
-
-Login Flow
-----------
-.. image:: images/login.jpg
-    :scale: 100%
-
-.. _authentication-label:
-
-Astakos Users and Authentication
---------------------------------
-
-Astakos incorporates django user authentication system and extends its User model.
-
-Since username field of django User model has a limitation of 30 characters, AstakosUser is **uniquely** identified by the ``email`` instead. Therefore, ``astakos.im.authentication_backends.EmailBackend`` is served to authenticate a user using email if the first argument is actually an email, otherwise tries the username.
-
-A new AstakosUser instance is assigned with a uui as username and also with a ``auth_token`` used by the cloud services to authenticate the user. ``astakos.im.authentication_backends.TokenBackend`` is also specified in order to authenticate the user using the email and the token fields.
-
-Logged on users can perform a number of actions:
-
-* access and edit their profile via: ``/im/profile``.
-* change their password via: ``/im/password``
-* invite somebody else via: ``/im/invite``
-* send feedback for grnet services via: ``/im/feedback``
-* logout (and delete cookie) via: ``/im/logout``
-
-User entries can also be modified/added via the ``snf-manage activateuser`` command.
-
-A superuser account can be created the first time you run the ``manage.py syncdb`` django command and then loading the extra user data from the ``admin_user`` fixture. At a later date, the ``manage.py createsuperuser`` command line utility can be used (as long as the extra user data for Astakos is added with a fixture or by hand).
-
-Internal Astakos requests are handled using cookie-based django user sessions.
-
-External systems in the same domain can delgate ``/login`` URI. The server, depending on its configuration will redirect to the appropriate login page. When done with logging in, the service's login URI should redirect to the URI provided with next, adding user and token parameters, which contain the email and token fields respectively.
-
-The login URI accepts the following parameters:
-
-======================  =========================
-Request Parameter Name  Value
-======================  =========================
-next                    The URI to redirect to when the process is finished
-renew                   Force token renewal (no value parameter)
-force                   Force logout current user (no value parameter)
-======================  =========================
-
-External systems outside the domain scope can acquire the user information by a cookie set identified by ASTAKOS_COOKIE_NAME setting.
-
-Finally, backend systems having acquired a token can use the :ref:`authenticate-api-label` api call from a private network or through HTTPS.
-
-The Astakos API
----------------
-
-.. _authenticate-api-label:
-
-Authenticate
-^^^^^^^^^^^^
-
-Authenticate API requests require a token. An application that wishes to connect to Astakos, but does not have a token, should redirect the user to ``/login``. (see :ref:`authentication-label`)
-
-==================== =========  ==================
-Uri                  Method     Description
-==================== =========  ==================
-``/im/authenticate`` GET        Authenticate user using token
-==================== =========  ==================
-
-|
-
-====================  ===========================
-Request Header Name   Value
-====================  ===========================
-X-Auth-Token          Authentication token
-====================  ===========================
-
-Extended information on the user serialized in the json format will be returned:
-
-===========================  ============================
-Name                         Description
-===========================  ============================
-username                     User uniq identifier
-uniq                         User email (uniq identifier used by Astakos)
-auth_token                   Authentication token
-auth_token_expires           Token expiration date
-auth_token_created           Token creation date
-has_credits                  Whether user has credits
-has_signed_terms             Whether user has aggred on terms
-===========================  ============================
-
-Example reply:
-
-::
-
-  {"userid": "270d191e09834408b7af65885f46a3",
-  "email": ["user111@example.com"],
-  "name": "user1 User1",
-  "auth_token_created": 1333372365000,
-  "auth_token_expires": 1335964365000,
-  "auth_token": "uiWDLAgtJOGW4mI4q9R/8w==",
-  "has_credits": true}
-
-|
-
-=========================== =====================
-Return Code                 Description
-=========================== =====================
-204 (No Content)            The request succeeded
-400 (Bad Request)           The request is invalid
-401 (Unauthorized)          Missing token or inactive user or penging approval terms
-500 (Internal Server Error) The request cannot be completed because of an internal error
-=========================== =====================
-
-Get Services
-^^^^^^^^^^^^
-
-Returns a json formatted list containing information about the supported cloud services.
-
-==================== =========  ==================
-Uri                  Method     Description
-==================== =========  ==================
-``/im/get_services`` GET        Get cloud services
-==================== =========  ==================
-
-Example reply:
-
-::
-
-[{"url": "/", "icon": "home-icon.png", "name": "grnet cloud", "id": "cloud"},
- {"url": "/okeanos.html", "name": "~okeanos", "id": "okeanos"},
- {"url": "/ui/", "name": "pithos+", "id": "pithos"}]
-Get Menu
-^^^^^^^^
-
-Returns a json formatted list containing the cloud bar links. 
-
-==================== =========  ==================
-Uri                  Method     Description
-==================== =========  ==================
-``/im/get_menu``     GET        Get cloud bar menu
-==================== =========  ==================
-
-|
-
-======================  =========================
-Request Parameter Name  Value
-======================  =========================
-location                Location to pass in the next parameter
-======================  =========================
-
-Example reply if request user is not authenticated:
-
-::
-
-[{"url": "/im/login?next=", "name": "login..."}]
-
-Example reply if request user is authenticated:
-
-[{"url": "/im/profile", "name": "spapagian@grnet.gr"},
- {"url": "/im/profile", "name": "view your profile..."},
- {"url": "/im/password", "name": "change your password..."},
- {"url": "/im/feedback", "name": "feedback..."},
- {"url": "/im/logout", "name": "logout..."}]
-
-
-
-
diff --git a/docs/source/forms.rst b/docs/source/forms.rst
deleted file mode 100644 (file)
index b9369d9..0000000
+++ /dev/null
@@ -1,5 +0,0 @@
-Forms
-==============
-
-.. automodule:: astakos.im.forms
-   :show-inheritance:
diff --git a/docs/source/images/login.jpg b/docs/source/images/login.jpg
deleted file mode 100644 (file)
index 8ff1ce0..0000000
Binary files a/docs/source/images/login.jpg and /dev/null differ
diff --git a/docs/source/images/signup.jpg b/docs/source/images/signup.jpg
deleted file mode 100644 (file)
index 35b36c6..0000000
Binary files a/docs/source/images/signup.jpg and /dev/null differ
diff --git a/docs/source/images/~okeanos.jpg b/docs/source/images/~okeanos.jpg
deleted file mode 100644 (file)
index 417dc38..0000000
Binary files a/docs/source/images/~okeanos.jpg and /dev/null differ
diff --git a/docs/source/index.rst b/docs/source/index.rst
deleted file mode 100644 (file)
index 5848db3..0000000
+++ /dev/null
@@ -1,21 +0,0 @@
-Astakos Documentation
-=====================
-
-Contents:
-
-.. toctree::
-   :maxdepth: 3
-   
-   devguide
-   views
-   models
-   forms
-   backends
-
-Indices and tables
-==================
-
-* :ref:`genindex`
-* :ref:`modindex`
-* :ref:`search`
-
diff --git a/docs/source/models.rst b/docs/source/models.rst
deleted file mode 100644 (file)
index d458b25..0000000
+++ /dev/null
@@ -1,7 +0,0 @@
-Models
-==============
-
-.. automodule:: astakos.im.models
-   :show-inheritance:
-   :members:
-   :undoc-members:
diff --git a/docs/source/views.rst b/docs/source/views.rst
deleted file mode 100644 (file)
index 391edc5..0000000
+++ /dev/null
@@ -1,7 +0,0 @@
-Views
-==============
-
-.. automodule:: astakos.im.views
-   :show-inheritance:
-   :members:
-   :undoc-members:
index ef0a3ba..b1a1bff 100644 (file)
@@ -1,33 +1,89 @@
 Changelog
-*********
+---------
+
+v0.6.2
+^^^^^^
+- fixed signup/profile/global user notifications display
+
+
+v0.6.1
+^^^^^^
+- skip csrf on login requests
+
+
+v0.6
+^^^^
+- Fixed default values in cloudbar sample conf file
+- Split api in admin (accessed by superuser and privileged users) and service 
+  (accessed by services)
+- Dynamically register/unregister services 
+  
+  Setting ``ASTAKOS_CLOUD_SERVICES`` is no longer used. You should remove
+  it from astakos configuration file and migrate the old services configuration
+  using ``snf-manage registerservice`` commands::
+
+       $ snf-manage registerservice "grnet cloud" https://okeanos.grnet.gr/ home-icon.png
+       $ snf-manage registerservice "cyclades" https://cyclades.okeanos.grnet.gr/ui/
+       $ snf-manage registerservice "pithos" https://pithos.okeanos.grnet.gr/
+
+- New management tools for assigning groups and permissions to users
+- New feedback api call
+- Save the date user activation sent
+- Save email returned by shibboleth
+- Add logging for main astakos functionality.
+  Logging level controlled by ASTAKOS_LOGGING_LEVEL setting.
+- Email change mechanism
+  Enabled using ASTAKOS_EMAILCHANGE_ENABLED setting (disabled by default)
+- Additional user notification settings
+  ASTAKOS_SIGNUP_MESSAGES, ASTAKOS_PROFILE_MESSAGES, ASTAKOS_GLOBAL_MESSAGES
+
+
+v0.5.1
+^^^^^^
+- Change next parameter to index page in activate url.
+- Fix shibboleth login link.
+
+
+v0.5.0
+^^^^^^
+- Improvements and fixes in shibboleth integration.
+- Minor code refactoring (removed unsed classes/functions).
+- Rate limit integration (requires django-ratelimit).
+- New setting added, ASTAKOS_RATELIMIT_RETRIES_ALLOWED
+- get_menu api call checks the ASTAKOS_COOKIE_NAME instead of the sessionid cookie.
+- Management commands improvements/fixes
+- Altered blank/null parameters for some AstakosUser fields (db migration
+  required, ``snf-manage migrate``)
+- Added user group functionality (initial group data can be loaded using
+  ``snf-manage loaddata groups``)
 
 v0.4.0
-=======
+^^^^^^
 - User terms.
 - Styling fixes/improvements.
 - Configurable recpatcha form field.
 
 
 v0.3.9
-======
+^^^^^^
 - Show user email in feedback email content
 
 
 v0.3.8
-======
+^^^^^^
 - New ASTAKOS_PROFILE_EXTRA_LINKS setting to display additional buttons on
   account pages.
 
 
 v0.3.7
-======
+^^^^^^
 - New ASTAKOS_LOGIN_MESSAGES setting to display messages on the login page
   header
 - login_base.html to make it easy override the login.html template
 
 
 v0.3.5
-======
+^^^^^^
 - New grnet styles
 - New setting for recaptcha to use SSL
 - New menu texts
@@ -35,13 +91,13 @@ v0.3.5
 
 
 v0.3.4
-======
+^^^^^^
 - Updated mail contents
 - Cloudbar improvements
 
 
 v0.3.3
-======
+^^^^^^
 - Updated grnet styles
 - Several styling fixes
 - Display page menu
@@ -52,13 +108,13 @@ v0.3.3
 - Updated snf-common dependency to >=0.9.0
 - New ASTAKOS_RE_USER_EMAIL_PATTERNS setting
 - Support for multiple accounts authentication 
-- New --set-active and --set-inactive in modifyuser command
+- New ^^set-active and ^^set-inactive in modifyuser command
 - Fixed circular redirects when visiting login page from the logout one
 - Removed im.context_processors.cloudbar (now using snf-common processor)
 
 
 v0.3.2
-======
+^^^^^^
 - improved styles of sign up button
 - do not send admin notification email if ASTAKOS_DEFAULT_ADMIN_EMAIL is not 
   set 
@@ -66,7 +122,7 @@ v0.3.2
 
 
 v0.3.1
-======
+^^^^^^
 - bug fixes
 - administrator email notification on sign up 
   (configurable from ASTAKOS_DEFAULT_ADMIN_EMAIL setting)
index 996f8ce..8743a0f 100644 (file)
@@ -40,16 +40,16 @@ Settings
 
 Configure in ``settings.py`` or a ``.conf`` file in ``/etc/synnefo`` if using snf-webproject.
 
-=================================   =============================================================================   ===========================================================================================
+=================================== =============================================================================   ===========================================================================================
 Name                                Default value                                                                   Description
-=================================   =============================================================================   ===========================================================================================
+=================================== =============================================================================   ===========================================================================================
 ASTAKOS_AUTH_TOKEN_DURATION         one month                                                                       Expiration time of newly created auth tokens
 ASTAKOS_DEFAULT_USER_LEVEL          4                                                                               Default (not-invited) user level
 ASTAKOS_INVITATIONS_PER_LEVEL       {0:100, 1:2, 2:0, 3:0, 4:0}                                                     Number of user invitations per user level
 ASTAKOS_DEFAULT_FROM_EMAIL          GRNET Cloud <no-reply\@grnet.gr>                                                ``from`` parameter passed in ``django.core.mail.send_mail``
 ASTAKOS_DEFAULT_CONTACT_EMAIL       support\@cloud.grnet.gr                                                         Contact email
 ASTAKOS_DEFAULT_ADMIN_EMAIL         support\@cloud.grnet.gr                                                         Administrator email to receive user creation notifications (if None disables notifications)
-ASTAKOS_IM_MODULES                  ['local', 'shibboleth']                                              Signup modules
+ASTAKOS_IM_MODULES                  ['local', 'shibboleth']                                                         Signup modules
 ASTAKOS_FORCE_PROFILE_UPDATE        True                                                                            Force user profile verification
 ASTAKOS_INVITATIONS_ENABLED         True                                                                            Enable invitations
 ASTAKOS_COOKIE_NAME                 _pithos2_a                                                                      ``Key`` parameter passed in ``django.http.HttpResponse.set_cookie``
@@ -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
@@ -76,12 +73,15 @@ ASTAKOS_RE_USER_EMAIL_PATTERNS      []
 
 ASTAKOS_LOGIN_MESSAGES              {}                                                                              Notification messages to display on login page header
                                                                                                                     e.g. {'warning': 'Warning message (can contain html)'}
-ASTAKOS_PROFILE_EXTRA_LINKS         {}                                                                               messages to display as extra actions in account forms
+ASTAKOS_PROFILE_EXTRA_LINKS         {}                                                                              Messages to display as extra actions in account forms
                                                                                                                     e.g. {'https://cms.okeanos.grnet.gr/': 'Back to ~okeanos'}
-ASTAKOS_RATELIMIT_RETRIES_ALLOWED   3                                                                               Number of unsuccessful login requests allowed for a specific account.
+ASTAKOS_RATELIMIT_RETRIES_ALLOWED   3                                                                               Number of unsuccessful login requests per minute allowed for a specific account.
                                                                                                                     When this number exceeds and ASTAKOS_RECAPTCHA_ENABLED is set the user has to solve a
                                                                                                                     captcha challenge.
-=================================   =============================================================================   ===========================================================================================
+ASTAKOS_EMAILCHANGE_ENABLED         False                                                                           Enable email change mechanism
+ASTAKOS_EMAILCHANGE_ACTIVATION_DAYS 10                                                                              Number of days that email change requests remain active
+ASTAKOS_LOGGING_LEVEL               INFO                                                                            Message logging severity
+=================================== =============================================================================   ===========================================================================================
 
 Administrator functions
 -----------------------
index 947f620..dc73ed1 100644 (file)
@@ -35,7 +35,6 @@ from django.utils.importlib import import_module
 from django.core.exceptions import ImproperlyConfigured
 from django.core.mail import send_mail
 from django.template.loader import render_to_string
-from django.contrib.sites.models import Site
 from django.contrib import messages
 from django.core.urlresolvers import reverse
 from django.utils.translation import ugettext as _
@@ -46,8 +45,10 @@ from urlparse import urljoin
 from astakos.im.models import AstakosUser, Invitation
 from astakos.im.forms import *
 from astakos.im.util import get_invitation
-from astakos.im.functions import send_verification, send_admin_notification, activate, SendMailError
-from astakos.im.settings import INVITATIONS_ENABLED, DEFAULT_CONTACT_EMAIL, DEFAULT_FROM_EMAIL, MODERATION_ENABLED, SITENAME, DEFAULT_ADMIN_EMAIL, RE_USER_EMAIL_PATTERNS
+from astakos.im.functions import send_verification, send_activation, \
+    send_admin_notification, activate, SendMailError
+from astakos.im.settings import INVITATIONS_ENABLED, DEFAULT_CONTACT_EMAIL, \
+    DEFAULT_FROM_EMAIL, MODERATION_ENABLED, SITENAME, DEFAULT_ADMIN_EMAIL, RE_USER_EMAIL_PATTERNS
 
 import socket
 import logging
@@ -101,7 +102,7 @@ class ActivationBackend(object):
         return globals()[formclass](initial_data, instance=instance, request=request)
     
     def handle_activation(self, user, \
-                          verification_template_name='im/activation_email.txt', \
+                          activation_template_name='im/activation_email.txt', \
                           greeting_template_name='im/welcome_email.txt', \
                           admin_email_template_name='im/admin_notification.txt', \
                           switch_accounts_email_template_name='im/switch_accounts_email.txt'):
@@ -128,7 +129,7 @@ class ActivationBackend(object):
                     activate(user, greeting_template_name)
                     return RegistationCompleted()
                 else:
-                    send_verification(user, verification_template_name)
+                    send_activation(user, activation_template_name)
                     return VerificationSent()
             else:
                 send_admin_notification(user, admin_email_template_name)
diff --git a/snf-astakos-app/astakos/im/api/__init__.py b/snf-astakos-app/astakos/im/api/__init__.py
new file mode 100644 (file)
index 0000000..6bb6daf
--- /dev/null
@@ -0,0 +1,90 @@
+# 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.api.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
similarity index 81%
rename from snf-astakos-app/astakos/im/api.py
rename to snf-astakos-app/astakos/im/api/admin.py
index 4116304..81dbeb4 100644 (file)
@@ -39,18 +39,21 @@ 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
-from astakos.im.models import AstakosUser
-from astakos.im.settings import CLOUD_SERVICES, INVITATIONS_ENABLED, COOKIE_NAME
+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')
 
 def render_fault(request, fault):
     if isinstance(fault, InternalServerError) and settings.DEBUG:
@@ -64,9 +67,11 @@ def render_fault(request, fault):
     response['Content-Length'] = len(response.content)
     return response
 
-def api_method(http_method=None, token_required=False, perms=[]):
+def api_method(http_method=None, token_required=False, perms=None):
     """Decorator function for views that implement an API method."""
-    
+    if not perms:
+        perms = []
+
     def decorator(func):
         @wraps(func)
         def wrapper(request, *args, **kwargs):
@@ -79,8 +84,11 @@ def api_method(http_method=None, token_required=False, perms=[]):
                         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 Unauthorized('Unauthorized request')
+                            raise Forbidden('Unauthorized request')
                     except AstakosUser.DoesNotExist, e:
                         raise Unauthorized('Invalid X-Auth-Token')
                     kwargs['user'] = user
@@ -103,7 +111,7 @@ def authenticate_old(request, user=None):
     #                       unauthorised (401)
     if not user:
         raise BadRequest('No user')
-    
+
     # Check if the is active.
     if not user.is_active:
         raise Unauthorized('User inactive')
@@ -111,10 +119,10 @@ def authenticate_old(request, user=None):
     # 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 = {'username':user.username,
@@ -123,7 +131,8 @@ def authenticate_old(request, user=None):
                  '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()}
+                 '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)
@@ -137,7 +146,7 @@ def authenticate(request, user=None):
     #                       unauthorised (401)
     if not user:
         raise BadRequest('No user')
-    
+
     # Check if the is active.
     if not user.is_active:
         raise Unauthorized('User inactive')
@@ -145,10 +154,10 @@ def authenticate(request, user=None):
     # 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 = {'userid':user.username,
@@ -168,7 +177,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({'id':s.pk, 'name':s.name, 'url':s.url, 'icon':s.icon} for s in services)
+    data = json.dumps(data)
     mimetype = 'application/json'
 
     if callback:
@@ -179,7 +190,6 @@ def get_services(request):
 
 @api_method()
 def get_menu(request, with_extra_links=False, with_signout=True):
-    exclude = []
     index_url = reverse('index')
     absolute = lambda (url): request.build_absolute_uri(url)
     l = [{ 'url': absolute(index_url), 'name': "Sign in"}]
@@ -199,6 +209,9 @@ def get_menu(request, with_extra_links=False, with_signout=True):
             if user.has_usable_password():
                 l.append({ 'url': absolute(reverse('password_change')),
                           'name': "Change password" })
+            if EMAILCHANGE_ENABLED:
+                l.append({'url':absolute(reverse('email_change')),
+                          'name': "Change email"})
             if INVITATIONS_ENABLED:
                 l.append({ 'url': absolute(reverse('astakos.im.views.invite')),
                           'name': "Invitations" })
@@ -207,7 +220,7 @@ def get_menu(request, with_extra_links=False, with_signout=True):
         if with_signout:
             l.append({ 'url': absolute(reverse('astakos.im.views.logout')),
                       'name': "Sign out"})
-    
+
     callback = request.GET.get('callback', None)
     data = json.dumps(tuple(l))
     mimetype = 'application/json'
@@ -218,46 +231,23 @@ 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=['astakos.im.can_find_userid'])
-def find_userid(request):
-    # Normal Response Codes: 204
+@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)
-    email = request.GET.get('email')
-    if not email:
-        raise BadRequest('Email missing')
-    try:
-        user = AstakosUser.objects.get(email = email, is_active=True)
-    except AstakosUser.DoesNotExist, e:
-        raise BadRequest('Invalid email')
-    else:
-        response = HttpResponse()
-        response.status=204
-        user_info = {'userid':user.username}
-        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=['astakos.im.can_find_email'])
-def find_email(request):
-    # Normal Response Codes: 204
+    #                       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)
-    userid = request.GET.get('userid')
-    if not userid:
-        raise BadRequest('Userid missing')
-    try:
-        user = AstakosUser.objects.get(username = userid)
-    except AstakosUser.DoesNotExist, e:
-        raise BadRequest('Invalid userid')
-    else:
-        response = HttpResponse()
-        response.status=204
-        user_info = {'userid':user.email}
-        response.content = json.dumps(user_info)
-        response['Content-Type'] = 'application/json; charset=UTF-8'
-        response['Content-Length'] = len(response.content)
-        return response
+    #                       forbidden (403)
+    #                       itemNotFound (404)
+    return _get_user_by_username(user_id)
similarity index 96%
rename from snf-astakos-app/astakos/im/faults.py
rename to snf-astakos-app/astakos/im/api/faults.py
index e5a5244..72408f1 100644 (file)
@@ -49,3 +49,9 @@ class Unauthorized(Fault):
 
 class InternalServerError(Fault):
     code = 500
+
+class Forbidden(Fault):
+    code = 403
+
+class ItemNotFound(Fault):
+    code = 404
\ No newline at end of file
diff --git a/snf-astakos-app/astakos/im/api/service.py b/snf-astakos-app/astakos/im/api/service.py
new file mode 100644 (file)
index 0000000..fd2be50
--- /dev/null
@@ -0,0 +1,151 @@
+# 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
index ba2f590..0d4c830 100644 (file)
@@ -1,3 +1,36 @@
+# Copyright 2011 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.contrib.auth.backends import ModelBackend
 from django.core.validators import email_re
 
index 01e7ff7..4f63315 100644 (file)
@@ -32,8 +32,9 @@
 # or implied, of GRNET S.A.
 
 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
+        COOKIE_NAME, LOGIN_MESSAGES, SIGNUP_MESSAGES, PROFILE_MESSAGES, \
+        GLOBAL_MESSAGES, PROFILE_EXTRA_LINKS
+from astakos.im.api.admin import get_menu
 from astakos.im.util import get_query
 
 from django.conf import settings
@@ -56,9 +57,15 @@ def media(request):
     return {'IM_STATIC_URL' : IM_STATIC_URL}
 
 def custom_messages(request):
+    EXTRA_MESSAGES_SET = bool(GLOBAL_MESSAGES or SIGNUP_MESSAGES or \
+            LOGIN_MESSAGES or PROFILE_MESSAGES)
     return {
+            'GLOBAL_MESSAGES' : GLOBAL_MESSAGES,
+            'SIGNUP_MESSAGES' : SIGNUP_MESSAGES,
             'LOGIN_MESSAGES' : LOGIN_MESSAGES,
-            'PROFILE_EXTRA_LINKS' : PROFILE_EXTRA_LINKS
+            'PROFILE_MESSAGES' : PROFILE_MESSAGES,
+            'PROFILE_EXTRA_LINKS' : PROFILE_EXTRA_LINKS,
+            'EXTRA_MESSAGES_SET' : EXTRA_MESSAGES_SET
            }
 
 def menu(request):
diff --git a/snf-astakos-app/astakos/im/fixtures/admin_user.json b/snf-astakos-app/astakos/im/fixtures/admin_user.json
deleted file mode 100644 (file)
index 1757ce3..0000000
+++ /dev/null
@@ -1,11 +0,0 @@
-[
-    {
-        "model": "im.AstakosUser",
-        "pk": 1,
-        "fields": {
-            "level": 0,
-            "invitations": 10000,
-            "updated": "2012-01-24"
-       }
-    }
-]
diff --git a/snf-astakos-app/astakos/im/fixtures/auth_test_data.json b/snf-astakos-app/astakos/im/fixtures/auth_test_data.json
deleted file mode 100644 (file)
index 458e43c..0000000
+++ /dev/null
@@ -1,193 +0,0 @@
-[
-    {
-        "model": "auth.user",
-        "pk": 3,
-        "fields": {
-            "username": "verigak",
-            "email": "verigak@example.com",
-            "password": "sha1$84fb5$d7d29831d42611a2ad56c136e4280fdc114539ff",
-            "is_superuser": 1
-        }
-    },
-    {
-        "model": "im.AstakosUser",
-        "pk": 3,
-        "fields": {
-            "level": 0,
-            "invitations": 10000,
-            "auth_token": "0001",
-            "auth_token_created": "2011-04-07 09:17:14",
-            "auth_token_expires": "2015-04-07 09:17:14",
-            "updated": "2011-02-06"
-       }
-    },
-    {
-        "model": "auth.user",
-        "pk": 4,
-        "fields": {
-            "username": "chazapis",
-            "email": "chazapis@example.com",
-            "password": "sha1$84fb5$d7d29831d42611a2ad56c136e4280fdc114539ff",
-            "is_superuser": 1
-        }
-    },
-    {
-        "model": "im.AstakosUser",
-        "pk": 4,
-        "fields": {
-            "level": 1,
-            "invitations": 3,
-            "auth_token": "0002",
-            "auth_token_created": "2011-04-07 09:17:14",
-            "auth_token_expires": "2015-04-07 09:17:14",
-            "updated": "2011-02-06"
-       }
-    },
-    {
-        "model": "auth.user",
-        "pk": 5,
-        "fields": {
-            "username": "gtsouk",
-            "email": "gtsouk@example.com",
-            "password": "sha1$84fb5$d7d29831d42611a2ad56c136e4280fdc114539ff"
-        }
-    },
-    {
-        "model": "im.AstakosUser",
-        "pk": 5,
-        "fields": {
-            "level": 1,
-            "invitations": 3,
-            "auth_token": "0003",
-            "auth_token_created": "2011-04-07 09:17:14",
-            "auth_token_expires": "2015-04-07 09:17:14",
-            "updated": "2011-02-06"
-       }
-    },
-    {
-        "model": "auth.user",
-        "pk": 6,
-        "fields": {
-            "username": "papagian",
-            "email": "papagian@example.com",
-            "password": "sha1$84fb5$d7d29831d42611a2ad56c136e4280fdc114539ff"
-        }
-    },
-    {
-        "model": "im.AstakosUser",
-        "pk": 6,
-        "fields": {
-            "level": 1,
-            "invitations": 3,
-            "auth_token": "0004",
-            "auth_token_created": "2011-04-07 09:17:14",
-            "auth_token_expires": "2015-04-07 09:17:14",
-            "updated": "2011-02-06"
-       }
-    },
-    {
-        "model": "auth.user",
-        "pk": 7,
-        "fields": {
-            "username": "louridas",
-            "email": "louridas@example.com",
-            "password": "sha1$84fb5$d7d29831d42611a2ad56c136e4280fdc114539ff"
-        }
-    },
-    {
-        "model": "im.AstakosUser",
-        "pk": 7,
-        "fields": {
-            "level": 1,
-            "invitations": 3,
-            "auth_token": "0005",
-            "auth_token_created": "2011-04-07 09:17:14",
-            "auth_token_expires": "2015-04-07 09:17:14",
-            "updated": "2011-02-06"
-       }
-    },
-    {
-        "model": "auth.user",
-        "pk": 7,
-        "fields": {
-            "username": "chstath",
-            "email": "chstath@example.com",
-            "password": "sha1$84fb5$d7d29831d42611a2ad56c136e4280fdc114539ff"
-        }
-    },
-    {
-        "model": "im.AstakosUser",
-        "pk": 7,
-        "fields": {
-            "level": 1,
-            "invitations": 3,
-            "auth_token": "0006",
-            "auth_token_created": "2011-04-07 09:17:14",
-            "auth_token_expires": "2015-04-07 09:17:14",
-            "updated": "2011-02-06"
-       }
-    },
-    {
-        "model": "auth.user",
-        "pk": 8,
-        "fields": {
-            "username": "pkanavos",
-            "email": "pkanavos@example.com",
-            "password": "sha1$84fb5$d7d29831d42611a2ad56c136e4280fdc114539ff"
-        }
-    },
-    {
-        "model": "im.AstakosUser",
-        "pk": 8,
-        "fields": {
-            "level": 1,
-            "invitations": 3,
-            "auth_token": "0007",
-            "auth_token_created": "2011-04-07 09:17:14",
-            "auth_token_expires": "2015-04-07 09:17:14",
-            "updated": "2011-02-06"
-       }
-    },
-    {
-        "model": "auth.user",
-        "pk": 8,
-        "fields": {
-            "username": "mvasilak",
-            "email": "mvasilak@example.com",
-            "password": "sha1$84fb5$d7d29831d42611a2ad56c136e4280fdc114539ff"
-        }
-    },
-    {
-        "model": "im.AstakosUser",
-        "pk": 8,
-        "fields": {
-            "level": 1,
-            "invitations": 3,
-            "auth_token": "0008",
-            "auth_token_created": "2011-04-07 09:17:14",
-            "auth_token_expires": "2015-04-07 09:17:14",
-            "updated": "2011-02-06"
-       }
-    },
-    {
-        "model": "auth.user",
-        "pk": 9,
-        "fields": {
-            "username": "διογένης",
-            "email": "diogenis@example.com",
-            "password": "sha1$84fb5$d7d29831d42611a2ad56c136e4280fdc114539ff"
-        }
-    },
-    {
-        "model": "im.AstakosUser",
-        "pk": 9,
-        "fields": {
-            "level": 1,
-            "invitations": 3,
-            "auth_token": "0009",
-            "auth_token_created": "2011-04-07 09:17:14",
-            "auth_token_expires": "2015-04-07 09:17:14",
-            "updated": "2011-02-06"
-       }
-    }
-]
index 472b56e..4b325cf 100644 (file)
         "fields": {
             "name": "shibboleth"
         }
+    },
+    {
+        "model": "auth.group",
+        "pk": 4,
+        "fields": {
+            "name": "helpdesk"
+        }
     }
 ]
diff --git a/snf-astakos-app/astakos/im/fixtures/test_user.json b/snf-astakos-app/astakos/im/fixtures/test_user.json
deleted file mode 100644 (file)
index c51b89b..0000000
+++ /dev/null
@@ -1,23 +0,0 @@
-[
-    {
-        "model": "auth.user",
-        "pk": 2,
-        "fields": {
-            "username": "test",
-            "email": "papagian@gmail.com",
-            "password": "sha1$84fb5$d7d29831d42611a2ad56c136e4280fdc114539ff"
-        }
-    },
-    {
-        "model": "im.AstakosUser",
-        "pk": 2,
-        "fields": {
-            "level": 1,
-            "invitations": 2,
-            "auth_token": "0000",
-            "auth_token_created": "2011-04-07 09:17:14",
-            "auth_token_expires": "2015-04-07 09:17:14",
-            "updated": "2011-02-06"
-       }
-    }
-]
index 958c98d..a8fce76 100644 (file)
@@ -44,16 +44,22 @@ from django.core.urlresolvers import reverse
 from django.utils.functional import lazy
 from django.utils.safestring import mark_safe
 from django.contrib import messages
+from django.utils.encoding import smart_str
 
-from astakos.im.models import AstakosUser, Invitation, get_latest_terms
-from astakos.im.settings import INVITATIONS_PER_LEVEL, DEFAULT_FROM_EMAIL, BASEURL, SITENAME, RECAPTCHA_PRIVATE_KEY, DEFAULT_CONTACT_EMAIL, RECAPTCHA_ENABLED
+from astakos.im.models import AstakosUser, Invitation, get_latest_terms, EmailChange
+from astakos.im.settings import INVITATIONS_PER_LEVEL, DEFAULT_FROM_EMAIL, \
+    BASEURL, SITENAME, RECAPTCHA_PRIVATE_KEY, DEFAULT_CONTACT_EMAIL, \
+    RECAPTCHA_ENABLED, LOGGING_LEVEL
 from astakos.im.widgets import DummyWidget, RecaptchaWidget
+from astakos.im.functions import send_change_email
 
 # since Django 1.4 use django.core.urlresolvers.reverse_lazy instead
 from astakos.im.util import reverse_lazy, reserved_email, get_query
 
 import logging
+import hashlib
 import recaptcha.client.captcha as captcha
+from random import random
 
 logger = logging.getLogger(__name__)
 
@@ -139,7 +145,7 @@ class LocalUserCreationForm(UserCreationForm):
         user.renew_token()
         if commit:
             user.save()
-        logger.info('Created user %s', user)
+            logger._log(LOGGING_LEVEL, 'Created user %s' % user.email, [])
         return user
 
 class InvitedLocalUserCreationForm(LocalUserCreationForm):
@@ -189,7 +195,7 @@ class ThirdPartyUserCreationForm(forms.ModelForm):
         if get_latest_terms():
             self.fields.keyOrder.append('has_signed_terms')
         #set readonly form fields
-        ro = ["third_party_identifier", "first_name", "last_name"]
+        ro = ["third_party_identifier"]
         for f in ro:
             self.fields[f].widget.attrs['readonly'] = True
         
@@ -220,7 +226,7 @@ class ThirdPartyUserCreationForm(forms.ModelForm):
         user.provider = get_query(self.request).get('provider')
         if commit:
             user.save()
-        logger.info('Created user %s', user)
+            logger._log(LOGGING_LEVEL, 'Created user %s' % user.email, [])
         return user
 
 class InvitedThirdPartyUserCreationForm(ThirdPartyUserCreationForm):
@@ -249,11 +255,24 @@ class InvitedThirdPartyUserCreationForm(ThirdPartyUserCreationForm):
         return user
 
 class ShibbolethUserCreationForm(ThirdPartyUserCreationForm):
+    additional_email = forms.CharField(widget=forms.HiddenInput(), label='', required = False)
+    
+    def __init__(self, *args, **kwargs):
+        super(ShibbolethUserCreationForm, self).__init__(*args, **kwargs)
+        self.fields.keyOrder.append('additional_email')
+        # copy email value to additional_mail in case user will change it
+        name = 'email'
+        field = self.fields[name]
+        self.initial['additional_email'] = self.initial.get(name, field.initial)
+    
     def clean_email(self):
         email = self.cleaned_data['email']
         for user in AstakosUser.objects.filter(email = email):
             if user.provider == 'shibboleth':
                 raise forms.ValidationError(_("This email is already associated with another shibboleth account."))
+            elif not user.is_active:
+                raise forms.ValidationError(_("This email is already associated with an inactive account. \
+                                              You need to wait to be activated before being able to switch to a shibboleth account."))
         super(ShibbolethUserCreationForm, self).clean_email()
         return email
 
@@ -389,6 +408,26 @@ class ExtendedPasswordResetForm(PasswordResetForm):
             send_mail(_("Password reset on %s alpha2 testing") % SITENAME,
                 t.render(Context(c)), from_email, [user.email])
 
+class EmailChangeForm(forms.ModelForm):
+    class Meta:
+        model = EmailChange
+        fields = ('new_email_address',)
+            
+    def clean_new_email_address(self):
+        addr = self.cleaned_data['new_email_address']
+        if AstakosUser.objects.filter(email__iexact=addr):
+            raise forms.ValidationError(_(u'This email address is already in use. Please supply a different email address.'))
+        return addr
+    
+    def save(self, email_template_name, request, commit=True):
+        ec = super(EmailChangeForm, self).save(commit=False)
+        ec.user = request.user
+        activation_key = hashlib.sha1(str(random()) + smart_str(ec.new_email_address))
+        ec.activation_key=activation_key.hexdigest()
+        if commit:
+            ec.save()
+        send_change_email(ec, request, email_template_name=email_template_name)
+
 class SignApprovalTermsForm(forms.ModelForm):
     class Meta:
         model = AstakosUser
index b1200c2..877acd4 100644 (file)
@@ -39,16 +39,42 @@ from django.template.loader import render_to_string
 from django.core.mail import send_mail
 from django.core.urlresolvers import reverse
 from django.core.exceptions import ValidationError
+from django.template import Context, loader
+from django.contrib.auth import login as auth_login, logout as auth_logout
+from django.http import HttpRequest
 
 from urllib import quote
 from urlparse import urljoin
 from smtplib import SMTPException
+from datetime import datetime
+from functools import wraps
 
-from astakos.im.settings import DEFAULT_CONTACT_EMAIL, DEFAULT_FROM_EMAIL, SITENAME, BASEURL, DEFAULT_ADMIN_EMAIL
+from astakos.im.settings import DEFAULT_CONTACT_EMAIL, DEFAULT_FROM_EMAIL, \
+    SITENAME, BASEURL, DEFAULT_ADMIN_EMAIL, LOGGING_LEVEL
 from astakos.im.models import Invitation, AstakosUser
 
 logger = logging.getLogger(__name__)
 
+def logged(func, msg):
+    @wraps(func)
+    def with_logging(*args, **kwargs):
+        email = ''
+        user = None
+        if len(args) == 2 and isinstance(args[1], AstakosUser):
+            user = args[1]
+        elif len(args) == 1 and isinstance(args[0], HttpRequest):
+            request = args[0]
+            user = request.user
+        email = user.email if user and user.is_authenticated() else ''
+        r = func(*args, **kwargs)
+        if LOGGING_LEVEL:
+            logger._log(LOGGING_LEVEL, msg % email, [])
+        return r
+    return with_logging
+
+login = logged(auth_login, '%s logged in.')
+logout = logged(auth_logout, '%s logged out.')
+
 def send_verification(user, template_name='im/activation_email.txt'):
     """
     Send email to user to verify his/her email and activate his/her account.
@@ -57,7 +83,7 @@ def send_verification(user, template_name='im/activation_email.txt'):
     """
     url = '%s?auth=%s&next=%s' % (urljoin(BASEURL, reverse('astakos.im.views.activate')),
                                     quote(user.auth_token),
-                                    quote(BASEURL))
+                                    quote(urljoin(BASEURL, reverse('astakos.im.views.index'))))
     message = render_to_string(template_name, {
             'user': user,
             'url': url,
@@ -71,7 +97,13 @@ def send_verification(user, template_name='im/activation_email.txt'):
         logger.exception(e)
         raise SendVerificationError()
     else:
-        logger.info('Sent activation %s', user)
+        msg = 'Sent activation %s' % user.email
+        logger._log(LOGGING_LEVEL, msg, [])
+
+def send_activation(user, template_name='im/activation_email.txt'):
+    send_verification(user, template_name)
+    user.activation_sent = datetime.now()
+    user.save()
 
 def send_admin_notification(user, template_name='im/admin_notification.txt'):
     """
@@ -93,7 +125,8 @@ def send_admin_notification(user, template_name='im/admin_notification.txt'):
         logger.exception(e)
         raise SendNotificationError()
     else:
-        logger.info('Sent admin notification for user %s', user)
+        msg = 'Sent admin notification for user %s' % user.email
+        logger._log(LOGGING_LEVEL, msg, [])
 
 def send_invitation(invitation, template_name='im/invitation.txt'):
     """
@@ -116,7 +149,8 @@ def send_invitation(invitation, template_name='im/invitation.txt'):
         logger.exception(e)
         raise SendInvitationError()
     else:
-        logger.info('Sent invitation %s', invitation)
+        msg = 'Sent invitation %s' % invitation
+        logger._log(LOGGING_LEVEL, msg, [])
 
 def send_greeting(user, email_template_name='im/welcome_email.txt'):
     """
@@ -138,7 +172,8 @@ def send_greeting(user, email_template_name='im/welcome_email.txt'):
         logger.exception(e)
         raise SendGreetingError()
     else:
-        logger.info('Sent greeting %s', user)
+        msg = 'Sent greeting %s' % user.email
+        logger._log(LOGGING_LEVEL, msg, [])
 
 def send_feedback(msg, data, user, email_template_name='im/feedback_mail.txt'):
     subject = _("Feedback from %s alpha2 testing" % SITENAME)
@@ -154,7 +189,25 @@ def send_feedback(msg, data, user, email_template_name='im/feedback_mail.txt'):
         logger.exception(e)
         raise SendFeedbackError()
     else:
-        logger.info('Sent feedback from %s', user.email)
+        msg = 'Sent feedback from %s' % user.email
+        logger._log(LOGGING_LEVEL, msg, [])
+
+def send_change_email(ec, request, email_template_name='registration/email_change_email.txt'):
+    try:
+        url = reverse('email_change_confirm',
+                      kwargs={'activation_key':ec.activation_key})
+        url = request.build_absolute_uri(url)
+        t = loader.get_template(email_template_name)
+        c = {'url': url, 'site_name': SITENAME}
+        from_email = DEFAULT_FROM_EMAIL
+        send_mail(_("Email change on %s alpha2 testing") % SITENAME,
+            t.render(Context(c)), from_email, [ec.new_email_address])
+    except (SMTPException, socket.error) as e:
+        logger.exception(e)
+        raise ChangeEmailError()
+    else:
+        msg = 'Sent change email for %s' % ec.user.email
+        logger._log(LOGGING_LEVEL, msg, [])
 
 def activate(user, email_template_name='im/welcome_email.txt'):
     """
@@ -214,4 +267,9 @@ class SendGreetingError(SendMailError):
 class SendFeedbackError(SendMailError):
     def __init__(self):
         self.message = _('Failed to send feedback')
-        super(SendFeedbackError, self).__init__()
\ No newline at end of file
+        super(SendFeedbackError, self).__init__()
+
+class ChangeEmailError(SendMailError):
+    def __init__(self):
+        self.message = _('Failed to send change email')
+        super(ChangeEmailError, self).__init__()
index 73fe569..0771989 100644 (file)
 from datetime import datetime
 
 from django.utils.timesince import timesince, timeuntil
+from django.contrib.auth.models import Permission
+from django.contrib.contenttypes.models import ContentType
 
 from astakos.im.models import AstakosUser
 
+content_type = None
 
 def get_user(email_or_id, **kwargs):
     try:
@@ -59,3 +62,59 @@ def format_date(d):
         return timesince(d) + ' ago'
     else:
         return 'in ' + timeuntil(d)
+
+def get_astakosuser_content_type():
+    if content_type:
+        return content_type
+    
+    try:
+        return ContentType.objects.get(app_label='im',
+                                       model='astakosuser')
+    except:
+        return content_type
+    
+def add_user_permission(user, pname):
+    content_type = get_astakosuser_content_type()
+    if user.has_perm(pname):
+        return 0, None
+    p, created = Permission.objects.get_or_create(codename=pname,
+                                                  name=pname.capitalize(),
+                                                  content_type=content_type)
+    user.user_permissions.add(p)
+    return 1, created
+
+def add_group_permission(group, pname):
+    content_type = get_astakosuser_content_type()
+    if pname in [p.codename for p in group.permissions.all()]:
+        return 0, None
+    content_type = ContentType.objects.get(app_label='im',
+                                           model='astakosuser')
+    p, created = Permission.objects.get_or_create(codename=pname,
+                                                  name=pname.capitalize(),
+                                                  content_type=content_type)
+    group.permissions.add(p)
+    return 1, created
+
+def remove_user_permission(user, pname):
+    content_type = get_astakosuser_content_type()
+    if user.has_perm(pname):
+        return 0
+    try:
+        p = Permission.objects.get(codename=pname,
+                                    content_type=content_type)
+        user.user_permissions.remove(p)
+        return 1
+    except Permission.DoesNotExist, e:
+        return -1
+
+def remove_group_permission(group, pname):
+    content_type = get_astakosuser_content_type()
+    if pname not in [p.codename for p in group.permissions.all()]:
+        return 0
+    try:
+        p = Permission.objects.get(codename=pname,
+                                    content_type=content_type)
+        group.permissions.remove(p)
+        return 1
+    except Permission.DoesNotExist, e:
+        return -1
\ No newline at end of file
index b37f89f..25620da 100644 (file)
@@ -39,15 +39,16 @@ from time import time
 from os.path import abspath
 
 from django.core.management.base import BaseCommand, CommandError
-
 from django.contrib.auth.models import Group
 
+from ._common import add_group_permission
+
 class Command(BaseCommand):
-    args = "<name>"
+    args = "<groupname> [<permission> ...]"
     help = "Insert group"
     
     def handle(self, *args, **options):
-        if len(args) != 1:
+        if len(args) < 1:
             raise CommandError("Invalid number of arguments")
         
         name = args[0].decode('utf8')
@@ -58,6 +59,16 @@ class Command(BaseCommand):
         except Group.DoesNotExist, e:
             group = Group(name=name)
             group.save()
-        
-        msg = "Created group id %d" % (group.id,)
-        self.stdout.write(msg + '\n')
+            msg = "Created group id %d" % (group.id,)
+            self.stdout.write(msg + '\n')
+            try:
+                for pname in args[1:]:
+                    r, created = add_group_permission(group, pname)
+                    if created:
+                        self.stdout.write('Permission: %s created successfully\n' % pname)
+                    if r == 0:
+                        self.stdout.write('Group has already permission: %s\n' % pname)
+                    else:
+                        self.stdout.write('Permission: %s added successfully\n' % pname)
+            except Exception, e:
+                raise CommandError(e)
\ No newline at end of file
diff --git a/snf-astakos-app/astakos/im/management/commands/addgrouppermissions.py b/snf-astakos-app/astakos/im/management/commands/addgrouppermissions.py
new file mode 100644 (file)
index 0000000..6f6b9b9
--- /dev/null
@@ -0,0 +1,73 @@
+# 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 django.contrib.auth.models import Group, Permission
+from django.contrib.contenttypes.models import ContentType
+from django.core.exceptions import ValidationError
+
+from astakos.im.models import AstakosUser
+from ._common import add_group_permission
+
+class Command(BaseCommand):
+    args = "<groupname> <permission> [<permissions> ...]"
+    help = "Add group permissions"
+    
+    def handle(self, *args, **options):
+        if len(args) < 2:
+            raise CommandError("Please provide a group name and at least one permission")
+        
+        group = None
+        try:
+            if args[0].isdigit():
+                group = Group.objects.get(id=args[0])
+            else:
+                group = Group.objects.get(name=args[0])
+        except Group.DoesNotExist, e:
+            raise CommandError("Invalid group")
+        
+        try:
+            content_type = ContentType.objects.get(app_label='im',
+                                                       model='astakosuser')
+            for pname in args[1:]:
+                r, created = add_group_permission(group, pname)
+                if created:
+                    self.stdout.write('Permission: %s created successfully\n' % pname)
+                if r == 0:
+                    self.stdout.write('Group has already permission: %s\n' % pname)
+                else:
+                    self.stdout.write('Permission: %s added successfully\n' % pname)
+        except Exception, e:
+            raise CommandError(e)
\ No newline at end of file
index 9c21447..749d168 100644 (file)
@@ -41,10 +41,13 @@ from uuid import uuid4
 from django.core.management.base import BaseCommand, CommandError
 from django.core.validators import validate_email
 from django.core.exceptions import ValidationError
+from django.contrib.auth.models import Group
 
 from astakos.im.models import AstakosUser
 from astakos.im.util import reserved_email
 
+from ._common import add_user_permission
+
 class Command(BaseCommand):
     args = "<email> <first name> <last name> <affiliation>"
     help = "Create a user"
@@ -63,7 +66,13 @@ class Command(BaseCommand):
         make_option('--password',
             dest='password',
             metavar='PASSWORD',
-            help="Set user's password")
+            help="Set user's password"),
+        make_option('--add-group',
+            dest='add-group',
+            help="Add user group"),
+        make_option('--add-permission',
+            dest='add-permission',
+            help="Add user permission")
         )
     
     def handle(self, *args, **options):
@@ -108,3 +117,25 @@ class Command(BaseCommand):
             if options['password'] is None:
                 msg += " with password '%s'" % (password,)
             self.stdout.write(msg + '\n')
+            
+            groupname = options.get('add-group')
+            if groupname is not None:
+                try:
+                    group = Group.objects.get(name=groupname)
+                    user.groups.add(group)
+                    self.stdout.write('Group: %s added successfully\n' % groupname)
+                except Group.DoesNotExist, e:
+                    self.stdout.write('Group named %s does not exist\n' % groupname)
+            
+            pname = options.get('add-permission')
+            if pname is not None:
+                try:
+                    r, created = add_user_permission(user, pname)
+                    if created:
+                        self.stdout.write('Permission: %s created successfully\n' % pname)
+                    if r > 0:
+                        self.stdout.write('Permission: %s added successfully\n' % pname)
+                    elif r==0:
+                        self.stdout.write('User has already permission: %s\n' % pname)
+                except Exception, e:
+                    raise CommandError(e)
\ No newline at end of file
index 275bcf5..31dfbe6 100644 (file)
@@ -53,7 +53,9 @@ class Command(BaseCommand):
         
         inviter = get_user(args[0], is_active=True)
         if not inviter:
-            raise CommandError("Unknown or inactive inviter")
+            raise CommandError("Unknown inviter")
+        if  not inviter.is_active:
+            raise CommandError("Inactive inviter")
         
         if inviter.invitations > 0:
             email = args[1]
index 9559aaf..9846370 100644 (file)
@@ -58,8 +58,8 @@ class Command(BaseCommand):
         
         groups = Group.objects.all()
         
-        labels = ('id', 'name')
-        columns = (1, 2)
+        labels = ('id', 'name', 'permissions')
+        columns = (3, 12, 50)
         
         if not options['csv']:
             line = ' '.join(l.rjust(w) for l, w in zip(labels, columns))
@@ -68,7 +68,8 @@ class Command(BaseCommand):
             self.stdout.write(sep + '\n')
         
         for group in groups:
-            fields = (str(group.id), group.name)
+            fields = (str(group.id), group.name,
+                      ','.join(p.codename for p in group.permissions.all()))
             
             if options['csv']:
                 line = '|'.join(fields)
index 191de16..c54e7c9 100644 (file)
@@ -57,7 +57,7 @@ class Command(BaseCommand):
         
         invitations = Invitation.objects.all()
         
-        labels = ('id', 'inviter', 'email', 'real name', 'code', 'used', 'consumed')
+        labels = ('id', 'inviter', 'email', 'real name', 'code', 'consumed')
         columns = (3, 24, 24, 24, 20, 4, 8)
         
         if not options['csv']:
@@ -69,10 +69,9 @@ class Command(BaseCommand):
         for invitation in invitations:
             id = str(invitation.id)
             code = str(invitation.code)
-            used = format_bool(invitation.is_accepted)
             consumed = format_bool(invitation.is_consumed)
             fields = (id, invitation.inviter.email, invitation.username, invitation.realname,
-                      code, used, consumed)
+                      code, consumed)
             
             if options['csv']:
                 line = '|'.join(fields)
diff --git a/snf-astakos-app/astakos/im/management/commands/listservices.py b/snf-astakos-app/astakos/im/management/commands/listservices.py
new file mode 100644 (file)
index 0000000..91cfd21
--- /dev/null
@@ -0,0 +1,76 @@
+# 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', 'auth_token', 'icon')
+        columns = (3, 12, 40, 20, 20)
+
+        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.auth_token,
+                    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')
index 48e78b8..453f4c6 100644 (file)
@@ -54,6 +54,11 @@ class Command(BaseCommand):
             dest='pending',
             default=False,
             help="List only users pending activation"),
+        make_option('-n',
+            action='store_true',
+            dest='pending_send_mail',
+            default=False,
+            help="List only users who have not received activation"),
         )
     
     def handle(self, *args, **options):
@@ -63,9 +68,11 @@ class Command(BaseCommand):
         users = AstakosUser.objects.all()
         if options['pending']:
             users = users.filter(is_active=False)
+        elif options['pending_send_mail']:
+            users = users.filter(is_active=False, activation_sent=None)
         
-        labels = ('id', 'email', 'real name', 'affiliation', 'active', 'admin', 'provider')
-        columns = (3, 24, 24, 12, 6, 5, 12)
+        labels = ('id', 'email', 'real name', 'active', 'admin', 'provider', 'groups')
+        columns = (3, 24, 24, 6, 5, 12, 24)
         
         if not options['csv']:
             line = ' '.join(l.rjust(w) for l, w in zip(labels, columns))
@@ -77,8 +84,8 @@ class Command(BaseCommand):
             id = str(user.id)
             active = format_bool(user.is_active)
             admin = format_bool(user.is_superuser)
-            fields = (id, user.email, user.realname, user.affiliation, active,
-                      admin, user.provider)
+            fields = (id, user.email, user.realname, active, admin, user.provider,
+                      ','.join([g.name for g in user.groups.all()]))
             
             if options['csv']:
                 line = '|'.join(fields)
index a387af9..45a5a8b 100644 (file)
 from optparse import make_option
 
 from django.core.management.base import BaseCommand, CommandError
-from django.contrib.auth.models import Group
+from django.contrib.auth.models import Group, Permission
+from django.contrib.contenttypes.models import ContentType
 from django.core.exceptions import ValidationError
 
-from ._common import get_user
-
 from astakos.im.models import AstakosUser
+from ._common import remove_user_permission, add_user_permission
 
 class Command(BaseCommand):
     args = "<user ID>"
@@ -89,6 +89,12 @@ class Command(BaseCommand):
         make_option('--delete-group',
             dest='delete-group',
             help="Delete user group"),
+        make_option('--add-permission',
+            dest='add-permission',
+            help="Add user permission"),
+        make_option('--delete-permission',
+            dest='delete-permission',
+            help="Delete user permission"),
         )
     
     def handle(self, *args, **options):
@@ -123,7 +129,7 @@ class Command(BaseCommand):
                 group = Group.objects.get(name=groupname)
                 user.groups.add(group)
             except Group.DoesNotExist, e:
-                raise CommandError("Group named %s does not exist." % groupname)
+                self.stdout.write("Group named %s does not exist\n" % groupname)
         
         groupname = options.get('delete-group')
         if groupname is not None:
@@ -131,7 +137,33 @@ class Command(BaseCommand):
                 group = Group.objects.get(name=groupname)
                 user.groups.remove(group)
             except Group.DoesNotExist, e:
-                raise CommandError("Group named %s does not exist." % groupname)
+                self.stdout.write("Group named %s does not exist\n" % groupname)
+        
+        pname = options.get('add-permission')
+        if pname is not None:
+            try:
+                r, created = add_user_permission(user, pname)
+                if created:
+                    self.stdout.write('Permission: %s created successfully\n' % pname)
+                if r > 0:
+                    self.stdout.write('Permission: %s added successfully\n' % pname)
+                elif r==0:
+                    self.stdout.write('User has already permission: %s\n' % pname)
+            except Exception, e:
+                raise CommandError(e)
+        
+        pname  = options.get('delete-permission')
+        if pname is not None and not user.has_perm(pname):
+            try:
+                r = remove_user_permission(user, pname)
+                if r < 0:
+                    self.stdout.write('Invalid permission codename: %s\n' % pname)
+                elif r == 0:
+                    self.stdout.write('User has not permission: %s\n' % pname)
+                elif r > 0:
+                    self.stdout.write('Permission: %s removed successfully\n' % pname)
+            except Exception, e:
+                raise CommandError(e)
         
         level = options.get('level')
         if level is not None:
@@ -1,18 +1,18 @@
 # 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
 # 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 astakos.im.queue import exchange_connect, exchange_send, Receipt
+from django.core.management.base import BaseCommand, CommandError
 
-class Queue(object):
-    """Queue.
-       Required constructor parameters: exchange, message_key, client_id.
-    """
-    
-    def __init__(self, **params):
-        exchange = params['exchange']
-        self.conn = exchange_connect(exchange)
-        self.message_key = params['message_key']
-        self.client_id = params['client_id']
-    
-    def send(self, user, resource, value, details):
-        body = Receipt(self.client_id, user, resource, value, details).format()
-        exchange_send(self.conn, self.message_key, body)
+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
diff --git a/snf-astakos-app/astakos/im/management/commands/removegrouppermissions.py b/snf-astakos-app/astakos/im/management/commands/removegrouppermissions.py
new file mode 100644 (file)
index 0000000..5ead6b0
--- /dev/null
@@ -0,0 +1,70 @@
+# 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 django.contrib.auth.models import Group
+from django.core.exceptions import ValidationError
+
+from astakos.im.models import AstakosUser
+from ._common import remove_group_permission
+
+class Command(BaseCommand):
+    args = "<groupname> <permission> [<permissions> ...]"
+    help = "Remove group permissions"
+    
+    def handle(self, *args, **options):
+        if len(args) < 2:
+            raise CommandError("Please provide a group name and at least one permission")
+        
+        group = None
+        try:
+            if args[0].isdigit():
+                group = Group.objects.get(id=args[0])
+            else:
+                group = Group.objects.get(name=args[0])
+        except Group.DoesNotExist, e:
+            raise CommandError("Invalid group")
+        
+        try:
+            for pname in args[1:]:
+                r = remove_group_permission(group, pname)
+                if r < 0:
+                    self.stdout.write('Invalid permission codename: %s\n' % pname)
+                elif r == 0:
+                    self.stdout.write('Group has not permission: %s\n' % pname)
+                elif r > 0:
+                    self.stdout.write('Permission: %s removed successfully\n' % pname)
+        except Exception, e:
+            raise CommandError(e)
\ No newline at end of file
diff --git a/snf-astakos-app/astakos/im/management/commands/renewservicetoken.py b/snf-astakos-app/astakos/im/management/commands/renewservicetoken.py
new file mode 100644 (file)
index 0000000..19e889a
--- /dev/null
@@ -0,0 +1,54 @@
+# 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
index fb4c1ef..e4d4060 100644 (file)
@@ -33,7 +33,7 @@
 
 from django.core.management.base import BaseCommand, CommandError
 
-from astakos.im.functions import send_verification, SendMailError
+from astakos.im.functions import send_activation, SendMailError
 
 from ._common import get_user
 
@@ -48,11 +48,14 @@ class Command(BaseCommand):
         for email_or_id in args:
             user = get_user(email_or_id, is_active=False)
             if not user:
-                self.stderr.write("Unknown or already active user '%s'\n" % (email_or_id,))
+                self.stderr.write("Unknown user '%s'\n" % (email_or_id,))
+                continue
+            if user.is_active:
+                self.stderr.write("Already active user '%s'\n" % (email_or_id,))
                 continue
             
             try:
-                send_verification(user)
+                send_activation(user)
             except SendMailError, e:
                 raise CommandError(e.message)
             
index 2e136d0..8dba065 100644 (file)
@@ -56,10 +56,8 @@ class Command(BaseCommand):
             'real name': invitation.realname,
             'email': invitation.username,
             'code': invitation.code,
-            'accepted': format_bool(invitation.is_accepted),
             'consumed': format_bool(invitation.is_consumed),
             'date created': format_date(invitation.created),
-            'date accepted': format_date(invitation.accepted),
             'date consumed': format_date(invitation.consumed),
             'inviter real name': invitation.inviter.realname,
             'invitater email': invitation.inviter.email,
index 598adaf..fa393df 100644 (file)
@@ -33,7 +33,7 @@
 
 from django.core.management.base import BaseCommand, CommandError
 
-from astakos.im.models import AstakosUser
+from astakos.im.models import AstakosUser, get_latest_terms
 
 from ._common import format_bool, format_date
 
@@ -67,19 +67,26 @@ class Command(BaseCommand):
                 'last login': format_date(user.last_login),
                 'date joined': format_date(user.date_joined),
                 'last update': format_date(user.updated),
-                'token': user.auth_token,
+                #'token': user.auth_token,
                 'token expiration': format_date(user.auth_token_expires),
                 'invitations': user.invitations,
                 'invitation level': user.level,
                 'provider': user.provider,
                 'verified': format_bool(user.is_verified),
                 'has_credits': format_bool(user.has_credits),
-                'has_signed_terms': format_bool(user.has_signed_terms),
-                'date_signed_terms': format_date(user.date_signed_terms),
                 'groups': [elem.name for elem in user.groups.all()],
+                'permissions': [elem.codename for elem in user.user_permissions.all()],
+                'group_permissions': user.get_group_permissions(),
                 'third_party_identifier': user.third_party_identifier,
-                'email_verified': format_bool(user.email_verified)
+                'email_verified': format_bool(user.email_verified),
+                'username': user.username,
+                'activation_sent_date': format_date(user.activation_sent)
             }
+            if get_latest_terms():
+                has_signed_terms = user.signed_terms()
+                kv['has_signed_terms'] = format_bool(has_signed_terms)
+                if has_signed_terms:
+                    kv['date_signed_terms'] = format_date(user.date_signed_terms)
             
             for key, val in sorted(kv.items()):
                 line = '%s: %s\n' % (key.rjust(22), val)
@@ -1,18 +1,18 @@
 # 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
 # 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 queue import Queue
+from django.core.management.base import BaseCommand, CommandError
 
-__all__ = ["Queue"]
+from astakos.im.models import Service
 
+class Command(BaseCommand):
+    args = "<name>"
+    help = "Unregister a service"
+    
+    def handle(self, *args, **options):
+        if len(args) < 1:
+            raise CommandError("Invalid number of arguments")
+        
+        try:
+            service = Service.objects.get(name=args[0])
+            service.delete()
+        except Service.DoesNotExist, e:
+            raise CommandError(e)
\ No newline at end of file
diff --git a/snf-astakos-app/astakos/im/middleware.py b/snf-astakos-app/astakos/im/middleware.py
new file mode 100644 (file)
index 0000000..898f03b
--- /dev/null
@@ -0,0 +1,59 @@
+# Copyright 2011 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 urllib import unquote
+from django.contrib.auth import authenticate
+
+from astakos.im.settings import COOKIE_NAME
+from astakos.im.models import AstakosUser
+from astakos.im.functions import login
+
+class CookieAuthenticationMiddleware(object):
+    def process_request(self, request):
+        assert hasattr(request, 'session'), "The Django authentication middleware requires session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'."
+        if request.user.is_authenticated():
+            return None
+        
+        cookie = unquote(request.COOKIES.get(COOKIE_NAME, ''))
+        email, sep, auth_token = cookie.partition('|')
+        if not sep:
+            return None
+        
+        try:
+            user = authenticate(email=email, auth_token=auth_token)
+            if user:
+                request.user = user
+            login(request, user)
+        except:
+            pass
+        return None
\ No newline at end of file
diff --git a/snf-astakos-app/astakos/im/migrations/0007_auto__chg_field_astakosuser_email_verified__chg_field_astakosuser_has_.py b/snf-astakos-app/astakos/im/migrations/0007_auto__chg_field_astakosuser_email_verified__chg_field_astakosuser_has_.py
new file mode 100644 (file)
index 0000000..5aa8322
--- /dev/null
@@ -0,0 +1,133 @@
+# encoding: utf-8
+import datetime
+from south.db import db
+from south.v2 import SchemaMigration
+from django.db import models
+
+class Migration(SchemaMigration):
+    
+    def forwards(self, orm):
+        
+        # Changing field 'AstakosUser.email_verified'
+        db.alter_column('im_astakosuser', 'email_verified', self.gf('django.db.models.fields.BooleanField')(blank=True))
+
+        # Changing field 'AstakosUser.has_credits'
+        db.alter_column('im_astakosuser', 'has_credits', self.gf('django.db.models.fields.BooleanField')(blank=True))
+
+        # Changing field 'AstakosUser.date_signed_terms'
+        db.alter_column('im_astakosuser', 'date_signed_terms', self.gf('django.db.models.fields.DateTimeField')(null=True, blank=True))
+
+        # Changing field 'AstakosUser.is_verified'
+        db.alter_column('im_astakosuser', 'is_verified', self.gf('django.db.models.fields.BooleanField')(blank=True))
+
+        # Changing field 'AstakosUser.has_signed_terms'
+        db.alter_column('im_astakosuser', 'has_signed_terms', self.gf('django.db.models.fields.BooleanField')(blank=True))
+
+        # Changing field 'Invitation.is_accepted'
+        db.alter_column('im_invitation', 'is_accepted', self.gf('django.db.models.fields.BooleanField')(blank=True))
+
+        # Changing field 'Invitation.is_consumed'
+        db.alter_column('im_invitation', 'is_consumed', self.gf('django.db.models.fields.BooleanField')(blank=True))
+    
+    
+    def backwards(self, orm):
+        
+        # Changing field 'AstakosUser.email_verified'
+        db.alter_column('im_astakosuser', 'email_verified', self.gf('django.db.models.fields.BooleanField')())
+
+        # Changing field 'AstakosUser.has_credits'
+        db.alter_column('im_astakosuser', 'has_credits', self.gf('django.db.models.fields.BooleanField')())
+
+        # Changing field 'AstakosUser.date_signed_terms'
+        db.alter_column('im_astakosuser', 'date_signed_terms', self.gf('django.db.models.fields.DateTimeField')(null=True))
+
+        # Changing field 'AstakosUser.is_verified'
+        db.alter_column('im_astakosuser', 'is_verified', self.gf('django.db.models.fields.BooleanField')())
+
+        # Changing field 'AstakosUser.has_signed_terms'
+        db.alter_column('im_astakosuser', 'has_signed_terms', self.gf('django.db.models.fields.BooleanField')())
+
+        # Changing field 'Invitation.is_accepted'
+        db.alter_column('im_invitation', 'is_accepted', self.gf('django.db.models.fields.BooleanField')())
+
+        # Changing field 'Invitation.is_consumed'
+        db.alter_column('im_invitation', 'is_consumed', self.gf('django.db.models.fields.BooleanField')())
+    
+    
+    models = {
+        'auth.group': {
+            'Meta': {'object_name': 'Group'},
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
+            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
+        },
+        'auth.permission': {
+            'Meta': {'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
+            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
+        },
+        'auth.user': {
+            'Meta': {'object_name': 'User'},
+            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
+            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
+            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
+            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}),
+            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
+            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
+            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
+            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
+            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
+            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
+            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
+        },
+        'contenttypes.contenttype': {
+            'Meta': {'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
+            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
+        },
+        'im.approvalterms': {
+            'Meta': {'object_name': 'ApprovalTerms'},
+            'date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2012, 5, 3, 11, 47, 35, 79841)', 'db_index': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'location': ('django.db.models.fields.CharField', [], {'max_length': '255'})
+        },
+        'im.astakosuser': {
+            'Meta': {'object_name': 'AstakosUser', '_ormbases': ['auth.User']},
+            'affiliation': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
+            'auth_token': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'blank': 'True'}),
+            'auth_token_created': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
+            'auth_token_expires': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
+            'date_signed_terms': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
+            'email_verified': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
+            'has_credits': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
+            'has_signed_terms': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
+            'invitations': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
+            'is_verified': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
+            'level': ('django.db.models.fields.IntegerField', [], {'default': '4'}),
+            'provider': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
+            'third_party_identifier': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
+            'updated': ('django.db.models.fields.DateTimeField', [], {}),
+            'user_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True', 'primary_key': 'True'})
+        },
+        'im.invitation': {
+            'Meta': {'object_name': 'Invitation'},
+            'accepted': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
+            'code': ('django.db.models.fields.BigIntegerField', [], {'db_index': 'True'}),
+            'consumed': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
+            'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'inviter': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'invitations_sent'", 'null': 'True', 'to': "orm['im.AstakosUser']"}),
+            'is_accepted': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
+            'is_consumed': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
+            'realname': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
+            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'})
+        }
+    }
+    
+    complete_apps = ['im']
diff --git a/snf-astakos-app/astakos/im/migrations/0007_auto__del_field_invitation_accepted__del_field_invitation_is_accepted.py b/snf-astakos-app/astakos/im/migrations/0007_auto__del_field_invitation_accepted__del_field_invitation_is_accepted.py
new file mode 100644 (file)
index 0000000..632938b
--- /dev/null
@@ -0,0 +1,101 @@
+# encoding: utf-8
+import datetime
+from south.db import db
+from south.v2 import SchemaMigration
+from django.db import models
+
+class Migration(SchemaMigration):
+
+    def forwards(self, orm):
+        
+        # Deleting field 'Invitation.accepted'
+        db.delete_column('im_invitation', 'accepted')
+
+        # Deleting field 'Invitation.is_accepted'
+        db.delete_column('im_invitation', 'is_accepted')
+
+
+    def backwards(self, orm):
+        
+        # Adding field 'Invitation.accepted'
+        db.add_column('im_invitation', 'accepted', self.gf('django.db.models.fields.DateTimeField')(null=True, blank=True), keep_default=False)
+
+        # Adding field 'Invitation.is_accepted'
+        db.add_column('im_invitation', 'is_accepted', self.gf('django.db.models.fields.BooleanField')(default=False), keep_default=False)
+
+
+    models = {
+        'auth.group': {
+            'Meta': {'object_name': 'Group'},
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
+            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
+        },
+        'auth.permission': {
+            'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
+            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
+        },
+        'auth.user': {
+            'Meta': {'object_name': 'User'},
+            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
+            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
+            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
+            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
+            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
+            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
+            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
+            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
+            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
+        },
+        'contenttypes.contenttype': {
+            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
+            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
+        },
+        'im.approvalterms': {
+            'Meta': {'object_name': 'ApprovalTerms'},
+            'date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2012, 5, 2, 16, 5, 29, 565763)', 'db_index': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'location': ('django.db.models.fields.CharField', [], {'max_length': '255'})
+        },
+        'im.astakosuser': {
+            'Meta': {'object_name': 'AstakosUser', '_ormbases': ['auth.User']},
+            'affiliation': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
+            'auth_token': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'blank': 'True'}),
+            'auth_token_created': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
+            'auth_token_expires': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
+            'date_signed_terms': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
+            'email_verified': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'has_credits': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'has_signed_terms': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'invitations': ('django.db.models.fields.IntegerField', [], {'default': '100'}),
+            'is_verified': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'level': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
+            'provider': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
+            'third_party_identifier': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
+            'updated': ('django.db.models.fields.DateTimeField', [], {}),
+            'user_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True', 'primary_key': 'True'})
+        },
+        'im.invitation': {
+            'Meta': {'object_name': 'Invitation'},
+            'code': ('django.db.models.fields.BigIntegerField', [], {'db_index': 'True'}),
+            'consumed': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
+            'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'inviter': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'invitations_sent'", 'null': 'True', 'to': "orm['im.AstakosUser']"}),
+            'is_consumed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'realname': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
+            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'})
+        }
+    }
+
+    complete_apps = ['im']
diff --git a/snf-astakos-app/astakos/im/migrations/0008_auto__add_emailchange.py b/snf-astakos-app/astakos/im/migrations/0008_auto__add_emailchange.py
new file mode 100644 (file)
index 0000000..7b460d6
--- /dev/null
@@ -0,0 +1,110 @@
+# encoding: utf-8
+import datetime
+from south.db import db
+from south.v2 import SchemaMigration
+from django.db import models
+
+class Migration(SchemaMigration):
+
+    def forwards(self, orm):
+        
+        # Adding model 'EmailChange'
+        db.create_table('im_emailchange', (
+            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
+            ('new_email_address', self.gf('django.db.models.fields.EmailField')(max_length=75)),
+            ('user', self.gf('django.db.models.fields.related.ForeignKey')(related_name='emailchange_user', unique=True, to=orm['im.AstakosUser'])),
+            ('requested_at', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime(2012, 5, 3, 12, 23, 46, 711119))),
+            ('activation_key', self.gf('django.db.models.fields.CharField')(unique=True, max_length=40, db_index=True)),
+        ))
+        db.send_create_signal('im', ['EmailChange'])
+
+
+    def backwards(self, orm):
+        
+        # Deleting model 'EmailChange'
+        db.delete_table('im_emailchange')
+
+
+    models = {
+        'auth.group': {
+            'Meta': {'object_name': 'Group'},
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
+            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
+        },
+        'auth.permission': {
+            'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
+            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
+        },
+        'auth.user': {
+            'Meta': {'object_name': 'User'},
+            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
+            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
+            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
+            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
+            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
+            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
+            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
+            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
+            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
+        },
+        'contenttypes.contenttype': {
+            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
+            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
+        },
+        'im.approvalterms': {
+            'Meta': {'object_name': 'ApprovalTerms'},
+            'date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2012, 5, 3, 12, 23, 46, 709576)', 'db_index': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'location': ('django.db.models.fields.CharField', [], {'max_length': '255'})
+        },
+        'im.astakosuser': {
+            'Meta': {'object_name': 'AstakosUser', '_ormbases': ['auth.User']},
+            'affiliation': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
+            'auth_token': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'blank': 'True'}),
+            'auth_token_created': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
+            'auth_token_expires': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
+            'date_signed_terms': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
+            'email_verified': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'has_credits': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'has_signed_terms': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'invitations': ('django.db.models.fields.IntegerField', [], {'default': '100'}),
+            'is_verified': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'level': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
+            'provider': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
+            'third_party_identifier': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
+            'updated': ('django.db.models.fields.DateTimeField', [], {}),
+            'user_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True', 'primary_key': 'True'})
+        },
+        'im.emailchange': {
+            'Meta': {'object_name': 'EmailChange'},
+            'activation_key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '40', 'db_index': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'new_email_address': ('django.db.models.fields.EmailField', [], {'max_length': '75'}),
+            'requested_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2012, 5, 3, 12, 23, 46, 711119)'}),
+            'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'emailchange_user'", 'unique': 'True', 'to': "orm['im.AstakosUser']"})
+        },
+        'im.invitation': {
+            'Meta': {'object_name': 'Invitation'},
+            'code': ('django.db.models.fields.BigIntegerField', [], {'db_index': 'True'}),
+            'consumed': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
+            'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'inviter': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'invitations_sent'", 'null': 'True', 'to': "orm['im.AstakosUser']"}),
+            'is_consumed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'realname': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
+            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'})
+        }
+    }
+
+    complete_apps = ['im']
diff --git a/snf-astakos-app/astakos/im/migrations/0009_auto__add_service.py b/snf-astakos-app/astakos/im/migrations/0009_auto__add_service.py
new file mode 100644 (file)
index 0000000..3c5931a
--- /dev/null
@@ -0,0 +1,122 @@
+# encoding: utf-8
+import datetime
+from south.db import db
+from south.v2 import SchemaMigration
+from django.db import models
+
+class Migration(SchemaMigration):
+
+    def forwards(self, orm):
+        
+        # Adding model 'Service'
+        db.create_table('im_service', (
+            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
+            ('name', self.gf('django.db.models.fields.CharField')(unique=True, max_length=255)),
+            ('url', self.gf('django.db.models.fields.URLField')(max_length=200)),
+            ('icon', self.gf('django.db.models.fields.FilePathField')(max_length=100)),
+            ('auth_token', self.gf('django.db.models.fields.CharField')(max_length=32, null=True, blank=True)),
+            ('auth_token_created', self.gf('django.db.models.fields.DateTimeField')(null=True)),
+            ('auth_token_expires', self.gf('django.db.models.fields.DateTimeField')(null=True)),
+        ))
+        db.send_create_signal('im', ['Service'])
+
+
+    def backwards(self, orm):
+        
+        # Deleting model 'Service'
+        db.delete_table('im_service')
+
+
+    models = {
+        'auth.group': {
+            'Meta': {'object_name': 'Group'},
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
+            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
+        },
+        'auth.permission': {
+            'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
+            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
+        },
+        'auth.user': {
+            'Meta': {'object_name': 'User'},
+            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
+            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
+            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
+            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
+            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
+            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
+            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
+            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
+            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
+        },
+        'contenttypes.contenttype': {
+            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
+            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
+        },
+        'im.approvalterms': {
+            'Meta': {'object_name': 'ApprovalTerms'},
+            'date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2012, 5, 21, 15, 21, 13, 352838)', 'db_index': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'location': ('django.db.models.fields.CharField', [], {'max_length': '255'})
+        },
+        'im.astakosuser': {
+            'Meta': {'object_name': 'AstakosUser', '_ormbases': ['auth.User']},
+            'affiliation': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
+            'auth_token': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'blank': 'True'}),
+            'auth_token_created': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
+            'auth_token_expires': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
+            'date_signed_terms': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
+            'email_verified': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'has_credits': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'has_signed_terms': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'invitations': ('django.db.models.fields.IntegerField', [], {'default': '100'}),
+            'is_verified': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'level': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
+            'provider': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
+            'third_party_identifier': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
+            'updated': ('django.db.models.fields.DateTimeField', [], {}),
+            'user_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True', 'primary_key': 'True'})
+        },
+        'im.emailchange': {
+            'Meta': {'object_name': 'EmailChange'},
+            'activation_key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '40', 'db_index': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'new_email_address': ('django.db.models.fields.EmailField', [], {'max_length': '75'}),
+            'requested_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2012, 5, 21, 15, 21, 13, 354390)'}),
+            'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'emailchange_user'", 'unique': 'True', 'to': "orm['im.AstakosUser']"})
+        },
+        'im.invitation': {
+            'Meta': {'object_name': 'Invitation'},
+            'code': ('django.db.models.fields.BigIntegerField', [], {'db_index': 'True'}),
+            'consumed': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
+            'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'inviter': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'invitations_sent'", 'null': 'True', 'to': "orm['im.AstakosUser']"}),
+            'is_consumed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'realname': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
+            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'})
+        },
+        'im.service': {
+            'Meta': {'object_name': 'Service'},
+            'auth_token': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'blank': 'True'}),
+            'auth_token_created': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
+            'auth_token_expires': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
+            'icon': ('django.db.models.fields.FilePathField', [], {'max_length': '100'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
+            'url': ('django.db.models.fields.URLField', [], {'max_length': '200'})
+        }
+    }
+
+    complete_apps = ['im']
diff --git a/snf-astakos-app/astakos/im/migrations/0010_auto__add_field_astakosuser_activation_sent__chg_field_service_url.py b/snf-astakos-app/astakos/im/migrations/0010_auto__add_field_astakosuser_activation_sent__chg_field_service_url.py
new file mode 100644 (file)
index 0000000..c9bd539
--- /dev/null
@@ -0,0 +1,120 @@
+# encoding: utf-8
+import datetime
+from south.db import db
+from south.v2 import SchemaMigration
+from django.db import models
+
+class Migration(SchemaMigration):
+
+    def forwards(self, orm):
+        
+        # Adding field 'AstakosUser.activation_sent'
+        db.add_column('im_astakosuser', 'activation_sent', self.gf('django.db.models.fields.DateTimeField')(null=True, blank=True), keep_default=False)
+
+        # Changing field 'Service.url'
+        db.alter_column('im_service', 'url', self.gf('django.db.models.fields.FilePathField')(max_length=100))
+
+
+    def backwards(self, orm):
+        
+        # Deleting field 'AstakosUser.activation_sent'
+        db.delete_column('im_astakosuser', 'activation_sent')
+
+        # Changing field 'Service.url'
+        db.alter_column('im_service', 'url', self.gf('django.db.models.fields.URLField')(max_length=200))
+
+
+    models = {
+        'auth.group': {
+            'Meta': {'object_name': 'Group'},
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
+            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
+        },
+        'auth.permission': {
+            'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
+            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
+        },
+        'auth.user': {
+            'Meta': {'object_name': 'User'},
+            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
+            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
+            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
+            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
+            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
+            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
+            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
+            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
+            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
+        },
+        'contenttypes.contenttype': {
+            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
+            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
+        },
+        'im.approvalterms': {
+            'Meta': {'object_name': 'ApprovalTerms'},
+            'date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2012, 5, 30, 9, 16, 18, 742353)', 'db_index': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'location': ('django.db.models.fields.CharField', [], {'max_length': '255'})
+        },
+        'im.astakosuser': {
+            'Meta': {'object_name': 'AstakosUser', '_ormbases': ['auth.User']},
+            'activation_sent': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
+            'affiliation': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
+            'auth_token': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'blank': 'True'}),
+            'auth_token_created': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
+            'auth_token_expires': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
+            'date_signed_terms': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
+            'email_verified': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'has_credits': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'has_signed_terms': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'invitations': ('django.db.models.fields.IntegerField', [], {'default': '100'}),
+            'is_verified': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'level': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
+            'provider': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
+            'third_party_identifier': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
+            'updated': ('django.db.models.fields.DateTimeField', [], {}),
+            'user_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True', 'primary_key': 'True'})
+        },
+        'im.emailchange': {
+            'Meta': {'object_name': 'EmailChange'},
+            'activation_key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '40', 'db_index': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'new_email_address': ('django.db.models.fields.EmailField', [], {'max_length': '75'}),
+            'requested_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2012, 5, 30, 9, 16, 18, 743926)'}),
+            'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'emailchange_user'", 'unique': 'True', 'to': "orm['im.AstakosUser']"})
+        },
+        'im.invitation': {
+            'Meta': {'object_name': 'Invitation'},
+            'code': ('django.db.models.fields.BigIntegerField', [], {'db_index': 'True'}),
+            'consumed': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
+            'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'inviter': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'invitations_sent'", 'null': 'True', 'to': "orm['im.AstakosUser']"}),
+            'is_consumed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'realname': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
+            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'})
+        },
+        'im.service': {
+            'Meta': {'object_name': 'Service'},
+            'auth_token': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'blank': 'True'}),
+            'auth_token_created': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
+            'auth_token_expires': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
+            'icon': ('django.db.models.fields.FilePathField', [], {'max_length': '100', 'blank': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
+            'url': ('django.db.models.fields.FilePathField', [], {'max_length': '100'})
+        }
+    }
+
+    complete_apps = ['im']
diff --git a/snf-astakos-app/astakos/im/migrations/0011_set_old_activation_sent.py b/snf-astakos-app/astakos/im/migrations/0011_set_old_activation_sent.py
new file mode 100644 (file)
index 0000000..4cf061c
--- /dev/null
@@ -0,0 +1,116 @@
+# encoding: utf-8
+import datetime
+from south.db import db
+from south.v2 import DataMigration
+from django.db import models
+
+class Migration(DataMigration):
+
+    def forwards(self, orm):
+        # set old users activation date sent to epoch
+        for u in orm.AstakosUser.objects.all():
+            if not u.is_active:
+                u.activation_sent = datetime.datetime.utcfromtimestamp(0)
+                u.save()
+
+    def backwards(self, orm):
+        # set old users activation date sent to None
+        for u in orm.AstakosUser.objects.all():
+            if u.activation_sent == datetime.datetime.utcfromtimestamp(0):
+                u.activation_sent = None
+                u.save()
+
+    models = {
+        'auth.group': {
+            'Meta': {'object_name': 'Group'},
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
+            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
+        },
+        'auth.permission': {
+            'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
+            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
+        },
+        'auth.user': {
+            'Meta': {'object_name': 'User'},
+            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
+            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
+            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
+            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
+            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
+            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
+            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
+            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
+            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
+        },
+        'contenttypes.contenttype': {
+            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
+            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
+        },
+        'im.approvalterms': {
+            'Meta': {'object_name': 'ApprovalTerms'},
+            'date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2012, 5, 30, 9, 25, 25, 741532)', 'db_index': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'location': ('django.db.models.fields.CharField', [], {'max_length': '255'})
+        },
+        'im.astakosuser': {
+            'Meta': {'object_name': 'AstakosUser', '_ormbases': ['auth.User']},
+            'activation_sent': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
+            'affiliation': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
+            'auth_token': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'blank': 'True'}),
+            'auth_token_created': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
+            'auth_token_expires': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
+            'date_signed_terms': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
+            'email_verified': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'has_credits': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'has_signed_terms': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'invitations': ('django.db.models.fields.IntegerField', [], {'default': '100'}),
+            'is_verified': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'level': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
+            'provider': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
+            'third_party_identifier': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
+            'updated': ('django.db.models.fields.DateTimeField', [], {}),
+            'user_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True', 'primary_key': 'True'})
+        },
+        'im.emailchange': {
+            'Meta': {'object_name': 'EmailChange'},
+            'activation_key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '40', 'db_index': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'new_email_address': ('django.db.models.fields.EmailField', [], {'max_length': '75'}),
+            'requested_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2012, 5, 30, 9, 25, 25, 743284)'}),
+            'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'emailchange_user'", 'unique': 'True', 'to': "orm['im.AstakosUser']"})
+        },
+        'im.invitation': {
+            'Meta': {'object_name': 'Invitation'},
+            'code': ('django.db.models.fields.BigIntegerField', [], {'db_index': 'True'}),
+            'consumed': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
+            'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'inviter': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'invitations_sent'", 'null': 'True', 'to': "orm['im.AstakosUser']"}),
+            'is_consumed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'realname': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
+            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'})
+        },
+        'im.service': {
+            'Meta': {'object_name': 'Service'},
+            'auth_token': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'blank': 'True'}),
+            'auth_token_created': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
+            'auth_token_expires': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
+            'icon': ('django.db.models.fields.FilePathField', [], {'max_length': '100', 'blank': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
+            'url': ('django.db.models.fields.FilePathField', [], {'max_length': '100'})
+        }
+    }
+
+    complete_apps = ['im']
diff --git a/snf-astakos-app/astakos/im/migrations/0012_auto__add_additionalmail.py b/snf-astakos-app/astakos/im/migrations/0012_auto__add_additionalmail.py
new file mode 100644 (file)
index 0000000..a6c5738
--- /dev/null
@@ -0,0 +1,125 @@
+# encoding: utf-8
+import datetime
+from south.db import db
+from south.v2 import SchemaMigration
+from django.db import models
+
+class Migration(SchemaMigration):
+
+    def forwards(self, orm):
+        
+        # Adding model 'AdditionalMail'
+        db.create_table('im_additionalmail', (
+            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
+            ('owner', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['im.AstakosUser'])),
+            ('email', self.gf('django.db.models.fields.EmailField')(unique=True, max_length=75)),
+        ))
+        db.send_create_signal('im', ['AdditionalMail'])
+
+
+    def backwards(self, orm):
+        
+        # Deleting model 'AdditionalMail'
+        db.delete_table('im_additionalmail')
+
+
+    models = {
+        'auth.group': {
+            'Meta': {'object_name': 'Group'},
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
+            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
+        },
+        'auth.permission': {
+            'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
+            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
+        },
+        'auth.user': {
+            'Meta': {'object_name': 'User'},
+            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
+            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
+            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
+            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
+            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
+            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
+            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
+            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
+            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
+        },
+        'contenttypes.contenttype': {
+            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
+            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
+        },
+        'im.additionalmail': {
+            'Meta': {'object_name': 'AdditionalMail'},
+            'email': ('django.db.models.fields.EmailField', [], {'unique': 'True', 'max_length': '75'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['im.AstakosUser']"})
+        },
+        'im.approvalterms': {
+            'Meta': {'object_name': 'ApprovalTerms'},
+            'date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2012, 6, 1, 10, 5, 42, 665990)', 'db_index': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'location': ('django.db.models.fields.CharField', [], {'max_length': '255'})
+        },
+        'im.astakosuser': {
+            'Meta': {'object_name': 'AstakosUser', '_ormbases': ['auth.User']},
+            'activation_sent': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
+            'affiliation': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
+            'auth_token': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'blank': 'True'}),
+            'auth_token_created': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
+            'auth_token_expires': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
+            'date_signed_terms': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
+            'email_verified': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'has_credits': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'has_signed_terms': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'invitations': ('django.db.models.fields.IntegerField', [], {'default': '100'}),
+            'is_verified': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'level': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
+            'provider': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
+            'third_party_identifier': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
+            'updated': ('django.db.models.fields.DateTimeField', [], {}),
+            'user_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True', 'primary_key': 'True'})
+        },
+        'im.emailchange': {
+            'Meta': {'object_name': 'EmailChange'},
+            'activation_key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '40', 'db_index': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'new_email_address': ('django.db.models.fields.EmailField', [], {'max_length': '75'}),
+            'requested_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2012, 6, 1, 10, 5, 42, 667593)'}),
+            'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'emailchange_user'", 'unique': 'True', 'to': "orm['im.AstakosUser']"})
+        },
+        'im.invitation': {
+            'Meta': {'object_name': 'Invitation'},
+            'code': ('django.db.models.fields.BigIntegerField', [], {'db_index': 'True'}),
+            'consumed': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
+            'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'inviter': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'invitations_sent'", 'null': 'True', 'to': "orm['im.AstakosUser']"}),
+            'is_consumed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'realname': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
+            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'})
+        },
+        'im.service': {
+            'Meta': {'object_name': 'Service'},
+            'auth_token': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'blank': 'True'}),
+            'auth_token_created': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
+            'auth_token_expires': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
+            'icon': ('django.db.models.fields.FilePathField', [], {'max_length': '100', 'blank': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
+            'url': ('django.db.models.fields.FilePathField', [], {'max_length': '100'})
+        }
+    }
+
+    complete_apps = ['im']
index af00f51..c77c198 100644 (file)
@@ -42,12 +42,18 @@ from base64 import b64encode
 from urlparse import urlparse, urlunparse
 from random import randint
 
-from django.db import models
+from django.db import models, IntegrityError
 from django.contrib.auth.models import User, UserManager, Group
 from django.utils.translation import ugettext as _
 from django.core.exceptions import ValidationError
+from django.template.loader import render_to_string
+from django.core.mail import send_mail
+from django.db import transaction
+from django.db.models.signals import post_save, post_syncdb
 
-from astakos.im.settings import DEFAULT_USER_LEVEL, INVITATIONS_PER_LEVEL, AUTH_TOKEN_DURATION, BILLING_FIELDS, QUEUE_CONNECTION
+from astakos.im.settings import DEFAULT_USER_LEVEL, INVITATIONS_PER_LEVEL, \
+    AUTH_TOKEN_DURATION, BILLING_FIELDS, QUEUE_CONNECTION, SITENAME, \
+    EMAILCHANGE_ACTIVATION_DAYS, LOGGING_LEVEL
 
 QUEUE_CLIENT_ID = 3 # Astakos.
 
@@ -85,6 +91,8 @@ class AstakosUser(User):
     has_signed_terms = models.BooleanField('Agree with the terms?', default=False)
     date_signed_terms = models.DateTimeField('Signed terms date', null=True, blank=True)
     
+    activation_sent = models.DateTimeField('Activation sent data', null=True, blank=True)
+    
     __has_signed_terms = False
     __groupnames = []
     
@@ -137,7 +145,10 @@ class AstakosUser(User):
             if not self.provider:
                 self.provider = 'local'
         report_user_event(self)
-        self.full_clean()
+        self.validate_unique_email_isactive()
+        if self.is_active and self.activation_sent:
+            # reset the activation sent
+            self.activation_sent = None
         super(AstakosUser, self).save(**kwargs)
         
         # set group if does not exist
@@ -159,6 +170,8 @@ class AstakosUser(User):
         self.auth_token_created = datetime.now()
         self.auth_token_expires = self.auth_token_created + \
                                   timedelta(hours=AUTH_TOKEN_DURATION)
+        msg = 'Token renewed for %s' % self.email
+        logger._log(LOGGING_LEVEL, msg, [])
 
     def __unicode__(self):
         return self.username
@@ -170,12 +183,10 @@ class AstakosUser(User):
             return True
         return False
     
-    def validate_unique(self, exclude=None):
+    def validate_unique_email_isactive(self):
         """
         Implements a unique_together constraint for email and is_active fields.
         """
-        super(AstakosUser, self).validate_unique(exclude)
-        
         q = AstakosUser.objects.exclude(username = self.username)
         q = q.filter(email = self.email)
         q = q.filter(is_active = self.is_active)
@@ -192,6 +203,7 @@ class AstakosUser(User):
             return False
         if self.date_signed_terms < term.date:
             self.has_signed_terms = False
+            self.date_signed_terms = None
             self.save()
             return False
         return True
@@ -213,12 +225,8 @@ class Invitation(models.Model):
     realname = models.CharField('Real name', max_length=255)
     username = models.CharField('Unique ID', max_length=255, unique=True)
     code = models.BigIntegerField('Invitation code', db_index=True)
-    #obsolete: we keep it just for transfering the data
-    is_accepted = models.BooleanField('Accepted?', default=False)
     is_consumed = models.BooleanField('Consumed?', default=False)
     created = models.DateTimeField('Creation date', auto_now_add=True)
-    #obsolete: we keep it just for transfering the data
-    accepted = models.DateTimeField('Acceptance date', null=True, blank=True)
     consumed = models.DateTimeField('Consumption date', null=True, blank=True)
     
     def __init__(self, *args, **kwargs):
@@ -276,4 +284,115 @@ def get_latest_terms():
         return term
     except IndexError:
         pass
-    return None
\ No newline at end of file
+    return None
+
+class EmailChangeManager(models.Manager):
+    @transaction.commit_on_success
+    def change_email(self, activation_key):
+        """
+        Validate an activation key and change the corresponding
+        ``User`` if valid.
+
+        If the key is valid and has not expired, return the ``User``
+        after activating.
+
+        If the key is not valid or has expired, return ``None``.
+
+        If the key is valid but the ``User`` is already active,
+        return ``None``.
+
+        After successful email change the activation record is deleted.
+
+        Throws ValueError if there is already
+        """
+        try:
+            email_change = self.model.objects.get(activation_key=activation_key)
+            if email_change.activation_key_expired():
+                email_change.delete()
+                raise EmailChange.DoesNotExist
+            # is there an active user with this address?
+            try:
+                AstakosUser.objects.get(email=email_change.new_email_address)
+            except AstakosUser.DoesNotExist:
+                pass
+            else:
+                raise ValueError(_('The new email address is reserved.'))
+            # update user
+            user = AstakosUser.objects.get(pk=email_change.user_id)
+            user.email = email_change.new_email_address
+            user.save()
+            email_change.delete()
+            return user
+        except EmailChange.DoesNotExist:
+            raise ValueError(_('Invalid activation key'))
+
+class EmailChange(models.Model):
+    new_email_address = models.EmailField(_(u'new e-mail address'), help_text=_(u'Your old email address will be used until you verify your new one.'))
+    user = models.ForeignKey(AstakosUser, unique=True, related_name='emailchange_user')
+    requested_at = models.DateTimeField(default=datetime.now())
+    activation_key = models.CharField(max_length=40, unique=True, db_index=True)
+
+    objects = EmailChangeManager()
+
+    def activation_key_expired(self):
+        expiration_date = timedelta(days=EMAILCHANGE_ACTIVATION_DAYS)
+        return self.requested_at + expiration_date < datetime.now()
+
+class Service(models.Model):
+    name = models.CharField('Name', max_length=255, unique=True)
+    url = models.FilePathField()
+    icon = models.FilePathField(blank=True)
+    auth_token = models.CharField('Authentication Token', max_length=32,
+                                  null=True, blank=True)
+    auth_token_created = models.DateTimeField('Token creation date', null=True)
+    auth_token_expires = models.DateTimeField('Token expiration date', null=True)
+    
+    def save(self, **kwargs):
+        if not self.id:
+            self.renew_token()
+        self.full_clean()
+        super(Service, self).save(**kwargs)
+    
+    def renew_token(self):
+        md5 = hashlib.md5()
+        md5.update(self.name.encode('ascii', 'ignore'))
+        md5.update(self.url.encode('ascii', 'ignore'))
+        md5.update(asctime())
+
+        self.auth_token = b64encode(md5.digest())
+        self.auth_token_created = datetime.now()
+        self.auth_token_expires = self.auth_token_created + \
+                                  timedelta(hours=AUTH_TOKEN_DURATION)
+
+class AdditionalMail(models.Model):
+    """
+    Model for registring invitations
+    """
+    owner = models.ForeignKey(AstakosUser)
+    email = models.EmailField(unique=True)
+
+def create_astakos_user(u):
+    try:
+        AstakosUser.objects.get(user_ptr=u.pk)
+    except AstakosUser.DoesNotExist:
+        extended_user = AstakosUser(user_ptr_id=u.pk)
+        extended_user.__dict__.update(u.__dict__)
+        extended_user.renew_token()
+        extended_user.save()
+    except:
+        pass
+
+def superuser_post_syncdb(sender, **kwargs):
+    # if there was created a superuser
+    # associate it with an AstakosUser
+    admins = User.objects.filter(is_superuser=True)
+    for u in admins:
+        create_astakos_user(u)
+
+post_syncdb.connect(superuser_post_syncdb)
+
+def superuser_post_save(sender, instance, **kwargs):
+    if instance.is_superuser:
+        create_astakos_user(instance)
+
+post_save.connect(superuser_post_save, sender=User)
\ No newline at end of file
index 3b32d43..33649f3 100644 (file)
@@ -44,12 +44,12 @@ class UserEvent(object):
         self.receivedMillis = self.occurredMillis
         self.clientID = client
         self.userID = user.email
-        self.is_active = user.is_active
+        self.isActive = user.is_active
         self.role = 'default'
         self.eventType = eventType
         self.details = details
         hash = sha1()
-        hash.update(json.dumps([client, self.userID, self.is_active, self.role,
+        hash.update(json.dumps([client, self.userID, self.isActive, self.role,
                                 self.eventType, self.details, self.occurredMillis]))
         self.id = hash.hexdigest()
     
index 342c866..42e252b 100644 (file)
@@ -47,12 +47,6 @@ BASEURL = getattr(settings, 'ASTAKOS_BASEURL', 'http://pithos.dev.grnet.gr')
 # Set service name
 SITENAME = getattr(settings, 'ASTAKOS_SITENAME', 'GRNET Cloud')
 
-# Set cloud services appear in the horizontal bar
-CLOUD_SERVICES = getattr(settings, 'ASTAKOS_CLOUD_SERVICES', (
-        { 'url':'/', 'name':'grnet cloud', 'id':'cloud', 'icon':'home-icon.png' },
-        { 'url':'/okeanos.html', 'name':'cyclades', 'id':'okeanos' },
-        { 'url':'/ui/', 'name':'pithos+', 'id':'pithos' }))
-
 # Set recaptcha keys
 RECAPTCHA_PUBLIC_KEY = getattr(settings, 'ASTAKOS_RECAPTCHA_PUBLIC_KEY', '')
 RECAPTCHA_PRIVATE_KEY = getattr(settings, 'ASTAKOS_RECAPTCHA_PRIVATE_KEY', '')
@@ -77,6 +71,18 @@ RE_USER_EMAIL_PATTERNS = getattr(settings, 'ASTAKOS_RE_USER_EMAIL_PATTERNS', [])
 # e.g. {'warning': 'This warning message will be displayed on the top of login page'}
 LOGIN_MESSAGES = getattr(settings, 'ASTAKOS_LOGIN_MESSAGES', {})
 
+# Messages to display on login page header
+# e.g. {'warning': 'This warning message will be displayed on the top of signup page'}
+SIGNUP_MESSAGES = getattr(settings, 'ASTAKOS_SIGNUP_MESSAGES', {})
+
+# Messages to display on login page header
+# e.g. {'warning': 'This warning message will be displayed on the top of profile page'}
+PROFILE_MESSAGES = getattr(settings, 'ASTAKOS_PROFILE_MESSAGES', {})
+
+# Messages to display on all pages
+# e.g. {'warning': 'This warning message will be displayed on the top of every page'}
+GLOBAL_MESSAGES = getattr(settings, 'ASTAKOS_GLOBAL_MESSAGES', {})
+
 # messages to display as extra actions in account forms
 # e.g. {'https://cms.okeanos.grnet.gr/': 'Back to ~okeanos'}
 PROFILE_EXTRA_LINKS = getattr(settings, 'ASTAKOS_PROFILE_EXTRA_LINKS', {})
@@ -84,3 +90,12 @@ PROFILE_EXTRA_LINKS = getattr(settings, 'ASTAKOS_PROFILE_EXTRA_LINKS', {})
 # The number of unsuccessful login requests per minute allowed for a specific email
 RATELIMIT_RETRIES_ALLOWED = getattr(settings, 'ASTAKOS_RATELIMIT_RETRIES_ALLOWED', 3)
 
+# If False the email change mechanism is disabled
+EMAILCHANGE_ENABLED = getattr(settings, 'ASTAKOS_EMAILCHANGE_ENABLED', False)
+
+# Set the expiration time (in days) of email change requests
+EMAILCHANGE_ACTIVATION_DAYS = getattr(settings, 'ASTAKOS_EMAILCHANGE_ACTIVATION_DAYS', 10)
+
+# Set the astakos main functions logging severity (None to disable)
+from logging import INFO
+LOGGING_LEVEL = getattr(settings, 'ASTAKOS_LOGGING_LEVEL', INFO)
index 00fa94b..4949de1 100644 (file)
@@ -53,7 +53,7 @@ $(document).ready(function(){
             slink.attr('title', el.name);
             sli.append(slink);
             services.append(sli);
-            if (el.id == ACTIVE_MENU) {
+            if (el.id == ACTIVE_MENU || el.name == ACTIVE_MENU) {
                 sli.addClass("active");
             }
         });
index e69de29..59b44be 100644 (file)
@@ -0,0 +1,10 @@
+ul.messages li { margin-bottom: 5px }
+ul.messages { background-color: transparent; }
+ul.messages li a { font-weight: normal !important }
+ul.messages li.notice { background-color: #284A5E }
+ul.messages li.notice { color: #FFF }
+ul.messages li.notice a { color: #FFF }
+ul.messages li.notice2 { background-color: #F54500 }
+ul.messages li.notice2 { color: #FFF }
+ul.messages li.notice2 { background-color: #F54500 }
+ul.messages li.notice2 a { color: #FFF }
index 8664c1f..838941d 100755 (executable)
                        
                        // Remove keydown event to save on CPU processing
                        base.$field.unbind('keydown.infieldlabel');
+
+            // ff3.5 fix, forces key to be written in input field
+            base.$field.val('');
                };
       
                // Run the initialization method
index afd1545..647d5ae 100644 (file)
@@ -48,6 +48,7 @@ installed_apps = [
 context_processors = [
     'django.core.context_processors.media',
     'django.core.context_processors.request',
+    'django.core.context_processors.csrf',
     'astakos.im.context_processors.media',
     'astakos.im.context_processors.im_modules',
     'astakos.im.context_processors.next',
@@ -60,8 +61,10 @@ context_processors = [
 
 middlware_classes = [
     'django.contrib.auth.middleware.AuthenticationMiddleware',
+    'astakos.im.middleware.CookieAuthenticationMiddleware',
     'synnefo.lib.middleware.LoggingConfigMiddleware',
-    'synnefo.lib.middleware.SecureMiddleware'
+    'synnefo.lib.middleware.SecureMiddleware',
+    'django.middleware.csrf.CsrfViewMiddleware'
 ]
 
 loggers = {
@@ -78,10 +81,5 @@ AUTHENTICATION_BACKENDS = ('astakos.im.auth_backends.EmailBackend',
                             'astakos.im.auth_backends.TokenBackend')
 LOGIN_URL = '/im'
 
-# The server is behind a proxy (apache and gunicorn setup).
-USE_X_FORWARDED_HOST = False
-
 CUSTOM_USER_MODEL = 'astakos.im.AstakosUser'
 
-SESSION_COOKIE_SECURE = True
-
index 0dce24c..3fe34ca 100644 (file)
@@ -37,8 +37,9 @@ from django.template import RequestContext
 from django.contrib.auth import authenticate
 from django.contrib import messages
 from django.utils.translation import ugettext as _
+from django.views.decorators.csrf import csrf_exempt
 
-from astakos.im.util import prepare_response
+from astakos.im.util import prepare_response, get_query
 from astakos.im.views import requires_anonymous
 from astakos.im.models import AstakosUser
 from astakos.im.forms import LoginForm
@@ -49,6 +50,7 @@ from ratelimit.decorators import ratelimit
 retries = RATELIMIT_RETRIES_ALLOWED-1
 rate = str(retries)+'/m'
 
+@csrf_exempt
 @requires_anonymous
 @ratelimit(field='username', method='POST', rate=rate)
 def login(request, on_failure='im/login.html'):
@@ -57,7 +59,7 @@ def login(request, on_failure='im/login.html'):
     """
     was_limited = getattr(request, 'limited', False)
     form = LoginForm(data=request.POST, was_limited=was_limited, request=request)
-    next = request.POST.get('next')
+    next = get_query(request).get('next', '')
     if not form.is_valid():
         return render_to_response(on_failure,
                                   {'login_form':form,
index dc07731..3c59c21 100644 (file)
@@ -36,7 +36,7 @@ from django.shortcuts import redirect
 from django.utils.translation import ugettext as _
 from django.contrib import messages
 from django.utils.http import urlencode
-from django.contrib.auth import login as auth_login, authenticate, logout
+from django.contrib.auth import authenticate
 from django.http import HttpResponse, HttpResponseBadRequest
 from django.core.exceptions import ValidationError
 
@@ -45,6 +45,7 @@ from urlparse import urlunsplit, urlsplit, urlparse, parse_qsl
 
 from astakos.im.settings import COOKIE_NAME, COOKIE_DOMAIN
 from astakos.im.util import set_cookie
+from astakos.im.functions import login as auth_login, logout
 
 import logging
 
index ccdc05e..175982b 100644 (file)
@@ -35,11 +35,12 @@ from django.http import HttpResponseBadRequest
 from django.utils.translation import ugettext as _
 from django.contrib import messages
 from django.template import RequestContext
+from django.forms.models import inlineformset_factory
 
 from astakos.im.util import prepare_response, get_context, get_invitation
 from astakos.im.views import requires_anonymous, render_response
 from astakos.im.settings import DEFAULT_USER_LEVEL
-from astakos.im.models import AstakosUser, Invitation
+from astakos.im.models import AstakosUser, Invitation, AdditionalMail
 from astakos.im.forms import LoginForm
 from astakos.im.activation_backends import get_backend, SimpleBackend
 
@@ -52,6 +53,7 @@ class Tokens:
     SHIB_DISPLAYNAME = "HTTP_SHIB_INETORGPERSON_DISPLAYNAME"
     SHIB_EP_AFFILIATION = "HTTP_SHIB_EP_AFFILIATION"
     SHIB_SESSION_ID = "HTTP_SHIB_SESSION_ID"
+    SHIB_MAIL = "HTTP_SHIB_MAIL"
 
 @requires_anonymous
 def login(request,  backend=None, on_login_template='im/login.html', on_creation_template='im/third_party_registration.html', extra_context={}):
@@ -72,6 +74,7 @@ def login(request,  backend=None, on_login_template='im/login.html', on_creation
         return HttpResponseBadRequest("Missing user name in request")
     
     affiliation = tokens.get(Tokens.SHIB_EP_AFFILIATION, '')
+    email = tokens.get(Tokens.SHIB_MAIL, None)
     
     try:
         user = AstakosUser.objects.get(provider='shibboleth', third_party_identifier=eppn)
@@ -88,7 +91,8 @@ def login(request,  backend=None, on_login_template='im/login.html', on_creation
                                    context_instance=RequestContext(request))
     except AstakosUser.DoesNotExist, e:
         user = AstakosUser(third_party_identifier=eppn, realname=realname,
-                           affiliation=affiliation, provider='shibboleth')
+                           affiliation=affiliation, provider='shibboleth',
+                           email=email)
         try:
             if not backend:
                 backend = get_backend(request)
@@ -96,8 +100,6 @@ def login(request,  backend=None, on_login_template='im/login.html', on_creation
         except Exception, e:
             form = SimpleBackend(request).get_signup_form(provider='shibboleth', instance=user)
             messages.add_message(request, messages.ERROR, e)
-        form.data.update({'third_party_identifier':eppn, 'realname':realname,
-                          'affiliation':affiliation})
         return render_response(on_creation_template,
                                signup_form = form,
                                provider = 'shibboleth',
index 52aa1b7..519a3e1 100644 (file)
@@ -1,5 +1,16 @@
 {% extends "im/base.html" %}
 
+{% block extra_messages %}
+    {% if not messages %}
+        {% for msg_type, msg in GLOBAL_MESSAGES.items %}
+            <li class="{{ msg_type }}">{{ msg|safe }}</li>
+        {% endfor %}
+        {% for msg_type, msg in PROFILE_MESSAGES.items %}
+            <li class="{{ msg_type }}">{{ msg|safe }}</li>
+        {% endfor %}
+    {% endif %}
+{% endblock %}
+
 {% load filters %}
 
 {% block page.title %}Profile{% endblock %}
@@ -35,4 +46,4 @@
 </div>
 
 {% endblock %}
\ No newline at end of file
index e1f491c..de70055 100644 (file)
@@ -72,7 +72,7 @@
 <body>
     <div class="container">
            <div class="wrapper">       
-               {% if messages or LOGIN_MESSAGES %}
+               {% if messages or EXTRA_MESSAGES_SET %}
                <div class="top-msg active">
                    {% block extra_messages %}{% endblock %}
                    {% for message in messages %}
@@ -99,8 +99,6 @@
                    </ul>
             </div>
             {% endblock %}
-                
-               
                <div class="content">
                    {% block page.body %}
                        <div class="full">
index 25ba789..9bba8e2 100644 (file)
@@ -2,8 +2,8 @@ Feedback message:
 {{ message }}
 
 User info:
-ID: {{ request.user.id }}
-Email: {{ request.user.email }}
+ID: {{ user.id }}
+Email: {{ user.email }}
 
 User application data:
 {{ data|safe }}
index fc725a7..d3e4bdf 100644 (file)
@@ -2,6 +2,9 @@
 
 {% block extra_messages %}
     {% if not messages %}
+        {% for msg_type, msg in GLOBAL_MESSAGES.items %}
+            <li class="{{ msg_type }}">{{ msg|safe }}</li>
+        {% endfor %}
         {% for msg_type, msg in LOGIN_MESSAGES.items %}
             <li class="{{ msg_type }}">{{ msg|safe }}</li>
         {% endfor %}
                    </div>
        </form>
     {% endif %}
-
     <div class="extralogin">
          {% for o in im_modules %}
        <div>
         {% if o != 'local' %}
         LOGIN using
-               <a href="/im/login/{{ o }}{% ifnotequal next "" %}&next={{ next|urlencode }}{% endifnotequal %}{% ifnotequal code ""%}{% if next != "" %}&{% else %}?{% endif %}code={{ code }}{% endifnotequal %}"
+            <a href="/im/login/{{ o }}?{% ifnotequal next "" %}&next={{ next|urlencode }}{% endifnotequal %}{% ifnotequal code ""%}{% if next != "" %}&{% else %}?{% endif %}code={{ code }}{% endifnotequal %}"
             alt="{{ o|title }}">{{ o }}</a>
         {% endif %}
         </div>
index 4144286..8e41245 100644 (file)
@@ -1,5 +1,15 @@
 {% extends 'im/base_two_cols.html' %}
 
+{% block extra_messages %}
+    {% if not messages %}
+        {% for msg_type, msg in GLOBAL_MESSAGES.items %}
+            <li class="{{ msg_type }}">{{ msg|safe }}</li>
+        {% endfor %}
+        {% for msg_type, msg in SIGNUP_MESSAGES.items %}
+            <li class="{{ msg_type }}">{{ msg|safe }}</li>
+        {% endfor %}
+    {% endif %}
+{% endblock %}
 
 {% block page.title %}
     Signup
index 54e086d..5b1b45d 100644 (file)
@@ -5,7 +5,7 @@
 
 Λάβαμε ένα αίτημα σας για να συσχετίσετε τη συγκεκριμένη ηλεκτρονική διεύθυνση με τον shibboleth λογαριασμό σας στην υπηρεσία {{ site_name }} της ΕΔΕΤ κατά την alpha2 (δεύτερη δοκιμαστική) φάση λειτουργίας της.
 Ωστόσο το συγκεκριμένο email έχει συσχετισθεί με έναν τοπικό λογαρισμό.
-Για να τον μετατρέψετε τον ήδη υπάρχοντα λογαρισμό σε shibboleth λογαρισμό, χρησιμοποιήστε το σύνδεσμο: {{ url }}.
+Για να μετατρέψετε τον ήδη υπάρχοντα λογαρισμό σε shibboleth λογαρισμό, χρησιμοποιήστε το σύνδεσμο: {{ url }}.
 Διαφορετικά αγνοήστε το παρόν email.
 
 {% endblock %}
diff --git a/snf-astakos-app/astakos/im/templates/registration/email_change_confirm.html b/snf-astakos-app/astakos/im/templates/registration/email_change_confirm.html
new file mode 100644 (file)
index 0000000..7de0f87
--- /dev/null
@@ -0,0 +1,8 @@
+{% extends 'im/one_col_base.html'%}
+
+{%block page.title %}Email change{% endblock %}
+{% block body %}
+<div class="section">
+    <p>Email change sent.</p>
+</div>
+{% endblock %}
diff --git a/snf-astakos-app/astakos/im/templates/registration/email_change_done.html b/snf-astakos-app/astakos/im/templates/registration/email_change_done.html
new file mode 100644 (file)
index 0000000..b5ee140
--- /dev/null
@@ -0,0 +1,10 @@
+{% extends 'im/one_col_base.html'%}
+
+{%block page.title %}Email change{% endblock %}
+{% block body %}
+<div class="section">
+    {% if modified_user %}
+    <h2>Email changed syccessfully for user {{modified_user.id}}.</h2>
+    {% endif %}
+</div>
+{% endblock %}
diff --git a/snf-astakos-app/astakos/im/templates/registration/email_change_email.txt b/snf-astakos-app/astakos/im/templates/registration/email_change_email.txt
new file mode 100644 (file)
index 0000000..2ea23e1
--- /dev/null
@@ -0,0 +1,13 @@
+{% extends "im/email.txt" %}
+
+{% block gr_content %}
+Για να ανανεώσετε τον email σας για την υπηρεσία {{ site_name }} της ΕΔΕΤ κατά την alpha2 (δεύτερη δοκιμαστική) φάση λειτουργίας της, χρησιμοποιήστε τον σύνδεσμο: {{url}}
+{% endblock %}
+
+{% block gr_note %}{% endblock%}
+
+{% block en_content %}
+To change your email for GRNET's {{ site_name }} for its alpha2 testing phase service, you can use the  link: {{ url }}.
+{% endblock %}
+
+{% block en_note %}{% endblock%}
\ No newline at end of file
diff --git a/snf-astakos-app/astakos/im/templates/registration/email_change_form.html b/snf-astakos-app/astakos/im/templates/registration/email_change_form.html
new file mode 100644 (file)
index 0000000..a18e05b
--- /dev/null
@@ -0,0 +1,14 @@
+{% extends "im/account_base.html" %}
+
+{% block body %}
+<form action="{% url astakos.im.views.change_email %}" method="post"
+    class="withlabels">{% csrf_token %}
+
+    {% include "im/form_render.html" %}
+
+    <div class="form-row submit">
+        <input type="hidden" name="next" value="{{ next }}">
+        <input type="submit" class="submit altcol" value="CHANGE" />
+    </div>
+</form>
+{% endblock body %}
index 9bb8241..af0f864 100644 (file)
@@ -3,7 +3,6 @@
 {%block page.title %}Logout{% endblock %}
 {% block body %}
 <div class="section">
-    <h2>Logout</h2>
-    <p>You have successfully logged out. <a href="{% url astakos.im.views.index %}">Login</a>.</p>
+    <h2>You have successfully logged out. <a href="{% url astakos.im.views.index %}">Login</a>.</h2>
 </div>
 {% endblock %}
index 825f74f..468ad2c 100644 (file)
@@ -1,9 +1,8 @@
 {% extends 'im/one_col_base.html'%}
 
-{%block page.title %}Logout{% endblock %}
+{%block page.title %}Password reset{% endblock %}
 {% block body %}
 <div class="section">
-    <h2>Password reset</h2>
-    <p>Password reset successfully</p>
+    <h2>Password reset successfully</h2>
 </div>
 {% endblock %}
index 7b3cda5..c1c74d7 100644 (file)
@@ -1,6 +1,6 @@
 {% extends 'im/one_col_base.html'%}
 
-{%block page.title %}Logout{% endblock %}
+{%block page.title %}Password reset{% endblock %}
 {% block body %}
 <div class="section">
     <h2>Please enter your new password</h2>
index 8feddb2..f73c81c 100644 (file)
@@ -1,9 +1,8 @@
 {% extends 'im/one_col_base.html'%}
 
-{%block page.title %}Logout{% endblock %}
+{%block page.title %}Password reset{% endblock %}
 {% block body %}
 <div class="section">
-    <h2>Password reset</h2>
-    <p>Email sent.</p>
+    <h2>Email sent.</h2>
 </div>
 {% endblock %}
index b9a82ce..99386a0 100644 (file)
@@ -35,8 +35,7 @@ from django.conf.urls.defaults import patterns, include, url
 from django.contrib.auth.views import password_change
 
 from astakos.im.forms import ExtendedPasswordResetForm, LoginForm
-from astakos.im.settings import IM_MODULES, INVITATIONS_ENABLED
-from astakos.im.views import signed_terms_required
+from astakos.im.settings import IM_MODULES, INVITATIONS_ENABLED, EMAILCHANGE_ENABLED
 
 urlpatterns = patterns('astakos.im.views',
     url(r'^$', 'index', {}, name='index'),
@@ -48,9 +47,16 @@ urlpatterns = patterns('astakos.im.views',
     url(r'^activate/?$', 'activate'),
     url(r'^approval_terms/?$', 'approval_terms', {}, name='latest_terms'),
     url(r'^approval_terms/(?P<term_id>\d+)/?$', 'approval_terms'),
-    url(r'^password/?$', 'change_password', {}, name='password_change')
+    url(r'^password/?$', 'change_password', {}, name='password_change'),
 )
 
+if EMAILCHANGE_ENABLED:
+    urlpatterns += patterns('astakos.im.views',
+        url(r'^email_change/?$', 'change_email', {}, name='email_change'),
+        url(r'^email_change/confirm/(?P<activation_key>\w+)/', 'change_email', {},
+            name='email_change_confirm')
+)
+    
 urlpatterns += patterns('astakos.im.target',
     url(r'^login/redirect/?$', 'redirect.login')
 )
@@ -86,11 +92,18 @@ if 'twitter' in IM_MODULES:
         url(r'^login/twitter/authenticated/?$', 'twitter.authenticated')
     )
 
-urlpatterns += patterns('astakos.im.api',
+urlpatterns += patterns('astakos.im.api.admin',
     url(r'^authenticate/?$', 'authenticate_old'),
-    url(r'^authenticate/v2/?$', 'authenticate'),
+    #url(r'^authenticate/v2/?$', 'authenticate'),
     url(r'^get_services/?$', 'get_services'),
     url(r'^get_menu/?$', 'get_menu'),
-    url(r'^find_userid/?$', 'find_userid'),
-    url(r'^find_email/?$', 'find_email'),
+    url(r'^admin/api/v2.0/users/?$', 'get_user_by_email'),
+    url(r'^admin/api/v2.0/users/(?P<user_id>.+?)/?$', 'get_user_by_username'),
 )
+
+urlpatterns += patterns('astakos.im.api.service',
+    #url(r'^service/api/v2.0/tokens/(?P<token_id>.+?)/?$', 'validate_token'),
+    url(r'^service/api/v2.0/feedback/?$', 'send_feedback'),
+    url(r'^service/api/v2.0/users/?$', 'get_user_by_email'),
+    url(r'^service/api/v2.0/users/(?P<user_id>.+?)/?$', 'get_user_by_username'),
+)
\ No newline at end of file
index 2eced4f..4aea9c2 100644 (file)
@@ -37,19 +37,19 @@ import time
 
 from urllib import quote
 from urlparse import urlsplit, urlunsplit
-from functools import wraps
 
 from datetime import tzinfo, timedelta
 from django.http import HttpResponse, HttpResponseBadRequest, urlencode
 from django.template import RequestContext
-from django.contrib.sites.models import Site
 from django.utils.translation import ugettext as _
-from django.contrib.auth import login, authenticate
+from django.contrib.auth import authenticate
 from django.core.urlresolvers import reverse
 from django.core.exceptions import ValidationError
 
 from astakos.im.models import AstakosUser, Invitation, ApprovalTerms
-from astakos.im.settings import INVITATIONS_PER_LEVEL, COOKIE_NAME, COOKIE_DOMAIN, COOKIE_SECURE, FORCE_PROFILE_UPDATE
+from astakos.im.settings import INVITATIONS_PER_LEVEL, COOKIE_NAME, \
+    COOKIE_DOMAIN, COOKIE_SECURE, FORCE_PROFILE_UPDATE, LOGGING_LEVEL
+from astakos.im.functions import login
 
 logger = logging.getLogger(__name__)
 
@@ -142,6 +142,8 @@ def set_cookie(response, user):
     response.set_cookie(COOKIE_NAME, value=cookie_value,
                         expires=expire_fmt, path='/',
                         domain=COOKIE_DOMAIN, secure=COOKIE_SECURE)
+    msg = 'Cookie [expiring %s] set for %s' % (user.auth_token_expires, user.email)
+    logger._log(LOGGING_LEVEL, msg, [])
 
 class lazy_string(object):
     def __init__(self, function, *args, **kwargs):
index 4b7efff..d32e039 100644 (file)
@@ -47,7 +47,6 @@ from django.core.urlresolvers import reverse
 from django.contrib.auth.decorators import login_required
 from django.contrib import messages
 from django.db import transaction
-from django.contrib.auth import logout as auth_logout
 from django.utils.http import urlencode
 from django.http import HttpResponseRedirect, HttpResponseBadRequest
 from django.db.utils import IntegrityError
@@ -58,9 +57,9 @@ from astakos.im.models import AstakosUser, Invitation, ApprovalTerms
 from astakos.im.activation_backends import get_backend, SimpleBackend
 from astakos.im.util import get_context, prepare_response, set_cookie, get_query
 from astakos.im.forms import *
-from astakos.im.functions import send_greeting, send_feedback, SendMailError
+from astakos.im.functions import send_greeting, send_feedback, SendMailError, \
+    invite as invite_func, logout as auth_logout
 from astakos.im.settings import DEFAULT_CONTACT_EMAIL, DEFAULT_FROM_EMAIL, COOKIE_NAME, COOKIE_DOMAIN, IM_MODULES, SITENAME, LOGOUT_NEXT
-from astakos.im.functions import invite as invite_func
 
 logger = logging.getLogger(__name__)
 
@@ -327,6 +326,10 @@ def signup(request, template_name='im/signup.html', on_success='im/signup_comple
                 status = messages.SUCCESS
                 message = result.message
                 user.save()
+                if 'additional_email' in form.cleaned_data:
+                    additional_email = form.cleaned_data['additional_email']
+                    if additional_email != user.email:
+                        user.additionalmail_set.create(email=additional_email)
                 if user and user.is_active:
                     next = request.POST.get('next', '')
                     return prepare_response(request, user, next=next)
@@ -421,7 +424,7 @@ def logout(request, template='registration/logged_out.html', extra_context={}):
     return response
 
 @transaction.commit_manually
-def activate(request, email_template_name='im/welcome_email.txt', on_failure=''):
+def activate(request, email_template_name='im/welcome_email.txt', on_failure='im/signup.html'):
     """
     Activates the user identified by the ``auth`` request parameter, sends a welcome email
     and renews the user token.
@@ -445,9 +448,8 @@ def activate(request, email_template_name='im/welcome_email.txt', on_failure='')
             user.save()
         except ValidationError, e:
             return HttpResponseBadRequest(e)
-        
     else:
-        # switch the local account to shibboleth one
+        # switch the existing account to shibboleth one
         local_user.provider = 'shibboleth'
         local_user.set_unusable_password()
         local_user.third_party_identifier = user.third_party_identifier
@@ -467,13 +469,14 @@ def activate(request, email_template_name='im/welcome_email.txt', on_failure='')
         message = e.message
         messages.add_message(request, messages.ERROR, message)
         transaction.rollback()
-        return signup(request, on_failure='im/signup.html')
+        return render_response(on_failure)
     except BaseException, e:
         status = messages.ERROR
         message = _('Something went wrong.')
+        messages.add_message(request, messages.ERROR, message)
         logger.exception(e)
         transaction.rollback()
-        return signup(request, on_failure='im/signup.html')
+        return signup(request, on_failure)
 
 def approval_terms(request, term_id=None, template_name='im/approval_terms.html', extra_context={}):
     term = None
@@ -518,3 +521,52 @@ def approval_terms(request, term_id=None, template_name='im/approval_terms.html'
 @signed_terms_required
 def change_password(request):
     return password_change(request, post_change_redirect=reverse('astakos.im.views.edit_profile'))
+
+@transaction.commit_manually
+def change_email(request, activation_key=None,
+                 email_template_name='registration/email_change_email.txt',
+                 form_template_name='registration/email_change_form.html',
+                 confirm_template_name='registration/email_change_done.html',
+                 extra_context={}):
+    if activation_key:
+        try:
+            user = EmailChange.objects.change_email(activation_key)
+            if request.user.is_authenticated() and request.user == user:
+                msg = _('Email changed successfully.')
+                messages.add_message(request, messages.SUCCESS, msg)
+                auth_logout(request)
+                response = prepare_response(request, user)
+                transaction.commit()
+                return response
+        except ValueError, e:
+            messages.add_message(request, messages.ERROR, e)
+        return render_response(confirm_template_name,
+                               modified_user = user if 'user' in locals() else None,
+                               context_instance = get_context(request,
+                                                              extra_context))
+    
+    if not request.user.is_authenticated():
+        path = quote(request.get_full_path())
+        url = request.build_absolute_uri(reverse('astakos.im.views.index'))
+        return HttpResponseRedirect(url + '?next=' + path)
+    form = EmailChangeForm(request.POST or None)
+    if request.method == 'POST' and form.is_valid():
+        try:
+            ec = form.save(email_template_name, request)
+        except SendMailError, e:
+            status = messages.ERROR
+            msg = e
+            transaction.rollback()
+        except IntegrityError, e:
+            status = messages.ERROR
+            msg = _('There is already a pending change email request.')
+        else:
+            status = messages.SUCCESS
+            msg = _('Change email request has been registered succefully.\
+                    You are going to receive a verification email in the new address.')
+            transaction.commit()
+        messages.add_message(request, status, msg)
+    return render_response(form_template_name,
+                           form = form,
+                           context_instance = get_context(request,
+                                                          extra_context))
index b22e8f8..7939864 100644 (file)
@@ -1,7 +1,5 @@
 #CLOUDBAR_ACTIVE = True
-#CLOUDBAR_LOCATION = '/static/im/cloudbar/'
+#CLOUDBAR_LOCATION = 'https://accounts.okeanos.grnet.gr/static/im/cloudbar/'
 #CLOUDBAR_COOKIE_NAME = '_pithos2_a'
-#CLOUDBAR_ACTIVE_SERVICE = 'cloud'
-#CLOUDBAR_SERVICES_URL = '/im/get_services'
-#CLOUDBAR_MENU_URL = '/im/get_menu'
-
+#CLOUDBAR_SERVICES_URL = 'https://accounts.okeanos.grnet.gr/im/get_services'
+#CLOUDBAR_MENU_URL = 'https://accounts.okeanos.grnet.gr/im/get_menu'
index 228c58c..6506337 100644 (file)
 # Set service name
 #ASTAKOS_SITENAME = 'GRNET Cloud'
 
-# Set cloud services appear in the horizontal bar
-#ASTAKOS_CLOUD_SERVICES = (
-#        { 'url':'/', 'name':'grnet cloud', 'id':'cloud', 'icon':'home-icon.png' },
-#        { 'url':'/okeanos.html', 'name':'~okeanos', 'id':'okeanos' },
-#        { 'url':'/ui/', 'name':'pithos+', 'id':'pithos' })
-#
-
 # Set recaptcha keys
 # http://www.google.com/recaptcha/whyrecaptcha 
 #ASTAKOS_RECAPTCHA_PUBLIC_KEY = ''
 # e.g. {'warning': 'This warning message will be displayed on the top of login page'}
 #ASTAKOS_LOGIN_MESSAGES = {}
 
+# Messages to display on signup page header
+# e.g. {'warning': 'This warning message will be displayed on the top of signup page'}
+#ASTAKOS_SIGNUP_MESSAGES = {}
+
+# Messages to display on profile page header
+# e.g. {'warning': 'This warning message will be displayed on the top of profile pages'}
+#ASTAKOS_PROFILE_MESSAGES = {}
+
+# Messages to display on global page header
+# e.g. {'warning': 'This warning message will be displayed on the top of all pages'}
+#ASTAKOS_GLOBAL_MESSAGES = {}
+
 # messages to display as extra actions in account forms
 # e.g. {'https://cms.okeanos.grnet.gr/': 'Back to ~okeanos'}
 #ASTAKOS_PROFILE_EXTRA_LINKS = {}
 
+# The number of unsuccessful login requests per minute allowed for a specific email
+#ASTAKOS_RATELIMIT_RETRIES_ALLOWED = 3
+
+# If False the email change mechanism is disabled
+#ASTAKOS_EMAILCHANGE_ENABLED = False
+
+# Set the expiration time (in days) of email change requests
+#ASTAKOS_EMAILCHANGE_ACTIVATION_DAYS = 10
+
+# Set the astakos main functions logging severity (None to disable)
+#from logging import INFO
+#ASTAKOS_LOGGING_LEVEL = INFO