[Mpuls-commits] r1231 - in wasko/branches/2.0: . mpulsweb/lib waskaweb/controllers waskaweb/lib waskaweb/model

scm-commit@wald.intevation.org scm-commit at wald.intevation.org
Thu Feb 4 11:21:55 CET 2010


Author: torsten
Date: 2010-02-04 11:21:45 +0100 (Thu, 04 Feb 2010)
New Revision: 1231

Added:
   wasko/branches/2.0/mpulsweb/lib/security.py
Removed:
   wasko/branches/2.0/waskaweb/lib/security.py
Modified:
   wasko/branches/2.0/ChangeLog
   wasko/branches/2.0/mpulsweb/lib/base.py
   wasko/branches/2.0/waskaweb/controllers/administration.py
   wasko/branches/2.0/waskaweb/controllers/annotations.py
   wasko/branches/2.0/waskaweb/controllers/appointment.py
   wasko/branches/2.0/waskaweb/controllers/case.py
   wasko/branches/2.0/waskaweb/controllers/case_overview.py
   wasko/branches/2.0/waskaweb/controllers/caseappointment.py
   wasko/branches/2.0/waskaweb/controllers/casedocument.py
   wasko/branches/2.0/waskaweb/controllers/document.py
   wasko/branches/2.0/waskaweb/controllers/formularpage.py
   wasko/branches/2.0/waskaweb/controllers/logbook.py
   wasko/branches/2.0/waskaweb/controllers/navigation.py
   wasko/branches/2.0/waskaweb/controllers/phase.py
   wasko/branches/2.0/waskaweb/controllers/statement.py
   wasko/branches/2.0/waskaweb/controllers/usersettings.py
   wasko/branches/2.0/waskaweb/controllers/waska.py
   wasko/branches/2.0/waskaweb/lib/app_globals.py
   wasko/branches/2.0/waskaweb/lib/helpers.py
   wasko/branches/2.0/waskaweb/lib/search.py
   wasko/branches/2.0/waskaweb/model/user.py
Log:
Moved lib/security into base

* mpulsweb/lib/security.py,
  waskaweb/lib/security.py: Moved file.
* waskaweb/model/user.py,
  waskaweb/controllers/caseappointment.py,
  waskaweb/controllers/logbook.py,
  waskaweb/controllers/annotations.py,
  waskaweb/controllers/appointment.py,
  waskaweb/controllers/navigation.py,
  waskaweb/controllers/usersettings.py,
  waskaweb/controllers/phase.py,
  waskaweb/controllers/case_overview.py,
  waskaweb/controllers/statement.py,
  waskaweb/controllers/waska.py,
  waskaweb/controllers/casedocument.py,
  waskaweb/controllers/case.py,
  waskaweb/controllers/document.py,
  waskaweb/controllers/formularpage.py,
  waskaweb/controllers/administration.py,
  waskaweb/lib/helpers.py,
  waskaweb/lib/search.py,
  waskaweb/lib/app_globals.py,
  mpulsweb/lib/base.py: Changed import of security



Modified: wasko/branches/2.0/ChangeLog
===================================================================
--- wasko/branches/2.0/ChangeLog	2010-02-04 10:13:59 UTC (rev 1230)
+++ wasko/branches/2.0/ChangeLog	2010-02-04 10:21:45 UTC (rev 1231)
@@ -1,5 +1,32 @@
 2010-02-04  Torsten Irländer <torsten.irlaender at intevation.de>
 
+	Moved lib/security into base
+
+	* mpulsweb/lib/security.py,
+	  waskaweb/lib/security.py: Moved file.
+	* waskaweb/model/user.py,
+	  waskaweb/controllers/caseappointment.py,
+	  waskaweb/controllers/logbook.py,
+	  waskaweb/controllers/annotations.py,
+	  waskaweb/controllers/appointment.py,
+	  waskaweb/controllers/navigation.py,
+	  waskaweb/controllers/usersettings.py,
+	  waskaweb/controllers/phase.py,
+	  waskaweb/controllers/case_overview.py,
+	  waskaweb/controllers/statement.py,
+	  waskaweb/controllers/waska.py,
+	  waskaweb/controllers/casedocument.py,
+	  waskaweb/controllers/case.py,
+	  waskaweb/controllers/document.py,
+	  waskaweb/controllers/formularpage.py,
+	  waskaweb/controllers/administration.py,
+	  waskaweb/lib/helpers.py,
+	  waskaweb/lib/search.py,
+	  waskaweb/lib/app_globals.py,
+	  mpulsweb/lib/base.py: Changed import of security
+
+2010-02-04  Torsten Irländer <torsten.irlaender at intevation.de>
+
 	* mpulsweb/lib/base.py: Get dbname, port, host and schemes for
 	  username and database name from config object and not from modul vars
 	  from lib.security

