diff --git a/modules/websession/lib/webaccount.py b/modules/websession/lib/webaccount.py
index afaa00570..0774f16ef 100644
--- a/modules/websession/lib/webaccount.py
+++ b/modules/websession/lib/webaccount.py
@@ -1,423 +1,434 @@
## $Id$
## CDSware User account information implementation. Useful for youraccount pages.
## 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.
## $Id$
## DO NOT EDIT THIS FILE! IT WAS AUTOMATICALLY GENERATED FROM CDSware WML SOURCES.
## read config variables:
#include "config.wml"
#include "configbis.wml"
import sys
import string
import cgi
from config import *
from webpage import page
-from dbquery import run_sql
+from dbquery import run_sql
from webuser import getUid,isGuestUser, get_user_preferences, set_user_preferences
from access_control_admin import acc_findUserRoleActions
from access_control_config import CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS, CFG_EXTERNAL_AUTHENTICATION
imagesurl = "%s/img" % weburl
# perform_info(): display the main features of CDS personalize
def perform_info(req):
out = ""
uid = getUid(req)
out += """
The CDS Search offers you a possibility to personalize the interface, to set up your own personal library
of documents, or to set up an automatic alert query that would run periodically and would notify you of search
results by email.
-
-
- -
- Your Settings
-
- Set or change your account Email address or password.
- Specify your preferences about the way the interface looks like.
+
"""
+
+ if not isGuestUser(uid):
+ out += """
+ -
+ Your Settings
+
- Set or change your account Email address or password.
+ Specify your preferences about the way the interface looks like."""
+ out += """
- Your Searches
- View all the searches you performed during the last 30 days.
-
+
- Your Baskets
- With baskets you can define specific collections of items,
store interesting records you want to access later or share with others."""
if isGuestUser(uid):
out+= warning_guest_user(type="baskets")
out += """
- Your Alerts
- Subscribe to a search which will be run periodically by our service. The result can be sent to you
via Email or stored in one of your baskets."""
if isGuestUser(uid):
out+= warning_guest_user(type="alerts")
if cfg_cern_site:
out += """
- Your Loans
- Check out book you have on load, submit borrowing requests, etc. Requires CERN ID."""
out += """
"""
return out
def perform_youradminactivities(uid):
"""Return text for the `Your Admin Activities' box. Analyze
whether user UID has some admin roles, and if yes, then print
suitable links for the actions he can do. If he's not admin,
print a simple non-authorized message."""
if isGuestUser(uid):
return """You seem to be the guest user. You have to login first."""
out = ""
your_role_actions = acc_findUserRoleActions(uid)
your_roles = []
your_admin_activities = []
for (role, action) in your_role_actions:
if role not in your_roles:
your_roles.append(role)
if not your_roles:
out += "You are not authorized to access administrative functions."
else:
out += "
You seem to be %s. " % string.join(your_roles, ", ")
out += "Here are some interesting web admin links for you:"
# add actions found by the RBAC:
for (role, action) in your_role_actions:
if action not in your_admin_activities:
your_admin_activities.append(action)
# add all actions if user is superadmin, to make sure he'll see all
# (since it is not necessary for the superadmin to be connected to actions in RBAC tables):
if "superadmin" in your_roles:
for action in ["cfgbibformat", "cfgbibrank", "cfgbibindex", "cfgwebaccess", "cfgwebsearch", "cfgwebsubmit"]:
if action not in your_admin_activities:
your_admin_activities.append(action)
# print proposed links:
for action in your_admin_activities:
if action == "cfgbibformat":
out += """
Configure BibFormat""" % weburl
if action == "cfgbibrank":
out += """
Configure BibRank""" % weburl
if action == "cfgbibindex":
out += """
Configure BibIndex""" % weburl
if action == "cfgwebaccess":
out += """
Configure WebAccess""" % weburl
if action == "cfgwebsearch":
out += """
Configure WebSearch""" % weburl
if action == "cfgwebsubmit":
out += """
Configure WebSubmit""" % weburl
out += """
For more admin-level activities, see the complete Admin Area.""" % weburl
return out
# perform_display_account(): display a dynamic page that shows the user's account
def perform_display_account(req,data,bask,aler,sear):
uid = getUid(req)
#your account
if isGuestUser(uid):
user ="guest"
accBody = """You are logged in as guest. You may want to login as a regular user
"""
bask=aler="""The guest users need to register first"""
sear="No queries found"
else:
user = data[0]
accBody ="""You are logged in as %s. You may want to a) logout; b) edit your account settings.
"""%user
out =""
out +=template_account("Your Account",accBody)
#your baskets
out +=template_account("Your Baskets",bask)
out +=template_account("Your Alert Searches",aler)
out +=template_account("Your Searches",sear)
out +=template_account("Your Submissions",
"""You can consult the list of your submissions
and inquire about their status.""" % weburl)
out +=template_account("Your Approvals",
"""You can consult the list of your approvals
with the documents you approved or refereed.""" % weburl)
out +=template_account("Your Administrative Activities", perform_youradminactivities(uid))
return out
# template_account() : it is a template for print each of the options from the user's account
def template_account(title,body):
out =""
out +="""
""" % (title, body)
return out
# warning_guest_user(): It returns an alert message,showing that the user is a guest user and should log into the system
def warning_guest_user(type):
msg="""You are logged in as a guest user, so your %s will disappear at the end of the current session. If you wish you can
login or register here.
"""%type
return """""" % msg
## perform_delete():delete the account of the user, not implement yet
def perform_delete():
out = """Deleting your account"""
return out
## perform_set(email,password): edit your account parameters, email and password.
def perform_set(email,password):
try:
uid = run_sql("SELECT id FROM user where email=%s", (email,))
uid = uid[0][0]
except:
uid = 0
CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS_LOCAL = CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS
prefs = get_user_preferences(uid)
if CFG_EXTERNAL_AUTHENTICATION.has_key(prefs['login_method']) and CFG_EXTERNAL_AUTHENTICATION[prefs['login_method']][1] != True:
CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS_LOCAL = 3
text = """
Edit parameters
""" % (CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS_LOCAL >= 2 and "disabled" or "", email, CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS_LOCAL >= 3 and "disabled" or "",password, CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS_LOCAL >= 3 and "disabled" or "", "")
if len(CFG_EXTERNAL_AUTHENTICATION) >= 1:
try:
uid = run_sql("SELECT id FROM user where email=%s", (email,))
uid = uid[0][0]
except:
uid = 0
prefs = get_user_preferences(uid)
current_login_method = prefs['login_method']
text += """"""
return text
## create_register_page_box(): register a new account
def create_register_page_box(referer=''):
text = ""
if CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS <= 1:
text += """Please enter the values of your preference and choose the register button."""
if CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS == 1:
text += "The account will not be possible to use before it has been verified and activated."
elif CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS >= 2:
text += """It is not possible to create an account yourself. Contact if you want an account."""
text += """
"
return text
# perform_logout: display the message of not longer authorized,
def perform_logout(req):
out =""
out+="""
You are no longer recognized. If you wish you can login here.
"""
return out
#def perform_lost: ask the user for his email, in order to send him the lost password
def perform_lost():
out =""
out +="""
"""
return out
# perform_emailSent(email): confirm that the password has been emailed to 'email' address
def perform_emailSent(email):
out =""
out +="Okay, password has been emailed to %s"%email
return out
# peform_emailMessage : display a error message when the email introduced is not correct, and sugest to try again
def perform_emailMessage(eMsg):
out =""
out +="""
%s Try again
"""%eMsg
return out
# perform_back(): template for return to a previous page, used for login,register and setting
def perform_back(mess,act,linkname=''):
if not linkname:
linkname = act
out =""
out+="""
"""%(mess,act,linkname)
return out
diff --git a/modules/websession/lib/webaccount.py.wml b/modules/websession/lib/webaccount.py.wml
index afaa00570..0774f16ef 100644
--- a/modules/websession/lib/webaccount.py.wml
+++ b/modules/websession/lib/webaccount.py.wml
@@ -1,423 +1,434 @@
## $Id$
## CDSware User account information implementation. Useful for youraccount pages.
## 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.
## $Id$
## DO NOT EDIT THIS FILE! IT WAS AUTOMATICALLY GENERATED FROM CDSware WML SOURCES.
## read config variables:
#include "config.wml"
#include "configbis.wml"
import sys
import string
import cgi
from config import *
from webpage import page
-from dbquery import run_sql
+from dbquery import run_sql
from webuser import getUid,isGuestUser, get_user_preferences, set_user_preferences
from access_control_admin import acc_findUserRoleActions
from access_control_config import CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS, CFG_EXTERNAL_AUTHENTICATION
imagesurl = "%s/img" % weburl
# perform_info(): display the main features of CDS personalize
def perform_info(req):
out = ""
uid = getUid(req)
out += """The CDS Search offers you a possibility to personalize the interface, to set up your own personal library
of documents, or to set up an automatic alert query that would run periodically and would notify you of search
results by email.
-
-
- -
- Your Settings
-
- Set or change your account Email address or password.
- Specify your preferences about the way the interface looks like.
+
"""
+
+ if not isGuestUser(uid):
+ out += """
+ -
+ Your Settings
+
- Set or change your account Email address or password.
+ Specify your preferences about the way the interface looks like."""
+ out += """
- Your Searches
- View all the searches you performed during the last 30 days.
-
+
- Your Baskets
- With baskets you can define specific collections of items,
store interesting records you want to access later or share with others."""
if isGuestUser(uid):
out+= warning_guest_user(type="baskets")
out += """
- Your Alerts
- Subscribe to a search which will be run periodically by our service. The result can be sent to you
via Email or stored in one of your baskets."""
if isGuestUser(uid):
out+= warning_guest_user(type="alerts")
if cfg_cern_site:
out += """
- Your Loans
- Check out book you have on load, submit borrowing requests, etc. Requires CERN ID."""
out += """
"""
return out
def perform_youradminactivities(uid):
"""Return text for the `Your Admin Activities' box. Analyze
whether user UID has some admin roles, and if yes, then print
suitable links for the actions he can do. If he's not admin,
print a simple non-authorized message."""
if isGuestUser(uid):
return """You seem to be the guest user. You have to login first."""
out = ""
your_role_actions = acc_findUserRoleActions(uid)
your_roles = []
your_admin_activities = []
for (role, action) in your_role_actions:
if role not in your_roles:
your_roles.append(role)
if not your_roles:
out += "You are not authorized to access administrative functions."
else:
out += "
You seem to be %s. " % string.join(your_roles, ", ")
out += "Here are some interesting web admin links for you:"
# add actions found by the RBAC:
for (role, action) in your_role_actions:
if action not in your_admin_activities:
your_admin_activities.append(action)
# add all actions if user is superadmin, to make sure he'll see all
# (since it is not necessary for the superadmin to be connected to actions in RBAC tables):
if "superadmin" in your_roles:
for action in ["cfgbibformat", "cfgbibrank", "cfgbibindex", "cfgwebaccess", "cfgwebsearch", "cfgwebsubmit"]:
if action not in your_admin_activities:
your_admin_activities.append(action)
# print proposed links:
for action in your_admin_activities:
if action == "cfgbibformat":
out += """
Configure BibFormat""" % weburl
if action == "cfgbibrank":
out += """
Configure BibRank""" % weburl
if action == "cfgbibindex":
out += """
Configure BibIndex""" % weburl
if action == "cfgwebaccess":
out += """
Configure WebAccess""" % weburl
if action == "cfgwebsearch":
out += """
Configure WebSearch""" % weburl
if action == "cfgwebsubmit":
out += """
Configure WebSubmit""" % weburl
out += """
For more admin-level activities, see the complete Admin Area.""" % weburl
return out
# perform_display_account(): display a dynamic page that shows the user's account
def perform_display_account(req,data,bask,aler,sear):
uid = getUid(req)
#your account
if isGuestUser(uid):
user ="guest"
accBody = """You are logged in as guest. You may want to login as a regular user
"""
bask=aler="""The guest users need to register first"""
sear="No queries found"
else:
user = data[0]
accBody ="""You are logged in as %s. You may want to a) logout; b) edit your account settings.
"""%user
out =""
out +=template_account("Your Account",accBody)
#your baskets
out +=template_account("Your Baskets",bask)
out +=template_account("Your Alert Searches",aler)
out +=template_account("Your Searches",sear)
out +=template_account("Your Submissions",
"""You can consult the list of your submissions
and inquire about their status.""" % weburl)
out +=template_account("Your Approvals",
"""You can consult the list of your approvals
with the documents you approved or refereed.""" % weburl)
out +=template_account("Your Administrative Activities", perform_youradminactivities(uid))
return out
# template_account() : it is a template for print each of the options from the user's account
def template_account(title,body):
out =""
out +="""
""" % (title, body)
return out
# warning_guest_user(): It returns an alert message,showing that the user is a guest user and should log into the system
def warning_guest_user(type):
msg="""You are logged in as a guest user, so your %s will disappear at the end of the current session. If you wish you can
login or register here.
"""%type
return """""" % msg
## perform_delete():delete the account of the user, not implement yet
def perform_delete():
out = """Deleting your account"""
return out
## perform_set(email,password): edit your account parameters, email and password.
def perform_set(email,password):
try:
uid = run_sql("SELECT id FROM user where email=%s", (email,))
uid = uid[0][0]
except:
uid = 0
CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS_LOCAL = CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS
prefs = get_user_preferences(uid)
if CFG_EXTERNAL_AUTHENTICATION.has_key(prefs['login_method']) and CFG_EXTERNAL_AUTHENTICATION[prefs['login_method']][1] != True:
CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS_LOCAL = 3
text = """
Edit parameters
""" % (CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS_LOCAL >= 2 and "disabled" or "", email, CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS_LOCAL >= 3 and "disabled" or "",password, CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS_LOCAL >= 3 and "disabled" or "", "")
if len(CFG_EXTERNAL_AUTHENTICATION) >= 1:
try:
uid = run_sql("SELECT id FROM user where email=%s", (email,))
uid = uid[0][0]
except:
uid = 0
prefs = get_user_preferences(uid)
current_login_method = prefs['login_method']
text += """"""
return text
## create_register_page_box(): register a new account
def create_register_page_box(referer=''):
text = ""
if CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS <= 1:
text += """Please enter the values of your preference and choose the register button."""
if CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS == 1:
text += "The account will not be possible to use before it has been verified and activated."
elif CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS >= 2:
text += """It is not possible to create an account yourself. Contact if you want an account."""
text += """
"
return text
# perform_logout: display the message of not longer authorized,
def perform_logout(req):
out =""
out+="""
You are no longer recognized. If you wish you can login here.
"""
return out
#def perform_lost: ask the user for his email, in order to send him the lost password
def perform_lost():
out =""
out +="""
"""
return out
# perform_emailSent(email): confirm that the password has been emailed to 'email' address
def perform_emailSent(email):
out =""
out +="Okay, password has been emailed to %s"%email
return out
# peform_emailMessage : display a error message when the email introduced is not correct, and sugest to try again
def perform_emailMessage(eMsg):
out =""
out +="""
%s Try again
"""%eMsg
return out
# perform_back(): template for return to a previous page, used for login,register and setting
def perform_back(mess,act,linkname=''):
if not linkname:
linkname = act
out =""
out+="""
"""%(mess,act,linkname)
return out
diff --git a/modules/websession/lib/webuser.py b/modules/websession/lib/webuser.py
index 9938d84b8..9d2d474f6 100644
--- a/modules/websession/lib/webuser.py
+++ b/modules/websession/lib/webuser.py
@@ -1,561 +1,559 @@
## $Id$
## CDSware User related utilities.
## 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.
"""
This file implements all methods necessary for working with users and sessions in cdsware.
Contains methods for logging/registration when a user log/register into the system, checking if it
is a guest user or not.
At the same time this presents all the stuff it could need with sessions managements, working with websession.
It also contains Apache-related user authentication stuff.
"""
from marshal import loads,dumps
from zlib import compress,decompress
from dbquery import run_sql
import sys
import time
import os
import crypt
import string
import session
import websession
import smtplib
import MySQLdb
from websession import pSession, pSessionMapping
from session import SessionError
from config import *
from messages import *
from access_control_engine import acc_authorize_action
from access_control_admin import acc_findUserRoleActions
from access_control_config import *
def createGuestUser():
"""Create a guest user , insert into user null values in all fields
createGuestUser() -> GuestUserID
"""
if CFG_ACCESS_CONTROL_LEVEL_GUESTS == 0:
return run_sql("insert into user (email, note) values ('', '1')")
elif CFG_ACCESS_CONTROL_LEVEL_GUESTS >= 1:
return run_sql("insert into user (email, note) values ('', '0')")
def page_not_authorized(req, referer='', uid='', text='', navtrail=''):
"""Show error message when account is not activated"""
from webpage import page
if not CFG_ACCESS_CONTROL_LEVEL_SITE:
title = cfg_webaccess_msgs[5]
if not uid: uid = getUid(req)
res = run_sql("SELECT email FROM user WHERE id=%s" % uid)
if res and res[0][0]:
if text: body = text
else: body = "%s %s" % (cfg_webaccess_warning_msgs[9] % res[0][0], ("%s %s" % (cfg_webaccess_msgs[0] % referer, cfg_webaccess_msgs[1])))
else:
if text: body = text
else: body = cfg_webaccess_msgs[3]
elif CFG_ACCESS_CONTROL_LEVEL_SITE == 1:
title = cfg_webaccess_msgs[8]
body = "%s %s" % (cfg_webaccess_msgs[7], cfg_webaccess_msgs[2])
elif CFG_ACCESS_CONTROL_LEVEL_SITE == 2:
title = cfg_webaccess_msgs[6]
body = "%s %s" % (cfg_webaccess_msgs[4], cfg_webaccess_msgs[2])
return page(title=title,
uid=getUid(req),
body=body,
navtrail=navtrail)
def getUid (req):
"""It gives the userId taking it from the cookie of the request,also has the control mechanism for the guest users,
inserting in the MySql table when need it, and raise the cookie to the client.
getUid(req) -> userId
"""
if CFG_ACCESS_CONTROL_LEVEL_SITE == 1: return 0
if CFG_ACCESS_CONTROL_LEVEL_SITE == 2: return -1
guest = 0
sm = session.MPSessionManager(pSession, pSessionMapping())
try:
s = sm.get_session(req)
except SessionError,e:
sm.revoke_session_cookie (req)
s = sm.get_session(req)
userId = s.getUid()
if userId == -1: # first time, so create a guest user
s.setUid(createGuestUser())
userId = s.getUid()
guest = 1
sm.maintain_session(req,s)
if guest == 0:
guest = isGuestUser(userId)
if guest:
if CFG_ACCESS_CONTROL_LEVEL_GUESTS == 0:
return userId
elif CFG_ACCESS_CONTROL_LEVEL_GUESTS >= 1:
return -1
else:
res = run_sql("SELECT note FROM user WHERE id=%s" % userId)
if CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS == 0:
return userId
elif CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS >= 1 and res and res[0][0] in [1, "1"]:
return userId
else:
return -1
def setUid(req,uid):
"""It sets the userId into the session, and raise the cookie to the client.
"""
sm = session.MPSessionManager(pSession, pSessionMapping())
try:
s = sm.get_session(req)
except SessionError,e:
sm.revoke_session_cookie (req)
s = sm.get_session(req)
s.setUid(uid)
sm.maintain_session(req,s)
return uid
def isGuestUser(uid):
"""It Checks if the userId corresponds to a guestUser or not
isGuestUser(uid) -> boolean
"""
out = 1
try:
res = run_sql("select email from user where id=%s", (uid,))
if res:
if res[0][0]:
out = 0
except:
pass
return out
def isUserSubmitter(uid):
u_email = get_email(uid)
res = run_sql("select * from sbmSUBMISSIONS where email=%s",(u_email,))
if len(res) > 0:
return 1
else:
return 0
def isUserReferee(uid):
res = run_sql("select sdocname from sbmDOCTYPE")
for row in res:
doctype = row[0]
categ = "*"
(auth_code, auth_message) = acc_authorize_action(uid, "referee",doctype=doctype, categ=categ)
if auth_code == 0:
return 1
res2 = run_sql("select sname from sbmCATEGORIES where doctype=%s",(doctype,))
for row2 in res2:
categ = row2[0]
(auth_code, auth_message) = acc_authorize_action(uid, "referee",doctype=doctype, categ=categ)
if auth_code == 0:
return 1
return 0
def isUserAdmin(uid):
"Return 1 if the user UID has some admin rights; 0 otherwise."
out = 0
if acc_findUserRoleActions(uid):
out = 1
return out
def checkRegister(user,passw):
"""It checks if the user is register with the correct password
checkRegister(user,passw) -> boolean
"""
query_result = run_sql("select * from user where email=%s and password=%s", (user,passw))
if len(query_result)> 0 :
return 0
return 1
def userOnSystem(user):
"""It checks if the user is registered already on the system
"""
query_register = run_sql("select * from user where email=%s", (user,))
if len(query_register)>0:
return 1
return 0
def checkemail(email):
"""Check whether the EMAIL address supplied by the user is valid.
At the moment we just check whether it contains '@' and
whether it doesn't contain blanks.
checkemail(email) -> boolean
"""
if (string.find(email, "@") <= 0) or (string.find(email, " ") > 0):
return 0
elif CFG_ACCESS_CONTROL_LIMIT_TO_DOMAIN:
if not email.endswith(CFG_ACCESS_CONTROL_LIMIT_TO_DOMAIN):
return 0
return 1
def getDataUid(req,uid):
"""It takes the email and password from a given userId, from the MySQL database, if don't exist it just returns
guest values for email and password
getDataUid(req,uid) -> [email,password]
"""
email = 'guest'
password = 'none'
query_result = run_sql("select email, password from user where id=%s", (uid,))
if len(query_result)>0:
email = query_result[0][0]
password = query_result[0][1]
if password == None or email =='':
email = 'guest'
list = [email] +[password]
return list
def registerUser(req,user,passw):
"""It registers the user, inserting into the user table of MySQL database, the email and the pasword
of the user. It returns 1 if the insertion is done, 0 if there is any failure with the email
and -1 if the user is already on the data base
registerUser(req,user,passw) -> int
"""
if userOnSystem(user) and user !='':
return -1
if checkRegister(user,passw) and checkemail(user):
if CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS == 0:
activated = 1
elif CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS == 1:
activated = 0
elif CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS >= 2:
return 0
user_preference = get_default_user_preferences()
setUid(req, run_sql("INSERT INTO user (email, password, note, settings) VALUES (%s,%s,%s,%s)",
(user,passw,activated,serialize_via_marshal(user_preference),)))
if CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_NEW_ACCOUNT:
sendNewUserAccountWarning(user, user, passw)
if CFG_ACCESS_CONTROL_NOTIFY_ADMIN_ABOUT_NEW_ACCOUNTS and CFG_ACCESS_CONTROL_SEND_TO_EMAIL:
sendNewAdminAccountWarning(user, CFG_ACCESS_CONTROL_SEND_TO_EMAIL)
return 1
return 0
def updateDataUser(req,uid,email,password):
"""It updates the data from the user. It is used when a user set his email and password
"""
if email =='guest':
return 0
if CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS >= 2:
query_result = run_sql("update user set password=%s where id=%s", (password,uid))
else:
query_result = run_sql("update user set email=%s,password=%s where id=%s", (email,password,uid))
return 1
def loginUser(req, p_email,p_pw, login_method):
"""It is a first simple version for the authentication of user. It returns the id of the user,
for checking afterwards if the login is correct
"""
user_prefs = get_user_preferences(emailUnique(p_email))
if user_prefs and login_method != user_prefs["login_method"]:
if CFG_EXTERNAL_AUTHENTICATION.has_key(user_prefs["login_method"]):
return ([], p_email, p_pw, 11)
if not CFG_EXTERNAL_AUTHENTICATION.has_key(login_method):
return ([], p_email, p_pw, 12)
if CFG_EXTERNAL_AUTHENTICATION[login_method][0]:
p_email = CFG_EXTERNAL_AUTHENTICATION[login_method][0].auth_user(p_email, p_pw)
if p_email:
p_pw = givePassword(p_email)
if not p_pw or p_pw < 0:
import random
p_pw = int(random.random() * 1000000)
if not registerUser(req,p_email,p_pw):
return ([], p_email, p_pw, 13)
else:
query_result = run_sql("SELECT id from user where email=%s and password=%s", (p_email,p_pw,))
user_prefs = get_user_preferences(query_result[0][0])
user_prefs["login_method"] = login_method
set_user_preferences(query_result[0][0], user_prefs)
else:
return ([], p_email, p_pw, 10)
query_result = run_sql("SELECT id from user where email=%s and password=%s", (p_email,p_pw,))
if query_result:
prefered_login_method = get_user_preferences(query_result[0][0])['login_method']
else:
return ([], p_email, p_pw, 14)
if login_method != prefered_login_method:
if CFG_EXTERNAL_AUTHENTICATION.has_key(prefered_login_method):
return ([], p_email, p_pw, 11)
return (query_result, p_email, p_pw, 0)
def logoutUser(req):
"""It logout the user of the system, creating a guest user.
"""
uid = getUid(req)
sm = session.MPSessionManager(pSession, pSessionMapping())
try:
s = sm.get_session(req)
except SessionError,e:
sm.revoke_session_cookie (req)
s = sm.get_session(req)
id1 = createGuestUser()
s.setUid(id1)
sm.maintain_session(req,s)
return id1
def userNotExist(p_email,p_pw):
"""Check if the user exists or not in the system
"""
query_result = run_sql("select email from user where email=%s", (p_email,))
if len(query_result)>0 and query_result[0]!='':
return 0
return 1
def emailUnique(p_email):
"""Check if the email address only exists once. If yes, return userid, if not, -1
"""
query_result = run_sql("select id, email from user where email=%s", (p_email,))
if len(query_result) == 1:
return query_result[0][0]
elif len(query_result) == 0:
return 0
return -1
def update_Uid(req,p_email,p_pw):
"""It updates the userId of the session. It is used when a guest user is logged in succesfully in the system
with a given email and password
"""
query_ID = int(run_sql("select id from user where email=%s and password=%s",
(p_email,p_pw))[0][0])
setUid(req,query_ID)
return query_ID
def givePassword(email):
""" It checks in the database the password for a given email. It is used to send the password to the email of the user.It returns
the password if the user exists, otherwise it returns -999
"""
query_pass = run_sql("select password from user where email =%s",(email,))
if len(query_pass)>0:
return query_pass[0][0]
return -999
def sendNewAdminAccountWarning(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: New account on '%s'" % cdsname
if CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS == 1:
sub += " - PLEASE ACTIVATE"
sub += "\n\n"
body = "A new account has been created on '%s'" % cdsname
if CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS == 1:
body += " and is awaiting activation"
body += ":\n\n"
body += " Username/Email: %s\n\n" % newAccountEmail
body += "You can approve or reject this account request at: %s/admin/webaccess/webaccessadmin.py/manageaccounts\n" % weburl
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: Your account created on '%s'\n\n" % cdsname
body = "You have created a new account on '%s':\n\n" % cdsname
body += " Username/Email: %s\n" % newAccountEmail
body += " Password: %s\n\n" % ("*" * len(password))
if CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS >= 1:
body += "This account is awaiting approval by the site administrators and therefore cannot be used as of yet.\nYou will receive an email notification as soon as your account request has been processed.\n"
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 get_email(uid):
"""Return email address of the user uid. Return string 'guest' in case
the user is not found."""
out = "guest"
res = run_sql("SELECT email FROM user WHERE id=%s", (uid,), 1)
if res and res[0][0]:
out = res[0][0]
return out
def create_userinfobox_body(uid, language="en"):
"""Create user info box body for user UID in language LANGUAGE."""
out = ""
if isGuestUser(uid):
out += """%s ::
%s ::
%s ::
%s ::
%s""" % \
(msg_guest[language], weburl, language, msg_session[language], weburl, language, msg_alerts[language],
weburl, language, msg_baskets[language], weburl, language, msg_login[language])
else:
out += """%s ::
%s ::
%s ::
%s :: """ % \
(get_email(uid), weburl, language, msg_account[language], weburl, language, msg_alerts[language],
weburl, language, msg_baskets[language])
if isUserSubmitter(uid):
out += """%s :: """ % \
(weburl, language, msg_submissions[language])
if isUserReferee(uid):
out += """%s :: """ % \
(weburl, language, msg_approvals[language])
if isUserAdmin(uid):
out += """%s :: """ % \
(weburl, language, msg_administration[language])
out += """%s""" % \
(weburl, language, msg_logout[language])
return """ %s""" % (weburl, out)
def list_registered_users():
"""List all registered users."""
return run_sql("SELECT id,email FROM user where email!=''")
## --- follow some functions for Apache user/group authentication
def auth_apache_user_p(user, password):
"""Check whether user-supplied credentials correspond to valid
Apache password data file. Return 0 in case of failure, 1 in case
of success."""
try:
pipe_input, pipe_output = os.popen2(["/bin/grep", "^" + user + ":", cfg_apache_password_file], 'r')
line = pipe_output.readlines()[0]
password_apache = string.split(string.strip(line),":")[1]
except: # no pw found, so return not-allowed status
return 0
salt = password_apache[:2]
if crypt.crypt(password, salt) == password_apache:
return 1
else:
return 0
def auth_apache_user_in_groups(user):
"""Return list of Apache groups to which Apache user belong."""
out = []
try:
pipe_input,pipe_output = os.popen2(["/bin/grep", user, cfg_apache_group_file], 'r')
for line in pipe_output.readlines():
out.append(string.split(string.strip(line),":")[0])
except: # no groups found, so return empty list
pass
return out
def auth_apache_user_collection_p(user, password, coll):
"""Check whether user-supplied credentials correspond to valid
Apache password data file, and whether this user is authorized to
see the given collections. Return 0 in case of failure, 1 in case
of success."""
from search_engine import coll_restricted_p, coll_restricted_group
if not auth_apache_user_p(user, password):
return 0
if not coll_restricted_p(coll):
return 1
if coll_restricted_group(coll) in auth_apache_user_in_groups(user):
return 1
else:
return 0
def get_user_preferences(uid):
pref = run_sql("SELECT id, settings FROM user WHERE id=%s", (uid,))
if pref:
try:
return deserialize_via_marshal(pref[0][1])
except:
return get_default_user_preferences()
- else:
- return get_default_user_preferences()
return None
def set_user_preferences(uid, pref):
res = run_sql("UPDATE user SET settings='%s' WHERE id=%s" % (serialize_via_marshal(pref),uid))
def get_default_user_preferences():
user_preference = {
'login_method': ''}
for system in CFG_EXTERNAL_AUTHENTICATION.keys():
if CFG_EXTERNAL_AUTHENTICATION[system][1]:
user_preference['login_method'] = system
break
return user_preference
def serialize_via_marshal(obj):
"""Serialize Python object via marshal into a compressed string."""
return MySQLdb.escape_string(compress(dumps(obj)))
def deserialize_via_marshal(string):
"""Decompress and deserialize string into a Python object via marshal."""
return loads(decompress(string))
diff --git a/modules/websession/lib/webuser.py.wml b/modules/websession/lib/webuser.py.wml
index 9938d84b8..9d2d474f6 100644
--- a/modules/websession/lib/webuser.py.wml
+++ b/modules/websession/lib/webuser.py.wml
@@ -1,561 +1,559 @@
## $Id$
## CDSware User related utilities.
## 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.
"""
This file implements all methods necessary for working with users and sessions in cdsware.
Contains methods for logging/registration when a user log/register into the system, checking if it
is a guest user or not.
At the same time this presents all the stuff it could need with sessions managements, working with websession.
It also contains Apache-related user authentication stuff.
"""
from marshal import loads,dumps
from zlib import compress,decompress
from dbquery import run_sql
import sys
import time
import os
import crypt
import string
import session
import websession
import smtplib
import MySQLdb
from websession import pSession, pSessionMapping
from session import SessionError
from config import *
from messages import *
from access_control_engine import acc_authorize_action
from access_control_admin import acc_findUserRoleActions
from access_control_config import *
def createGuestUser():
"""Create a guest user , insert into user null values in all fields
createGuestUser() -> GuestUserID
"""
if CFG_ACCESS_CONTROL_LEVEL_GUESTS == 0:
return run_sql("insert into user (email, note) values ('', '1')")
elif CFG_ACCESS_CONTROL_LEVEL_GUESTS >= 1:
return run_sql("insert into user (email, note) values ('', '0')")
def page_not_authorized(req, referer='', uid='', text='', navtrail=''):
"""Show error message when account is not activated"""
from webpage import page
if not CFG_ACCESS_CONTROL_LEVEL_SITE:
title = cfg_webaccess_msgs[5]
if not uid: uid = getUid(req)
res = run_sql("SELECT email FROM user WHERE id=%s" % uid)
if res and res[0][0]:
if text: body = text
else: body = "%s %s" % (cfg_webaccess_warning_msgs[9] % res[0][0], ("%s %s" % (cfg_webaccess_msgs[0] % referer, cfg_webaccess_msgs[1])))
else:
if text: body = text
else: body = cfg_webaccess_msgs[3]
elif CFG_ACCESS_CONTROL_LEVEL_SITE == 1:
title = cfg_webaccess_msgs[8]
body = "%s %s" % (cfg_webaccess_msgs[7], cfg_webaccess_msgs[2])
elif CFG_ACCESS_CONTROL_LEVEL_SITE == 2:
title = cfg_webaccess_msgs[6]
body = "%s %s" % (cfg_webaccess_msgs[4], cfg_webaccess_msgs[2])
return page(title=title,
uid=getUid(req),
body=body,
navtrail=navtrail)
def getUid (req):
"""It gives the userId taking it from the cookie of the request,also has the control mechanism for the guest users,
inserting in the MySql table when need it, and raise the cookie to the client.
getUid(req) -> userId
"""
if CFG_ACCESS_CONTROL_LEVEL_SITE == 1: return 0
if CFG_ACCESS_CONTROL_LEVEL_SITE == 2: return -1
guest = 0
sm = session.MPSessionManager(pSession, pSessionMapping())
try:
s = sm.get_session(req)
except SessionError,e:
sm.revoke_session_cookie (req)
s = sm.get_session(req)
userId = s.getUid()
if userId == -1: # first time, so create a guest user
s.setUid(createGuestUser())
userId = s.getUid()
guest = 1
sm.maintain_session(req,s)
if guest == 0:
guest = isGuestUser(userId)
if guest:
if CFG_ACCESS_CONTROL_LEVEL_GUESTS == 0:
return userId
elif CFG_ACCESS_CONTROL_LEVEL_GUESTS >= 1:
return -1
else:
res = run_sql("SELECT note FROM user WHERE id=%s" % userId)
if CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS == 0:
return userId
elif CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS >= 1 and res and res[0][0] in [1, "1"]:
return userId
else:
return -1
def setUid(req,uid):
"""It sets the userId into the session, and raise the cookie to the client.
"""
sm = session.MPSessionManager(pSession, pSessionMapping())
try:
s = sm.get_session(req)
except SessionError,e:
sm.revoke_session_cookie (req)
s = sm.get_session(req)
s.setUid(uid)
sm.maintain_session(req,s)
return uid
def isGuestUser(uid):
"""It Checks if the userId corresponds to a guestUser or not
isGuestUser(uid) -> boolean
"""
out = 1
try:
res = run_sql("select email from user where id=%s", (uid,))
if res:
if res[0][0]:
out = 0
except:
pass
return out
def isUserSubmitter(uid):
u_email = get_email(uid)
res = run_sql("select * from sbmSUBMISSIONS where email=%s",(u_email,))
if len(res) > 0:
return 1
else:
return 0
def isUserReferee(uid):
res = run_sql("select sdocname from sbmDOCTYPE")
for row in res:
doctype = row[0]
categ = "*"
(auth_code, auth_message) = acc_authorize_action(uid, "referee",doctype=doctype, categ=categ)
if auth_code == 0:
return 1
res2 = run_sql("select sname from sbmCATEGORIES where doctype=%s",(doctype,))
for row2 in res2:
categ = row2[0]
(auth_code, auth_message) = acc_authorize_action(uid, "referee",doctype=doctype, categ=categ)
if auth_code == 0:
return 1
return 0
def isUserAdmin(uid):
"Return 1 if the user UID has some admin rights; 0 otherwise."
out = 0
if acc_findUserRoleActions(uid):
out = 1
return out
def checkRegister(user,passw):
"""It checks if the user is register with the correct password
checkRegister(user,passw) -> boolean
"""
query_result = run_sql("select * from user where email=%s and password=%s", (user,passw))
if len(query_result)> 0 :
return 0
return 1
def userOnSystem(user):
"""It checks if the user is registered already on the system
"""
query_register = run_sql("select * from user where email=%s", (user,))
if len(query_register)>0:
return 1
return 0
def checkemail(email):
"""Check whether the EMAIL address supplied by the user is valid.
At the moment we just check whether it contains '@' and
whether it doesn't contain blanks.
checkemail(email) -> boolean
"""
if (string.find(email, "@") <= 0) or (string.find(email, " ") > 0):
return 0
elif CFG_ACCESS_CONTROL_LIMIT_TO_DOMAIN:
if not email.endswith(CFG_ACCESS_CONTROL_LIMIT_TO_DOMAIN):
return 0
return 1
def getDataUid(req,uid):
"""It takes the email and password from a given userId, from the MySQL database, if don't exist it just returns
guest values for email and password
getDataUid(req,uid) -> [email,password]
"""
email = 'guest'
password = 'none'
query_result = run_sql("select email, password from user where id=%s", (uid,))
if len(query_result)>0:
email = query_result[0][0]
password = query_result[0][1]
if password == None or email =='':
email = 'guest'
list = [email] +[password]
return list
def registerUser(req,user,passw):
"""It registers the user, inserting into the user table of MySQL database, the email and the pasword
of the user. It returns 1 if the insertion is done, 0 if there is any failure with the email
and -1 if the user is already on the data base
registerUser(req,user,passw) -> int
"""
if userOnSystem(user) and user !='':
return -1
if checkRegister(user,passw) and checkemail(user):
if CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS == 0:
activated = 1
elif CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS == 1:
activated = 0
elif CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS >= 2:
return 0
user_preference = get_default_user_preferences()
setUid(req, run_sql("INSERT INTO user (email, password, note, settings) VALUES (%s,%s,%s,%s)",
(user,passw,activated,serialize_via_marshal(user_preference),)))
if CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_NEW_ACCOUNT:
sendNewUserAccountWarning(user, user, passw)
if CFG_ACCESS_CONTROL_NOTIFY_ADMIN_ABOUT_NEW_ACCOUNTS and CFG_ACCESS_CONTROL_SEND_TO_EMAIL:
sendNewAdminAccountWarning(user, CFG_ACCESS_CONTROL_SEND_TO_EMAIL)
return 1
return 0
def updateDataUser(req,uid,email,password):
"""It updates the data from the user. It is used when a user set his email and password
"""
if email =='guest':
return 0
if CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS >= 2:
query_result = run_sql("update user set password=%s where id=%s", (password,uid))
else:
query_result = run_sql("update user set email=%s,password=%s where id=%s", (email,password,uid))
return 1
def loginUser(req, p_email,p_pw, login_method):
"""It is a first simple version for the authentication of user. It returns the id of the user,
for checking afterwards if the login is correct
"""
user_prefs = get_user_preferences(emailUnique(p_email))
if user_prefs and login_method != user_prefs["login_method"]:
if CFG_EXTERNAL_AUTHENTICATION.has_key(user_prefs["login_method"]):
return ([], p_email, p_pw, 11)
if not CFG_EXTERNAL_AUTHENTICATION.has_key(login_method):
return ([], p_email, p_pw, 12)
if CFG_EXTERNAL_AUTHENTICATION[login_method][0]:
p_email = CFG_EXTERNAL_AUTHENTICATION[login_method][0].auth_user(p_email, p_pw)
if p_email:
p_pw = givePassword(p_email)
if not p_pw or p_pw < 0:
import random
p_pw = int(random.random() * 1000000)
if not registerUser(req,p_email,p_pw):
return ([], p_email, p_pw, 13)
else:
query_result = run_sql("SELECT id from user where email=%s and password=%s", (p_email,p_pw,))
user_prefs = get_user_preferences(query_result[0][0])
user_prefs["login_method"] = login_method
set_user_preferences(query_result[0][0], user_prefs)
else:
return ([], p_email, p_pw, 10)
query_result = run_sql("SELECT id from user where email=%s and password=%s", (p_email,p_pw,))
if query_result:
prefered_login_method = get_user_preferences(query_result[0][0])['login_method']
else:
return ([], p_email, p_pw, 14)
if login_method != prefered_login_method:
if CFG_EXTERNAL_AUTHENTICATION.has_key(prefered_login_method):
return ([], p_email, p_pw, 11)
return (query_result, p_email, p_pw, 0)
def logoutUser(req):
"""It logout the user of the system, creating a guest user.
"""
uid = getUid(req)
sm = session.MPSessionManager(pSession, pSessionMapping())
try:
s = sm.get_session(req)
except SessionError,e:
sm.revoke_session_cookie (req)
s = sm.get_session(req)
id1 = createGuestUser()
s.setUid(id1)
sm.maintain_session(req,s)
return id1
def userNotExist(p_email,p_pw):
"""Check if the user exists or not in the system
"""
query_result = run_sql("select email from user where email=%s", (p_email,))
if len(query_result)>0 and query_result[0]!='':
return 0
return 1
def emailUnique(p_email):
"""Check if the email address only exists once. If yes, return userid, if not, -1
"""
query_result = run_sql("select id, email from user where email=%s", (p_email,))
if len(query_result) == 1:
return query_result[0][0]
elif len(query_result) == 0:
return 0
return -1
def update_Uid(req,p_email,p_pw):
"""It updates the userId of the session. It is used when a guest user is logged in succesfully in the system
with a given email and password
"""
query_ID = int(run_sql("select id from user where email=%s and password=%s",
(p_email,p_pw))[0][0])
setUid(req,query_ID)
return query_ID
def givePassword(email):
""" It checks in the database the password for a given email. It is used to send the password to the email of the user.It returns
the password if the user exists, otherwise it returns -999
"""
query_pass = run_sql("select password from user where email =%s",(email,))
if len(query_pass)>0:
return query_pass[0][0]
return -999
def sendNewAdminAccountWarning(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: New account on '%s'" % cdsname
if CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS == 1:
sub += " - PLEASE ACTIVATE"
sub += "\n\n"
body = "A new account has been created on '%s'" % cdsname
if CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS == 1:
body += " and is awaiting activation"
body += ":\n\n"
body += " Username/Email: %s\n\n" % newAccountEmail
body += "You can approve or reject this account request at: %s/admin/webaccess/webaccessadmin.py/manageaccounts\n" % weburl
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: Your account created on '%s'\n\n" % cdsname
body = "You have created a new account on '%s':\n\n" % cdsname
body += " Username/Email: %s\n" % newAccountEmail
body += " Password: %s\n\n" % ("*" * len(password))
if CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS >= 1:
body += "This account is awaiting approval by the site administrators and therefore cannot be used as of yet.\nYou will receive an email notification as soon as your account request has been processed.\n"
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 get_email(uid):
"""Return email address of the user uid. Return string 'guest' in case
the user is not found."""
out = "guest"
res = run_sql("SELECT email FROM user WHERE id=%s", (uid,), 1)
if res and res[0][0]:
out = res[0][0]
return out
def create_userinfobox_body(uid, language="en"):
"""Create user info box body for user UID in language LANGUAGE."""
out = ""
if isGuestUser(uid):
out += """%s ::
%s ::
%s ::
%s ::
%s""" % \
(msg_guest[language], weburl, language, msg_session[language], weburl, language, msg_alerts[language],
weburl, language, msg_baskets[language], weburl, language, msg_login[language])
else:
out += """%s ::
%s ::
%s ::
%s :: """ % \
(get_email(uid), weburl, language, msg_account[language], weburl, language, msg_alerts[language],
weburl, language, msg_baskets[language])
if isUserSubmitter(uid):
out += """%s :: """ % \
(weburl, language, msg_submissions[language])
if isUserReferee(uid):
out += """%s :: """ % \
(weburl, language, msg_approvals[language])
if isUserAdmin(uid):
out += """%s :: """ % \
(weburl, language, msg_administration[language])
out += """%s""" % \
(weburl, language, msg_logout[language])
return """ %s""" % (weburl, out)
def list_registered_users():
"""List all registered users."""
return run_sql("SELECT id,email FROM user where email!=''")
## --- follow some functions for Apache user/group authentication
def auth_apache_user_p(user, password):
"""Check whether user-supplied credentials correspond to valid
Apache password data file. Return 0 in case of failure, 1 in case
of success."""
try:
pipe_input, pipe_output = os.popen2(["/bin/grep", "^" + user + ":", cfg_apache_password_file], 'r')
line = pipe_output.readlines()[0]
password_apache = string.split(string.strip(line),":")[1]
except: # no pw found, so return not-allowed status
return 0
salt = password_apache[:2]
if crypt.crypt(password, salt) == password_apache:
return 1
else:
return 0
def auth_apache_user_in_groups(user):
"""Return list of Apache groups to which Apache user belong."""
out = []
try:
pipe_input,pipe_output = os.popen2(["/bin/grep", user, cfg_apache_group_file], 'r')
for line in pipe_output.readlines():
out.append(string.split(string.strip(line),":")[0])
except: # no groups found, so return empty list
pass
return out
def auth_apache_user_collection_p(user, password, coll):
"""Check whether user-supplied credentials correspond to valid
Apache password data file, and whether this user is authorized to
see the given collections. Return 0 in case of failure, 1 in case
of success."""
from search_engine import coll_restricted_p, coll_restricted_group
if not auth_apache_user_p(user, password):
return 0
if not coll_restricted_p(coll):
return 1
if coll_restricted_group(coll) in auth_apache_user_in_groups(user):
return 1
else:
return 0
def get_user_preferences(uid):
pref = run_sql("SELECT id, settings FROM user WHERE id=%s", (uid,))
if pref:
try:
return deserialize_via_marshal(pref[0][1])
except:
return get_default_user_preferences()
- else:
- return get_default_user_preferences()
return None
def set_user_preferences(uid, pref):
res = run_sql("UPDATE user SET settings='%s' WHERE id=%s" % (serialize_via_marshal(pref),uid))
def get_default_user_preferences():
user_preference = {
'login_method': ''}
for system in CFG_EXTERNAL_AUTHENTICATION.keys():
if CFG_EXTERNAL_AUTHENTICATION[system][1]:
user_preference['login_method'] = system
break
return user_preference
def serialize_via_marshal(obj):
"""Serialize Python object via marshal into a compressed string."""
return MySQLdb.escape_string(compress(dumps(obj)))
def deserialize_via_marshal(string):
"""Decompress and deserialize string into a Python object via marshal."""
return loads(decompress(string))
diff --git a/modules/websession/web/youraccount.py b/modules/websession/web/youraccount.py
index 8f060a476..cb6dc6ad1 100644
--- a/modules/websession/web/youraccount.py
+++ b/modules/websession/web/youraccount.py
@@ -1,385 +1,384 @@
## $Id$
## CDSware User account information.
## 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 ACCOUNT HANDLING"""
__lastupdated__ = """<: print `date +"%d %b %Y %H:%M:%S %Z"`; :>"""
## fill config variables:
pylibdir = "/python"
import sys
sys.path.append('%s' % pylibdir)
from cdsware import webuser
from cdsware.config import weburl,cdsname,cdslang,supportemail
from cdsware.webpage import page
from cdsware import webaccount
from cdsware import webbasket
from cdsware import webalert
from cdsware import webuser
from cdsware.access_control_config import *
from mod_python import apache
from cdsware.access_control_config import CFG_ACCESS_CONTROL_LEVEL_SITE, cfg_webaccess_warning_msgs, CFG_EXTERNAL_AUTHENTICATION
import smtplib
def edit(req, ln=cdslang):
uid = webuser.getUid(req)
if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
return webuser.page_not_authorized(req, "../youraccount.py/set")
data = webuser.getDataUid(req,uid)
email = data[0]
passw = data[1]
return page(title="Your Settings",
body=webaccount.perform_set(email,passw),
navtrail="""Your Account""" % (weburl, ln),
description="CDS Personalize, Your Settings",
keywords="CDS, personalize",
uid=uid,
language=ln,
lastupdated=__lastupdated__)
def change(req,email=None,password=None,password2=None,login_method="",ln=cdslang):
uid = webuser.getUid(req)
if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
return webuser.page_not_authorized(req, "../youraccount.py/change")
if login_method and CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS < 4:
title = "Settings edited"
act = "display"
linkname = "Show account"
prefs = webuser.get_user_preferences(uid)
prefs['login_method'] = login_method
webuser.set_user_preferences(uid, prefs)
mess = "Login method successfully selected."
elif login_method and CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS >= 4:
return webuser.page_not_authorized(req, "../youraccount.py/change")
elif email:
if (CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS >= 2 or (CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS <= 1 and webuser.checkemail(email))) and uid2 != -1 and (uid2 == uid or uid2 == 0) and password == password2:
if CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS < 3:
change = webuser.updateDataUser(req,uid,email,password)
else:
return webuser.page_not_authorized(req, "../youraccount.py/change")
if change and CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS >= 2:
mess = "Password successfully edited."
elif change:
mess = "Settings successfully edited."
act = "display"
linkname = "Show account"
title = "Settings edited"
elif uid2 == -1 or uid2 != uid and not uid2 == 0:
mess = "The email address is already in use, please try again."
act = "edit"
linkname = "Edit settings"
title = "Editing settings failed"
elif not webuser.checkemail(email):
mess = "The email address is not valid, please try again."
act = "edit"
linkname = "Edit settings"
title = "Editing settings failed"
elif password != password2:
mess = "The passwords do not match, please try again."
act = "edit"
linkname = "Edit settings"
title = "Editing settings failed"
else:
mess = "Could not update settings."
act = "edit"
linkname = "Edit settings"
title = "Editing settings failed"
return page(title=title,
body=webaccount.perform_back(mess,act, linkname),
navtrail="""Your Account""" % (weburl, ln),
description="CDS Personalize, Main page",
keywords="CDS, personalize",
uid=uid,
language=ln,
lastupdated=__lastupdated__)
def lost(req, ln=cdslang):
uid = webuser.getUid(req)
if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
return webuser.page_not_authorized(req, "../youraccount.py/lost")
return page(title="Lost your password?",
body=webaccount.perform_lost(),
navtrail="""Your Account""" % (weburl, ln),
description="CDS Personalize, Main page",
keywords="CDS, personalize",
uid=uid,
language=ln,
lastupdated=__lastupdated__)
def display(req, ln=cdslang):
uid = webuser.getUid(req)
if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
return webuser.page_not_authorized(req, "../youraccount.py/display")
- if webuser.isGuestUser(uid):
-
+ if webuser.isGuestUser(uid):
return page(title="Your Account",
body=webaccount.perform_info(req),
description="CDS Personalize, Main page",
keywords="CDS, personalize",
uid=uid,
language=ln,
lastupdated=__lastupdated__)
data = webuser.getDataUid(req,uid)
bask = webbasket.account_list_baskets(uid)
aler = webalert.account_list_alerts(uid)
sear = webalert.account_list_searches(uid)
return page(title="Your Account",
body=webaccount.perform_display_account(req,data,bask,aler,sear),
description="CDS Personalize, Main page",
keywords="CDS, personalize",
uid=uid,
language=ln,
lastupdated=__lastupdated__)
def send_email(req, p_email=None, ln=cdslang):
uid = webuser.getUid(req)
if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
return webuser.page_not_authorized(req, "../youraccount.py/send_email")
user_prefs = webuser.get_user_preferences(webuser.emailUnique(p_email))
if user_prefs:
if CFG_EXTERNAL_AUTHENTICATION.has_key(user_prefs['login_method']) or CFG_EXTERNAL_AUTHENTICATION.has_key(user_prefs['login_method']) and CFG_EXTERNAL_AUTHENTICATION[user_prefs['login_method']][0] != None:
Msg = """If you have lost password for your CERN Document Server internal
account, then please enter your email address below and the lost
password will be emailed to you.
Note that if you have been using an external login system (such
as CERN NICE), then we cannot do anything and you have to ask
there. Alternatively, you can ask
to change your login system from external to internal.
"""
return page(title="Your Account",
body=Msg,
description="CDS Personalize, Main page",
keywords="CDS, personalize",
uid=uid,
language=ln,
lastupdated=__lastupdated__)
passw = webuser.givePassword(p_email)
if passw == -999:
eMsg = "The entered e-mail address doesn't exist in the database"
return page(title="Your Account",
body=webaccount.perform_emailMessage(eMsg),
description="CDS Personalize, Main page",
keywords="CDS, personalize",
uid=uid,
language=ln,
lastupdated=__lastupdated__)
fromaddr = "From: %s" % supportemail
toaddrs = "To: " + p_email
to = toaddrs + "\n"
sub = "Subject: Credentials for %s\n\n" % cdsname
body = "Here are your user credentials for %s:\n\n" % cdsname
body += " username: %s\n password: %s\n\n" % (p_email, passw)
body += "You can login at %s/youraccount.py/login" % weburl
msg = to + sub + body
server = smtplib.SMTP('localhost')
server.set_debuglevel(1)
try:
server.sendmail(fromaddr, toaddrs, msg)
except smtplib.SMTPRecipientsRefused,e:
eMsg = "The entered email address is incorrect, please check that it is written correctly (e.g. johndoe@example.com)."
return page(title="Incorrect email address",
body=webaccount.perform_emailMessage(eMsg),
description="CDS Personalize, Main page",
keywords="CDS, personalize",
uid=uid,
language=ln,
lastupdated=__lastupdated__)
server.quit()
return page(title="Lost password sent",
body=webaccount.perform_emailSent(p_email),
description="CDS Personalize, Main page",
keywords="CDS, personalize",
uid=uid,
language=ln,
lastupdated=__lastupdated__)
def youradminactivities(req, ln=cdslang):
uid = webuser.getUid(req)
if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
return webuser.page_not_authorized(req, "../youraccount.py/youradminactivities")
return page(title="Your Administrative Activities",
body=webaccount.perform_youradminactivities(uid),
navtrail="""Your Account""" % (weburl, ln),
description="CDS Personalize, Main page",
keywords="CDS, personalize",
uid=uid,
language=ln,
lastupdated=__lastupdated__)
def delete(req, ln=cdslang):
uid = webuser.getUid(req)
if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
return webuser.page_not_authorized(req, "../youraccount.py/delete")
return page(title="Delete Account",
body=webaccount.perform_delete(),
navtrail="""Your Account""" % (weburl, ln),
description="CDS Personalize, Main page",
keywords="CDS, personalize",
uid=uid,
language=ln,
lastupdated=__lastupdated__)
def logout(req, ln=cdslang):
uid = webuser.logoutUser(req)
if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
return webuser.page_not_authorized(req, "../youraccount.py/logout")
return page(title="Logout",
body=webaccount.perform_logout(req),
navtrail="""Your Account""" % (weburl, ln),
description="CDS Personalize, Main page",
keywords="CDS, personalize",
uid=uid,
language=ln,
lastupdated=__lastupdated__)
def login(req, p_email=None, p_pw=None, login_method=None, action='login', referer='', ln=cdslang):
if CFG_ACCESS_CONTROL_LEVEL_SITE > 0:
return webuser.page_not_authorized(req, "../youraccount.py/login")
uid = webuser.getUid(req)
if action =='login':
if p_email==None or not login_method:
return page(title="Login",
body=webaccount.create_login_page_box(referer),
navtrail="""Your Account""" % (weburl, ln),
description="CDS Personalize, Main page",
keywords="CDS, personalize",
uid=uid,
language=ln,
lastupdated=__lastupdated__)
(iden, p_email, p_pw, msgcode) = webuser.loginUser(req,p_email,p_pw, login_method)
if len(iden)>0:
uid = webuser.update_Uid(req,p_email,p_pw)
uid2 = webuser.getUid(req)
if uid2 == -1:
webuser.logoutUser(req)
return webuser.page_not_authorized(req, "../youraccount.py/login?ln=%s" % ln, uid=uid)
# login successful!
if referer:
req.err_headers_out.add("Location", referer)
raise apache.SERVER_RETURN, apache.HTTP_MOVED_PERMANENTLY
else:
return display(req)
else:
mess = cfg_webaccess_warning_msgs[msgcode] % login_method
if msgcode == 14:
if not webuser.userNotExist(p_email,p_pw) or p_email=='' or p_email==' ':
mess = cfg_webaccess_warning_msgs[15] % login_method
act = "login"
return page(title="Login",
body=webaccount.perform_back(mess,act),
navtrail="""Your Account""" % (weburl, ln),
description="CDS Personalize, Main page",
keywords="CDS, personalize",
uid=uid,
language=ln,
lastupdated=__lastupdated__)
def register(req, p_email=None, p_pw=None, p_pw2=None, action='login', referer='', ln=cdslang):
if CFG_ACCESS_CONTROL_LEVEL_SITE > 0:
return webuser.page_not_authorized(req, "../youraccount.py/register")
uid = webuser.getUid(req)
if p_email==None:
return page(title="Register",
body=webaccount.create_register_page_box(referer),
navtrail="""Your Account""" % (weburl, ln),
description="CDS Personalize, Main page",
keywords="CDS, personalize",
uid=uid,
language=ln,
lastupdated=__lastupdated__)
mess=""
act=""
if p_pw == p_pw2:
ruid = webuser.registerUser(req,p_email,p_pw)
else:
ruid = -2
if ruid == 1:
uid = webuser.update_Uid(req,p_email,p_pw)
mess = "Your account has been successfully created."
title = "Account created"
if CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_NEW_ACCOUNT == 1:
mess += " An email has been sent to the given address with the account information."
if CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS >= 1:
mess += " A second email will be sent when the account has been activated and can be used."
else:
mess += """ You can now access your account.""" % (weburl, ln)
elif ruid == -1:
mess = "The user already exists in the database, please try again."
act = "register"
title = "Register failure"
elif ruid == -2:
mess = "Both passwords must match, please try again."
act = "register"
title = "Register failure"
else:
mess = "The email address given is not valid, please try again."
act = "register"
title = "Register failure"
return page(title=title,
body=webaccount.perform_back(mess,act),
navtrail="""Your Account""" % (weburl, ln),
description="CDS Personalize, Main page",
keywords="CDS, personalize",
uid=uid,
language=ln,
lastupdated=__lastupdated__)
diff --git a/modules/websession/web/youraccount.py.wml b/modules/websession/web/youraccount.py.wml
index 8f060a476..cb6dc6ad1 100644
--- a/modules/websession/web/youraccount.py.wml
+++ b/modules/websession/web/youraccount.py.wml
@@ -1,385 +1,384 @@
## $Id$
## CDSware User account information.
## 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 ACCOUNT HANDLING"""
__lastupdated__ = """<: print `date +"%d %b %Y %H:%M:%S %Z"`; :>"""
## fill config variables:
pylibdir = "/python"
import sys
sys.path.append('%s' % pylibdir)
from cdsware import webuser
from cdsware.config import weburl,cdsname,cdslang,supportemail
from cdsware.webpage import page
from cdsware import webaccount
from cdsware import webbasket
from cdsware import webalert
from cdsware import webuser
from cdsware.access_control_config import *
from mod_python import apache
from cdsware.access_control_config import CFG_ACCESS_CONTROL_LEVEL_SITE, cfg_webaccess_warning_msgs, CFG_EXTERNAL_AUTHENTICATION
import smtplib
def edit(req, ln=cdslang):
uid = webuser.getUid(req)
if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
return webuser.page_not_authorized(req, "../youraccount.py/set")
data = webuser.getDataUid(req,uid)
email = data[0]
passw = data[1]
return page(title="Your Settings",
body=webaccount.perform_set(email,passw),
navtrail="""Your Account""" % (weburl, ln),
description="CDS Personalize, Your Settings",
keywords="CDS, personalize",
uid=uid,
language=ln,
lastupdated=__lastupdated__)
def change(req,email=None,password=None,password2=None,login_method="",ln=cdslang):
uid = webuser.getUid(req)
if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
return webuser.page_not_authorized(req, "../youraccount.py/change")
if login_method and CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS < 4:
title = "Settings edited"
act = "display"
linkname = "Show account"
prefs = webuser.get_user_preferences(uid)
prefs['login_method'] = login_method
webuser.set_user_preferences(uid, prefs)
mess = "Login method successfully selected."
elif login_method and CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS >= 4:
return webuser.page_not_authorized(req, "../youraccount.py/change")
elif email:
if (CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS >= 2 or (CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS <= 1 and webuser.checkemail(email))) and uid2 != -1 and (uid2 == uid or uid2 == 0) and password == password2:
if CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS < 3:
change = webuser.updateDataUser(req,uid,email,password)
else:
return webuser.page_not_authorized(req, "../youraccount.py/change")
if change and CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS >= 2:
mess = "Password successfully edited."
elif change:
mess = "Settings successfully edited."
act = "display"
linkname = "Show account"
title = "Settings edited"
elif uid2 == -1 or uid2 != uid and not uid2 == 0:
mess = "The email address is already in use, please try again."
act = "edit"
linkname = "Edit settings"
title = "Editing settings failed"
elif not webuser.checkemail(email):
mess = "The email address is not valid, please try again."
act = "edit"
linkname = "Edit settings"
title = "Editing settings failed"
elif password != password2:
mess = "The passwords do not match, please try again."
act = "edit"
linkname = "Edit settings"
title = "Editing settings failed"
else:
mess = "Could not update settings."
act = "edit"
linkname = "Edit settings"
title = "Editing settings failed"
return page(title=title,
body=webaccount.perform_back(mess,act, linkname),
navtrail="""Your Account""" % (weburl, ln),
description="CDS Personalize, Main page",
keywords="CDS, personalize",
uid=uid,
language=ln,
lastupdated=__lastupdated__)
def lost(req, ln=cdslang):
uid = webuser.getUid(req)
if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
return webuser.page_not_authorized(req, "../youraccount.py/lost")
return page(title="Lost your password?",
body=webaccount.perform_lost(),
navtrail="""Your Account""" % (weburl, ln),
description="CDS Personalize, Main page",
keywords="CDS, personalize",
uid=uid,
language=ln,
lastupdated=__lastupdated__)
def display(req, ln=cdslang):
uid = webuser.getUid(req)
if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
return webuser.page_not_authorized(req, "../youraccount.py/display")
- if webuser.isGuestUser(uid):
-
+ if webuser.isGuestUser(uid):
return page(title="Your Account",
body=webaccount.perform_info(req),
description="CDS Personalize, Main page",
keywords="CDS, personalize",
uid=uid,
language=ln,
lastupdated=__lastupdated__)
data = webuser.getDataUid(req,uid)
bask = webbasket.account_list_baskets(uid)
aler = webalert.account_list_alerts(uid)
sear = webalert.account_list_searches(uid)
return page(title="Your Account",
body=webaccount.perform_display_account(req,data,bask,aler,sear),
description="CDS Personalize, Main page",
keywords="CDS, personalize",
uid=uid,
language=ln,
lastupdated=__lastupdated__)
def send_email(req, p_email=None, ln=cdslang):
uid = webuser.getUid(req)
if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
return webuser.page_not_authorized(req, "../youraccount.py/send_email")
user_prefs = webuser.get_user_preferences(webuser.emailUnique(p_email))
if user_prefs:
if CFG_EXTERNAL_AUTHENTICATION.has_key(user_prefs['login_method']) or CFG_EXTERNAL_AUTHENTICATION.has_key(user_prefs['login_method']) and CFG_EXTERNAL_AUTHENTICATION[user_prefs['login_method']][0] != None:
Msg = """If you have lost password for your CERN Document Server internal
account, then please enter your email address below and the lost
password will be emailed to you.
Note that if you have been using an external login system (such
as CERN NICE), then we cannot do anything and you have to ask
there. Alternatively, you can ask
to change your login system from external to internal.
"""
return page(title="Your Account",
body=Msg,
description="CDS Personalize, Main page",
keywords="CDS, personalize",
uid=uid,
language=ln,
lastupdated=__lastupdated__)
passw = webuser.givePassword(p_email)
if passw == -999:
eMsg = "The entered e-mail address doesn't exist in the database"
return page(title="Your Account",
body=webaccount.perform_emailMessage(eMsg),
description="CDS Personalize, Main page",
keywords="CDS, personalize",
uid=uid,
language=ln,
lastupdated=__lastupdated__)
fromaddr = "From: %s" % supportemail
toaddrs = "To: " + p_email
to = toaddrs + "\n"
sub = "Subject: Credentials for %s\n\n" % cdsname
body = "Here are your user credentials for %s:\n\n" % cdsname
body += " username: %s\n password: %s\n\n" % (p_email, passw)
body += "You can login at %s/youraccount.py/login" % weburl
msg = to + sub + body
server = smtplib.SMTP('localhost')
server.set_debuglevel(1)
try:
server.sendmail(fromaddr, toaddrs, msg)
except smtplib.SMTPRecipientsRefused,e:
eMsg = "The entered email address is incorrect, please check that it is written correctly (e.g. johndoe@example.com)."
return page(title="Incorrect email address",
body=webaccount.perform_emailMessage(eMsg),
description="CDS Personalize, Main page",
keywords="CDS, personalize",
uid=uid,
language=ln,
lastupdated=__lastupdated__)
server.quit()
return page(title="Lost password sent",
body=webaccount.perform_emailSent(p_email),
description="CDS Personalize, Main page",
keywords="CDS, personalize",
uid=uid,
language=ln,
lastupdated=__lastupdated__)
def youradminactivities(req, ln=cdslang):
uid = webuser.getUid(req)
if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
return webuser.page_not_authorized(req, "../youraccount.py/youradminactivities")
return page(title="Your Administrative Activities",
body=webaccount.perform_youradminactivities(uid),
navtrail="""Your Account""" % (weburl, ln),
description="CDS Personalize, Main page",
keywords="CDS, personalize",
uid=uid,
language=ln,
lastupdated=__lastupdated__)
def delete(req, ln=cdslang):
uid = webuser.getUid(req)
if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
return webuser.page_not_authorized(req, "../youraccount.py/delete")
return page(title="Delete Account",
body=webaccount.perform_delete(),
navtrail="""Your Account""" % (weburl, ln),
description="CDS Personalize, Main page",
keywords="CDS, personalize",
uid=uid,
language=ln,
lastupdated=__lastupdated__)
def logout(req, ln=cdslang):
uid = webuser.logoutUser(req)
if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
return webuser.page_not_authorized(req, "../youraccount.py/logout")
return page(title="Logout",
body=webaccount.perform_logout(req),
navtrail="""Your Account""" % (weburl, ln),
description="CDS Personalize, Main page",
keywords="CDS, personalize",
uid=uid,
language=ln,
lastupdated=__lastupdated__)
def login(req, p_email=None, p_pw=None, login_method=None, action='login', referer='', ln=cdslang):
if CFG_ACCESS_CONTROL_LEVEL_SITE > 0:
return webuser.page_not_authorized(req, "../youraccount.py/login")
uid = webuser.getUid(req)
if action =='login':
if p_email==None or not login_method:
return page(title="Login",
body=webaccount.create_login_page_box(referer),
navtrail="""Your Account""" % (weburl, ln),
description="CDS Personalize, Main page",
keywords="CDS, personalize",
uid=uid,
language=ln,
lastupdated=__lastupdated__)
(iden, p_email, p_pw, msgcode) = webuser.loginUser(req,p_email,p_pw, login_method)
if len(iden)>0:
uid = webuser.update_Uid(req,p_email,p_pw)
uid2 = webuser.getUid(req)
if uid2 == -1:
webuser.logoutUser(req)
return webuser.page_not_authorized(req, "../youraccount.py/login?ln=%s" % ln, uid=uid)
# login successful!
if referer:
req.err_headers_out.add("Location", referer)
raise apache.SERVER_RETURN, apache.HTTP_MOVED_PERMANENTLY
else:
return display(req)
else:
mess = cfg_webaccess_warning_msgs[msgcode] % login_method
if msgcode == 14:
if not webuser.userNotExist(p_email,p_pw) or p_email=='' or p_email==' ':
mess = cfg_webaccess_warning_msgs[15] % login_method
act = "login"
return page(title="Login",
body=webaccount.perform_back(mess,act),
navtrail="""Your Account""" % (weburl, ln),
description="CDS Personalize, Main page",
keywords="CDS, personalize",
uid=uid,
language=ln,
lastupdated=__lastupdated__)
def register(req, p_email=None, p_pw=None, p_pw2=None, action='login', referer='', ln=cdslang):
if CFG_ACCESS_CONTROL_LEVEL_SITE > 0:
return webuser.page_not_authorized(req, "../youraccount.py/register")
uid = webuser.getUid(req)
if p_email==None:
return page(title="Register",
body=webaccount.create_register_page_box(referer),
navtrail="""Your Account""" % (weburl, ln),
description="CDS Personalize, Main page",
keywords="CDS, personalize",
uid=uid,
language=ln,
lastupdated=__lastupdated__)
mess=""
act=""
if p_pw == p_pw2:
ruid = webuser.registerUser(req,p_email,p_pw)
else:
ruid = -2
if ruid == 1:
uid = webuser.update_Uid(req,p_email,p_pw)
mess = "Your account has been successfully created."
title = "Account created"
if CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_NEW_ACCOUNT == 1:
mess += " An email has been sent to the given address with the account information."
if CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS >= 1:
mess += " A second email will be sent when the account has been activated and can be used."
else:
mess += """ You can now access your account.""" % (weburl, ln)
elif ruid == -1:
mess = "The user already exists in the database, please try again."
act = "register"
title = "Register failure"
elif ruid == -2:
mess = "Both passwords must match, please try again."
act = "register"
title = "Register failure"
else:
mess = "The email address given is not valid, please try again."
act = "register"
title = "Register failure"
return page(title=title,
body=webaccount.perform_back(mess,act),
navtrail="""Your Account""" % (weburl, ln),
description="CDS Personalize, Main page",
keywords="CDS, personalize",
uid=uid,
language=ln,
lastupdated=__lastupdated__)