diff --git a/modules/webaccess/doc/admin/guide.html.wml b/modules/webaccess/doc/admin/guide.html.wml
index 360c4b0ec..6b32d588b 100644
--- a/modules/webaccess/doc/admin/guide.html.wml
+++ b/modules/webaccess/doc/admin/guide.html.wml
@@ -1,874 +1,878 @@
## $Id$
## This file is part of the CERN Document Server Software (CDSware).
## Copyright (C) 2002 CERN.
##
## The CDSware is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your option) any later version.
##
## The CDSware 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
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with CDSware; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
#include "cdspage.wml" \
title="WebAccess Admin Guide" \
navtrail_previous_links="/admin/>Admin Area > /admin/webaccess/>WebAccess Admin " \
navbar_name="admin" \
navbar_select="webaccess-admin-guide"
Version <: print generate_pretty_revision_date_string('$Id$'); :>
WebAccess is a common RBAC, role based access control, for all of
CDSware. This means that users are connected to roles that cover
different areas of access. I.e administrator of the photo
collection or system librarian. Users can be active in
different areas and of course connected to as many roles as needed.
The roles are connected to actions. An action identifies a task you
can perform in CDSware. It can be defined to take any number of
arguments in order to more clearly describe what you are allowing
connected users to do.
For example the system librarian can be allowed to run bibwords on
the different indexes. To allow system librarians to run the
bibwords indexing on the field author we connect role system
librarian with action runbibwords using the argument
index='author'.
WebAccess is based on allowing users to perform actions. This means
that only allowed actions are stored in the access control engine's
database.
All the WebAccess Administration web pages have certain
features/design choices in common
- Divided into steps
The process of adding new authorizations/information is
stepwise. The subtitle contains information about wich step you are
on and what you are supposed to do.
- Restart from any wanted step
You can always start from an earlier step by simply clicking the
wanted button. This is not a way to undo changes! No information
about previous database is kept, so all changes are definite.
- Change or new entry must confirmed
On all the pages you will be asked to confirm the change, with
information about what kind of change you are about to perform.
- Links to other relevant admin areas on the right side
To make it easier to perform your administration tasks, we have
added a menu area on the right hand side of these pages. The menu
contain links to other relevant admin pages and change according to
the page you are on and the information you have selected.
I. Role area
II. Example - connecting role and user
I. Role area
Administration tasks starts in one of the administration areas. The
role area is the main area from where you can perform all your
managing tasks. The other admin areas are just other ways of
entering.
II. Example - connecting role and user
One of the important tasks that can be handled via the WebAccess Admin Web Interface
is the delegation of access rights to users. This is done by connecting them to the
different roles offered.
The task is divided into 5 simple and comprehensive steps. Below follows the pages from
the different steps with comments on the ongoing procedure.
- step 1 - select a role
You must first select the role you want to connect users to. All the available roles are
listed alfabetically in a select box. Just find the wanted role and select it. Then click on
the button saying "select role".
If you start from the Role Area, this step is already done, and you start directly on step 2.
- step 2 - search for users
As you can see, the subtitle of the page has now changed. The subtitle always tells you
which step you are on and what your current task is.
There can be possibly thousands of users using your online library, therefore it is important
to make it easier to identify the user you are looking for. Give part of, or the entire search
string and all users with partly matching e-mails will be listed on the next step.
You can also see that the right hand menu has changed. This area is always updated with links
to related admin areas.
start adding new authorizations to role superadmin.
- step 3 - select a user.
The select box contains all users with partly matching e-mail adresses. Select the one
you want to connect to the role and continue.
Notice the navigation trail that tells you were on the Administrator pages you are currently
working.
start adding new authorizations to role superadmin.
- step 4 - confirm to add user
All WebAccess Administrator web pages display the action you are about to peform, this
means explaining what kind of addition, change or update will be done to your access control
data.
If you are happy with your decision, simply confirm it.
start adding new authorizations to role superadmin.
- step 5 - confirm user added.
The user has now been added to this role. You can easily continue adding more users to this
role be restarting from step 2 or 3. You can also go directly to another area and keep working
on the same role.
start adding new authorizations to role superadmin.
- we are done
This example is very similar to all the other pages where you administrate WebAccess. The pages
are an easy gateway to maintaing access control rights and share a lot of features.
- divided into steps
- restart from any wanted step (not undo)
- changes must be confirmed
- link to other relevant areas
- prevent unwanted input
As an administrator with access to these pages you are free to manage the rights any way you want.
Here you can administrate the accounts and the access policy for your CDSware installation.
- Access policy:
To change the access policy, the access_control_config.py file must be edited manually in a
- text editor. You can edit the access policy level for guest accounts, registered accounts
- and decide when to warn the owner of the account when something happens with it, either when
- it is created, deleted or approved. The apache server must be restarted after modifying these
- settings.
+ text editor. The site can here be defined as opened or closed, you can edit the access policy
+ level for guest accounts, registered accounts and decide when to warn the owner of the
+ account when something happens with it, either when it is created, deleted or approved.
+ The apache server must be restarted after modifying these settings.
The two levels for guest account, are:
0 - Allow guest accounts
1 - Do not allow guest accounts
The three levels for normal accounts, are:
0 - Allow user to create account, automatically activate new accounts
1 - Allow user to create account, administrator must activate account
2 - Only administrators can create account. User cannot edit the email address.
You can configure CDSware to send an email:
1. To an admin email-address when an account is created
2. To the owner of an account when it is created
3. To the owner of an account when it is activated
4. To the owner of an account when it is deleted
- The variables in access_control_config.py:
+ - Site open or closed for all access
+ 0 = closed
+ 1 = open
+ CFG_SITE_OPEN = 1
- Access policy for guests.
0 = Allow guests to search,
1 = Guests cannot search (all users must login)
CFG_ACCESS_CONTROL_LEVEL_GUESTS = 0
- Access policy for accounts.
0 = Users can register, automatically acticate accounts
1 = Users can register, but admin must activate the accounts
2 = Users cannot register or change email address, only admin can register accounts.
CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS = 0
- Limit email addresses available to use when register a new account (example: cern.ch).
CFG_ACCESS_CONTROL_LIMIT_TO_DOMAIN = ""
- Send an email when a new account is created by an user
CFG_ACCESS_CONTROL_NOTIFY_ADMIN_ABOUT_NEW_ACCOUNTS = 0
- Send it to this email-address
CFG_ACCESS_CONTROL_SEND_TO_EMAIL = adminemail
- Send an email to the user notifying when the account is created
CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_NEW_ACCOUNT = 0
- Send an email to the user notifying when the account is activated
CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_ACTIVATION = 0
- Send an email to the user notifying when the account is deleted/rejected
CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_DELETION = 0
- Account overview:
Here you find an overview of the number of guest accounts, registered accounts and accounts
awaiting activation, with a link to the activation page.
- Create account:
For creating new accounts, the email address must be unique. If configured to do so, an email
will be sent to the given address when an account is created.
- Edit accounts:
For activating or rejecting accounts in addition to modifying them. An activated account can be
inactivated for a short period of time, but this will not warn the account owner. To find accounts
enter a part of the email address of the account and then search. This may take some time. If there
are more than the selected number of accounts per page, you can use the next/prev links to switch
pages. The accounts to search in can also be limited to only activated or not activated accounts.
- Edit account:
When editing one account, you can change the email address, password, delete the account, or modify
the baskets or alerts belonging to one account. To modify baskets or alerts, you need to login
as the user, and modify the desired data as a normal user. Remember to log out as the user when you
are finished editing.
- end of file -
diff --git a/modules/webaccess/lib/access_control_config.py b/modules/webaccess/lib/access_control_config.py
index e34d5cd9e..d6ad93aa5 100644
--- a/modules/webaccess/lib/access_control_config.py
+++ b/modules/webaccess/lib/access_control_config.py
@@ -1,135 +1,141 @@
## $Id$
## CDSware Access Control Config in mod_python.
## This file is part of the CERN Document Server Software (CDSware).
## Copyright (C) 2002 CERN.
##
## The CDSware is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your option) any later version.
##
## The CDSware 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
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with CDSware; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
#include "config.wml"
#include "configbis.wml"
supportemail = ""
adminemail = ""
"""CDSware Access Control Config. """
## okay, rest of the Python code goes below #######
__version__ = "$Id$"
from config import *
# VALUES TO BE EXPORTED
# CURRENTLY USED BY THE FILES access_control_engine.py access_control_admin.py webaccessadmin_lib.py
# name of the role giving superadmin rights
SUPERADMINROLE = 'superadmin'
# name of the webaccess webadmin role
WEBACCESSADMINROLE = 'webaccessadmin'
# name of the action allowing roles to access the web administrator interface
WEBACCESSACTION = 'cfgwebaccess'
# name of the action allowing roles to delegate the rights to other roles
# ex: libraryadmin to delegate libraryworker
DELEGATEADDUSERROLE = 'accdelegaterole'
# max number of users to display in the drop down selects
MAXSELECTUSERS = 25
# max number of users to display in a page (mainly for user area)
MAXPAGEUSERS = 25
+# site open or closed for all access
+#0 = closed
+#1 = open
+CFG_SITE_OPEN = 1
# access policy for guests.
#0 = Allow guests to search,
#1 = Guests cannot search (all users must login)
CFG_ACCESS_CONTROL_LEVEL_GUESTS = 0
# access policy for accounts.
#0 = Users can register, automatically acticate accounts
#1 = Users can register, but admin must activate the accounts
#2 = Users cannot register or update email address, only admin can register accounts.
CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS = 0
# limit email addresses available to use when register a new account (example: cern.ch):
CFG_ACCESS_CONTROL_LIMIT_TO_DOMAIN = ""
# send an email when a new account is created by an user
CFG_ACCESS_CONTROL_NOTIFY_ADMIN_ABOUT_NEW_ACCOUNTS = 0
# send it to this email-address
CFG_ACCESS_CONTROL_SEND_TO_EMAIL = adminemail
# send an email to the user notifying when the account is created
CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_NEW_ACCOUNT = 0
# send an email to the user notifying when the account is activated
CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_ACTIVATION = 0
# send an email to the user notifying when the account is deleted/rejected
CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_DELETION = 0
# default data for the add_default_settings function
# roles
# name description
def_roles = ((SUPERADMINROLE, 'superuser with all rights'),
('photoadmin', 'Photo collection administrator'),
(WEBACCESSADMINROLE, 'WebAccess administrator'))
# users
# list of e-mail addresses
def_users = []
# actions
# name desc allowedkeywords optional
def_actions = (
('cfgwebsearch', 'configure WebSearch', '', 'no'),
('cfgbibformat', 'configure BibFormat', '', 'no'),
('cfgwebsubmit', 'configure WebSubmit', '', 'no'),
('runbibindex', 'run BibIndex', '', 'no'),
('runbibupload', 'run BibUpload', '', 'no'),
('runwebcoll', 'run webcoll', 'collection', 'yes'),
('runbibformat', 'run BibFormat', 'format', 'yes'),
(WEBACCESSACTION, 'configure WebAccess', '', 'no'),
(DELEGATEADDUSERROLE, 'delegate subroles inside WebAccess', 'role', 'no'),
('runbibtaskex', 'run BibTaskEx example', '', 'no'),
('referee', 'referee document type doctype/category categ', 'doctype,categ', 'yes'),
('submit', 'use webSubmit', 'doctype,act', 'yes'),
('runbibrank', 'run BibRank', '', 'no'),
('cfgbibrank', 'configure BibRank', '', 'no'),
)
# authorizations
# role action arglistid optional arguments
def_auths = (
(SUPERADMINROLE, 'cfgwebsearch', -1, 0, {}),
(SUPERADMINROLE, 'cfgbibformat', -1, 0, {}),
(SUPERADMINROLE, 'cfgwebsubmit', -1, 0, {}),
(SUPERADMINROLE, 'runbibindex', -1, 0, {}),
(SUPERADMINROLE, 'runbibupload', -1, 0, {}),
(SUPERADMINROLE, 'runbibformat', -1, 1, {}),
(SUPERADMINROLE, WEBACCESSACTION, -1, 0, {}),
('photoadmin', 'runwebcoll', -1, 0, {'collection': 'Pictures'}),
(WEBACCESSADMINROLE,WEBACCESSACTION, -1, 0, {}),
(SUPERADMINROLE, 'runtaskex', -1, 0, {}),
(SUPERADMINROLE, 'referee', -1, 1, {}),
(SUPERADMINROLE, 'submit', -1, 1, {}),
(SUPERADMINROLE, 'runbibrank', -1, 0, {}),
(SUPERADMINROLE, 'cfgbibrank', -1, 0, {}),
)
cfg_webaccess_msgs = {
0: 'Try to login with another account.' % (weburl, weburl, "%s"),
- 1: ' If you think this is not correct, please contact: %s' % (supportemail, supportemail)
+ 1: ' If you think this is not correct, please contact: %s' % (supportemail, supportemail),
+ 2: ' Any questions should be sent to: %s' % (supportemail, supportemail)
}
cfg_webaccess_warning_msgs = {
0: 'Authorization granted',
1: 'Error(1): You are not authorized to perform this action.',
2: 'Error(2): You are not authorized to perform any action.',
3: 'Error(3): The action %s does not exist.',
4: 'Error(4): Unexpected error occurred.',
5: 'Error(5): Missing mandatory keyword argument(s) for this action.',
6: 'Error(6): Guest accounts are not authorized to perform this action.',
7: 'Error(7): Not enough arguments, user ID and action name required.',
8: 'Error(8): Incorrect keyword argument(s) for this action.',
- 9: """Error(9): Account '%s' is not yet activated."""
+ 9: """Error(9): Account '%s' is not yet activated.""",
+ 10: """The site is currently closed for maintenance."""
}
\ No newline at end of file
diff --git a/modules/webaccess/lib/access_control_config.py.wml b/modules/webaccess/lib/access_control_config.py.wml
index e34d5cd9e..d6ad93aa5 100644
--- a/modules/webaccess/lib/access_control_config.py.wml
+++ b/modules/webaccess/lib/access_control_config.py.wml
@@ -1,135 +1,141 @@
## $Id$
## CDSware Access Control Config in mod_python.
## This file is part of the CERN Document Server Software (CDSware).
## Copyright (C) 2002 CERN.
##
## The CDSware is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your option) any later version.
##
## The CDSware 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
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with CDSware; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
#include "config.wml"
#include "configbis.wml"
supportemail = ""
adminemail = ""
"""CDSware Access Control Config. """
## okay, rest of the Python code goes below #######
__version__ = "$Id$"
from config import *
# VALUES TO BE EXPORTED
# CURRENTLY USED BY THE FILES access_control_engine.py access_control_admin.py webaccessadmin_lib.py
# name of the role giving superadmin rights
SUPERADMINROLE = 'superadmin'
# name of the webaccess webadmin role
WEBACCESSADMINROLE = 'webaccessadmin'
# name of the action allowing roles to access the web administrator interface
WEBACCESSACTION = 'cfgwebaccess'
# name of the action allowing roles to delegate the rights to other roles
# ex: libraryadmin to delegate libraryworker
DELEGATEADDUSERROLE = 'accdelegaterole'
# max number of users to display in the drop down selects
MAXSELECTUSERS = 25
# max number of users to display in a page (mainly for user area)
MAXPAGEUSERS = 25
+# site open or closed for all access
+#0 = closed
+#1 = open
+CFG_SITE_OPEN = 1
# access policy for guests.
#0 = Allow guests to search,
#1 = Guests cannot search (all users must login)
CFG_ACCESS_CONTROL_LEVEL_GUESTS = 0
# access policy for accounts.
#0 = Users can register, automatically acticate accounts
#1 = Users can register, but admin must activate the accounts
#2 = Users cannot register or update email address, only admin can register accounts.
CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS = 0
# limit email addresses available to use when register a new account (example: cern.ch):
CFG_ACCESS_CONTROL_LIMIT_TO_DOMAIN = ""
# send an email when a new account is created by an user
CFG_ACCESS_CONTROL_NOTIFY_ADMIN_ABOUT_NEW_ACCOUNTS = 0
# send it to this email-address
CFG_ACCESS_CONTROL_SEND_TO_EMAIL = adminemail
# send an email to the user notifying when the account is created
CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_NEW_ACCOUNT = 0
# send an email to the user notifying when the account is activated
CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_ACTIVATION = 0
# send an email to the user notifying when the account is deleted/rejected
CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_DELETION = 0
# default data for the add_default_settings function
# roles
# name description
def_roles = ((SUPERADMINROLE, 'superuser with all rights'),
('photoadmin', 'Photo collection administrator'),
(WEBACCESSADMINROLE, 'WebAccess administrator'))
# users
# list of e-mail addresses
def_users = []
# actions
# name desc allowedkeywords optional
def_actions = (
('cfgwebsearch', 'configure WebSearch', '', 'no'),
('cfgbibformat', 'configure BibFormat', '', 'no'),
('cfgwebsubmit', 'configure WebSubmit', '', 'no'),
('runbibindex', 'run BibIndex', '', 'no'),
('runbibupload', 'run BibUpload', '', 'no'),
('runwebcoll', 'run webcoll', 'collection', 'yes'),
('runbibformat', 'run BibFormat', 'format', 'yes'),
(WEBACCESSACTION, 'configure WebAccess', '', 'no'),
(DELEGATEADDUSERROLE, 'delegate subroles inside WebAccess', 'role', 'no'),
('runbibtaskex', 'run BibTaskEx example', '', 'no'),
('referee', 'referee document type doctype/category categ', 'doctype,categ', 'yes'),
('submit', 'use webSubmit', 'doctype,act', 'yes'),
('runbibrank', 'run BibRank', '', 'no'),
('cfgbibrank', 'configure BibRank', '', 'no'),
)
# authorizations
# role action arglistid optional arguments
def_auths = (
(SUPERADMINROLE, 'cfgwebsearch', -1, 0, {}),
(SUPERADMINROLE, 'cfgbibformat', -1, 0, {}),
(SUPERADMINROLE, 'cfgwebsubmit', -1, 0, {}),
(SUPERADMINROLE, 'runbibindex', -1, 0, {}),
(SUPERADMINROLE, 'runbibupload', -1, 0, {}),
(SUPERADMINROLE, 'runbibformat', -1, 1, {}),
(SUPERADMINROLE, WEBACCESSACTION, -1, 0, {}),
('photoadmin', 'runwebcoll', -1, 0, {'collection': 'Pictures'}),
(WEBACCESSADMINROLE,WEBACCESSACTION, -1, 0, {}),
(SUPERADMINROLE, 'runtaskex', -1, 0, {}),
(SUPERADMINROLE, 'referee', -1, 1, {}),
(SUPERADMINROLE, 'submit', -1, 1, {}),
(SUPERADMINROLE, 'runbibrank', -1, 0, {}),
(SUPERADMINROLE, 'cfgbibrank', -1, 0, {}),
)
cfg_webaccess_msgs = {
0: 'Try to login with another account.' % (weburl, weburl, "%s"),
- 1: ' If you think this is not correct, please contact: %s' % (supportemail, supportemail)
+ 1: ' If you think this is not correct, please contact: %s' % (supportemail, supportemail),
+ 2: ' Any questions should be sent to: %s' % (supportemail, supportemail)
}
cfg_webaccess_warning_msgs = {
0: 'Authorization granted',
1: 'Error(1): You are not authorized to perform this action.',
2: 'Error(2): You are not authorized to perform any action.',
3: 'Error(3): The action %s does not exist.',
4: 'Error(4): Unexpected error occurred.',
5: 'Error(5): Missing mandatory keyword argument(s) for this action.',
6: 'Error(6): Guest accounts are not authorized to perform this action.',
7: 'Error(7): Not enough arguments, user ID and action name required.',
8: 'Error(8): Incorrect keyword argument(s) for this action.',
- 9: """Error(9): Account '%s' is not yet activated."""
+ 9: """Error(9): Account '%s' is not yet activated.""",
+ 10: """The site is currently closed for maintenance."""
}
\ No newline at end of file
diff --git a/modules/webaccess/lib/webaccessadmin_lib.py b/modules/webaccess/lib/webaccessadmin_lib.py
index 8dc0097d1..5902b1e34 100644
--- a/modules/webaccess/lib/webaccessadmin_lib.py
+++ b/modules/webaccess/lib/webaccessadmin_lib.py
@@ -1,3407 +1,3408 @@
## $Id$
## Administrator interface for WebAccess
## This file is part of the CERN Document Server Software (CDSware).
## Copyright (C) 2002 CERN.
##
## The CDSware is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your option) any later version.
##
## The CDSware 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
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with CDSware; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
## read config variables:
#include "config.wml"
#include "configbis.wml"
## $Id$## DO NOT EDIT THIS FILE! IT WAS AUTOMATICALLY GENERATED FROM CDSware WML SOURCES.
"""CDSware WebAccess Administrator Interface."""
__lastupdated__ = """<: print `date +"%d %b %Y %H:%M:%S %Z"`; :>"""
## fill config variables:
import access_control_engine as acce
import access_control_admin as acca
# reload(acce)
# reload(acca)
import cgi
import re
import random
import MySQLdb
import string
import smtplib
from bibrankadminlib import adderrorbox,addadminbox,tupletotable,tupletotable_onlyselected,addcheckboxes,createhiddenform
from access_control_config import *
from dbquery import run_sql
from config import *
from webpage import page, pageheaderonly, pagefooteronly
from webuser import getUid, get_email
from mod_python import apache
from search_engine import print_record
from cdsware.webuser import checkemail
__version__ = "$Id$"
def index(req, title='', body='', subtitle='', adminarea=2, authorized=0):
"""main function to show pages for webaccessadmin.
1. if user not logged in and administrator, show the mustlogin page
2. if used without body argument, show the startpage
3. show admin page with title, body, subtitle and navtrail.
adminarea - number codes that tell what extra info to put in the navtrail
0 - nothing extra
1 - add Delegate Rights
2 - add Manage WebAccess
maybe add:
3: role admin
4: action admin
5: user area
6: reset area
authorized - if 1, don't check if the user is allowed to be webadmin """
navtrail_previous_links = """Admin Area > WebAccess Admin """ % (weburl, weburl)
if body:
if adminarea == 1: navtrail_previous_links += '> Delegate Rights ' % (weburl, )
if adminarea >= 2 and adminarea < 7: navtrail_previous_links += '> Manage WebAccess ' % (weburl, )
if adminarea == 3: navtrail_previous_links += '> Role Administration ' % (weburl, )
elif adminarea == 4: navtrail_previous_links += '> Action Administration ' % (weburl, )
elif adminarea == 5: navtrail_previous_links += '> User Administration ' % (weburl, )
elif adminarea == 6: navtrail_previous_links += '> Reset Authorizations ' % (weburl, )
elif adminarea == 7: navtrail_previous_links += '> Manage Accounts ' % (weburl, )
id_user = getUid(req)
(auth_code, auth_message) = is_adminuser(req)
if not authorized and auth_code != 0: return mustloginpage(req, auth_message)
elif not body:
title = 'Manage WebAccess'
body = startpage()
elif type(body) != str: body = addadminbox(subtitle, datalist=body)
return page(title=title,
uid=id_user,
body=body,
navtrail=navtrail_previous_links,
lastupdated=__lastupdated__)
def mustloginpage(req, message):
"""show a page asking the user to login."""
navtrail_previous_links = """Admin Area > WebAccess Admin """ % (weburl, weburl)
return page(title='Authorization failure',
uid=getUid(req),
body=adderrorbox('Reason:',
datalist=[message]),
navtrail=navtrail_previous_links,
lastupdated=__lastupdated__)
def is_adminuser(req):
"""check if user is a registered administrator. """
id_user = getUid(req)
return acce.acc_authorize_action(id_user, WEBACCESSACTION)
def perform_rolearea(req):
"""create the role area menu page."""
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
header = ['id', 'name', 'description', 'users', 'authorizations / actions', 'role', '']
roles = acca.acc_getAllRoles()
roles2 = []
for (id, name, desc) in roles:
if len(desc) > 30: desc = desc[:30] + '...'
roles2.append([id, name, desc])
for col in [(('add', 'adduserrole'),
('remove', 'deleteuserrole')),
(('add', 'addauthorization'),
('modify', 'modifyauthorizations'),
('remove', 'deleteroleaction')),
(('delete', 'deleterole'), ),
(('show details', 'showroledetails'), )]:
roles2[-1].append('%s' % (col[0][1], id, col[0][0]))
for (str, function) in col[1:]:
roles2[-1][-1] += ' / %s' % (function, id, str)
output = """
Users:
add or remove users from the access to a role and its priviliges.
Authorizations/Actions:
these terms means almost the same, but an authorization is a
connection between a role and an action (possibly) containing arguments.
Roles:
see all the information attached to a role and decide if you want to delete it.
"""
output += tupletotable(header=header, tuple=roles2)
extra = """
"""
return index(req=req,
title='Action Administration',
subtitle='administration with actions as access point',
body=[output, extra],
adminarea=2)
def perform_userarea(req, email_user_pattern=''):
"""create area to show info about users. """
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
subtitle = 'step 1 - search for users'
output = """
search for users to display.
"""
# remove letters not allowed in an email
email_user_pattern = cleanstring_email(email_user_pattern)
text = ' 1. search for user\n'
text += ' \n' % (email_user_pattern, )
output += createhiddenform(action="userarea",
text=text,
button="search for users")
if email_user_pattern:
users1 = run_sql("""SELECT id, email FROM user WHERE email RLIKE '%s' ORDER BY email LIMIT %s""" % (email_user_pattern, MAXPAGEUSERS+1))
if not users1:
output += '
no matching users
'
else:
subtitle = 'step 2 - select what to do with user'
users = []
for (id, email) in users1[:MAXPAGEUSERS]:
users.append([id, email])
for col in [(('add', 'addroleuser'),
('remove', 'deleteuserrole')),
(('show details', 'showuserdetails'), )]:
users[-1].append('%s' % (col[0][1], email_user_pattern, id, col[0][0]))
for (str, function) in col[1:]:
users[-1][-1] += ' / %s' % (function, email_user_pattern, id, str)
output += '
keep all changes and add the default authorization settings.
"""
return index(req=req,
title='Reset Authorizations',
subtitle='reseting to or adding default authorizations',
body=[output],
adminarea=2)
def perform_resetdefaultsettings(req, superusers=[], confirm=0):
"""delete all roles, actions and authorizations presently in the database
and add only the default roles.
only selected users will be added to superadmin, rest is blank """
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
# cleaning input
if type(superusers) == str: superusers = [superusers]
# remove not valid e-mails
for email in superusers:
if not check_email(email): superusers.remove(email)
# instructions
output = """
before you reset the settings, we need some users
to connect to %s.
enter as many e-mail adresses you want and press reset. confirm reset settings when you have added enough e-mails. is added as default.
'
output += tupletotable(header=['e-mail address'],
tuple=superusers,
start=start,
extracolumn=extra,
end=end)
if confirm in [1, "1"]:
res = acca.acc_reset_default_settings(superusers)
if res:
output += '
successfully reset default settings
'
else:
output += '
sorry, could not reset default settings
'
return index(req=req,
title='Reset Default Settings',
subtitle='reset settings',
body=[output],
adminarea=6)
def perform_adddefaultsettings(req, superusers=[], confirm=0):
"""add the default settings, and keep everything else.
probably nothing will be deleted, except if there has been made changes to the defaults."""
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
# cleaning input
if type(superusers) == str: superusers = [superusers]
# remove not valid e-mails
for email in superusers:
if not check_email(email): superusers.remove(email)
# instructions
output = """
before you add the settings, we need some users
to connect to %s.
enter as many e-mail adresses you want and press add. confirm add settings when you have added enough e-mails. is added as default.
""" % (weburl, weburl, weburl, weburl, weburl)
if mtype == "perform_accesspolicy" and content:
fin_output += content
elif mtype == "perform_accesspolicy" or mtype == "perform_showall":
fin_output += perform_accesspolicy(req, callback='')
fin_output += " "
if mtype == "perform_accountoverview" and content:
fin_output += content
elif mtype == "perform_accountoverview" or mtype == "perform_showall":
fin_output += perform_accountoverview(req, callback='')
fin_output += " "
if mtype == "perform_createaccount" and content:
fin_output += content
elif mtype == "perform_createaccount" or mtype == "perform_showall":
fin_output += perform_createaccount(req, callback='')
fin_output += " "
if mtype == "perform_modifyaccounts" and content:
fin_output += content
elif mtype == "perform_modifyaccounts" or mtype == "perform_showall":
fin_output += perform_modifyaccounts(req, callback='')
fin_output += " "
return index(req=req,
title='Manage Accounts',
subtitle=subtitle,
body=[fin_output],
adminarea=0,
authorized=1)
def perform_accesspolicy(req, callback='yes', confirm=0):
"""Modify default behaviour of a guest user or if new accounts should automatically/manually be modified."""
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
subtitle = """1. Access policy.   [?]""" % weburl
account_policy = {}
account_policy[0] = "Users can register new accounts. New accounts automatically activated."
account_policy[1] = "Users can register new accounts. Admin users must activate the accounts."
account_policy[2] = "Only admin can register new accounts. User cannot edit email address."
output = " Current settings: "
+ output += "Site open: %s " % (CFG_SITE_OPEN == 1 and "Yes" or "No")
output += "Guest accounts allowed: %s " % (CFG_ACCESS_CONTROL_LEVEL_GUESTS == 0 and "Yes" or "No")
output += "Account policy: %s " % (account_policy[CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS])
output += "Allowed email addresses limited: %s " % (CFG_ACCESS_CONTROL_LIMIT_TO_DOMAIN and CFG_ACCESS_CONTROL_LIMIT_TO_DOMAIN or "Not limited")
output += "Send email to admin when new account: %s " % (CFG_ACCESS_CONTROL_NOTIFY_ADMIN_ABOUT_NEW_ACCOUNTS == 1 and "Yes" or "No")
output += "Use which email address: %s " % (CFG_ACCESS_CONTROL_SEND_TO_EMAIL)
output += "Send email to user after creating new account: %s " % (CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_NEW_ACCOUNT == 1 and "Yes" or "No")
output += "Send email to user when account is activated: %s " % (CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_ACTIVATION == 1 and "Yes" or "No")
output += "Send email to user when account is deleted/rejected: %s " % (CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_DELETION == 1 and "Yes" or "No")
output += " Changing the settings: "
output += "Currently, all changes must be done using your favourite editor, and the webserver restarted for changes to take effect. For the settings to change, either look in the guide or in access_control_config.py ."
try:
body = [output, extra]
except NameError:
body = [output]
if callback:
return perform_manageaccounts(req, "perform_accesspolicy", addadminbox(subtitle, body))
else:
return addadminbox(subtitle, body)
def perform_accountoverview(req, callback='yes', confirm=0):
"""Modify default behaviour of a guest user or if new accounts should automatically/manually be modified."""
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
subtitle = """2. Account overview.   [?]""" % weburl
output = ""
res = run_sql("SELECT COUNT(*) FROM user WHERE email=''")
output += "Guest accounts: %s " % res[0][0]
res = run_sql("SELECT COUNT(*) FROM user WHERE email!=''")
output += "Registered accounts: %s " % res[0][0]
res = run_sql("SELECT COUNT(*) FROM user WHERE email!='' AND note='0' OR note IS NULL")
output += "Inactive accounts: %s " % res[0][0]
if res[0][0] > 0:
output += ' [Activate/Reject accounts]'
res = run_sql("SELECT COUNT(*) FROM user")
output += " Total nr of accounts: %s " % res[0][0]
try:
body = [output, extra]
except NameError:
body = [output]
if callback:
return perform_manageaccounts(req, "perform_accountoverview", addadminbox(subtitle, body))
else:
return addadminbox(subtitle, body)
def perform_createaccount(req, email='', password='', callback='yes', confirm=0):
"""Modify default behaviour of a guest user or if new accounts should automatically/manually be modified."""
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
subtitle = """3. Create account.   [?]""" % weburl
output = ""
text = ' Email:\n'
text += ' ' % (email, )
text += ' Password:\n'
text += ' ' % (password, )
output += createhiddenform(action="createaccount",
text=text,
confirm=1,
button="Create")
if confirm in [1, "1"] and email and checkemail(email):
res = run_sql("SELECT * FROM user WHERE email='%s'" % MySQLdb.escape_string(email))
if not res:
res = run_sql("INSERT INTO user (email,password, note) values('%s','%s', '1')" % (MySQLdb.escape_string(email), MySQLdb.escape_string(password)))
if CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_NEW_ACCOUNT == 1:
emailsent = sendNewUserAccountWarning(email, email, password)
if password:
output += 'Account created with password and activated.'
else:
output += 'Account created without password and activated.'
if CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_NEW_ACCOUNT == 1:
if emailsent:
output += ' An email has been sent to the owner of the account.'
else:
output += ' Could not send an email to the owner of the account.'
else:
output += 'An account with the same email already exists.'
elif confirm in [1, "1"]:
output += 'Please specify an valid email-address.'
try:
body = [output, extra]
except NameError:
body = [output]
if callback:
return perform_manageaccounts(req, "perform_createaccount", addadminbox(subtitle, body))
else:
return addadminbox(subtitle, body)
def perform_modifyaccountstatus(req, userID, email_user_pattern, limit_to, maxpage, page, callback='yes', confirm=0):
"""set a disabled account to enabled and opposite"""
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
res = run_sql("SELECT id, email, note, password FROM user WHERE id=%s" % userID)
output = ""
if res:
if res[0][2] in [0, "0", None]:
res2 = run_sql("UPDATE user SET note=1 WHERE id=%s" % userID)
output += """The account '%s' has been activated.""" % res[0][1]
if CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_ACTIVATION == 1:
emailsent = sendAccountActivatedMessage(res[0][1], res[0][1], res[0][3])
if emailsent:
output += """ An email has been sent to the owner of the account."""
else:
output += """ Could not send an email to the owner of the account."""
elif res[0][2] in [1, "1"]:
res2 = run_sql("UPDATE user SET note=0 WHERE id=%s" % userID)
output += """The account '%s' has been set inactive.""" % res[0][1]
else:
output += 'The account id given does not exist.'
try:
body = [output, extra]
except NameError:
body = [output]
if callback:
return perform_modifyaccounts(req, email_user_pattern, limit_to, maxpage, page, content=output, callback='yes')
else:
return addadminbox(subtitle, body)
def perform_editaccount(req, userID, mtype='', content='', callback='yes', confirm=-1):
"""form to modify an account. this method is calling other methods which again is calling this and sending back the output of the method.
if callback, the method will call perform_editcollection, if not, it will just return its output.
userID - id of the user
mtype - the method that called this method.
content - the output from that method."""
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
res = run_sql("SELECT id, email FROM user WHERE id=%s" % userID)
if not res:
if mtype == "perform_deleteaccount":
text = """The selected account has been deleted, to continue editing, go back to 'Manage Accounts'."""
if CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_DELETION == 1:
text += """ An email has been sent to the owner of the account."""
else:
text = """The selected accounts does not exist, please go back and select an account to edit."""
return index(req=req,
title='Edit Account',
subtitle="Edit account",
body=[text],
adminarea=7,
authorized=1)
fin_output = """
""" % (weburl, userID, weburl, userID, weburl, userID, weburl, userID, weburl, userID, weburl, userID)
if mtype == "perform_modifylogindata" and content:
fin_output += content
elif mtype == "perform_modifylogindata" or not mtype:
fin_output += perform_modifylogindata(req, userID, callback='')
if mtype == "perform_modifybasket" and content:
fin_output += content
elif mtype == "perform_modifybasket" or not mtype:
fin_output += perform_modifybasket(req, userID, callback='')
if mtype == "perform_modifypreferences" and content:
fin_output += content
elif mtype == "perform_modifypreferences" or not mtype:
fin_output += perform_modifypreferences(req, userID, callback='')
if mtype == "perform_modifyalerts" and content:
fin_output += content
elif mtype == "perform_modifyalerts" or not mtype:
fin_output += perform_modifyalerts(req, userID, callback='')
if mtype == "perform_deleteaccount" and content:
fin_output += content
elif mtype == "perform_deleteaccount" or not mtype:
fin_output += perform_deleteaccount(req, userID, callback='')
return index(req=req,
title='Edit Account',
subtitle="Edit account '%s'" % res[0][1],
body=[fin_output],
adminarea=7,
authorized=1)
def perform_modifybasket(req, userID, callback='yes', confirm=0):
"""modify email and password of an account"""
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
subtitle = """2. Modify baskets.   [?]""" % weburl
res = run_sql("SELECT id, email, password FROM user WHERE id=%s" % userID)
output = ""
if res:
text = """To modify the baskets for this account, you have to login as the user."""
output += createhiddenform(action="%s/youraccount.py/login?" % weburl,
text=text,
p_email=res[0][1],
p_pw=res[0][2],
referer="%s/yourbaskets.py/display" % weburl,
button="Login")
output += "Remember that you will be logged out as the current user."
#baskets = run_sql("SELECT basket.id, basket.name, basket.public FROM basket, user_basket WHERE id_user=%s and user_basket.id_basket=basket.id" % userID)
#output += "
" % (name, (public=="y" and "Yes" or "No"))
# basket_records = run_sql("SELECT id_record, nb_order FROM basket_record WHERE id_basket=%s" % id)
# for (id_record, nb_order) in basket_records:
# output += "
"
else:
output += 'The account id given does not exist.'
try:
body = [output, extra]
except NameError:
body = [output]
if callback:
return perform_editaccount(req, userID, mtype='perform_modifybasket', content=addadminbox(subtitle, body), callback='yes')
else:
return addadminbox(subtitle, body)
def perform_modifylogindata(req, userID, email='', password='', callback='yes', confirm=0):
"""modify email and password of an account"""
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
subtitle = """1. Edit login-data.   [?]""" % weburl
res = run_sql("SELECT id, email, password FROM user WHERE id=%s" % userID)
output = ""
if res:
if not email and not password:
email = res[0][1]
password = res[0][2]
text = ' Account id:%s \n' % userID
text += ' Email:\n'
text += ' ' % (email, )
text += ' Password:\n'
text += ' ' % (password, )
output += createhiddenform(action="modifylogindata",
text=text,
userID=userID,
confirm=1,
button="Modify")
if confirm in [1, "1"] and email and checkemail(email):
res = run_sql("UPDATE user SET email='%s' WHERE id=%s" % (MySQLdb.escape_string(email), userID))
res = run_sql("UPDATE user SET password='%s' WHERE id=%s" % (MySQLdb.escape_string(password), userID))
output += 'Email and/or password modified.'
elif confirm in [1, "1"]:
output += 'Please specify an valid email-address.'
else:
output += 'The account id given does not exist.'
try:
body = [output, extra]
except NameError:
body = [output]
if callback:
return perform_editaccount(req, userID, mtype='perform_modifylogindata', content=addadminbox(subtitle, body), callback='yes')
else:
return addadminbox(subtitle, body)
def perform_modifyalerts(req, userID, callback='yes', confirm=0):
"""modify email and password of an account"""
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
subtitle = """3. Modify alerts.   [?]""" % weburl
res = run_sql("SELECT id, email, password FROM user WHERE id=%s" % userID)
output = ""
if res:
text = """To modify the alerts for this account, you have to login as the user."""
output += createhiddenform(action="%s/youraccount.py/login?" % weburl,
text=text,
p_email=res[0][1],
p_pw=res[0][2],
referer="%s/youralerts.py/display" % weburl,
button="Login")
output += "Remember that you will be logged out as the current user."
res= """ SELECT q.id, q.urlargs, a.id_basket,
a.alert_name, a.frequency, a.notification,
DATE_FORMAT(a.date_creation,'%%d %%b %%Y'),
DATE_FORMAT(a.date_lastrun,'%%d %%b %%Y')
FROM query q, user_query_basket a
WHERE a.id_user='%s' AND a.id_query=q.id
ORDER BY a.alert_name ASC """ % userID
#res = run_sql(res)
#for (qID, qurlargs, id_basket, alertname, frequency, notification, date_creation, date_lastrun) in res:
# output += "%s - %s - %s - %s - %s - %s - %s " % (qID, id_basket, alertname, frequency, notification, date_creation, date_lastrun)
else:
output += 'The account id given does not exist.'
try:
body = [output, extra]
except NameError:
body = [output]
if callback:
return perform_editaccount(req, userID, mtype='perform_modifyalerts', content=addadminbox(subtitle, body), callback='yes')
else:
return addadminbox(subtitle, body)
def perform_modifypreferences(req, userID, callback='yes', confirm=0):
"""modify email and password of an account"""
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
subtitle = """4. Modify preferences.   [?]""" % weburl
res = run_sql("SELECT id, email, password FROM user WHERE id=%s" % userID)
output = ""
if res:
output += """Not implemented yet."""
else:
output += 'The account id given does not exist.'
try:
body = [output, extra]
except NameError:
body = [output]
if callback:
return perform_editaccount(req, userID, mtype='perform_modifypreferences', content=addadminbox(subtitle, body), callback='yes')
else:
return addadminbox(subtitle, body)
def perform_deleteaccount(req, userID, callback='yes', confirm=0):
"""delete account"""
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
subtitle = """5. Delete account.   [?]""" % weburl
res = run_sql("SELECT id, email, password FROM user WHERE id=%s" % userID)
output = ""
if res:
if confirm in [0, "0"]:
text = 'Are you sure you want to delete the account with email: "%s"?' % res[0][1]
output += createhiddenform(action="deleteaccount",
text=text,
userID=userID,
confirm=1,
button="Delete")
elif confirm in [1, "1"]:
res2 = run_sql("DELETE FROM user WHERE id=%s" % userID)
output += 'Account deleted.'
if CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_DELETION == 1:
emailsent = sendAccountDeletedMessage(res[0][1], res[0][1])
else:
output += 'The account id given does not exist.'
try:
body = [output, extra]
except NameError:
body = [output]
if callback:
return perform_editaccount(req, userID, mtype='perform_deleteaccount', content=addadminbox(subtitle, body), callback='yes')
else:
return addadminbox(subtitle, body)
def perform_rejectaccount(req, userID, email_user_pattern, limit_to, maxpage, page, callback='yes', confirm=0):
"""Delete account and send an email to the owner."""
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
res = run_sql("SELECT id, email, password, note FROM user WHERE id=%s" % userID)
output = ""
if res:
res2 = run_sql("DELETE FROM user WHERE id=%s" % userID)
output += 'Account rejected and deleted.'
if CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_DELETION == 1:
if not res[0][3] or res[0][3] == "0":
emailsent = sendAccountRejectedMessage(res[0][1], res[0][1])
elif res[0][3] == "1":
emailsent = sendAccountDeletedMessage(res[0][1], res[0][1])
if emailsent:
output += """ An email has been sent to the owner of the account."""
else:
output += """ Could not send an email to the owner of the account."""
else:
output += 'The account id given does not exist.'
try:
body = [output, extra]
except NameError:
body = [output]
if callback:
return perform_modifyaccounts(req, email_user_pattern, limit_to, maxpage, page, content=output, callback='yes')
else:
return addadminbox(subtitle, body)
def perform_modifyaccounts(req, email_user_pattern='', limit_to=-1, maxpage=MAXPAGEUSERS, page=1, content='', callback='yes', confirm=0):
"""Modify default behaviour of a guest user or if new accounts should automatically/manually be modified."""
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
subtitle = """4. Edit accounts.   [?]""" % weburl
output = ""
# remove letters not allowed in an email
email_user_pattern = cleanstring_email(email_user_pattern)
try:
maxpage = int(maxpage)
except:
maxpage = MAXPAGEUSERS
try:
page = int(page)
if page < 1:
page = 1
except:
page = 1
text = ' Email (part of):\n'
text += ' ' % (email_user_pattern, )
text += """Limit to: """ % ((limit_to=="all" and "selected" or ""), (limit_to=="enabled" and "selected" or ""), (limit_to=="disabled" and "selected" or ""))
text += """Accounts per page: """ % ((maxpage==25 and "selected" or ""), (maxpage==50 and "selected" or ""), (maxpage==100 and "selected" or ""), (maxpage==250 and "selected" or ""), (maxpage==500 and "selected" or ""), (maxpage==1000 and "selected" or ""))
output += createhiddenform(action="modifyaccounts",
text=text,
button="search for accounts")
if limit_to not in [-1, "-1"] and maxpage:
users1 = "SELECT id,email,note FROM user WHERE "
if limit_to == "enabled":
users1 += " email!='' AND note=1"
elif limit_to == "disabled":
users1 += " email!='' AND note=0 OR note IS NULL"
elif limit_to == "guest":
users1 += " email=''"
else:
users1 += " email!=''"
if email_user_pattern:
users1 += " AND email RLIKE '%s'" % (email_user_pattern)
users1 += " ORDER BY email LIMIT %s" % (maxpage * page + 1)
users1 = run_sql(users1)
if not users1:
output += 'There are no accounts matching the email given.'
else:
users = []
if maxpage * (page - 1) > len(users1):
page = len(users1) / maxpage + 1
for (id, email, note) in users1[maxpage * (page - 1):(maxpage * page)]:
users.append(['', id, email, (note=="1" and 'Active' or 'Inactive')])
for col in [(((note=="1" and 'Inactivate' or 'Activate'), 'modifyaccountstatus'), ((note == "0" and 'Reject' or 'Delete'), 'rejectaccount'), ),
(('Edit account', 'editaccount'), ),]:
users[-1].append('%s' % (col[0][1], id, email_user_pattern, limit_to, maxpage, page, random.randint(0,1000), col[0][0]))
for (str, function) in col[1:]:
users[-1][-1] += ' / %s' % (function, id, email_user_pattern, limit_to, maxpage, page, random.randint(0,1000), str)
last = ""
next = ""
if len(users1) > maxpage:
if page > 1:
last += 'Last Page' % (email_user_pattern, limit_to, maxpage, (page - 1))
if len(users1[maxpage * (page - 1):(maxpage * page)]) == maxpage:
next += 'Next page' % (email_user_pattern, limit_to, maxpage, (page + 1))
output += 'Showing accounts %s-%s:' % (1 + maxpage * (page - 1), maxpage * page)
else:
output += '%s matching account(s):' % len(users1)
output += tupletotable(header=[last, 'id', 'email', 'Status', '', '',next], tuple=users)
else:
output += 'Please select which accounts to find and how many to show per page.'
if content:
output += " %s" % content
try:
body = [output, extra]
except NameError:
body = [output]
if callback:
return perform_manageaccounts(req, "perform_modifyaccounts", addadminbox(subtitle, body))
else:
return addadminbox(subtitle, body)
def perform_delegate_startarea(req):
"""start area for lower level delegation of rights."""
subtitle = 'select what to do'
output = ''
if is_adminuser(req)[0] == 0:
output += """
You are also allowed to be in the Main Admin Area which gives you
the access to the full functionality of WebAccess.
spesialized area to set up the delegation rights used in the areas above.
you need to be a web administrator to access the area.
"""
return index(req=req,
title='Delegate Rights',
subtitle=subtitle,
body=[output],
adminarea=0,
authorized=1)
def perform_delegate_adminsetup(req, id_role_admin=0, id_role_delegate=0, confirm=0):
"""lets the webadmins set up the delegation rights for the other roles
id_role_admin - the role to be given delegation rights
id_role_delegate - the role over which the delegation rights are given
confirm - make the connection happen """
subtitle = 'step 1 - select admin role'
admin_roles = acca.acc_getAllRoles()
output = """
This is a specialized area to handle a task that also can be handled
from the "add authorization" interface.
By handling the delegation rights here you get the advantage of
not having to select the correct action (%s) or
remembering the names of available roles.
""" % (DELEGATEADDUSERROLE, )
output += createroleselect(id_role=id_role_admin,
step=1,
button='select admin role',
name='id_role_admin',
action='delegate_adminsetup',
roles=admin_roles)
if str(id_role_admin) != '0':
subtitle = 'step 2 - select delegate role'
name_role_admin = acca.acc_getRoleName(id_role=id_role_admin)
delegate_roles_old = acca.acc_find_delegated_roles(id_role_admin=id_role_admin)
delegate_roles = []
delegate_roles_old_names = []
for role in admin_roles:
if (role,) not in delegate_roles_old:
delegate_roles.append(role)
else:
delegate_roles_old_names.append(role[1])
if delegate_roles_old_names:
delegate_roles_old_names.sort()
names_str = ''
for name in delegate_roles_old_names:
if names_str: names_str += ', '
names_str += name
output += '
Warning: don't hand out delegation rights that can harm the system (e.g. delegating superrole).
"""
output += createhiddenform(action="delegate_adminsetup",
text='let role %s delegate rights over role %s?' % (name_role_admin, name_role_delegate),
id_role_admin=id_role_admin,
id_role_delegate=id_role_delegate,
confirm=1)
if int(confirm):
subtitle = 'step 4 - confirm delegation right added'
# res1 = acca.acc_addRoleActionArguments_names(name_role=name_role_admin,
# name_action=DELEGATEADDUSERROLE,
# arglistid=-1,
# optional=0,
# role=name_role_delegate)
res1 = acca.acc_addAuthorization(name_role=name_role_admin,
name_action=DELEGATEADDUSERROLE,
optional=0,
role=name_role_delegate)
if res1:
output += '
confirm: role %s delegates role %s.' % (name_role_admin, name_role_delegate)
else: output += '
sorry, delegation right could not be added, it probably already exists.
'
# see if right hand menu is available
try: body = [output, extra]
except NameError: body = [output]
return index(req=req,
title='Delegate Rights',
subtitle=subtitle,
body=body,
adminarea=1)
def perform_delegate_adduserrole(req, id_role=0, email_user_pattern='', id_user=0, confirm=0):
"""let a lower level web admin add users to a limited set of roles.
id_role - the role to connect to a user
id_user - the user to connect to a role
confirm - make the connection happen """
# finding the allowed roles for this user
id_admin = getUid(req)
id_action = acca.acc_getActionId(name_action=DELEGATEADDUSERROLE)
actions = acca.acc_findPossibleActionsUser(id_user=id_admin, id_action=id_action)
allowed_roles = []
allowed_id_roles = []
for (id, arglistid, name_role_help) in actions[1:]:
id_role_help = acca.acc_getRoleId(name_role=name_role_help)
if id_role_help and [id_role_help, name_role_help, ''] not in allowed_roles:
allowed_roles.append([id_role_help, name_role_help, ''])
allowed_id_roles.append(str(id_role_help))
output = ''
if not allowed_roles:
subtitle = 'no delegation rights'
output += """
You do not have the delegation rights over any roles.
If you think you should have such rights, contact a WebAccess Administrator.
Lower level delegation of access rights to roles.
An administrator with all rights have to give you these rights.
"""
email_out = acca.acc_getUserEmail(id_user=id_user)
name_role = acca.acc_getRoleName(id_role=id_role)
output += createroleselect(id_role=id_role, step=1, name='id_role',
action='delegate_adduserrole', roles=allowed_roles)
if str(id_role) != '0' and str(id_role) in allowed_id_roles:
subtitle = 'step 2 - search for users'
# remove letters not allowed in an email
email_user_pattern = cleanstring_email(email_user_pattern)
text = ' 2. search for user \n'
text += ' \n' % (email_user_pattern, )
output += createhiddenform(action="delegate_adduserrole",
text=text,
button="search for users",
id_role=id_role)
# pattern is entered
if email_user_pattern:
# users with matching email-address
users1 = run_sql("""SELECT id, email FROM user WHERE email RLIKE '%s' ORDER BY email """ % (email_user_pattern, ))
# users that are connected
users2 = run_sql("""SELECT DISTINCT u.id, u.email
FROM user u LEFT JOIN user_accROLE ur ON u.id = ur.id_user
WHERE ur.id_accROLE = '%s' AND u.email RLIKE '%s'
ORDER BY u.email """ % (id_role, email_user_pattern))
# no users that match the pattern
if not (users1 or users2):
output += '
no qualified users, try new search.
'
# too many matching users
elif len(users1) > MAXSELECTUSERS:
output += '
%s hits, too many qualified users, specify more narrow search. (limit %s)
' % (len(users1), MAXSELECTUSERS)
# show matching users
else:
subtitle = 'step 3 - select a user'
users = []
extrausers = []
for (id, email) in users1:
if (id, email) not in users2: users.append([id,email,''])
for (id, email) in users2:
extrausers.append([-id, email,''])
output += createuserselect(id_user=id_user,
action="delegate_adduserrole",
step=3,
users=users,
extrausers=extrausers,
button="add this user",
id_role=id_role,
email_user_pattern=email_user_pattern)
try: id_user = int(id_user)
except ValueError: pass
# user selected already connected to role
if id_user < 0:
output += '
users in brackets are already attached to the role, try another one...
'
# a user is selected
elif email_out:
subtitle = "step 4 - confirm to add user"
output += createhiddenform(action="delegate_adduserrole",
text='add user %s to role %s?' % (email_out, name_role),
id_role=id_role,
email_user_pattern=email_user_pattern,
id_user=id_user,
confirm=1)
# it is confirmed that this user should be added
if confirm:
# add user
result = acca.acc_addUserRole(id_user=id_user, id_role=id_role)
if result and result[2]:
subtitle = 'step 5 - confirm user added'
output += '
confirm: user %s added to role %s.
' % (email_out, name_role)
else:
subtitle = 'step 5 - user could not be added'
output += '
remove users from the roles you have delegating rights to.
""" % (id_role, )
return index(req=req,
title='Connect users to roles',
subtitle=subtitle,
body=[output, extra],
adminarea=1,
authorized=1)
def perform_delegate_deleteuserrole(req, id_role=0, id_user=0, confirm=0):
"""let a lower level web admin remove users from a limited set of roles.
id_role - the role to connect to a user
id_user - the user to connect to a role
confirm - make the connection happen """
subtitle = 'in progress...'
output = '
in progress...
'
# finding the allowed roles for this user
id_admin = getUid(req)
id_action = acca.acc_getActionId(name_action=DELEGATEADDUSERROLE)
actions = acca.acc_findPossibleActionsUser(id_user=id_admin, id_action=id_action)
output = ''
if not actions:
subtitle = 'no delegation rights'
output += """
You do not have the delegation rights over any roles.
If you think you should have such rights, contact a WebAccess Administrator.
Lower level delegation of access rights to roles.
An administrator with all rights have to give you these rights.
"""
email_out = acca.acc_getUserEmail(id_user=id_user)
name_role = acca.acc_getRoleName(id_role=id_role)
# create list of allowed roles
allowed_roles = []
allowed_id_roles = []
for (id, arglistid, name_role_help) in actions[1:]:
id_role_help = acca.acc_getRoleId(name_role=name_role_help)
if id_role_help and [id_role_help, name_role_help, ''] not in allowed_roles:
allowed_roles.append([id_role_help, name_role_help, ''])
allowed_id_roles.append(str(id_role_help))
output += createroleselect(id_role=id_role, step=1,
action='delegate_deleteuserrole', roles=allowed_roles)
if str(id_role) != '0' and str(id_role) in allowed_id_roles:
subtitle = 'step 2 - select user'
users = acca.acc_getRoleUsers(id_role)
output += createuserselect(id_user=id_user,
step=2,
action='delegate_deleteuserrole',
users=users,
id_role=id_role)
if str(id_user) != '0':
subtitle = 'step 3 - confirm delete of user'
email_user = acca.acc_getUserEmail(id_user=id_user)
output += createhiddenform(action="delegate_deleteuserrole",
text='delete user %s from %s?'
% (headerstrong(user=id_user), headerstrong(role=id_role)),
id_role=id_role,
id_user=id_user,
confirm=1)
if confirm:
res = acca.acc_deleteUserRole(id_user=id_user, id_role=id_role)
if res:
subtitle = 'step 4 - confirm user deleted from role'
output += '
confirm: deleted user %s from role %s.
' % (email_user, name_role)
else:
subtitle = 'step 4 - user could not be deleted'
output += 'sorry, but user could not be deleted user is probably already deleted.'
extra = """
'
return output
def perform_addrole(req, name_role='', description='put description here.', confirm=0):
"""form to add a new role with these values:
name_role - name of the new role
description - optional description of the role """
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
name_role = cleanstring(name_role)
title='Add Role'
subtitle = 'step 1 - give values to the requested fields'
output = """
""" % (name_role, description)
if name_role:
# description must be changed before submitting
subtitle = 'step 2 - confirm to add role'
internaldesc = ''
if description != 'put description here.':
internaldesc = description
text = """
add role with: \n
name: %s """ % (name_role, )
if internaldesc:
text += 'description: %s?\n' % (description, )
output += createhiddenform(action="addrole",
text=text,
name_role=name_role,
description=description,
confirm=1)
if confirm not in ["0", 0]:
result = acca.acc_addRole(name_role=name_role,
description=internaldesc)
if result:
subtitle = 'step 3 - role added'
output += '
role added:
'
output += tupletotable(header=['id', 'action name', 'description', 'allowedkeywords'],
tuple=[result])
else:
subtitle = 'step 3 - role could not be added'
output += '
sorry, could not add role, role with the same name probably exists.
'
id_role = acca.acc_getRoleId(name_role=name_role)
extra = """
'
return details
def perform_adduserrole(req, id_role='0', email_user_pattern='', id_user='0', confirm=0):
"""create connection between user and role.
id_role - id of the role to add user to
email_user_pattern - search for users using this pattern
id_user - id of user to add to the role. """
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
email_out = acca.acc_getUserEmail(id_user=id_user)
name_role = acca.acc_getRoleName(id_role=id_role)
title = 'Connect user to role '
subtitle = 'step 1 - select a role'
output = createroleselect(id_role=id_role,
action="adduserrole",
step=1,
roles=acca.acc_getAllRoles())
# role is selected
if id_role != "0":
title += name_role
subtitle = 'step 2 - search for users'
# remove letters not allowed in an email
email_user_pattern = cleanstring_email(email_user_pattern)
text = ' 2. search for user \n'
text += ' \n' % (email_user_pattern, )
output += createhiddenform(action="adduserrole",
text=text,
button="search for users",
id_role=id_role)
# pattern is entered
if email_user_pattern:
# users with matching email-address
users1 = run_sql("""SELECT id, email FROM user WHERE email RLIKE '%s' ORDER BY email """ % (email_user_pattern, ))
# users that are connected
users2 = run_sql("""SELECT DISTINCT u.id, u.email
FROM user u LEFT JOIN user_accROLE ur ON u.id = ur.id_user
WHERE ur.id_accROLE = '%s' AND u.email RLIKE '%s'
ORDER BY u.email """ % (id_role, email_user_pattern))
# no users that match the pattern
if not (users1 or users2):
output += '
no qualified users, try new search.
'
elif len(users1) > MAXSELECTUSERS:
output += '
%s hits, too many qualified users, specify more narrow search. (limit %s)
' % (len(users1), MAXSELECTUSERS)
# show matching users
else:
subtitle = 'step 3 - select a user'
users = []
extrausers = []
for (id, email) in users1:
if (id, email) not in users2: users.append([id,email,''])
for (id, email) in users2:
extrausers.append([-id, email,''])
output += createuserselect(id_user=id_user,
action="adduserrole",
step=3,
users=users,
extrausers=extrausers,
button="add this user",
id_role=id_role,
email_user_pattern=email_user_pattern)
try: id_user = int(id_user)
except ValueError: pass
# user selected already connected to role
if id_user < 0:
output += '
users in brackets are already attached to the role, try another one...
'
# a user is selected
elif email_out:
subtitle = "step 4 - confirm to add user"
output += createhiddenform(action="adduserrole",
text='add user %s to role %s?' % (email_out, name_role),
id_role=id_role,
email_user_pattern=email_user_pattern,
id_user=id_user,
confirm=1)
# it is confirmed that this user should be added
if confirm:
# add user
result = acca.acc_addUserRole(id_user=id_user, id_role=id_role)
if result and result[2]:
subtitle = 'step 5 - confirm user added'
output += '
confirm: user %s added to role %s.
' % (email_out, name_role)
else:
subtitle = 'step 5 - user could not be added'
output += '
""" % (id_role, name_role, id_role, name_role, id_role, name_role)
return index(req=req,
title=title,
subtitle=subtitle,
body=[output, extra],
adminarea=3)
def perform_addroleuser(req, email_user_pattern='', id_user='0', id_role='0', confirm=0):
"""delete connection between role and user.
id_role - id of role to disconnect
id_user - id of user to disconnect. """
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
email_out = acca.acc_getUserEmail(id_user=id_user)
name_role = acca.acc_getRoleName(id_role=id_role)
# used to sort roles, and also to determine right side links
con_roles = []
not_roles = []
title = 'Connect user to roles'
subtitle = 'step 1 - search for users'
# clean email search string
email_user_pattern = cleanstring_email(email_user_pattern)
text = ' 1. search for user \n'
text += ' \n' % (email_user_pattern, )
output = createhiddenform(action='addroleuser',
text=text,
button='search for users',
id_role=id_role)
if email_user_pattern:
subtitle = 'step 2 - select user'
users1 = run_sql("""SELECT id, email FROM user WHERE email RLIKE '%s' ORDER BY email """ % (email_user_pattern, ))
users = []
for (id, email) in users1: users.append([id, email, ''])
# no users
if not users:
output += '
no qualified users, try new search.
'
# too many users
elif len(users) > MAXSELECTUSERS:
output += '
%s hits, too many qualified users, specify more narrow search. (limit %s)
' % (len(users), MAXSELECTUSERS)
# ok number of users
else:
output += createuserselect(id_user=id_user,
action='addroleuser',
step=2,
users=users,
button='select user',
email_user_pattern=email_user_pattern)
if int(id_user):
subtitle = 'step 3 - select role'
# roles the user is connected to
role_ids = acca.acc_getUserRoles(id_user=id_user)
# all the roles, lists are sorted on the background of these...
all_roles = acca.acc_getAllRoles()
# sort the roles in connected and not connected roles
for (id, name, description) in all_roles:
if (id, ) in role_ids: con_roles.append([-id, name, description])
else: not_roles.append([id, name, description])
# create roleselect
output += createroleselect(id_role=id_role,
action='addroleuser',
step=3,
roles=not_roles,
extraroles=con_roles,
extrastamp='(connected)',
button='add this role',
email_user_pattern=email_user_pattern,
id_user=id_user)
if int(id_role) < 0:
name_role = acca.acc_getRoleName(id_role=-int(id_role))
output += '
role %s already connected to the user, try another one...
' % (name_role, )
elif int(id_role):
subtitle = 'step 4 - confirm to add role to user'
output += createhiddenform(action='addroleuser',
text='add role %s to user %s?' % (name_role, email_out),
email_user_pattern=email_user_pattern,
id_user=id_user,
id_role=id_role,
confirm=1)
if confirm:
# add role
result = acca.acc_addUserRole(id_user=id_user, id_role=id_role)
if result and result[2]:
subtitle = 'step 5 - confirm role added'
output += '
confirm: role %s added to user %s.
' % (name_role, email_out)
else:
subtitle = 'step 5 - role could not be added'
output += '
""" % (id_role, name_role)
return index(req=req,
title=title,
subtitle=subtitle,
body=[output, extra],
adminarea=5)
def perform_deleteuserrole(req, id_role='0', id_user='0', reverse=0, confirm=0):
"""delete connection between role and user.
id_role - id of role to disconnect
id_user - id of user to disconnect. """
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
title = 'Remove user from role'
email_user = acca.acc_getUserEmail(id_user=id_user)
name_role = acca.acc_getRoleName(id_role=id_role)
output = ''
if reverse in [0, '0']:
adminarea = 3
subtitle = 'step 1 - select the role'
output += createroleselect(id_role=id_role,
action="deleteuserrole",
step=1,
roles=acca.acc_getAllRoles())
if id_role != "0":
subtitle = 'step 2 - select the user'
output += createuserselect(id_user=id_user,
action="deleteuserrole",
step=2,
users=acca.acc_getRoleUsers(id_role=id_role),
id_role=id_role)
else:
adminarea = 5
# show only if user is connected to a role, get users connected to roles
users = run_sql("""SELECT DISTINCT(u.id), u.email, u.note
FROM user u LEFT JOIN user_accROLE ur
ON u.id = ur.id_user
WHERE ur.id_accROLE != 'NULL' AND u.email != ''
ORDER BY u.email """)
has_roles = 1
# check if the user is connected to any roles
for (id, email, note) in users:
if str(id) == str(id_user): break
# user not connected to a role
else:
subtitle = 'step 1 - user not connected'
output += '
no need to remove roles from user %s, user is not connected to any roles.
' % (email_user, )
has_roles, id_user = 0, '0' # stop the rest of the output below...
# user connected to roles
if has_roles:
output += createuserselect(id_user=id_user,
action="deleteuserrole",
step=1,
users=users,
reverse=reverse)
if id_user != "0":
subtitle = 'step 2 - select the role'
role_ids = acca.acc_getUserRoles(id_user=id_user)
all_roles = acca.acc_getAllRoles()
roles = []
for (id, name, desc) in all_roles:
if (id, ) in role_ids: roles.append([id, name, desc])
output += createroleselect(id_role=id_role,
action="deleteuserrole",
step=2,
roles=roles,
id_user=id_user,
reverse=reverse)
if id_role != '0' and id_user != '0':
subtitle = 'step 3 - confirm delete of user'
output += createhiddenform(action="deleteuserrole",
text='delete user %s from %s?' % (headerstrong(user=id_user), headerstrong(role=id_role)),
id_role=id_role,
id_user=id_user,
reverse=reverse,
confirm=1)
if confirm:
res = acca.acc_deleteUserRole(id_user=id_user, id_role=id_role)
if res:
subtitle = 'step 4 - confirm delete of user'
output += '
confirm: deleted user %s from role %s.
' % (email_user, name_role)
else:
subtitle = 'step 4 - user could not be deleted'
output += 'sorry, but user could not be deleted user is probably already deleted.'
extra = ''
if str(id_role) != "0":
extra += """
""" % (id_user, email_user, email_user)
extra += '
'
if extra: body = [output, extra]
else: body = [output]
return index(req=req,
title=title,
subtitle=subtitle,
body=body,
adminarea=adminarea)
def perform_showuserdetails(req, id_user=0):
"""show the details of a user. """
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
if id_user not in [0, '0']:
output = userdetails(id_user=id_user)
email_user = acca.acc_getUserEmail(id_user=id_user)
extra = """
' % (email_user, )
return details
def perform_addauthorization(req, id_role="0", id_action="0", optional=0, reverse="0", confirm=0, **keywords):
""" form to add new connection between user and role:
id_role - role to connect
id_action - action to connect
reverse - role or action first? """
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
# values that might get used
name_role = acca.acc_getRoleName(id_role=id_role) or id_role
name_action = acca.acc_getActionName(id_action=id_action) or id_action
optional = optional == 'on' and 1 or int(optional)
extra = """
"""
# create the page according to which step the user is on
# role -> action -> arguments
if reverse in ["0", 0]:
adminarea = 3
subtitle = 'step 1 - select role'
output = createroleselect(id_role=id_role,
action="addauthorization",
step=1,
roles=acca.acc_getAllRoles(),
reverse=reverse)
if str(id_role) != "0":
subtitle = 'step 2 - select action'
rolacts = acca.acc_getRoleActions(id_role)
allhelp = acca.acc_getAllActions()
allacts = []
for r in allhelp:
if r not in rolacts: allacts.append(r)
output += createactionselect(id_action=id_action,
action="addauthorization",
step=2,
actions=rolacts,
extraactions=allacts,
id_role=id_role,
reverse=reverse)
# action -> role -> arguments
else:
adminarea = 4
subtitle = 'step 1 - select action'
output = createactionselect(id_action=id_action,
action="addauthorization",
step=1,
actions=acca.acc_getAllActions(),
reverse=reverse)
if str(id_action) != "0":
subtitle = 'step 2 - select role'
actroles = acca.acc_getActionRoles(id_action)
allhelp = acca.acc_getAllRoles()
allroles = []
for r in allhelp:
if r not in actroles: allroles.append(r)
output += createroleselect(id_role=id_role,
action="addauthorization",
step=2,
roles=actroles,
extraroles=allroles,
id_action=id_action,
reverse=reverse)
# ready for step 3 no matter which direction we took to get here
if id_action != "0" and id_role != "0":
# links to adding authorizations in the other direction
if str(reverse) == "0":
extra += """
connect %s to %s for any arguments
connect %s to %s for only these argument cases:
""" % (optional and 'checked="checked"' or '', name_role, name_action, not optional and 'checked="checked"' or '', name_role, name_action)
# list the arguments
allkeys = 1
for key in res_keys:
output += '%s \n \n'
output = output[:-5] + ' \n'
output += '\n'
# ask for confirmation
if str(allkeys) != "0" or optional:
keys = keywords.keys()
keys.reverse()
subtitle = 'step 4 - confirm add of authorization\n'
text = """
create connection between
%s
""" % (headerstrong(role=name_role, action=name_action, query=0), )
if optional:
text += 'withouth arguments'
keywords = {}
else:
for key in keys:
text += '%s: %s \n' % (key, keywords[key])
output += createhiddenform(action="addauthorization",
text=text,
id_role=id_role,
id_action=id_action,
reverse=reverse,
confirm=1,
optional=optional,
**keywords)
# show existing authorizations, found authorizations further up in the code...
# res_auths = acca.acc_findPossibleActions(id_role, id_action)
output += '
existing authorizations:
'
if res_auths:
output += tupletotable(header=res_auths[0], tuple=res_auths[1:])
# shortcut to modifying authorizations
extra += """
sorry, authorization could not be added, it probably already exists
'
# trying to put extra link on the right side
try: body = [output, extra]
except NameError: body = [output]
return index(req=req,
title = 'Create entry for new authorization',
subtitle=subtitle,
body=body,
adminarea=adminarea)
def perform_deleteroleaction(req, id_role="0", id_action="0", reverse=0, confirm=0):
"""delete all connections between a role and an action.
id_role - id of the role
id_action - id of the action
reverse - 0: ask for role first
1: ask for action first"""
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
title = 'Remove action from role '
if reverse in ["0", 0]:
# select role -> action
adminarea = 3
subtitle = 'step 1 - select a role'
output = createroleselect(id_role=id_role,
action="deleteroleaction",
step=1,
roles=acca.acc_getAllRoles(),
reverse=reverse)
if id_role != "0":
rolacts = acca.acc_getRoleActions(id_role=id_role)
subtitle = 'step 2 - select the action'
output += createactionselect(id_action=id_action,
action="deleteroleaction",
step=2,
actions=rolacts,
reverse=reverse,
id_role=id_role,
button="remove connection and all authorizations")
else:
# select action -> role
adminarea = 4
subtitle = 'step 1 - select an action'
output = createactionselect(id_action=id_action,
action="deleteroleaction",
step=1,
actions=acca.acc_getAllActions(),
reverse=reverse)
if id_action != "0":
actroles = acca.acc_getActionRoles(id_action=id_action)
subtitle = 'step 2 - select the role'
output += createroleselect(id_role=id_role,
action="deleteroleaction",
step=2,
roles=actroles,
button="remove connection and all authorizations",
id_action=id_action,
reverse=reverse)
if id_action != "0" and id_role != "0":
subtitle = 'step 3 - confirm to remove authorizations'
# ask for confirmation
res = acca.acc_findPossibleActions(id_role, id_action)
if res:
output += '
authorizations that will be deleted:
'
output += tupletotable(header=res[0], tuple=res[1:])
output += createhiddenform(action="deleteroleaction",
text='remove %s from %s' % (headerstrong(action=id_action), headerstrong(role=id_role)),
confirm=1,
id_role=id_role,
id_action=id_action,
reverse=reverse)
else:
output += 'no authorizations'
# confirmation is given
if confirm:
subtitle = 'step 4 - confirm authorizations removed '
res = acca.acc_deleteRoleAction(id_role=id_role, id_action=id_action)
if res:
output += '
confirm: removed %s from %s ' % (headerstrong(action=id_action), headerstrong(role=id_role))
output += '%s entries were removed.
' % (res, )
else:
output += '
sorry, no entries could be removed.
'
return index(req=req,
title=title,
subtitle=subtitle,
body=[output],
adminarea=adminarea)
def perform_modifyauthorizations(req, id_role="0", id_action="0", reverse=0, confirm=0, errortext='', sel='', authids=[]):
"""given ids of a role and an action, show all possible action combinations
with checkboxes and allow user to access other functions.
id_role - id of the role
id_action - id of the action
reverse - 0: ask for role first
1: ask for action first
sel - which button and modification that is selected
errortext - text to print when no connection exist between role and action
authids - ids of checked checkboxes """
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
name_role = acca.acc_getRoleName(id_role)
name_action = acca.acc_getActionName(id_action)
output = ''
try: id_role, id_action, reverse = int(id_role), int(id_action), int(reverse)
except ValueError: pass
extra = """
\n'
if not reverse:
# role -> action
adminarea = 3
subtitle = 'step 1 - select the role'
output += createroleselect(id_role=str(id_role),
action="modifyauthorizations",
step=1,
roles=acca.acc_getAllRoles(),
reverse=reverse)
if id_role:
rolacts = acca.acc_getRoleActions(id_role=id_role)
subtitle = 'step 2 - select the action'
output += createactionselect(id_action=str(id_action),
action="modifyauthorizations",
step=2,
actions=rolacts,
id_role=id_role,
reverse=reverse)
else:
adminarea = 4
# action -> role
subtitle = 'step 1 - select the action'
output += createactionselect(id_action=str(id_action),
action="modifyauthorizations",
step=1,
actions=acca.acc_getAllActions(),
reverse=reverse)
if id_action:
actroles = acca.acc_getActionRoles(id_action=id_action)
subtitle = 'step 2 - select the role'
output += createroleselect(id_role=str(id_role),
action="modifyauthorizations",
step=2,
roles=actroles,
id_action=id_action,
reverse=reverse)
if errortext: output += '
%s
' % (errortext, )
if id_role and id_action:
# adding to main area
if type(authids) is not list: authids = [authids]
subtitle = 'step 3 - select groups and modification'
# get info
res = acca.acc_findPossibleActions(id_role, id_action)
# clean the authids
hiddenids = []
if sel in ['delete selected']:
hiddenids = authids[:]
elif sel in ['split groups', 'merge groups']:
for authid in authids:
arghlp = res[int(authid)][0]
if authid not in hiddenids and arghlp not in [-1, '-1', 0, '0']: hiddenids.append(authid)
authids = hiddenids[:]
if confirm:
# do selected modification and output with new authorizations
if sel == 'split groups':
res = splitgroups(id_role, id_action, authids)
elif sel == 'merge groups':
res = mergegroups(id_role, id_action, authids)
elif sel == 'delete selected':
res = deleteselected(id_role, id_action, authids)
authids = []
res = acca.acc_findPossibleActions(id_role, id_action)
output += 'authorizations after %s. \n' % (sel, )
elif sel and authids:
output += 'confirm choice of authorizations and modification. \n'
else:
output += 'select authorizations and perform modification. \n'
if not res:
errortext='all connections deleted, try different '
if reverse in ["0", 0]:
return perform_modifyauthorizations(req=req, id_role=id_role, errortext=errortext + 'action.')
else:
return perform_modifyauthorizations(req=req, id_action=id_action, reverse=reverse, errortext=errortext + 'role.')
# display
output += modifyauthorizationsmenu(id_role, id_action, header=res[0], tuple=res[1:], checked=authids, reverse=reverse)
if sel and authids:
subtitle = 'step 4 - confirm to perform modification'
# form with hidden authids
output += ''
# tried to perform modification without something selected
elif sel and not authids and not confirm:
output += '
no valid groups selected
'
# trying to put extra link on the right side
try: body = [output, extra]
except NameError: body = [output]
# Display the page
return index(req=req,
title='Modify Authorizations',
subtitle=subtitle,
body=body,
adminarea=adminarea)
def modifyauthorizationsmenu(id_role, id_action, tuple=[], header=[], checked=[], reverse=0):
"""create table with header and checkboxes, used for multiple choice.
makes use of tupletotable to add the actual table
id_role - selected role, hidden value in the form
id_action - selected action, hidden value in the form
tuple - all rows to be put in the table (with checkboxes)
header - column headers, empty strings added at start and end
checked - ids of rows to be checked """
if not tuple:
return 'no authorisations...'
argnum = len(acca.acc_getActionKeywords(id_action=id_action))
tuple2 = []
for t in tuple: tuple2.append(t[:])
tuple2 = addcheckboxes(datalist=tuple2, name='authids', startindex=1, checked=checked)
hidden = ' \n' % (id_role, )
hidden += ' \n' % (id_action, )
hidden += ' \n' % (reverse, )
button = '\n'
if argnum > 1:
button += '\n'
button += '\n'
hdrstr = ''
for h in [''] + header + ['']: hdrstr += '
%s
\n' % (h, )
if hdrstr: hdrstr = '
\n%s\n
\n' % (hdrstr, )
output = '\n'
return output
def splitgroups(id_role=0, id_action=0, authids=[]):
"""get all the old ones, gather up the arglistids find a list of
arglistidgroups to be split, unique get all actions in groups outside
of the old ones, (old arglistid is allowed).
show them like in showselect. """
if not id_role or not id_action or not authids:
return 0
# find all the actions
datalist = acca.acc_findPossibleActions(id_role, id_action)
if type(authids) is str: authids = [authids]
for i in range(len(authids)): authids[i] = int(authids[i])
# argumentlistids of groups to be split
splitgrps = []
for authid in authids:
hlp = datalist[authid][0]
if hlp not in splitgrps and authid in range(1,len(datalist)):
splitgrps.append(hlp)
# split groups and return success or failure
result = 1
for splitgroup in splitgrps:
result = 1 and acca.acc_splitArgumentGroup(id_role, id_action, splitgroup)
return result
def mergegroups(id_role=0, id_action=0, authids=[]):
"""get all the old ones, gather up the argauthids find a list
of arglistidgroups to be split, unique get all actions in groups
outside of the old ones, (old arglistid is allowed).
show them like in showselect."""
if not id_role or not id_action or not authids:
return 0
datalist = acca.acc_findPossibleActions(id_role, id_action)
if type(authids) is str: authids = [authids]
for i in range(len(authids)): authids[i] = int(authids[i])
# argumentlistids of groups to be merged
mergegroups = []
for authid in authids:
hlp = datalist[authid][0]
if hlp not in mergegroups and authid in range(1, len(datalist)):
mergegroups.append(hlp)
# merge groups and return success or failure
if acca.acc_mergeArgumentGroups(id_role, id_action, mergegroups):
return 1
else:
return 0
def deleteselected(id_role=0, id_action=0, authids=[]):
"""delete checked authorizations/possible actions, ids in authids.
id_role - role to delete from
id_action - action to delete from
authids - listids for which possible actions to delete."""
if not id_role or not id_action or not authids:
return 0
if type(authids) in [str, int]: authids = [authids]
for i in range(len(authids)): authids[i] = int(authids[i])
result = acca.acc_deletePossibleActions(id_role=id_role,
id_action=id_action,
authids=authids)
return result
def headeritalic(**ids):
"""transform keyword=value pairs to string with value in italics.
**ids - a dictionary of pairs to create string from """
output = ''
value = ''
table = ''
for key in ids.keys():
if key in ['User', 'user']:
value, table = 'email', 'user'
elif key in ['Role', 'role']:
value, table = 'name', 'accROLE'
elif key in ['Action', 'action']:
value, table = 'name', 'accACTION'
else:
if output: output += ' and '
output += ' %s %s' % (key, ids[key])
continue
res = run_sql("""SELECT %s FROM %s WHERE id = %s""" % (value, table, ids[key]))
if res:
if output: output += ' and '
output += ' %s %s' % (key, res[0][0])
return output
def headerstrong(query=1, **ids):
"""transform keyword=value pairs to string with value in strong text.
**ids - a dictionary of pairs to create string from
query - 1 -> try to find names to ids of role, user and action.
0 -> do not try to find names, use the value passed on """
output = ''
value = ''
table = ''
for key in ids.keys():
if key in ['User', 'user']:
value, table = 'email', 'user'
elif key in ['Role', 'role']:
value, table = 'name', 'accROLE'
elif key in ['Action', 'action']:
value, table = 'name', 'accACTION'
else:
if output: output += ' and '
output += ' %s %s' % (key, ids[key])
continue
if query:
res = run_sql("""SELECT %s FROM %s WHERE id = %s""" % (value, table, ids[key]))
if res:
if output: output += ' and '
output += ' %s %s' % (key, res[0][0])
else:
if output: output += ' and '
output += ' %s %s' % (key, ids[key])
return output
def startpage():
"""create the menu for the startpage"""
body = """
"""
return body
def rankarea():
return "Rankmethod area"
def perform_simpleauthorization(req, id_role=0, id_action=0):
"""show a page with simple overview of authorizations between a
connected role and action. """
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
res = acca.acc_findPossibleActions(id_role, id_action)
if res:
extra = createhiddenform(action='modifyauthorizations',
button='modify authorizations',
id_role=id_role,
id_action=id_action)
output = '
authorizations for %s:
' % (headerstrong(action=id_action, role=id_role), )
output += tupletotable(header=res[0], tuple=res[1:], extracolumn=extra)
else:
output = 'no details to show'
return index(req=req,
title='Simple authorization details',
subtitle='simple authorization details',
body=[output],
adminarea=3)
def perform_showroleusers(req, id_role=0):
"""show a page with simple overview of a role and connected users. """
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
res = acca.acc_getRoleUsers(id_role=id_role)
name_role = acca.acc_getRoleName(id_role=id_role)
if res:
users = []
for (id, name, dontcare) in res: users.append([id, name, 'show user details'
% (id, )])
output = '
users connected to %s:
' % (headerstrong(role=id_role), )
output += tupletotable(header=['id', 'name', ''], tuple=users)
else:
output = 'no users connected to role %s' % (name_role, )
extra = """
""" % (id_role, )
return index(req=req,
title='Users connected to role %s' % (name_role, ),
subtitle='simple details',
body=[output, extra],
adminarea=3)
def createselect(id_input="0", label="", step=0, name="",
action="", list=[], extralist=[], extrastamp='',
button="", **hidden):
"""create form with select and hidden values
id - the one to choose as selected if exists
label - label shown to the left of the select
name - the name of the select on which to reference it
list - primary list to select from
extralist - list of options to be put in paranthesis
extrastamp - stamp extralist entries with this if not ''
usually paranthesis around the entry
button - the value/text to be put on the button
**hidden - name=value pairs to be put as hidden in the form. """
step = step and '%s. ' % step or ''
output = '\n'
return output
def createactionselect(id_action="0", label="select action", step=0, name="id_action",
action="", actions=[], extraactions=[], extrastamp='',
button="select action", **hidden):
"""create a select for roles in a form. see createselect."""
return createselect(id_input=id_action, label=label, step=step, name=name,
action=action, list=actions, extralist=extraactions, extrastamp=extrastamp,
button=button, **hidden)
def createroleselect(id_role="0", label="select role", step=0, name="id_role",
action="", roles=[], extraroles=[], extrastamp='',
button="select role", **hidden):
"""create a select for roles in a form. see createselect."""
return createselect(id_input=id_role, label=label, step=step, name=name,
action=action, list=roles, extralist=extraroles, extrastamp=extrastamp,
button=button, **hidden)
def createuserselect(id_user="0", label="select user", step=0, name="id_user",
action="", users=[], extrausers=[], extrastamp='(connected)',
button="select user", **hidden):
"""create a select for users in a form.see createselect."""
return createselect(id_input=id_user, label=label, step=step, name=name,
action=action, list=users, extralist=extrausers, extrastamp=extrastamp,
button=button, **hidden)
def cleanstring(str='', comma=0):
"""clean all the strings before submitting to access control admin.
remove characters not letter, number or underscore, also remove leading
underscores and numbers. return cleaned string.
str - string to be cleaned
comma - 1 -> allow the comma to divide multiple arguments
0 -> wash commas as well """
# remove not allowed characters
str = re.sub(r'[^a-zA-Z0-9_,]', '', str)
# split string on commas
items = str.split(',')
str = ''
for item in items:
if not item: continue
if comma and str: str += ','
# create valid variable names
str += re.sub(r'^([0-9_])*', '', item)
return str
def cleanstring_argumentvalue(str=''):
"""clean the value of an argument before submitting it.
allowed characters: a-z A-Z 0-9 _ and space
str - string to be cleaned """
# remove not allowed characters
str = re.sub(r'[^a-zA-Z0-9_ .]', '', str)
# trim leading and ending spaces
str = re.sub(r'^ *| *$', '', str)
return str
def cleanstring_email(str=''):
"""clean the string and return a valid email address.
str - string to be cleaned """
# remove not allowed characters
str = re.sub(r'[^a-zA-Z0-9_.@-]', '', str)
return str
def check_email(str=''):
"""control that submitted emails are correct.
this little check is not very good, but better than nothing. """
r = re.compile(r'(.)+\@(.)+\.(.)+')
return r.match(str) and 1 or 0
def sendAccountActivatedMessage(AccountEmail, sendTo, password, ln=cdslang):
"""Send an email to the address given by sendTo about the new activated account."""
fromaddr = "From: %s" % supportemail
toaddrs = "To: %s" % sendTo
to = toaddrs + "\n"
sub = "Subject: Your account on '%s' has been activated\n\n" % cdsname
body = "Your account earlier created on '%s' has been activated:\n\n" % cdsname
body += " Username/Email: %s\n" % AccountEmail
body += " Password: %s\n" % ("*" * len(password))
body += "\n---------------------------------"
body += "\n%s" % cdsname
body += "\nContact: %s" % supportemail
msg = to + sub + body
server = smtplib.SMTP('localhost')
server.set_debuglevel(1)
try:
server.sendmail(fromaddr, toaddrs, msg)
except smtplib.SMTPRecipientsRefused,e:
return 0
server.quit()
return 1
def sendNewUserAccountWarning(newAccountEmail, sendTo, password, ln=cdslang):
"""Send an email to the address given by sendTo about the new account newAccountEmail."""
fromaddr = "From: %s" % supportemail
toaddrs = "To: %s" % sendTo
to = toaddrs + "\n"
sub = "Subject: Account created on '%s'\n\n" % cdsname
body = "An account has been created for you on '%s':\n\n" % cdsname
body += " Username/Email: %s\n" % newAccountEmail
body += " Password: %s\n" % ("*" * len(password))
body += "\n---------------------------------"
body += "\n%s" % cdsname
body += "\nContact: %s" % supportemail
msg = to + sub + body
server = smtplib.SMTP('localhost')
server.set_debuglevel(1)
try:
server.sendmail(fromaddr, toaddrs, msg)
except smtplib.SMTPRecipientsRefused,e:
return 0
server.quit()
return 1
def sendAccountRejectedMessage(newAccountEmail, sendTo, ln=cdslang):
"""Send an email to the address given by sendTo about the new account newAccountEmail."""
fromaddr = "From: %s" % supportemail
toaddrs = "To: %s" % sendTo
to = toaddrs + "\n"
sub = "Subject: Account rejected on '%s'\n\n" % cdsname
body = "Your request for an account has been rejected on '%s':\n\n" % cdsname
body += " Username/Email: %s\n" % newAccountEmail
body += "\n---------------------------------"
body += "\n%s" % cdsname
body += "\nContact: %s" % supportemail
msg = to + sub + body
server = smtplib.SMTP('localhost')
server.set_debuglevel(1)
try:
server.sendmail(fromaddr, toaddrs, msg)
except smtplib.SMTPRecipientsRefused,e:
return 0
server.quit()
return 1
def sendAccountDeletedMessage(newAccountEmail, sendTo, ln=cdslang):
"""Send an email to the address given by sendTo about the new account newAccountEmail."""
fromaddr = "From: %s" % supportemail
toaddrs = "To: %s" % sendTo
to = toaddrs + "\n"
sub = "Subject: Account deleted on '%s'\n\n" % cdsname
body = "Your account on '%s' has been deleted:\n\n" % cdsname
body += " Username/Email: %s\n" % newAccountEmail
body += "\n---------------------------------"
body += "\n%s" % cdsname
body += "\nContact: %s" % supportemail
msg = to + sub + body
server = smtplib.SMTP('localhost')
server.set_debuglevel(1)
try:
server.sendmail(fromaddr, toaddrs, msg)
except smtplib.SMTPRecipientsRefused,e:
return 0
server.quit()
return 1
diff --git a/modules/webaccess/lib/webaccessadmin_lib.py.wml b/modules/webaccess/lib/webaccessadmin_lib.py.wml
index 8dc0097d1..5902b1e34 100644
--- a/modules/webaccess/lib/webaccessadmin_lib.py.wml
+++ b/modules/webaccess/lib/webaccessadmin_lib.py.wml
@@ -1,3407 +1,3408 @@
## $Id$
## Administrator interface for WebAccess
## This file is part of the CERN Document Server Software (CDSware).
## Copyright (C) 2002 CERN.
##
## The CDSware is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your option) any later version.
##
## The CDSware 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
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with CDSware; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
## read config variables:
#include "config.wml"
#include "configbis.wml"
## $Id$## DO NOT EDIT THIS FILE! IT WAS AUTOMATICALLY GENERATED FROM CDSware WML SOURCES.
"""CDSware WebAccess Administrator Interface."""
__lastupdated__ = """<: print `date +"%d %b %Y %H:%M:%S %Z"`; :>"""
## fill config variables:
import access_control_engine as acce
import access_control_admin as acca
# reload(acce)
# reload(acca)
import cgi
import re
import random
import MySQLdb
import string
import smtplib
from bibrankadminlib import adderrorbox,addadminbox,tupletotable,tupletotable_onlyselected,addcheckboxes,createhiddenform
from access_control_config import *
from dbquery import run_sql
from config import *
from webpage import page, pageheaderonly, pagefooteronly
from webuser import getUid, get_email
from mod_python import apache
from search_engine import print_record
from cdsware.webuser import checkemail
__version__ = "$Id$"
def index(req, title='', body='', subtitle='', adminarea=2, authorized=0):
"""main function to show pages for webaccessadmin.
1. if user not logged in and administrator, show the mustlogin page
2. if used without body argument, show the startpage
3. show admin page with title, body, subtitle and navtrail.
adminarea - number codes that tell what extra info to put in the navtrail
0 - nothing extra
1 - add Delegate Rights
2 - add Manage WebAccess
maybe add:
3: role admin
4: action admin
5: user area
6: reset area
authorized - if 1, don't check if the user is allowed to be webadmin """
navtrail_previous_links = """Admin Area > WebAccess Admin """ % (weburl, weburl)
if body:
if adminarea == 1: navtrail_previous_links += '> Delegate Rights ' % (weburl, )
if adminarea >= 2 and adminarea < 7: navtrail_previous_links += '> Manage WebAccess ' % (weburl, )
if adminarea == 3: navtrail_previous_links += '> Role Administration ' % (weburl, )
elif adminarea == 4: navtrail_previous_links += '> Action Administration ' % (weburl, )
elif adminarea == 5: navtrail_previous_links += '> User Administration ' % (weburl, )
elif adminarea == 6: navtrail_previous_links += '> Reset Authorizations ' % (weburl, )
elif adminarea == 7: navtrail_previous_links += '> Manage Accounts ' % (weburl, )
id_user = getUid(req)
(auth_code, auth_message) = is_adminuser(req)
if not authorized and auth_code != 0: return mustloginpage(req, auth_message)
elif not body:
title = 'Manage WebAccess'
body = startpage()
elif type(body) != str: body = addadminbox(subtitle, datalist=body)
return page(title=title,
uid=id_user,
body=body,
navtrail=navtrail_previous_links,
lastupdated=__lastupdated__)
def mustloginpage(req, message):
"""show a page asking the user to login."""
navtrail_previous_links = """Admin Area > WebAccess Admin """ % (weburl, weburl)
return page(title='Authorization failure',
uid=getUid(req),
body=adderrorbox('Reason:',
datalist=[message]),
navtrail=navtrail_previous_links,
lastupdated=__lastupdated__)
def is_adminuser(req):
"""check if user is a registered administrator. """
id_user = getUid(req)
return acce.acc_authorize_action(id_user, WEBACCESSACTION)
def perform_rolearea(req):
"""create the role area menu page."""
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
header = ['id', 'name', 'description', 'users', 'authorizations / actions', 'role', '']
roles = acca.acc_getAllRoles()
roles2 = []
for (id, name, desc) in roles:
if len(desc) > 30: desc = desc[:30] + '...'
roles2.append([id, name, desc])
for col in [(('add', 'adduserrole'),
('remove', 'deleteuserrole')),
(('add', 'addauthorization'),
('modify', 'modifyauthorizations'),
('remove', 'deleteroleaction')),
(('delete', 'deleterole'), ),
(('show details', 'showroledetails'), )]:
roles2[-1].append('%s' % (col[0][1], id, col[0][0]))
for (str, function) in col[1:]:
roles2[-1][-1] += ' / %s' % (function, id, str)
output = """
Users:
add or remove users from the access to a role and its priviliges.
Authorizations/Actions:
these terms means almost the same, but an authorization is a
connection between a role and an action (possibly) containing arguments.
Roles:
see all the information attached to a role and decide if you want to delete it.
"""
output += tupletotable(header=header, tuple=roles2)
extra = """
"""
return index(req=req,
title='Action Administration',
subtitle='administration with actions as access point',
body=[output, extra],
adminarea=2)
def perform_userarea(req, email_user_pattern=''):
"""create area to show info about users. """
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
subtitle = 'step 1 - search for users'
output = """
search for users to display.
"""
# remove letters not allowed in an email
email_user_pattern = cleanstring_email(email_user_pattern)
text = ' 1. search for user\n'
text += ' \n' % (email_user_pattern, )
output += createhiddenform(action="userarea",
text=text,
button="search for users")
if email_user_pattern:
users1 = run_sql("""SELECT id, email FROM user WHERE email RLIKE '%s' ORDER BY email LIMIT %s""" % (email_user_pattern, MAXPAGEUSERS+1))
if not users1:
output += '
no matching users
'
else:
subtitle = 'step 2 - select what to do with user'
users = []
for (id, email) in users1[:MAXPAGEUSERS]:
users.append([id, email])
for col in [(('add', 'addroleuser'),
('remove', 'deleteuserrole')),
(('show details', 'showuserdetails'), )]:
users[-1].append('%s' % (col[0][1], email_user_pattern, id, col[0][0]))
for (str, function) in col[1:]:
users[-1][-1] += ' / %s' % (function, email_user_pattern, id, str)
output += '
keep all changes and add the default authorization settings.
"""
return index(req=req,
title='Reset Authorizations',
subtitle='reseting to or adding default authorizations',
body=[output],
adminarea=2)
def perform_resetdefaultsettings(req, superusers=[], confirm=0):
"""delete all roles, actions and authorizations presently in the database
and add only the default roles.
only selected users will be added to superadmin, rest is blank """
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
# cleaning input
if type(superusers) == str: superusers = [superusers]
# remove not valid e-mails
for email in superusers:
if not check_email(email): superusers.remove(email)
# instructions
output = """
before you reset the settings, we need some users
to connect to %s.
enter as many e-mail adresses you want and press reset. confirm reset settings when you have added enough e-mails. is added as default.
'
output += tupletotable(header=['e-mail address'],
tuple=superusers,
start=start,
extracolumn=extra,
end=end)
if confirm in [1, "1"]:
res = acca.acc_reset_default_settings(superusers)
if res:
output += '
successfully reset default settings
'
else:
output += '
sorry, could not reset default settings
'
return index(req=req,
title='Reset Default Settings',
subtitle='reset settings',
body=[output],
adminarea=6)
def perform_adddefaultsettings(req, superusers=[], confirm=0):
"""add the default settings, and keep everything else.
probably nothing will be deleted, except if there has been made changes to the defaults."""
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
# cleaning input
if type(superusers) == str: superusers = [superusers]
# remove not valid e-mails
for email in superusers:
if not check_email(email): superusers.remove(email)
# instructions
output = """
before you add the settings, we need some users
to connect to %s.
enter as many e-mail adresses you want and press add. confirm add settings when you have added enough e-mails. is added as default.
""" % (weburl, weburl, weburl, weburl, weburl)
if mtype == "perform_accesspolicy" and content:
fin_output += content
elif mtype == "perform_accesspolicy" or mtype == "perform_showall":
fin_output += perform_accesspolicy(req, callback='')
fin_output += " "
if mtype == "perform_accountoverview" and content:
fin_output += content
elif mtype == "perform_accountoverview" or mtype == "perform_showall":
fin_output += perform_accountoverview(req, callback='')
fin_output += " "
if mtype == "perform_createaccount" and content:
fin_output += content
elif mtype == "perform_createaccount" or mtype == "perform_showall":
fin_output += perform_createaccount(req, callback='')
fin_output += " "
if mtype == "perform_modifyaccounts" and content:
fin_output += content
elif mtype == "perform_modifyaccounts" or mtype == "perform_showall":
fin_output += perform_modifyaccounts(req, callback='')
fin_output += " "
return index(req=req,
title='Manage Accounts',
subtitle=subtitle,
body=[fin_output],
adminarea=0,
authorized=1)
def perform_accesspolicy(req, callback='yes', confirm=0):
"""Modify default behaviour of a guest user or if new accounts should automatically/manually be modified."""
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
subtitle = """1. Access policy.   [?]""" % weburl
account_policy = {}
account_policy[0] = "Users can register new accounts. New accounts automatically activated."
account_policy[1] = "Users can register new accounts. Admin users must activate the accounts."
account_policy[2] = "Only admin can register new accounts. User cannot edit email address."
output = " Current settings: "
+ output += "Site open: %s " % (CFG_SITE_OPEN == 1 and "Yes" or "No")
output += "Guest accounts allowed: %s " % (CFG_ACCESS_CONTROL_LEVEL_GUESTS == 0 and "Yes" or "No")
output += "Account policy: %s " % (account_policy[CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS])
output += "Allowed email addresses limited: %s " % (CFG_ACCESS_CONTROL_LIMIT_TO_DOMAIN and CFG_ACCESS_CONTROL_LIMIT_TO_DOMAIN or "Not limited")
output += "Send email to admin when new account: %s " % (CFG_ACCESS_CONTROL_NOTIFY_ADMIN_ABOUT_NEW_ACCOUNTS == 1 and "Yes" or "No")
output += "Use which email address: %s " % (CFG_ACCESS_CONTROL_SEND_TO_EMAIL)
output += "Send email to user after creating new account: %s " % (CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_NEW_ACCOUNT == 1 and "Yes" or "No")
output += "Send email to user when account is activated: %s " % (CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_ACTIVATION == 1 and "Yes" or "No")
output += "Send email to user when account is deleted/rejected: %s " % (CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_DELETION == 1 and "Yes" or "No")
output += " Changing the settings: "
output += "Currently, all changes must be done using your favourite editor, and the webserver restarted for changes to take effect. For the settings to change, either look in the guide or in access_control_config.py ."
try:
body = [output, extra]
except NameError:
body = [output]
if callback:
return perform_manageaccounts(req, "perform_accesspolicy", addadminbox(subtitle, body))
else:
return addadminbox(subtitle, body)
def perform_accountoverview(req, callback='yes', confirm=0):
"""Modify default behaviour of a guest user or if new accounts should automatically/manually be modified."""
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
subtitle = """2. Account overview.   [?]""" % weburl
output = ""
res = run_sql("SELECT COUNT(*) FROM user WHERE email=''")
output += "Guest accounts: %s " % res[0][0]
res = run_sql("SELECT COUNT(*) FROM user WHERE email!=''")
output += "Registered accounts: %s " % res[0][0]
res = run_sql("SELECT COUNT(*) FROM user WHERE email!='' AND note='0' OR note IS NULL")
output += "Inactive accounts: %s " % res[0][0]
if res[0][0] > 0:
output += ' [Activate/Reject accounts]'
res = run_sql("SELECT COUNT(*) FROM user")
output += " Total nr of accounts: %s " % res[0][0]
try:
body = [output, extra]
except NameError:
body = [output]
if callback:
return perform_manageaccounts(req, "perform_accountoverview", addadminbox(subtitle, body))
else:
return addadminbox(subtitle, body)
def perform_createaccount(req, email='', password='', callback='yes', confirm=0):
"""Modify default behaviour of a guest user or if new accounts should automatically/manually be modified."""
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
subtitle = """3. Create account.   [?]""" % weburl
output = ""
text = ' Email:\n'
text += ' ' % (email, )
text += ' Password:\n'
text += ' ' % (password, )
output += createhiddenform(action="createaccount",
text=text,
confirm=1,
button="Create")
if confirm in [1, "1"] and email and checkemail(email):
res = run_sql("SELECT * FROM user WHERE email='%s'" % MySQLdb.escape_string(email))
if not res:
res = run_sql("INSERT INTO user (email,password, note) values('%s','%s', '1')" % (MySQLdb.escape_string(email), MySQLdb.escape_string(password)))
if CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_NEW_ACCOUNT == 1:
emailsent = sendNewUserAccountWarning(email, email, password)
if password:
output += 'Account created with password and activated.'
else:
output += 'Account created without password and activated.'
if CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_NEW_ACCOUNT == 1:
if emailsent:
output += ' An email has been sent to the owner of the account.'
else:
output += ' Could not send an email to the owner of the account.'
else:
output += 'An account with the same email already exists.'
elif confirm in [1, "1"]:
output += 'Please specify an valid email-address.'
try:
body = [output, extra]
except NameError:
body = [output]
if callback:
return perform_manageaccounts(req, "perform_createaccount", addadminbox(subtitle, body))
else:
return addadminbox(subtitle, body)
def perform_modifyaccountstatus(req, userID, email_user_pattern, limit_to, maxpage, page, callback='yes', confirm=0):
"""set a disabled account to enabled and opposite"""
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
res = run_sql("SELECT id, email, note, password FROM user WHERE id=%s" % userID)
output = ""
if res:
if res[0][2] in [0, "0", None]:
res2 = run_sql("UPDATE user SET note=1 WHERE id=%s" % userID)
output += """The account '%s' has been activated.""" % res[0][1]
if CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_ACTIVATION == 1:
emailsent = sendAccountActivatedMessage(res[0][1], res[0][1], res[0][3])
if emailsent:
output += """ An email has been sent to the owner of the account."""
else:
output += """ Could not send an email to the owner of the account."""
elif res[0][2] in [1, "1"]:
res2 = run_sql("UPDATE user SET note=0 WHERE id=%s" % userID)
output += """The account '%s' has been set inactive.""" % res[0][1]
else:
output += 'The account id given does not exist.'
try:
body = [output, extra]
except NameError:
body = [output]
if callback:
return perform_modifyaccounts(req, email_user_pattern, limit_to, maxpage, page, content=output, callback='yes')
else:
return addadminbox(subtitle, body)
def perform_editaccount(req, userID, mtype='', content='', callback='yes', confirm=-1):
"""form to modify an account. this method is calling other methods which again is calling this and sending back the output of the method.
if callback, the method will call perform_editcollection, if not, it will just return its output.
userID - id of the user
mtype - the method that called this method.
content - the output from that method."""
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
res = run_sql("SELECT id, email FROM user WHERE id=%s" % userID)
if not res:
if mtype == "perform_deleteaccount":
text = """The selected account has been deleted, to continue editing, go back to 'Manage Accounts'."""
if CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_DELETION == 1:
text += """ An email has been sent to the owner of the account."""
else:
text = """The selected accounts does not exist, please go back and select an account to edit."""
return index(req=req,
title='Edit Account',
subtitle="Edit account",
body=[text],
adminarea=7,
authorized=1)
fin_output = """
""" % (weburl, userID, weburl, userID, weburl, userID, weburl, userID, weburl, userID, weburl, userID)
if mtype == "perform_modifylogindata" and content:
fin_output += content
elif mtype == "perform_modifylogindata" or not mtype:
fin_output += perform_modifylogindata(req, userID, callback='')
if mtype == "perform_modifybasket" and content:
fin_output += content
elif mtype == "perform_modifybasket" or not mtype:
fin_output += perform_modifybasket(req, userID, callback='')
if mtype == "perform_modifypreferences" and content:
fin_output += content
elif mtype == "perform_modifypreferences" or not mtype:
fin_output += perform_modifypreferences(req, userID, callback='')
if mtype == "perform_modifyalerts" and content:
fin_output += content
elif mtype == "perform_modifyalerts" or not mtype:
fin_output += perform_modifyalerts(req, userID, callback='')
if mtype == "perform_deleteaccount" and content:
fin_output += content
elif mtype == "perform_deleteaccount" or not mtype:
fin_output += perform_deleteaccount(req, userID, callback='')
return index(req=req,
title='Edit Account',
subtitle="Edit account '%s'" % res[0][1],
body=[fin_output],
adminarea=7,
authorized=1)
def perform_modifybasket(req, userID, callback='yes', confirm=0):
"""modify email and password of an account"""
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
subtitle = """2. Modify baskets.   [?]""" % weburl
res = run_sql("SELECT id, email, password FROM user WHERE id=%s" % userID)
output = ""
if res:
text = """To modify the baskets for this account, you have to login as the user."""
output += createhiddenform(action="%s/youraccount.py/login?" % weburl,
text=text,
p_email=res[0][1],
p_pw=res[0][2],
referer="%s/yourbaskets.py/display" % weburl,
button="Login")
output += "Remember that you will be logged out as the current user."
#baskets = run_sql("SELECT basket.id, basket.name, basket.public FROM basket, user_basket WHERE id_user=%s and user_basket.id_basket=basket.id" % userID)
#output += "
" % (name, (public=="y" and "Yes" or "No"))
# basket_records = run_sql("SELECT id_record, nb_order FROM basket_record WHERE id_basket=%s" % id)
# for (id_record, nb_order) in basket_records:
# output += "
"
else:
output += 'The account id given does not exist.'
try:
body = [output, extra]
except NameError:
body = [output]
if callback:
return perform_editaccount(req, userID, mtype='perform_modifybasket', content=addadminbox(subtitle, body), callback='yes')
else:
return addadminbox(subtitle, body)
def perform_modifylogindata(req, userID, email='', password='', callback='yes', confirm=0):
"""modify email and password of an account"""
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
subtitle = """1. Edit login-data.   [?]""" % weburl
res = run_sql("SELECT id, email, password FROM user WHERE id=%s" % userID)
output = ""
if res:
if not email and not password:
email = res[0][1]
password = res[0][2]
text = ' Account id:%s \n' % userID
text += ' Email:\n'
text += ' ' % (email, )
text += ' Password:\n'
text += ' ' % (password, )
output += createhiddenform(action="modifylogindata",
text=text,
userID=userID,
confirm=1,
button="Modify")
if confirm in [1, "1"] and email and checkemail(email):
res = run_sql("UPDATE user SET email='%s' WHERE id=%s" % (MySQLdb.escape_string(email), userID))
res = run_sql("UPDATE user SET password='%s' WHERE id=%s" % (MySQLdb.escape_string(password), userID))
output += 'Email and/or password modified.'
elif confirm in [1, "1"]:
output += 'Please specify an valid email-address.'
else:
output += 'The account id given does not exist.'
try:
body = [output, extra]
except NameError:
body = [output]
if callback:
return perform_editaccount(req, userID, mtype='perform_modifylogindata', content=addadminbox(subtitle, body), callback='yes')
else:
return addadminbox(subtitle, body)
def perform_modifyalerts(req, userID, callback='yes', confirm=0):
"""modify email and password of an account"""
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
subtitle = """3. Modify alerts.   [?]""" % weburl
res = run_sql("SELECT id, email, password FROM user WHERE id=%s" % userID)
output = ""
if res:
text = """To modify the alerts for this account, you have to login as the user."""
output += createhiddenform(action="%s/youraccount.py/login?" % weburl,
text=text,
p_email=res[0][1],
p_pw=res[0][2],
referer="%s/youralerts.py/display" % weburl,
button="Login")
output += "Remember that you will be logged out as the current user."
res= """ SELECT q.id, q.urlargs, a.id_basket,
a.alert_name, a.frequency, a.notification,
DATE_FORMAT(a.date_creation,'%%d %%b %%Y'),
DATE_FORMAT(a.date_lastrun,'%%d %%b %%Y')
FROM query q, user_query_basket a
WHERE a.id_user='%s' AND a.id_query=q.id
ORDER BY a.alert_name ASC """ % userID
#res = run_sql(res)
#for (qID, qurlargs, id_basket, alertname, frequency, notification, date_creation, date_lastrun) in res:
# output += "%s - %s - %s - %s - %s - %s - %s " % (qID, id_basket, alertname, frequency, notification, date_creation, date_lastrun)
else:
output += 'The account id given does not exist.'
try:
body = [output, extra]
except NameError:
body = [output]
if callback:
return perform_editaccount(req, userID, mtype='perform_modifyalerts', content=addadminbox(subtitle, body), callback='yes')
else:
return addadminbox(subtitle, body)
def perform_modifypreferences(req, userID, callback='yes', confirm=0):
"""modify email and password of an account"""
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
subtitle = """4. Modify preferences.   [?]""" % weburl
res = run_sql("SELECT id, email, password FROM user WHERE id=%s" % userID)
output = ""
if res:
output += """Not implemented yet."""
else:
output += 'The account id given does not exist.'
try:
body = [output, extra]
except NameError:
body = [output]
if callback:
return perform_editaccount(req, userID, mtype='perform_modifypreferences', content=addadminbox(subtitle, body), callback='yes')
else:
return addadminbox(subtitle, body)
def perform_deleteaccount(req, userID, callback='yes', confirm=0):
"""delete account"""
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
subtitle = """5. Delete account.   [?]""" % weburl
res = run_sql("SELECT id, email, password FROM user WHERE id=%s" % userID)
output = ""
if res:
if confirm in [0, "0"]:
text = 'Are you sure you want to delete the account with email: "%s"?' % res[0][1]
output += createhiddenform(action="deleteaccount",
text=text,
userID=userID,
confirm=1,
button="Delete")
elif confirm in [1, "1"]:
res2 = run_sql("DELETE FROM user WHERE id=%s" % userID)
output += 'Account deleted.'
if CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_DELETION == 1:
emailsent = sendAccountDeletedMessage(res[0][1], res[0][1])
else:
output += 'The account id given does not exist.'
try:
body = [output, extra]
except NameError:
body = [output]
if callback:
return perform_editaccount(req, userID, mtype='perform_deleteaccount', content=addadminbox(subtitle, body), callback='yes')
else:
return addadminbox(subtitle, body)
def perform_rejectaccount(req, userID, email_user_pattern, limit_to, maxpage, page, callback='yes', confirm=0):
"""Delete account and send an email to the owner."""
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
res = run_sql("SELECT id, email, password, note FROM user WHERE id=%s" % userID)
output = ""
if res:
res2 = run_sql("DELETE FROM user WHERE id=%s" % userID)
output += 'Account rejected and deleted.'
if CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_DELETION == 1:
if not res[0][3] or res[0][3] == "0":
emailsent = sendAccountRejectedMessage(res[0][1], res[0][1])
elif res[0][3] == "1":
emailsent = sendAccountDeletedMessage(res[0][1], res[0][1])
if emailsent:
output += """ An email has been sent to the owner of the account."""
else:
output += """ Could not send an email to the owner of the account."""
else:
output += 'The account id given does not exist.'
try:
body = [output, extra]
except NameError:
body = [output]
if callback:
return perform_modifyaccounts(req, email_user_pattern, limit_to, maxpage, page, content=output, callback='yes')
else:
return addadminbox(subtitle, body)
def perform_modifyaccounts(req, email_user_pattern='', limit_to=-1, maxpage=MAXPAGEUSERS, page=1, content='', callback='yes', confirm=0):
"""Modify default behaviour of a guest user or if new accounts should automatically/manually be modified."""
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
subtitle = """4. Edit accounts.   [?]""" % weburl
output = ""
# remove letters not allowed in an email
email_user_pattern = cleanstring_email(email_user_pattern)
try:
maxpage = int(maxpage)
except:
maxpage = MAXPAGEUSERS
try:
page = int(page)
if page < 1:
page = 1
except:
page = 1
text = ' Email (part of):\n'
text += ' ' % (email_user_pattern, )
text += """Limit to: """ % ((limit_to=="all" and "selected" or ""), (limit_to=="enabled" and "selected" or ""), (limit_to=="disabled" and "selected" or ""))
text += """Accounts per page: """ % ((maxpage==25 and "selected" or ""), (maxpage==50 and "selected" or ""), (maxpage==100 and "selected" or ""), (maxpage==250 and "selected" or ""), (maxpage==500 and "selected" or ""), (maxpage==1000 and "selected" or ""))
output += createhiddenform(action="modifyaccounts",
text=text,
button="search for accounts")
if limit_to not in [-1, "-1"] and maxpage:
users1 = "SELECT id,email,note FROM user WHERE "
if limit_to == "enabled":
users1 += " email!='' AND note=1"
elif limit_to == "disabled":
users1 += " email!='' AND note=0 OR note IS NULL"
elif limit_to == "guest":
users1 += " email=''"
else:
users1 += " email!=''"
if email_user_pattern:
users1 += " AND email RLIKE '%s'" % (email_user_pattern)
users1 += " ORDER BY email LIMIT %s" % (maxpage * page + 1)
users1 = run_sql(users1)
if not users1:
output += 'There are no accounts matching the email given.'
else:
users = []
if maxpage * (page - 1) > len(users1):
page = len(users1) / maxpage + 1
for (id, email, note) in users1[maxpage * (page - 1):(maxpage * page)]:
users.append(['', id, email, (note=="1" and 'Active' or 'Inactive')])
for col in [(((note=="1" and 'Inactivate' or 'Activate'), 'modifyaccountstatus'), ((note == "0" and 'Reject' or 'Delete'), 'rejectaccount'), ),
(('Edit account', 'editaccount'), ),]:
users[-1].append('%s' % (col[0][1], id, email_user_pattern, limit_to, maxpage, page, random.randint(0,1000), col[0][0]))
for (str, function) in col[1:]:
users[-1][-1] += ' / %s' % (function, id, email_user_pattern, limit_to, maxpage, page, random.randint(0,1000), str)
last = ""
next = ""
if len(users1) > maxpage:
if page > 1:
last += 'Last Page' % (email_user_pattern, limit_to, maxpage, (page - 1))
if len(users1[maxpage * (page - 1):(maxpage * page)]) == maxpage:
next += 'Next page' % (email_user_pattern, limit_to, maxpage, (page + 1))
output += 'Showing accounts %s-%s:' % (1 + maxpage * (page - 1), maxpage * page)
else:
output += '%s matching account(s):' % len(users1)
output += tupletotable(header=[last, 'id', 'email', 'Status', '', '',next], tuple=users)
else:
output += 'Please select which accounts to find and how many to show per page.'
if content:
output += " %s" % content
try:
body = [output, extra]
except NameError:
body = [output]
if callback:
return perform_manageaccounts(req, "perform_modifyaccounts", addadminbox(subtitle, body))
else:
return addadminbox(subtitle, body)
def perform_delegate_startarea(req):
"""start area for lower level delegation of rights."""
subtitle = 'select what to do'
output = ''
if is_adminuser(req)[0] == 0:
output += """
You are also allowed to be in the Main Admin Area which gives you
the access to the full functionality of WebAccess.
spesialized area to set up the delegation rights used in the areas above.
you need to be a web administrator to access the area.
"""
return index(req=req,
title='Delegate Rights',
subtitle=subtitle,
body=[output],
adminarea=0,
authorized=1)
def perform_delegate_adminsetup(req, id_role_admin=0, id_role_delegate=0, confirm=0):
"""lets the webadmins set up the delegation rights for the other roles
id_role_admin - the role to be given delegation rights
id_role_delegate - the role over which the delegation rights are given
confirm - make the connection happen """
subtitle = 'step 1 - select admin role'
admin_roles = acca.acc_getAllRoles()
output = """
This is a specialized area to handle a task that also can be handled
from the "add authorization" interface.
By handling the delegation rights here you get the advantage of
not having to select the correct action (%s) or
remembering the names of available roles.
""" % (DELEGATEADDUSERROLE, )
output += createroleselect(id_role=id_role_admin,
step=1,
button='select admin role',
name='id_role_admin',
action='delegate_adminsetup',
roles=admin_roles)
if str(id_role_admin) != '0':
subtitle = 'step 2 - select delegate role'
name_role_admin = acca.acc_getRoleName(id_role=id_role_admin)
delegate_roles_old = acca.acc_find_delegated_roles(id_role_admin=id_role_admin)
delegate_roles = []
delegate_roles_old_names = []
for role in admin_roles:
if (role,) not in delegate_roles_old:
delegate_roles.append(role)
else:
delegate_roles_old_names.append(role[1])
if delegate_roles_old_names:
delegate_roles_old_names.sort()
names_str = ''
for name in delegate_roles_old_names:
if names_str: names_str += ', '
names_str += name
output += '
Warning: don't hand out delegation rights that can harm the system (e.g. delegating superrole).
"""
output += createhiddenform(action="delegate_adminsetup",
text='let role %s delegate rights over role %s?' % (name_role_admin, name_role_delegate),
id_role_admin=id_role_admin,
id_role_delegate=id_role_delegate,
confirm=1)
if int(confirm):
subtitle = 'step 4 - confirm delegation right added'
# res1 = acca.acc_addRoleActionArguments_names(name_role=name_role_admin,
# name_action=DELEGATEADDUSERROLE,
# arglistid=-1,
# optional=0,
# role=name_role_delegate)
res1 = acca.acc_addAuthorization(name_role=name_role_admin,
name_action=DELEGATEADDUSERROLE,
optional=0,
role=name_role_delegate)
if res1:
output += '
confirm: role %s delegates role %s.' % (name_role_admin, name_role_delegate)
else: output += '
sorry, delegation right could not be added, it probably already exists.
'
# see if right hand menu is available
try: body = [output, extra]
except NameError: body = [output]
return index(req=req,
title='Delegate Rights',
subtitle=subtitle,
body=body,
adminarea=1)
def perform_delegate_adduserrole(req, id_role=0, email_user_pattern='', id_user=0, confirm=0):
"""let a lower level web admin add users to a limited set of roles.
id_role - the role to connect to a user
id_user - the user to connect to a role
confirm - make the connection happen """
# finding the allowed roles for this user
id_admin = getUid(req)
id_action = acca.acc_getActionId(name_action=DELEGATEADDUSERROLE)
actions = acca.acc_findPossibleActionsUser(id_user=id_admin, id_action=id_action)
allowed_roles = []
allowed_id_roles = []
for (id, arglistid, name_role_help) in actions[1:]:
id_role_help = acca.acc_getRoleId(name_role=name_role_help)
if id_role_help and [id_role_help, name_role_help, ''] not in allowed_roles:
allowed_roles.append([id_role_help, name_role_help, ''])
allowed_id_roles.append(str(id_role_help))
output = ''
if not allowed_roles:
subtitle = 'no delegation rights'
output += """
You do not have the delegation rights over any roles.
If you think you should have such rights, contact a WebAccess Administrator.
Lower level delegation of access rights to roles.
An administrator with all rights have to give you these rights.
"""
email_out = acca.acc_getUserEmail(id_user=id_user)
name_role = acca.acc_getRoleName(id_role=id_role)
output += createroleselect(id_role=id_role, step=1, name='id_role',
action='delegate_adduserrole', roles=allowed_roles)
if str(id_role) != '0' and str(id_role) in allowed_id_roles:
subtitle = 'step 2 - search for users'
# remove letters not allowed in an email
email_user_pattern = cleanstring_email(email_user_pattern)
text = ' 2. search for user \n'
text += ' \n' % (email_user_pattern, )
output += createhiddenform(action="delegate_adduserrole",
text=text,
button="search for users",
id_role=id_role)
# pattern is entered
if email_user_pattern:
# users with matching email-address
users1 = run_sql("""SELECT id, email FROM user WHERE email RLIKE '%s' ORDER BY email """ % (email_user_pattern, ))
# users that are connected
users2 = run_sql("""SELECT DISTINCT u.id, u.email
FROM user u LEFT JOIN user_accROLE ur ON u.id = ur.id_user
WHERE ur.id_accROLE = '%s' AND u.email RLIKE '%s'
ORDER BY u.email """ % (id_role, email_user_pattern))
# no users that match the pattern
if not (users1 or users2):
output += '
no qualified users, try new search.
'
# too many matching users
elif len(users1) > MAXSELECTUSERS:
output += '
%s hits, too many qualified users, specify more narrow search. (limit %s)
' % (len(users1), MAXSELECTUSERS)
# show matching users
else:
subtitle = 'step 3 - select a user'
users = []
extrausers = []
for (id, email) in users1:
if (id, email) not in users2: users.append([id,email,''])
for (id, email) in users2:
extrausers.append([-id, email,''])
output += createuserselect(id_user=id_user,
action="delegate_adduserrole",
step=3,
users=users,
extrausers=extrausers,
button="add this user",
id_role=id_role,
email_user_pattern=email_user_pattern)
try: id_user = int(id_user)
except ValueError: pass
# user selected already connected to role
if id_user < 0:
output += '
users in brackets are already attached to the role, try another one...
'
# a user is selected
elif email_out:
subtitle = "step 4 - confirm to add user"
output += createhiddenform(action="delegate_adduserrole",
text='add user %s to role %s?' % (email_out, name_role),
id_role=id_role,
email_user_pattern=email_user_pattern,
id_user=id_user,
confirm=1)
# it is confirmed that this user should be added
if confirm:
# add user
result = acca.acc_addUserRole(id_user=id_user, id_role=id_role)
if result and result[2]:
subtitle = 'step 5 - confirm user added'
output += '
confirm: user %s added to role %s.
' % (email_out, name_role)
else:
subtitle = 'step 5 - user could not be added'
output += '
remove users from the roles you have delegating rights to.
""" % (id_role, )
return index(req=req,
title='Connect users to roles',
subtitle=subtitle,
body=[output, extra],
adminarea=1,
authorized=1)
def perform_delegate_deleteuserrole(req, id_role=0, id_user=0, confirm=0):
"""let a lower level web admin remove users from a limited set of roles.
id_role - the role to connect to a user
id_user - the user to connect to a role
confirm - make the connection happen """
subtitle = 'in progress...'
output = '
in progress...
'
# finding the allowed roles for this user
id_admin = getUid(req)
id_action = acca.acc_getActionId(name_action=DELEGATEADDUSERROLE)
actions = acca.acc_findPossibleActionsUser(id_user=id_admin, id_action=id_action)
output = ''
if not actions:
subtitle = 'no delegation rights'
output += """
You do not have the delegation rights over any roles.
If you think you should have such rights, contact a WebAccess Administrator.
Lower level delegation of access rights to roles.
An administrator with all rights have to give you these rights.
"""
email_out = acca.acc_getUserEmail(id_user=id_user)
name_role = acca.acc_getRoleName(id_role=id_role)
# create list of allowed roles
allowed_roles = []
allowed_id_roles = []
for (id, arglistid, name_role_help) in actions[1:]:
id_role_help = acca.acc_getRoleId(name_role=name_role_help)
if id_role_help and [id_role_help, name_role_help, ''] not in allowed_roles:
allowed_roles.append([id_role_help, name_role_help, ''])
allowed_id_roles.append(str(id_role_help))
output += createroleselect(id_role=id_role, step=1,
action='delegate_deleteuserrole', roles=allowed_roles)
if str(id_role) != '0' and str(id_role) in allowed_id_roles:
subtitle = 'step 2 - select user'
users = acca.acc_getRoleUsers(id_role)
output += createuserselect(id_user=id_user,
step=2,
action='delegate_deleteuserrole',
users=users,
id_role=id_role)
if str(id_user) != '0':
subtitle = 'step 3 - confirm delete of user'
email_user = acca.acc_getUserEmail(id_user=id_user)
output += createhiddenform(action="delegate_deleteuserrole",
text='delete user %s from %s?'
% (headerstrong(user=id_user), headerstrong(role=id_role)),
id_role=id_role,
id_user=id_user,
confirm=1)
if confirm:
res = acca.acc_deleteUserRole(id_user=id_user, id_role=id_role)
if res:
subtitle = 'step 4 - confirm user deleted from role'
output += '
confirm: deleted user %s from role %s.
' % (email_user, name_role)
else:
subtitle = 'step 4 - user could not be deleted'
output += 'sorry, but user could not be deleted user is probably already deleted.'
extra = """
'
return output
def perform_addrole(req, name_role='', description='put description here.', confirm=0):
"""form to add a new role with these values:
name_role - name of the new role
description - optional description of the role """
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
name_role = cleanstring(name_role)
title='Add Role'
subtitle = 'step 1 - give values to the requested fields'
output = """
""" % (name_role, description)
if name_role:
# description must be changed before submitting
subtitle = 'step 2 - confirm to add role'
internaldesc = ''
if description != 'put description here.':
internaldesc = description
text = """
add role with: \n
name: %s """ % (name_role, )
if internaldesc:
text += 'description: %s?\n' % (description, )
output += createhiddenform(action="addrole",
text=text,
name_role=name_role,
description=description,
confirm=1)
if confirm not in ["0", 0]:
result = acca.acc_addRole(name_role=name_role,
description=internaldesc)
if result:
subtitle = 'step 3 - role added'
output += '
role added:
'
output += tupletotable(header=['id', 'action name', 'description', 'allowedkeywords'],
tuple=[result])
else:
subtitle = 'step 3 - role could not be added'
output += '
sorry, could not add role, role with the same name probably exists.
'
id_role = acca.acc_getRoleId(name_role=name_role)
extra = """
'
return details
def perform_adduserrole(req, id_role='0', email_user_pattern='', id_user='0', confirm=0):
"""create connection between user and role.
id_role - id of the role to add user to
email_user_pattern - search for users using this pattern
id_user - id of user to add to the role. """
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
email_out = acca.acc_getUserEmail(id_user=id_user)
name_role = acca.acc_getRoleName(id_role=id_role)
title = 'Connect user to role '
subtitle = 'step 1 - select a role'
output = createroleselect(id_role=id_role,
action="adduserrole",
step=1,
roles=acca.acc_getAllRoles())
# role is selected
if id_role != "0":
title += name_role
subtitle = 'step 2 - search for users'
# remove letters not allowed in an email
email_user_pattern = cleanstring_email(email_user_pattern)
text = ' 2. search for user \n'
text += ' \n' % (email_user_pattern, )
output += createhiddenform(action="adduserrole",
text=text,
button="search for users",
id_role=id_role)
# pattern is entered
if email_user_pattern:
# users with matching email-address
users1 = run_sql("""SELECT id, email FROM user WHERE email RLIKE '%s' ORDER BY email """ % (email_user_pattern, ))
# users that are connected
users2 = run_sql("""SELECT DISTINCT u.id, u.email
FROM user u LEFT JOIN user_accROLE ur ON u.id = ur.id_user
WHERE ur.id_accROLE = '%s' AND u.email RLIKE '%s'
ORDER BY u.email """ % (id_role, email_user_pattern))
# no users that match the pattern
if not (users1 or users2):
output += '
no qualified users, try new search.
'
elif len(users1) > MAXSELECTUSERS:
output += '
%s hits, too many qualified users, specify more narrow search. (limit %s)
' % (len(users1), MAXSELECTUSERS)
# show matching users
else:
subtitle = 'step 3 - select a user'
users = []
extrausers = []
for (id, email) in users1:
if (id, email) not in users2: users.append([id,email,''])
for (id, email) in users2:
extrausers.append([-id, email,''])
output += createuserselect(id_user=id_user,
action="adduserrole",
step=3,
users=users,
extrausers=extrausers,
button="add this user",
id_role=id_role,
email_user_pattern=email_user_pattern)
try: id_user = int(id_user)
except ValueError: pass
# user selected already connected to role
if id_user < 0:
output += '
users in brackets are already attached to the role, try another one...
'
# a user is selected
elif email_out:
subtitle = "step 4 - confirm to add user"
output += createhiddenform(action="adduserrole",
text='add user %s to role %s?' % (email_out, name_role),
id_role=id_role,
email_user_pattern=email_user_pattern,
id_user=id_user,
confirm=1)
# it is confirmed that this user should be added
if confirm:
# add user
result = acca.acc_addUserRole(id_user=id_user, id_role=id_role)
if result and result[2]:
subtitle = 'step 5 - confirm user added'
output += '
confirm: user %s added to role %s.
' % (email_out, name_role)
else:
subtitle = 'step 5 - user could not be added'
output += '
""" % (id_role, name_role, id_role, name_role, id_role, name_role)
return index(req=req,
title=title,
subtitle=subtitle,
body=[output, extra],
adminarea=3)
def perform_addroleuser(req, email_user_pattern='', id_user='0', id_role='0', confirm=0):
"""delete connection between role and user.
id_role - id of role to disconnect
id_user - id of user to disconnect. """
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
email_out = acca.acc_getUserEmail(id_user=id_user)
name_role = acca.acc_getRoleName(id_role=id_role)
# used to sort roles, and also to determine right side links
con_roles = []
not_roles = []
title = 'Connect user to roles'
subtitle = 'step 1 - search for users'
# clean email search string
email_user_pattern = cleanstring_email(email_user_pattern)
text = ' 1. search for user \n'
text += ' \n' % (email_user_pattern, )
output = createhiddenform(action='addroleuser',
text=text,
button='search for users',
id_role=id_role)
if email_user_pattern:
subtitle = 'step 2 - select user'
users1 = run_sql("""SELECT id, email FROM user WHERE email RLIKE '%s' ORDER BY email """ % (email_user_pattern, ))
users = []
for (id, email) in users1: users.append([id, email, ''])
# no users
if not users:
output += '
no qualified users, try new search.
'
# too many users
elif len(users) > MAXSELECTUSERS:
output += '
%s hits, too many qualified users, specify more narrow search. (limit %s)
' % (len(users), MAXSELECTUSERS)
# ok number of users
else:
output += createuserselect(id_user=id_user,
action='addroleuser',
step=2,
users=users,
button='select user',
email_user_pattern=email_user_pattern)
if int(id_user):
subtitle = 'step 3 - select role'
# roles the user is connected to
role_ids = acca.acc_getUserRoles(id_user=id_user)
# all the roles, lists are sorted on the background of these...
all_roles = acca.acc_getAllRoles()
# sort the roles in connected and not connected roles
for (id, name, description) in all_roles:
if (id, ) in role_ids: con_roles.append([-id, name, description])
else: not_roles.append([id, name, description])
# create roleselect
output += createroleselect(id_role=id_role,
action='addroleuser',
step=3,
roles=not_roles,
extraroles=con_roles,
extrastamp='(connected)',
button='add this role',
email_user_pattern=email_user_pattern,
id_user=id_user)
if int(id_role) < 0:
name_role = acca.acc_getRoleName(id_role=-int(id_role))
output += '
role %s already connected to the user, try another one...
' % (name_role, )
elif int(id_role):
subtitle = 'step 4 - confirm to add role to user'
output += createhiddenform(action='addroleuser',
text='add role %s to user %s?' % (name_role, email_out),
email_user_pattern=email_user_pattern,
id_user=id_user,
id_role=id_role,
confirm=1)
if confirm:
# add role
result = acca.acc_addUserRole(id_user=id_user, id_role=id_role)
if result and result[2]:
subtitle = 'step 5 - confirm role added'
output += '
confirm: role %s added to user %s.
' % (name_role, email_out)
else:
subtitle = 'step 5 - role could not be added'
output += '
""" % (id_role, name_role)
return index(req=req,
title=title,
subtitle=subtitle,
body=[output, extra],
adminarea=5)
def perform_deleteuserrole(req, id_role='0', id_user='0', reverse=0, confirm=0):
"""delete connection between role and user.
id_role - id of role to disconnect
id_user - id of user to disconnect. """
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
title = 'Remove user from role'
email_user = acca.acc_getUserEmail(id_user=id_user)
name_role = acca.acc_getRoleName(id_role=id_role)
output = ''
if reverse in [0, '0']:
adminarea = 3
subtitle = 'step 1 - select the role'
output += createroleselect(id_role=id_role,
action="deleteuserrole",
step=1,
roles=acca.acc_getAllRoles())
if id_role != "0":
subtitle = 'step 2 - select the user'
output += createuserselect(id_user=id_user,
action="deleteuserrole",
step=2,
users=acca.acc_getRoleUsers(id_role=id_role),
id_role=id_role)
else:
adminarea = 5
# show only if user is connected to a role, get users connected to roles
users = run_sql("""SELECT DISTINCT(u.id), u.email, u.note
FROM user u LEFT JOIN user_accROLE ur
ON u.id = ur.id_user
WHERE ur.id_accROLE != 'NULL' AND u.email != ''
ORDER BY u.email """)
has_roles = 1
# check if the user is connected to any roles
for (id, email, note) in users:
if str(id) == str(id_user): break
# user not connected to a role
else:
subtitle = 'step 1 - user not connected'
output += '
no need to remove roles from user %s, user is not connected to any roles.
' % (email_user, )
has_roles, id_user = 0, '0' # stop the rest of the output below...
# user connected to roles
if has_roles:
output += createuserselect(id_user=id_user,
action="deleteuserrole",
step=1,
users=users,
reverse=reverse)
if id_user != "0":
subtitle = 'step 2 - select the role'
role_ids = acca.acc_getUserRoles(id_user=id_user)
all_roles = acca.acc_getAllRoles()
roles = []
for (id, name, desc) in all_roles:
if (id, ) in role_ids: roles.append([id, name, desc])
output += createroleselect(id_role=id_role,
action="deleteuserrole",
step=2,
roles=roles,
id_user=id_user,
reverse=reverse)
if id_role != '0' and id_user != '0':
subtitle = 'step 3 - confirm delete of user'
output += createhiddenform(action="deleteuserrole",
text='delete user %s from %s?' % (headerstrong(user=id_user), headerstrong(role=id_role)),
id_role=id_role,
id_user=id_user,
reverse=reverse,
confirm=1)
if confirm:
res = acca.acc_deleteUserRole(id_user=id_user, id_role=id_role)
if res:
subtitle = 'step 4 - confirm delete of user'
output += '
confirm: deleted user %s from role %s.
' % (email_user, name_role)
else:
subtitle = 'step 4 - user could not be deleted'
output += 'sorry, but user could not be deleted user is probably already deleted.'
extra = ''
if str(id_role) != "0":
extra += """
""" % (id_user, email_user, email_user)
extra += '
'
if extra: body = [output, extra]
else: body = [output]
return index(req=req,
title=title,
subtitle=subtitle,
body=body,
adminarea=adminarea)
def perform_showuserdetails(req, id_user=0):
"""show the details of a user. """
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
if id_user not in [0, '0']:
output = userdetails(id_user=id_user)
email_user = acca.acc_getUserEmail(id_user=id_user)
extra = """
' % (email_user, )
return details
def perform_addauthorization(req, id_role="0", id_action="0", optional=0, reverse="0", confirm=0, **keywords):
""" form to add new connection between user and role:
id_role - role to connect
id_action - action to connect
reverse - role or action first? """
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
# values that might get used
name_role = acca.acc_getRoleName(id_role=id_role) or id_role
name_action = acca.acc_getActionName(id_action=id_action) or id_action
optional = optional == 'on' and 1 or int(optional)
extra = """
"""
# create the page according to which step the user is on
# role -> action -> arguments
if reverse in ["0", 0]:
adminarea = 3
subtitle = 'step 1 - select role'
output = createroleselect(id_role=id_role,
action="addauthorization",
step=1,
roles=acca.acc_getAllRoles(),
reverse=reverse)
if str(id_role) != "0":
subtitle = 'step 2 - select action'
rolacts = acca.acc_getRoleActions(id_role)
allhelp = acca.acc_getAllActions()
allacts = []
for r in allhelp:
if r not in rolacts: allacts.append(r)
output += createactionselect(id_action=id_action,
action="addauthorization",
step=2,
actions=rolacts,
extraactions=allacts,
id_role=id_role,
reverse=reverse)
# action -> role -> arguments
else:
adminarea = 4
subtitle = 'step 1 - select action'
output = createactionselect(id_action=id_action,
action="addauthorization",
step=1,
actions=acca.acc_getAllActions(),
reverse=reverse)
if str(id_action) != "0":
subtitle = 'step 2 - select role'
actroles = acca.acc_getActionRoles(id_action)
allhelp = acca.acc_getAllRoles()
allroles = []
for r in allhelp:
if r not in actroles: allroles.append(r)
output += createroleselect(id_role=id_role,
action="addauthorization",
step=2,
roles=actroles,
extraroles=allroles,
id_action=id_action,
reverse=reverse)
# ready for step 3 no matter which direction we took to get here
if id_action != "0" and id_role != "0":
# links to adding authorizations in the other direction
if str(reverse) == "0":
extra += """
connect %s to %s for any arguments
connect %s to %s for only these argument cases:
""" % (optional and 'checked="checked"' or '', name_role, name_action, not optional and 'checked="checked"' or '', name_role, name_action)
# list the arguments
allkeys = 1
for key in res_keys:
output += '%s \n \n'
output = output[:-5] + ' \n'
output += '\n'
# ask for confirmation
if str(allkeys) != "0" or optional:
keys = keywords.keys()
keys.reverse()
subtitle = 'step 4 - confirm add of authorization\n'
text = """
create connection between
%s
""" % (headerstrong(role=name_role, action=name_action, query=0), )
if optional:
text += 'withouth arguments'
keywords = {}
else:
for key in keys:
text += '%s: %s \n' % (key, keywords[key])
output += createhiddenform(action="addauthorization",
text=text,
id_role=id_role,
id_action=id_action,
reverse=reverse,
confirm=1,
optional=optional,
**keywords)
# show existing authorizations, found authorizations further up in the code...
# res_auths = acca.acc_findPossibleActions(id_role, id_action)
output += '
existing authorizations:
'
if res_auths:
output += tupletotable(header=res_auths[0], tuple=res_auths[1:])
# shortcut to modifying authorizations
extra += """
sorry, authorization could not be added, it probably already exists
'
# trying to put extra link on the right side
try: body = [output, extra]
except NameError: body = [output]
return index(req=req,
title = 'Create entry for new authorization',
subtitle=subtitle,
body=body,
adminarea=adminarea)
def perform_deleteroleaction(req, id_role="0", id_action="0", reverse=0, confirm=0):
"""delete all connections between a role and an action.
id_role - id of the role
id_action - id of the action
reverse - 0: ask for role first
1: ask for action first"""
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
title = 'Remove action from role '
if reverse in ["0", 0]:
# select role -> action
adminarea = 3
subtitle = 'step 1 - select a role'
output = createroleselect(id_role=id_role,
action="deleteroleaction",
step=1,
roles=acca.acc_getAllRoles(),
reverse=reverse)
if id_role != "0":
rolacts = acca.acc_getRoleActions(id_role=id_role)
subtitle = 'step 2 - select the action'
output += createactionselect(id_action=id_action,
action="deleteroleaction",
step=2,
actions=rolacts,
reverse=reverse,
id_role=id_role,
button="remove connection and all authorizations")
else:
# select action -> role
adminarea = 4
subtitle = 'step 1 - select an action'
output = createactionselect(id_action=id_action,
action="deleteroleaction",
step=1,
actions=acca.acc_getAllActions(),
reverse=reverse)
if id_action != "0":
actroles = acca.acc_getActionRoles(id_action=id_action)
subtitle = 'step 2 - select the role'
output += createroleselect(id_role=id_role,
action="deleteroleaction",
step=2,
roles=actroles,
button="remove connection and all authorizations",
id_action=id_action,
reverse=reverse)
if id_action != "0" and id_role != "0":
subtitle = 'step 3 - confirm to remove authorizations'
# ask for confirmation
res = acca.acc_findPossibleActions(id_role, id_action)
if res:
output += '
authorizations that will be deleted:
'
output += tupletotable(header=res[0], tuple=res[1:])
output += createhiddenform(action="deleteroleaction",
text='remove %s from %s' % (headerstrong(action=id_action), headerstrong(role=id_role)),
confirm=1,
id_role=id_role,
id_action=id_action,
reverse=reverse)
else:
output += 'no authorizations'
# confirmation is given
if confirm:
subtitle = 'step 4 - confirm authorizations removed '
res = acca.acc_deleteRoleAction(id_role=id_role, id_action=id_action)
if res:
output += '
confirm: removed %s from %s ' % (headerstrong(action=id_action), headerstrong(role=id_role))
output += '%s entries were removed.
' % (res, )
else:
output += '
sorry, no entries could be removed.
'
return index(req=req,
title=title,
subtitle=subtitle,
body=[output],
adminarea=adminarea)
def perform_modifyauthorizations(req, id_role="0", id_action="0", reverse=0, confirm=0, errortext='', sel='', authids=[]):
"""given ids of a role and an action, show all possible action combinations
with checkboxes and allow user to access other functions.
id_role - id of the role
id_action - id of the action
reverse - 0: ask for role first
1: ask for action first
sel - which button and modification that is selected
errortext - text to print when no connection exist between role and action
authids - ids of checked checkboxes """
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
name_role = acca.acc_getRoleName(id_role)
name_action = acca.acc_getActionName(id_action)
output = ''
try: id_role, id_action, reverse = int(id_role), int(id_action), int(reverse)
except ValueError: pass
extra = """
\n'
if not reverse:
# role -> action
adminarea = 3
subtitle = 'step 1 - select the role'
output += createroleselect(id_role=str(id_role),
action="modifyauthorizations",
step=1,
roles=acca.acc_getAllRoles(),
reverse=reverse)
if id_role:
rolacts = acca.acc_getRoleActions(id_role=id_role)
subtitle = 'step 2 - select the action'
output += createactionselect(id_action=str(id_action),
action="modifyauthorizations",
step=2,
actions=rolacts,
id_role=id_role,
reverse=reverse)
else:
adminarea = 4
# action -> role
subtitle = 'step 1 - select the action'
output += createactionselect(id_action=str(id_action),
action="modifyauthorizations",
step=1,
actions=acca.acc_getAllActions(),
reverse=reverse)
if id_action:
actroles = acca.acc_getActionRoles(id_action=id_action)
subtitle = 'step 2 - select the role'
output += createroleselect(id_role=str(id_role),
action="modifyauthorizations",
step=2,
roles=actroles,
id_action=id_action,
reverse=reverse)
if errortext: output += '
%s
' % (errortext, )
if id_role and id_action:
# adding to main area
if type(authids) is not list: authids = [authids]
subtitle = 'step 3 - select groups and modification'
# get info
res = acca.acc_findPossibleActions(id_role, id_action)
# clean the authids
hiddenids = []
if sel in ['delete selected']:
hiddenids = authids[:]
elif sel in ['split groups', 'merge groups']:
for authid in authids:
arghlp = res[int(authid)][0]
if authid not in hiddenids and arghlp not in [-1, '-1', 0, '0']: hiddenids.append(authid)
authids = hiddenids[:]
if confirm:
# do selected modification and output with new authorizations
if sel == 'split groups':
res = splitgroups(id_role, id_action, authids)
elif sel == 'merge groups':
res = mergegroups(id_role, id_action, authids)
elif sel == 'delete selected':
res = deleteselected(id_role, id_action, authids)
authids = []
res = acca.acc_findPossibleActions(id_role, id_action)
output += 'authorizations after %s. \n' % (sel, )
elif sel and authids:
output += 'confirm choice of authorizations and modification. \n'
else:
output += 'select authorizations and perform modification. \n'
if not res:
errortext='all connections deleted, try different '
if reverse in ["0", 0]:
return perform_modifyauthorizations(req=req, id_role=id_role, errortext=errortext + 'action.')
else:
return perform_modifyauthorizations(req=req, id_action=id_action, reverse=reverse, errortext=errortext + 'role.')
# display
output += modifyauthorizationsmenu(id_role, id_action, header=res[0], tuple=res[1:], checked=authids, reverse=reverse)
if sel and authids:
subtitle = 'step 4 - confirm to perform modification'
# form with hidden authids
output += ''
# tried to perform modification without something selected
elif sel and not authids and not confirm:
output += '
no valid groups selected
'
# trying to put extra link on the right side
try: body = [output, extra]
except NameError: body = [output]
# Display the page
return index(req=req,
title='Modify Authorizations',
subtitle=subtitle,
body=body,
adminarea=adminarea)
def modifyauthorizationsmenu(id_role, id_action, tuple=[], header=[], checked=[], reverse=0):
"""create table with header and checkboxes, used for multiple choice.
makes use of tupletotable to add the actual table
id_role - selected role, hidden value in the form
id_action - selected action, hidden value in the form
tuple - all rows to be put in the table (with checkboxes)
header - column headers, empty strings added at start and end
checked - ids of rows to be checked """
if not tuple:
return 'no authorisations...'
argnum = len(acca.acc_getActionKeywords(id_action=id_action))
tuple2 = []
for t in tuple: tuple2.append(t[:])
tuple2 = addcheckboxes(datalist=tuple2, name='authids', startindex=1, checked=checked)
hidden = ' \n' % (id_role, )
hidden += ' \n' % (id_action, )
hidden += ' \n' % (reverse, )
button = '\n'
if argnum > 1:
button += '\n'
button += '\n'
hdrstr = ''
for h in [''] + header + ['']: hdrstr += '
%s
\n' % (h, )
if hdrstr: hdrstr = '
\n%s\n
\n' % (hdrstr, )
output = '\n'
return output
def splitgroups(id_role=0, id_action=0, authids=[]):
"""get all the old ones, gather up the arglistids find a list of
arglistidgroups to be split, unique get all actions in groups outside
of the old ones, (old arglistid is allowed).
show them like in showselect. """
if not id_role or not id_action or not authids:
return 0
# find all the actions
datalist = acca.acc_findPossibleActions(id_role, id_action)
if type(authids) is str: authids = [authids]
for i in range(len(authids)): authids[i] = int(authids[i])
# argumentlistids of groups to be split
splitgrps = []
for authid in authids:
hlp = datalist[authid][0]
if hlp not in splitgrps and authid in range(1,len(datalist)):
splitgrps.append(hlp)
# split groups and return success or failure
result = 1
for splitgroup in splitgrps:
result = 1 and acca.acc_splitArgumentGroup(id_role, id_action, splitgroup)
return result
def mergegroups(id_role=0, id_action=0, authids=[]):
"""get all the old ones, gather up the argauthids find a list
of arglistidgroups to be split, unique get all actions in groups
outside of the old ones, (old arglistid is allowed).
show them like in showselect."""
if not id_role or not id_action or not authids:
return 0
datalist = acca.acc_findPossibleActions(id_role, id_action)
if type(authids) is str: authids = [authids]
for i in range(len(authids)): authids[i] = int(authids[i])
# argumentlistids of groups to be merged
mergegroups = []
for authid in authids:
hlp = datalist[authid][0]
if hlp not in mergegroups and authid in range(1, len(datalist)):
mergegroups.append(hlp)
# merge groups and return success or failure
if acca.acc_mergeArgumentGroups(id_role, id_action, mergegroups):
return 1
else:
return 0
def deleteselected(id_role=0, id_action=0, authids=[]):
"""delete checked authorizations/possible actions, ids in authids.
id_role - role to delete from
id_action - action to delete from
authids - listids for which possible actions to delete."""
if not id_role or not id_action or not authids:
return 0
if type(authids) in [str, int]: authids = [authids]
for i in range(len(authids)): authids[i] = int(authids[i])
result = acca.acc_deletePossibleActions(id_role=id_role,
id_action=id_action,
authids=authids)
return result
def headeritalic(**ids):
"""transform keyword=value pairs to string with value in italics.
**ids - a dictionary of pairs to create string from """
output = ''
value = ''
table = ''
for key in ids.keys():
if key in ['User', 'user']:
value, table = 'email', 'user'
elif key in ['Role', 'role']:
value, table = 'name', 'accROLE'
elif key in ['Action', 'action']:
value, table = 'name', 'accACTION'
else:
if output: output += ' and '
output += ' %s %s' % (key, ids[key])
continue
res = run_sql("""SELECT %s FROM %s WHERE id = %s""" % (value, table, ids[key]))
if res:
if output: output += ' and '
output += ' %s %s' % (key, res[0][0])
return output
def headerstrong(query=1, **ids):
"""transform keyword=value pairs to string with value in strong text.
**ids - a dictionary of pairs to create string from
query - 1 -> try to find names to ids of role, user and action.
0 -> do not try to find names, use the value passed on """
output = ''
value = ''
table = ''
for key in ids.keys():
if key in ['User', 'user']:
value, table = 'email', 'user'
elif key in ['Role', 'role']:
value, table = 'name', 'accROLE'
elif key in ['Action', 'action']:
value, table = 'name', 'accACTION'
else:
if output: output += ' and '
output += ' %s %s' % (key, ids[key])
continue
if query:
res = run_sql("""SELECT %s FROM %s WHERE id = %s""" % (value, table, ids[key]))
if res:
if output: output += ' and '
output += ' %s %s' % (key, res[0][0])
else:
if output: output += ' and '
output += ' %s %s' % (key, ids[key])
return output
def startpage():
"""create the menu for the startpage"""
body = """
"""
return body
def rankarea():
return "Rankmethod area"
def perform_simpleauthorization(req, id_role=0, id_action=0):
"""show a page with simple overview of authorizations between a
connected role and action. """
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
res = acca.acc_findPossibleActions(id_role, id_action)
if res:
extra = createhiddenform(action='modifyauthorizations',
button='modify authorizations',
id_role=id_role,
id_action=id_action)
output = '
authorizations for %s:
' % (headerstrong(action=id_action, role=id_role), )
output += tupletotable(header=res[0], tuple=res[1:], extracolumn=extra)
else:
output = 'no details to show'
return index(req=req,
title='Simple authorization details',
subtitle='simple authorization details',
body=[output],
adminarea=3)
def perform_showroleusers(req, id_role=0):
"""show a page with simple overview of a role and connected users. """
(auth_code, auth_message) = is_adminuser(req)
if auth_code != 0: return mustloginpage(req, auth_message)
res = acca.acc_getRoleUsers(id_role=id_role)
name_role = acca.acc_getRoleName(id_role=id_role)
if res:
users = []
for (id, name, dontcare) in res: users.append([id, name, 'show user details'
% (id, )])
output = '
users connected to %s:
' % (headerstrong(role=id_role), )
output += tupletotable(header=['id', 'name', ''], tuple=users)
else:
output = 'no users connected to role %s' % (name_role, )
extra = """
""" % (id_role, )
return index(req=req,
title='Users connected to role %s' % (name_role, ),
subtitle='simple details',
body=[output, extra],
adminarea=3)
def createselect(id_input="0", label="", step=0, name="",
action="", list=[], extralist=[], extrastamp='',
button="", **hidden):
"""create form with select and hidden values
id - the one to choose as selected if exists
label - label shown to the left of the select
name - the name of the select on which to reference it
list - primary list to select from
extralist - list of options to be put in paranthesis
extrastamp - stamp extralist entries with this if not ''
usually paranthesis around the entry
button - the value/text to be put on the button
**hidden - name=value pairs to be put as hidden in the form. """
step = step and '%s. ' % step or ''
output = '\n'
return output
def createactionselect(id_action="0", label="select action", step=0, name="id_action",
action="", actions=[], extraactions=[], extrastamp='',
button="select action", **hidden):
"""create a select for roles in a form. see createselect."""
return createselect(id_input=id_action, label=label, step=step, name=name,
action=action, list=actions, extralist=extraactions, extrastamp=extrastamp,
button=button, **hidden)
def createroleselect(id_role="0", label="select role", step=0, name="id_role",
action="", roles=[], extraroles=[], extrastamp='',
button="select role", **hidden):
"""create a select for roles in a form. see createselect."""
return createselect(id_input=id_role, label=label, step=step, name=name,
action=action, list=roles, extralist=extraroles, extrastamp=extrastamp,
button=button, **hidden)
def createuserselect(id_user="0", label="select user", step=0, name="id_user",
action="", users=[], extrausers=[], extrastamp='(connected)',
button="select user", **hidden):
"""create a select for users in a form.see createselect."""
return createselect(id_input=id_user, label=label, step=step, name=name,
action=action, list=users, extralist=extrausers, extrastamp=extrastamp,
button=button, **hidden)
def cleanstring(str='', comma=0):
"""clean all the strings before submitting to access control admin.
remove characters not letter, number or underscore, also remove leading
underscores and numbers. return cleaned string.
str - string to be cleaned
comma - 1 -> allow the comma to divide multiple arguments
0 -> wash commas as well """
# remove not allowed characters
str = re.sub(r'[^a-zA-Z0-9_,]', '', str)
# split string on commas
items = str.split(',')
str = ''
for item in items:
if not item: continue
if comma and str: str += ','
# create valid variable names
str += re.sub(r'^([0-9_])*', '', item)
return str
def cleanstring_argumentvalue(str=''):
"""clean the value of an argument before submitting it.
allowed characters: a-z A-Z 0-9 _ and space
str - string to be cleaned """
# remove not allowed characters
str = re.sub(r'[^a-zA-Z0-9_ .]', '', str)
# trim leading and ending spaces
str = re.sub(r'^ *| *$', '', str)
return str
def cleanstring_email(str=''):
"""clean the string and return a valid email address.
str - string to be cleaned """
# remove not allowed characters
str = re.sub(r'[^a-zA-Z0-9_.@-]', '', str)
return str
def check_email(str=''):
"""control that submitted emails are correct.
this little check is not very good, but better than nothing. """
r = re.compile(r'(.)+\@(.)+\.(.)+')
return r.match(str) and 1 or 0
def sendAccountActivatedMessage(AccountEmail, sendTo, password, ln=cdslang):
"""Send an email to the address given by sendTo about the new activated account."""
fromaddr = "From: %s" % supportemail
toaddrs = "To: %s" % sendTo
to = toaddrs + "\n"
sub = "Subject: Your account on '%s' has been activated\n\n" % cdsname
body = "Your account earlier created on '%s' has been activated:\n\n" % cdsname
body += " Username/Email: %s\n" % AccountEmail
body += " Password: %s\n" % ("*" * len(password))
body += "\n---------------------------------"
body += "\n%s" % cdsname
body += "\nContact: %s" % supportemail
msg = to + sub + body
server = smtplib.SMTP('localhost')
server.set_debuglevel(1)
try:
server.sendmail(fromaddr, toaddrs, msg)
except smtplib.SMTPRecipientsRefused,e:
return 0
server.quit()
return 1
def sendNewUserAccountWarning(newAccountEmail, sendTo, password, ln=cdslang):
"""Send an email to the address given by sendTo about the new account newAccountEmail."""
fromaddr = "From: %s" % supportemail
toaddrs = "To: %s" % sendTo
to = toaddrs + "\n"
sub = "Subject: Account created on '%s'\n\n" % cdsname
body = "An account has been created for you on '%s':\n\n" % cdsname
body += " Username/Email: %s\n" % newAccountEmail
body += " Password: %s\n" % ("*" * len(password))
body += "\n---------------------------------"
body += "\n%s" % cdsname
body += "\nContact: %s" % supportemail
msg = to + sub + body
server = smtplib.SMTP('localhost')
server.set_debuglevel(1)
try:
server.sendmail(fromaddr, toaddrs, msg)
except smtplib.SMTPRecipientsRefused,e:
return 0
server.quit()
return 1
def sendAccountRejectedMessage(newAccountEmail, sendTo, ln=cdslang):
"""Send an email to the address given by sendTo about the new account newAccountEmail."""
fromaddr = "From: %s" % supportemail
toaddrs = "To: %s" % sendTo
to = toaddrs + "\n"
sub = "Subject: Account rejected on '%s'\n\n" % cdsname
body = "Your request for an account has been rejected on '%s':\n\n" % cdsname
body += " Username/Email: %s\n" % newAccountEmail
body += "\n---------------------------------"
body += "\n%s" % cdsname
body += "\nContact: %s" % supportemail
msg = to + sub + body
server = smtplib.SMTP('localhost')
server.set_debuglevel(1)
try:
server.sendmail(fromaddr, toaddrs, msg)
except smtplib.SMTPRecipientsRefused,e:
return 0
server.quit()
return 1
def sendAccountDeletedMessage(newAccountEmail, sendTo, ln=cdslang):
"""Send an email to the address given by sendTo about the new account newAccountEmail."""
fromaddr = "From: %s" % supportemail
toaddrs = "To: %s" % sendTo
to = toaddrs + "\n"
sub = "Subject: Account deleted on '%s'\n\n" % cdsname
body = "Your account on '%s' has been deleted:\n\n" % cdsname
body += " Username/Email: %s\n" % newAccountEmail
body += "\n---------------------------------"
body += "\n%s" % cdsname
body += "\nContact: %s" % supportemail
msg = to + sub + body
server = smtplib.SMTP('localhost')
server.set_debuglevel(1)
try:
server.sendmail(fromaddr, toaddrs, msg)
except smtplib.SMTPRecipientsRefused,e:
return 0
server.quit()
return 1