Modified: wasko/branches/2.0/mpulsweb/lib/base.py
===================================================================
--- wasko/branches/2.0/mpulsweb/lib/base.py	2010-02-04 10:13:59 UTC (rev 1230)
+++ wasko/branches/2.0/mpulsweb/lib/base.py	2010-02-04 10:21:45 UTC (rev 1231)
@@ -44,7 +44,7 @@
 from mpulsweb.lib.timelog import timeLog
 
 import waskaweb.lib.helpers as h
-from waskaweb.lib.security import getDbName, userIdentity
+from mpulsweb.lib.security import getDbName, userIdentity
 
 import waskaweb.model as model
 

Copied: wasko/branches/2.0/mpulsweb/lib/security.py (from rev 1229, wasko/branches/2.0/waskaweb/lib/security.py)
===================================================================
--- wasko/branches/2.0/waskaweb/lib/security.py	2010-02-04 10:13:11 UTC (rev 1229)
+++ wasko/branches/2.0/mpulsweb/lib/security.py	2010-02-04 10:21:45 UTC (rev 1231)
@@ -0,0 +1,290 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright 2007, 2008 Intevation GmbH, Germany, <info at intevation.de>
+#
+# This file is part of mpuls WASKA (CoMPUter-based case fiLeS -
+# Web-Anwendungs-Server fuer Kompetenzagenturen).
+#
+# mpuls WASKA is free software: you can redistribute it and/or modify it under
+# the terms of the GNU Affero General Public License as published by the
+# Free Software Foundation, either version 3 of the License, or (at your
+# option) any later version.
+#
+# mpuls WASKA is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
+# License for more details.
+#
+# You should have received a copy of the GNU Affero General Public
+# License along with mpuls WASKA. If not, see <http://www.gnu.org/licenses/>.
+#
+# mpuls WASKA has been developed on behalf of the
+# Projekttraeger im Deutschen Zentrum fuer Luft- und Raumfahrt e.V. (PT-DLR)
+# within the programme Kompetenzagenturen (Durchfuehrungsphase) funded by
+# the Bundesministerium fuer Familie, Senioren, Frauen und Jugend and
+# European Social Fund resources.
+#
+# Authors:
+# Sascha L. Teichmann <teichmann at intevation.de>
+# Torsten Irlaender <torsten.irlaender at intevation.de>
+#
+
+import sys
+import os
+import time
+import re
+import random
+import md5
+import traceback
+import logging
+from codecs import getdecoder
+from types import ListType, TupleType
+
+import psycopg2 as dbapi
+
+from decorator import decorator
+
+from paste.httpexceptions import HTTPUnauthorized
+from pylons import request, session, config
+
+from mpulsweb.lib.db import DB, db, enter, leave
+
+
+log = logging.getLogger(__name__)
+
+# maps new FKZs to old
+NEW_DBS = {}
+
+check_re = re.compile(r"^[a-z_0-9]+$")
+
+FETCH_USER_DATA_SQL = """\
+SELECT id, vorname, nachname, passwort_aendern, aktiviert,
+       rolle, gid, last_login, vertreter
+FROM ka_benutzer_tbl_view
+WHERE login = %(login)s
+"""
+UPDATE_LASTLOGIN_SQL = """SELECT set_last_logintime(%(user_id)s)"""
+UNAUTHORIZED_DETAIL = \
+"""Sie sind nicht authorisiert, das angeforderte Dokument anzuschauen.
+"""
+
+ASCII_DECODER = getdecoder("ascii")
+
+log = logging.getLogger(__name__)
+
+
+def slashSplit(s):
+    for p in s.split("/"):
+        if p.find("=") == -1 and out:
+            out[-1] += '/'+ p
+        else:
+            out.append(p)
+    return out
+
+def validPassword(s):
+    try:
+        ASCII_DECODER(s)
+    except (UnicodeEncodeError, UnicodeDecodeError):
+        return False
+    return True
+
+def checkLogin(user, password):
+    dbname = getDbName()
+    if (not password or not validPassword(password)
+        or not dbname or not check_re.match(dbname)
+        or not check_re.match(user)):
+        return None
+
+    # imported here, because waskaweb.lib.helpers also imports
+    # mpulsweb.lib.security which leads to circular imports.
+    # ensure_unicode shouldn't be needed here anymore anyway when the
+    # database returns Unicode objects directly.
+    from waskaweb.lib.helpers import ensure_unicode
+
+    log.info('Login: user "%s" in "%s"' % (user, dbname))
+    try:
+        mydb = DB(dbname=config.get('mpuls.db.database') % dbname, 
+                  host=config.get('mpuls.db.host'), 
+                  port=config.get('mpuls.db.port'),
+                  user=config.get('mpuls.db.user') % (dbname, user), 
+                  password=password)
+        try:
+            enter(mydb)
+            conn, cursor = None, None
+            try:
+                conn = db.getConnection()
+                cursor = conn.cursor()
+                login = "ka_%s_%s" % (dbname, user)
+                fields = {'login': login}
+                cursor.execute(FETCH_USER_DATA_SQL, fields)
+                try:
+                    result = cursor.fetchone()
+                    data = {}
+                    data['id'] = result[0]
+                    data['firstname'] = ensure_unicode(result[1])
+                    data['lastname'] = ensure_unicode(result[2])
+                    data['newpass'] = result[3]
+                    data['activated'] = result[4]
+                    data['role'] = ensure_unicode(result[5])
+                    data['gid'] = result[6]
+                    data['last_login'] = result[7]
+                    data['standin'] = result[8]
+                except:
+                    log.exception("Error fetching user data")
+                    data = None
+            finally:
+                db.recycleConnection(conn, cursor)
+
+            try:
+                from waskaweb.model.user import SessionUser, SessionSuperAdmin
+                if data:
+                    userobject = SessionUser(login, password)
+                    userobject.setData(data)
+                elif user == 'adm':
+                    userobject = SessionSuperAdmin(login, password)
+                else:
+                    return None
+
+                # UPDATE last login time
+                conn, cursor = None, None
+                try:
+                    conn = db.getConnection()
+                    cursor = conn.cursor()
+                    if data:
+                        try:
+                            fields = {'user_id': data.get('id')}
+                            cursor.execute(UPDATE_LASTLOGIN_SQL, fields)
+                            conn.commit()
+                        except StandardError:
+                            log.exception("Error setting last logintime: %r",
+                                          cursor.query)
+                finally:
+                    db.recycleConnection(conn, cursor)
+
+            except StandardError:
+                log.exception("Error creating user Object")
+
+            #RETURN userobject
+            log.info('Login ok :)')
+            return userobject
+        finally:
+            leave(mydb)
+            mydb.closeConnections()
+    except dbapi.OperationalError, err:
+        # This is likely a login failure
+        # XXX: Is there a way in DB Api 2.0 to determine
+        # this database independent?
+        log.exception("OperationalError from database"
+                      " while checking user credentials")
+    except:
+        log.exception("Exception while checking user credentials")
+    log.info('Login failed :(')
+    return None
+
+def generateID(obj=None):
+    array = [time.time(), os.times(), random.random()]
+    if not obj is None:
+        array.append(id(obj))
+    return md5.new(str(array)).hexdigest()
+
+def subnet(addr):
+    """poor man's subnet splitting"""
+    x = addr.rsplit('.', 1) # IPv4
+    if len(x) == 2:
+        return x[0]
+    x = addr.rsplit(':', 1) # IPv6
+    if len(x) == 2:
+        return x[0]
+    return addr
+
+def userIdentity():
+    env = request.environ
+    return "%s" % env.get('HTTP_USER_AGENT', '')
+
+def load_db_mapping_from_file(fname):
+    if os.path.isfile(fname):
+        global NEW_DBS
+        f = None
+        try:
+            f = open(fname, "r")
+            for line in f:
+                line = line.strip()
+                if not line or line.startswith("#"):
+                    continue
+                parts = line.split(';')
+                if len(parts) > 1:
+                    NEW_DBS[parts[0]] = parts[1]
+        finally:
+            if f:
+                try: f.close()
+                except StandardError:
+                    log.exception("Exception while closing db mapping file %r",
+                                  fname)
+    else:
+        log.warning("No file mapping file found named: %r", fname)
+
+def getDbName():
+    dbname = None
+    try:
+        dbname = request.environ['SSL_CLIENT_S_DN_CN'].split(' ')[3].lower()
+        return NEW_DBS.get(dbname, dbname)
+    except:
+        try:
+            dbname = config.get('mpuls.db.name')
+            return NEW_DBS.get(dbname, dbname)
+        except:
+            log.exception("Could not fetch database name from client"
+                          " certificate")
+    return dbname
+
+def getKAName():
+    kaname = ""
+    try:
+        for f in slashSplit(request.environ['SSL_CLIENT_S_DN'])[::-1]:
+            field = f.split('=')
+            # There are two OU. We want the one != WASKA
+            if field[0] == "OU" and field[1] != "WASKA":
+                kaname = field[1]
+    except:
+        try:
+            kaname = config.get('mpuls.app.name')
+        except:
+            log.error("Could not fetch KA-name from client certificate")
+    return kaname
+
+def checkRole(role):
+    if type(role) in (ListType, TupleType):
+        _role = role
+    else:
+        _role = (role,)
+
+    def validate(func, self, *args, **kwargs):
+        if not hasRole(_role):
+            raise HTTPUnauthorized(detail=UNAUTHORIZED_DETAIL)
+        try:
+            return func(self, *args, **kwargs)
+        except dbapi.OperationalError, err:
+            raise HTTPUnauthorized(detail=UNAUTHORIZED_DETAIL)
+
+    return decorator(validate)
+
+def hasRole(rolelist):
+    old_role_names = {
+        'cm_ka': 'cm',
+        'admin_ka': 'admin',
+        'pb_ka': 'pb',
+        }
+    try:
+        user = session['USER_AUTHORIZED']
+        conv_roles = []
+        for r in rolelist:
+            # Mapping of rolenames. The old rolenames are used all over the
+            # application. So change them here.
+            conv_roles.append(old_role_names.get(r, r))
+        user_role = user.getPermissionRole()
+        return user_role in conv_roles
+    except KeyError:
+        return False
+
+
+# vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:


Property changes on: wasko/branches/2.0/mpulsweb/lib/security.py
___________________________________________________________________
Name: svn:mergeinfo
   + 

Modified: wasko/branches/2.0/waskaweb/controllers/administration.py
===================================================================
--- wasko/branches/2.0/waskaweb/controllers/administration.py	2010-02-04 10:13:59 UTC (rev 1230)
+++ wasko/branches/2.0/waskaweb/controllers/administration.py	2010-02-04 10:21:45 UTC (rev 1231)
@@ -34,12 +34,12 @@
 
 from formencode                    import htmlfill
 from waskaweb.lib.base             import *
-from waskaweb.lib.security         import getDbName 
+from mpulsweb.lib.security         import getDbName 
 from waskaweb.lib.validators       import ValidatorStateObject, NewUserForm, EditUserForm, NewPasswordForm, EditSettingsForm, DeleteUserHelperForm, NewUserGroupForm, EditUserGroupForm
 from waskaweb.model.user           import UserObject, UserListObject, UserGroup, UserGroupList, UserGroupFactory
 from waskaweb.model.case           import CaseOverview, CaseBundle 
 from waskaweb.model.agencysettings import Agency
-from waskaweb.lib.security         import checkRole
+from mpulsweb.lib.security         import checkRole
 
 log = logging.getLogger(__name__)
 

Modified: wasko/branches/2.0/waskaweb/controllers/annotations.py
===================================================================
--- wasko/branches/2.0/waskaweb/controllers/annotations.py	2010-02-04 10:13:59 UTC (rev 1230)
+++ wasko/branches/2.0/waskaweb/controllers/annotations.py	2010-02-04 10:21:45 UTC (rev 1231)
@@ -5,7 +5,7 @@
 from pylons import request, response, session, c
 from pylons.controllers.util import abort, redirect_to
 
-from waskaweb.lib.security         import checkRole
+from mpulsweb.lib.security         import checkRole
 from waskaweb.lib.base import BaseController, render
 
 log = logging.getLogger(__name__)

Modified: wasko/branches/2.0/waskaweb/controllers/appointment.py
===================================================================
--- wasko/branches/2.0/waskaweb/controllers/appointment.py	2010-02-04 10:13:59 UTC (rev 1230)
+++ wasko/branches/2.0/waskaweb/controllers/appointment.py	2010-02-04 10:21:45 UTC (rev 1231)
@@ -36,7 +36,7 @@
 from waskaweb.lib.base import BaseController, c, redirect_to, render, request
 
 from waskaweb.lib.helpers import dd_mm_YYYY, HH_MM
-from waskaweb.lib.security import checkRole
+from mpulsweb.lib.security import checkRole
 from waskaweb.lib.validators import CreateAppointmentForm
 
 from waskaweb.model.appointment import GlobalAppointmentOverview, \

Modified: wasko/branches/2.0/waskaweb/controllers/case.py
===================================================================
--- wasko/branches/2.0/waskaweb/controllers/case.py	2010-02-04 10:13:59 UTC (rev 1230)
+++ wasko/branches/2.0/waskaweb/controllers/case.py	2010-02-04 10:21:45 UTC (rev 1231)
@@ -45,7 +45,7 @@
 from waskaweb.lib.search import INCONSISTENCY_CHECK_AFTER
 
 from waskaweb.lib.navigation import get_navigation
-from waskaweb.lib.security import checkRole
+from mpulsweb.lib.security import checkRole
 #from waskaweb.lib.xmlimport import importFromXML
 from waskaweb.lib.validators import NewCaseForm, SetStandinForm, \
      SetEditorForm, WiederaufnahmeCaseForm, \

Modified: wasko/branches/2.0/waskaweb/controllers/case_overview.py
===================================================================
--- wasko/branches/2.0/waskaweb/controllers/case_overview.py	2010-02-04 10:13:59 UTC (rev 1230)
+++ wasko/branches/2.0/waskaweb/controllers/case_overview.py	2010-02-04 10:21:45 UTC (rev 1231)
@@ -39,7 +39,7 @@
 import waskaweb.lib.filters as F
 from waskaweb.lib.validators import SearchCaseForm, BundleActionForm, \
      SetBundleEditorForm, SetBundleStandinForm, CasePartSelectionForm
-from waskaweb.lib.security import checkRole
+from mpulsweb.lib.security import checkRole
 from waskaweb.lib.search import INCONSISTENCY_CHECK_AFTER
 from waskaweb.lib.exportselection import CasePartsSelection
 

Modified: wasko/branches/2.0/waskaweb/controllers/caseappointment.py
===================================================================
--- wasko/branches/2.0/waskaweb/controllers/caseappointment.py	2010-02-04 10:13:59 UTC (rev 1230)
+++ wasko/branches/2.0/waskaweb/controllers/caseappointment.py	2010-02-04 10:21:45 UTC (rev 1231)
@@ -7,7 +7,7 @@
 from pylons import request, response, session, tmpl_context as c
 from pylons.controllers.util import abort, redirect_to
 
-from waskaweb.lib.security import checkRole
+from mpulsweb.lib.security import checkRole
 from waskaweb.lib.base import BaseController, render
 from waskaweb.lib.helpers import url_for, dd_mm_YYYY, HH_MM 
 from waskaweb.lib.validators import CreateAppointmentForm 

Modified: wasko/branches/2.0/waskaweb/controllers/casedocument.py
===================================================================
--- wasko/branches/2.0/waskaweb/controllers/casedocument.py	2010-02-04 10:13:59 UTC (rev 1230)
+++ wasko/branches/2.0/waskaweb/controllers/casedocument.py	2010-02-04 10:21:45 UTC (rev 1231)
@@ -7,7 +7,7 @@
 from pylons.controllers.util import abort, redirect_to
 
 from waskaweb.lib.base import BaseController, render
-from waskaweb.lib.security import checkRole
+from mpulsweb.lib.security import checkRole
 import waskaweb.lib.helpers as h
 from waskaweb.model.case import CaseFactory, LoadCaseNotExistsError
 from waskaweb.model.document import Document, deleteDocument

Modified: wasko/branches/2.0/waskaweb/controllers/document.py
===================================================================
--- wasko/branches/2.0/waskaweb/controllers/document.py	2010-02-04 10:13:59 UTC (rev 1230)
+++ wasko/branches/2.0/waskaweb/controllers/document.py	2010-02-04 10:21:45 UTC (rev 1231)
@@ -41,7 +41,7 @@
 
 from pylons import config
 
-from waskaweb.lib.security import checkRole
+from mpulsweb.lib.security import checkRole
 
 log = logging.getLogger(__name__)
 

Modified: wasko/branches/2.0/waskaweb/controllers/formularpage.py
===================================================================
--- wasko/branches/2.0/waskaweb/controllers/formularpage.py	2010-02-04 10:13:59 UTC (rev 1230)
+++ wasko/branches/2.0/waskaweb/controllers/formularpage.py	2010-02-04 10:21:45 UTC (rev 1231)
@@ -8,7 +8,7 @@
 from pylons import g
 from pylons.i18n import _
 from pylons.controllers.util import abort, redirect_to
-from waskaweb.lib.security          import checkRole
+from mpulsweb.lib.security          import checkRole
 
 from waskaweb.lib.base import BaseController, render
 from mpulsweb.lib.db import  PostgresDBInterface

Modified: wasko/branches/2.0/waskaweb/controllers/logbook.py
===================================================================
--- wasko/branches/2.0/waskaweb/controllers/logbook.py	2010-02-04 10:13:59 UTC (rev 1230)
+++ wasko/branches/2.0/waskaweb/controllers/logbook.py	2010-02-04 10:21:45 UTC (rev 1231)
@@ -28,7 +28,7 @@
 from datetime import datetime
 
 from waskaweb.lib.base import *
-from waskaweb.lib.security import checkRole
+from mpulsweb.lib.security import checkRole
 from waskaweb.lib.validators import CreateLogbookForm, EditLogbookForm
 from waskaweb.model.logbook import Logbook, LogbookEntry, LogbookEntryChecker
 

Modified: wasko/branches/2.0/waskaweb/controllers/navigation.py
===================================================================
--- wasko/branches/2.0/waskaweb/controllers/navigation.py	2010-02-04 10:13:59 UTC (rev 1230)
+++ wasko/branches/2.0/waskaweb/controllers/navigation.py	2010-02-04 10:21:45 UTC (rev 1231)
@@ -34,7 +34,7 @@
 
 from waskaweb.controllers.CaseBase  import CasebaseController 
 from waskaweb.controllers.case      import CaseController 
-from waskaweb.lib.security          import checkRole
+from mpulsweb.lib.security          import checkRole
 from waskaweb.lib.base              import *
 from waskaweb.lib.navigation        import mark_folderopen, mark_folderclose 
 from waskaweb.controllers.formularpage import FormularpageController

Modified: wasko/branches/2.0/waskaweb/controllers/phase.py
===================================================================
--- wasko/branches/2.0/waskaweb/controllers/phase.py	2010-02-04 10:13:59 UTC (rev 1230)
+++ wasko/branches/2.0/waskaweb/controllers/phase.py	2010-02-04 10:21:45 UTC (rev 1231)
@@ -3,7 +3,7 @@
 
 from pylons import session, g, c
 from waskaweb.lib.base import *
-from waskaweb.lib.security import checkRole
+from mpulsweb.lib.security import checkRole
 from waskaweb.model.phase import PhaseFactory 
 
 SET_PHASE_NOTIFICATION_SUCCESS = u"""Phase gewechselt!"""

Modified: wasko/branches/2.0/waskaweb/controllers/statement.py
===================================================================
--- wasko/branches/2.0/waskaweb/controllers/statement.py	2010-02-04 10:13:59 UTC (rev 1230)
+++ wasko/branches/2.0/waskaweb/controllers/statement.py	2010-02-04 10:21:45 UTC (rev 1231)
@@ -33,7 +33,7 @@
 
 from waskaweb.lib.base import c, h, redirect_to, render, session
 from waskaweb.lib.search import INCONSISTENCY_CHECK_AFTER
-from waskaweb.lib.security import checkRole
+from mpulsweb.lib.security import checkRole
 
 from waskaweb.model.phase_transition import PHASE_DESCRIPTIONS
 

Modified: wasko/branches/2.0/waskaweb/controllers/usersettings.py
===================================================================
--- wasko/branches/2.0/waskaweb/controllers/usersettings.py	2010-02-04 10:13:59 UTC (rev 1230)
+++ wasko/branches/2.0/waskaweb/controllers/usersettings.py	2010-02-04 10:21:45 UTC (rev 1231)
@@ -35,7 +35,7 @@
 from waskaweb.lib.base import BaseController, c, h, render, request, session, _
 
 from waskaweb.lib.validators import BaseFormValidator, NewPasswordForm
-from waskaweb.lib.security import checkRole
+from mpulsweb.lib.security import checkRole
 
 from waskaweb.model.user import UserListObject, UserObject, UserGroupList, \
      UserGroup

Modified: wasko/branches/2.0/waskaweb/controllers/waska.py
===================================================================
--- wasko/branches/2.0/waskaweb/controllers/waska.py	2010-02-04 10:13:59 UTC (rev 1230)
+++ wasko/branches/2.0/waskaweb/controllers/waska.py	2010-02-04 10:21:45 UTC (rev 1231)
@@ -34,7 +34,7 @@
 
 from waskaweb.lib.base import BaseController, c, g, h, redirect_to, render, \
      request, response, session
-from waskaweb.lib.security import checkLogin, userIdentity, generateID, \
+from mpulsweb.lib.security import checkLogin, userIdentity, generateID, \
      checkRole
 from waskaweb.model.user import UserObject
 from waskaweb.model.news import NewsList

Modified: wasko/branches/2.0/waskaweb/lib/app_globals.py
===================================================================
--- wasko/branches/2.0/waskaweb/lib/app_globals.py	2010-02-04 10:13:59 UTC (rev 1230)
+++ wasko/branches/2.0/waskaweb/lib/app_globals.py	2010-02-04 10:21:45 UTC (rev 1231)
@@ -35,7 +35,7 @@
 from mpulsweb.lib.config import MpulsConfig
 from mpulsweb.model.annotations import AnnotationsProvider
 
-import waskaweb.lib.security as security
+import mpulsweb.lib.security as security
 
 log = logging.getLogger(__name__)
 

Modified: wasko/branches/2.0/waskaweb/lib/helpers.py
===================================================================
--- wasko/branches/2.0/waskaweb/lib/helpers.py	2010-02-04 10:13:59 UTC (rev 1230)
+++ wasko/branches/2.0/waskaweb/lib/helpers.py	2010-02-04 10:21:45 UTC (rev 1231)
@@ -44,7 +44,7 @@
 from webhelpers.html.tags import *
 
 from waskaweb.lib.navigation import get_pagename, render_navigation
-from waskaweb.lib.security import hasRole, getKAName
+from mpulsweb.lib.security import hasRole, getKAName
 from waskaweb.lib.filters import shorten, nl_to_br
 
 

Modified: wasko/branches/2.0/waskaweb/lib/search.py
===================================================================
--- wasko/branches/2.0/waskaweb/lib/search.py	2010-02-04 10:13:59 UTC (rev 1230)
+++ wasko/branches/2.0/waskaweb/lib/search.py	2010-02-04 10:21:45 UTC (rev 1231)
@@ -35,7 +35,7 @@
 import psycopg2.extras
 
 from mpulsweb.lib.db import db
-from waskaweb.lib.security import hasRole
+from mpulsweb.lib.security import hasRole
 
 SAVE_SEARCH = re.compile(r'[^\w:;\-\. ]', re.UNICODE)
 

Deleted: wasko/branches/2.0/waskaweb/lib/security.py
===================================================================
--- wasko/branches/2.0/waskaweb/lib/security.py	2010-02-04 10:13:59 UTC (rev 1230)
+++ wasko/branches/2.0/waskaweb/lib/security.py	2010-02-04 10:21:45 UTC (rev 1231)
@@ -1,290 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# Copyright 2007, 2008 Intevation GmbH, Germany, <info at intevation.de>
-#
-# This file is part of mpuls WASKA (CoMPUter-based case fiLeS -
-# Web-Anwendungs-Server fuer Kompetenzagenturen).
-#
-# mpuls WASKA is free software: you can redistribute it and/or modify it under
-# the terms of the GNU Affero General Public License as published by the
-# Free Software Foundation, either version 3 of the License, or (at your
-# option) any later version.
-#
-# mpuls WASKA is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
-# License for more details.
-#
-# You should have received a copy of the GNU Affero General Public
-# License along with mpuls WASKA. If not, see <http://www.gnu.org/licenses/>.
-#
-# mpuls WASKA has been developed on behalf of the
-# Projekttraeger im Deutschen Zentrum fuer Luft- und Raumfahrt e.V. (PT-DLR)
-# within the programme Kompetenzagenturen (Durchfuehrungsphase) funded by
-# the Bundesministerium fuer Familie, Senioren, Frauen und Jugend and
-# European Social Fund resources.
-#
-# Authors:
-# Sascha L. Teichmann <teichmann at intevation.de>
-# Torsten Irlaender <torsten.irlaender at intevation.de>
-#
-
-import sys
-import os
-import time
-import re
-import random
-import md5
-import traceback
-import logging
-from codecs import getdecoder
-from types import ListType, TupleType
-
-import psycopg2 as dbapi
-
-from decorator import decorator
-
-from paste.httpexceptions import HTTPUnauthorized
-from pylons import request, session, config
-
-from mpulsweb.lib.db import DB, db, enter, leave
-
-
-log = logging.getLogger(__name__)
-
-# maps new FKZs to old
-NEW_DBS = {}
-
-check_re = re.compile(r"^[a-z_0-9]+$")
-
-FETCH_USER_DATA_SQL = """\
-SELECT id, vorname, nachname, passwort_aendern, aktiviert,
-       rolle, gid, last_login, vertreter
-FROM ka_benutzer_tbl_view
-WHERE login = %(login)s
-"""
-UPDATE_LASTLOGIN_SQL = """SELECT set_last_logintime(%(user_id)s)"""
-UNAUTHORIZED_DETAIL = \
-"""Sie sind nicht authorisiert, das angeforderte Dokument anzuschauen.
-"""
-
-ASCII_DECODER = getdecoder("ascii")
-
-log = logging.getLogger(__name__)
-
-
-def slashSplit(s):
-    for p in s.split("/"):
-        if p.find("=") == -1 and out:
-            out[-1] += '/'+ p
-        else:
-            out.append(p)
-    return out
-
-def validPassword(s):
-    try:
-        ASCII_DECODER(s)
-    except (UnicodeEncodeError, UnicodeDecodeError):
-        return False
-    return True
-
-def checkLogin(user, password):
-    dbname = getDbName()
-    if (not password or not validPassword(password)
-        or not dbname or not check_re.match(dbname)
-        or not check_re.match(user)):
-        return None
-
-    # imported here, because waskaweb.lib.helpers also imports
-    # waskaweb.lib.security which leads to circular imports.
-    # ensure_unicode shouldn't be needed here anymore anyway when the
-    # database returns Unicode objects directly.
-    from waskaweb.lib.helpers import ensure_unicode
-
-    log.info('Login: user "%s" in "%s"' % (user, dbname))
-    try:
-        mydb = DB(dbname=config.get('mpuls.db.database') % dbname, 
-                  host=config.get('mpuls.db.host'), 
-                  port=config.get('mpuls.db.port'),
-                  user=config.get('mpuls.db.user') % (dbname, user), 
-                  password=password)
-        try:
-            enter(mydb)
-            conn, cursor = None, None
-            try:
-                conn = db.getConnection()
-                cursor = conn.cursor()
-                login = "ka_%s_%s" % (dbname, user)
-                fields = {'login': login}
-                cursor.execute(FETCH_USER_DATA_SQL, fields)
-                try:
-                    result = cursor.fetchone()
-                    data = {}
-                    data['id'] = result[0]
-                    data['firstname'] = ensure_unicode(result[1])
-                    data['lastname'] = ensure_unicode(result[2])
-                    data['newpass'] = result[3]
-                    data['activated'] = result[4]
-                    data['role'] = ensure_unicode(result[5])
-                    data['gid'] = result[6]
-                    data['last_login'] = result[7]
-                    data['standin'] = result[8]
-                except:
-                    log.exception("Error fetching user data")
-                    data = None
-            finally:
-                db.recycleConnection(conn, cursor)
-
-            try:
-                from waskaweb.model.user import SessionUser, SessionSuperAdmin
-                if data:
-                    userobject = SessionUser(login, password)
-                    userobject.setData(data)
-                elif user == 'adm':
-                    userobject = SessionSuperAdmin(login, password)
-                else:
-                    return None
-
-                # UPDATE last login time
-                conn, cursor = None, None
-                try:
-                    conn = db.getConnection()
-                    cursor = conn.cursor()
-                    if data:
-                        try:
-                            fields = {'user_id': data.get('id')}
-                            cursor.execute(UPDATE_LASTLOGIN_SQL, fields)
-                            conn.commit()
-                        except StandardError:
-                            log.exception("Error setting last logintime: %r",
-                                          cursor.query)
-                finally:
-                    db.recycleConnection(conn, cursor)
-
-            except StandardError:
-                log.exception("Error creating user Object")
-
-            #RETURN userobject
-            log.info('Login ok :)')
-            return userobject
-        finally:
-            leave(mydb)
-            mydb.closeConnections()
-    except dbapi.OperationalError, err:
-        # This is likely a login failure
-        # XXX: Is there a way in DB Api 2.0 to determine
-        # this database independent?
-        log.exception("OperationalError from database"
-                      " while checking user credentials")
-    except:
-        log.exception("Exception while checking user credentials")
-    log.info('Login failed :(')
-    return None
-
-def generateID(obj=None):
-    array = [time.time(), os.times(), random.random()]
-    if not obj is None:
-        array.append(id(obj))
-    return md5.new(str(array)).hexdigest()
-
-def subnet(addr):
-    """poor man's subnet splitting"""
-    x = addr.rsplit('.', 1) # IPv4
-    if len(x) == 2:
-        return x[0]
-    x = addr.rsplit(':', 1) # IPv6
-    if len(x) == 2:
-        return x[0]
-    return addr
-
-def userIdentity():
-    env = request.environ
-    return "%s" % env.get('HTTP_USER_AGENT', '')
-
-def load_db_mapping_from_file(fname):
-    if os.path.isfile(fname):
-        global NEW_DBS
-        f = None
-        try:
-            f = open(fname, "r")
-            for line in f:
-                line = line.strip()
-                if not line or line.startswith("#"):
-                    continue
-                parts = line.split(';')
-                if len(parts) > 1:
-                    NEW_DBS[parts[0]] = parts[1]
-        finally:
-            if f:
-                try: f.close()
-                except StandardError:
-                    log.exception("Exception while closing db mapping file %r",
-                                  fname)
-    else:
-        log.warning("No file mapping file found named: %r", fname)
-
-def getDbName():
-    dbname = None
-    try:
-        dbname = request.environ['SSL_CLIENT_S_DN_CN'].split(' ')[3].lower()
-        return NEW_DBS.get(dbname, dbname)
-    except:
-        try:
-            dbname = config.get('mpuls.db.name')
-            return NEW_DBS.get(dbname, dbname)
-        except:
-            log.exception("Could not fetch database name from client"
-                          " certificate")
-    return dbname
-
-def getKAName():
-    kaname = ""
-    try:
-        for f in slashSplit(request.environ['SSL_CLIENT_S_DN'])[::-1]:
-            field = f.split('=')
-            # There are two OU. We want the one != WASKA
-            if field[0] == "OU" and field[1] != "WASKA":
-                kaname = field[1]
-    except:
-        try:
-            kaname = config.get('mpuls.app.name')
-        except:
-            log.error("Could not fetch KA-name from client certificate")
-    return kaname
-
-def checkRole(role):
-    if type(role) in (ListType, TupleType):
-        _role = role
-    else:
-        _role = (role,)
-
-    def validate(func, self, *args, **kwargs):
-        if not hasRole(_role):
-            raise HTTPUnauthorized(detail=UNAUTHORIZED_DETAIL)
-        try:
-            return func(self, *args, **kwargs)
-        except dbapi.OperationalError, err:
-            raise HTTPUnauthorized(detail=UNAUTHORIZED_DETAIL)
-
-    return decorator(validate)
-
-def hasRole(rolelist):
-    old_role_names = {
-        'cm_ka': 'cm',
-        'admin_ka': 'admin',
-        'pb_ka': 'pb',
-        }
-    try:
-        user = session['USER_AUTHORIZED']
-        conv_roles = []
-        for r in rolelist:
-            # Mapping of rolenames. The old rolenames are used all over the
-            # application. So change them here.
-            conv_roles.append(old_role_names.get(r, r))
-        user_role = user.getPermissionRole()
-        return user_role in conv_roles
-    except KeyError:
-        return False
-
-
-# vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:

Modified: wasko/branches/2.0/waskaweb/model/user.py
===================================================================
--- wasko/branches/2.0/waskaweb/model/user.py	2010-02-04 10:13:59 UTC (rev 1230)
+++ wasko/branches/2.0/waskaweb/model/user.py	2010-02-04 10:21:45 UTC (rev 1231)
@@ -28,7 +28,7 @@
 from pylons import session
 
 import waskaweb.lib.helpers as h
-from waskaweb.lib.security import getDbName
+from mpulsweb.lib.security import getDbName
 from mpulsweb.lib.db import db
 
 



More information about the Mpuls-commits mailing list