def MailResetPass(self, name, mail="default", currentUser=None, **kw): """ returns status and report list """ report=[] if not name: report.append(_(u"Please enter your sign in name or email address.")) return None, report if isinstance(name, basestring): obj = self.GetUserByName(name) if not obj: report.append(_(u"No matching account found.")) return None, report else: obj = name email = obj.data.get("email") if not email: report.append(_("No email address found.")) return None, report recv = [(email, obj.meta.title)] token = self.GenerateID(25) obj.data["token"] = token obj.Commit(user=currentUser) app = self.app if mail=="default": try: mail = self.app.configuration.mailResetPass except AttributeError, e: raise ConfigurationError, str(e)
def Login(self, name, password, raiseUnauthorized=1): """ returns user/none and report list """ report = [] # session login user = self.GetUserByName(name) if not user: if raiseUnauthorized: raise Unauthorized, "Login failed" report.append( _(u"Sign in failed. Please check your username and password.")) return None, report if not user.Authenticate(password): if raiseUnauthorized: raise Unauthorized, "Login failed" report.append( _(u"Sign in failed. Please check your username and password.")) return None, report # call user user.Login() report.append(_(u"You are now signed in.")) return user, report
def MailResetPass(self, name, mail="default", currentUser=None, **kw): """ returns status and report list """ report = [] if not name: report.append( _(u"Please enter your sign in name or email address.")) return None, report if isinstance(name, basestring): obj = self.GetUserByName(name) if not obj: report.append(_(u"No matching account found.")) return None, report else: obj = name email = obj.data.get("email") if not email: report.append(_("No email address found.")) return None, report recv = [(email, obj.meta.title)] token = self.GenerateID(25) obj.data["token"] = token obj.Commit(user=currentUser) app = self.app if mail == "default": try: mail = self.app.configuration.mailResetPass except AttributeError, e: raise ConfigurationError, str(e)
def delete(self): ids = self.GetFormValue("ids") confirm = self.GetFormValue("confirm") users = [] msgs = [] root = self.context.dataroot if isinstance(ids, basestring): ids = (ids,) elif not ids: ids = () for i in ids: u = root.GetUserByID(i, activeOnly=0) if not u: msgs.append(self.Translate(_(u"User not found. (id %(name)s)", mapping={"name": i}))) else: users.append(u) result = True if confirm: for u in users: name = u.data.name if not root.Delete(id=u.id, obj=u, user=self.User()): result = False msgs.append(self.Translate(_(u"Delete failed: User '%(name)s'", mapping={"name": u.meta.title}))) users=() if result: if len(ids)>1: msgs.append(self.Translate(_(u"OK. Users deleted."))) else: msgs.append(self.Translate(_(u"OK. User deleted."))) return self.Redirect(self.Url(root), msgs) return {"ids": ids, "users":users, "result": result, "msgs": msgs, "confirm": confirm}
def GetAdminWidgets(self): url = self.FolderUrl(self.context.dataroot) confs = [ Conf(id="admin.root", viewmapper=url+"list", name=_(u"List users")), Conf(id="admin.add", viewmapper=url+"add", name=_(u"Add user")) ] return confs
def EmailValidator(node, value): """ Validator which succeeds if the email does not exist. Can be used for the email input field in a sign up form. """ # validate email format Email()(node, value) if IsReservedUserName(value): err = _( u"Email '${name}' already in use. Please choose a different email.", mapping={'name': value}) raise Invalid(node, err) # lookup email in database r = node.widget.form.context.root() u = r.Select(pool_type=u"user", parameter={u"email": value}, fields=[u"id", u"name", u"email"], max=2, operators={u"email": u"="}) if not u: u = r.Select(pool_type=u"user", parameter={u"name": value}, fields=[u"id", u"name", u"email"], max=2, operators={u"name": u"="}) if u: # check if its the current user ctx = node.widget.form.context if len(u) == 1 and ctx.id == u[0][0]: return err = _( u"Email '${name}' already in use. Please choose a different email.", mapping={'name': value}) raise Invalid(node, err)
def UpdateMailToken(self, action, **kw): """ Form action: activate the mail in tempcache if token matches """ msgs = [] errors = [] result = False data = self.GetFormValue("token",method="ALL") if data: if data.find(u"token=")!=-1: data = data.split(u"token=")[-1] user = self.context.GetUserForToken(data) if user: mail = user.data.tempcache if mail.startswith(u"verifymail:"): mail = mail.replace(u"verifymail:",u"") user.data["email"] = mail user.data["tempcache"] = u"" user.data["token"] = u"" user.Commit(user=user) msgs = [_(u"OK. The new email address has been activated.")] result = True if not result: msgs = [_(u"The token is invalid. Please make sure it is complete.")] data = {"token": data or u""} return self._FinishFormProcessing(result, data, msgs, errors, **kw)
def GetAdminWidgets(self): url = self.FolderUrl(self.context.dataroot) confs = [ Conf(id="admin.root", viewmapper=url + "list", name=_(u"List users")), Conf(id="admin.add", viewmapper=url + "add", name=_(u"Add user")) ] return confs
def AcceptValidator(node, value): """ Validator which succeeds if the checkbox is ticked (true). """ if not value==True: err = _(u"Please accept the terms and conditions.") raise Invalid(node, err)
def AcceptValidator(node, value): """ Validator which succeeds if the checkbox is ticked (true). """ if not value == True: err = _(u"Please accept the terms and conditions.") raise Invalid(node, err)
def MailVerifyNewEmail(self, name, newmail, mail="default", currentUser=None, **kw): """ returns status and report list """ report = [] if not newmail: report.append(_(u"Please enter your new email address.")) return False, report if isinstance(name, basestring): obj = self.GetUserByName(name) if not obj: report.append(_(u"No matching account found.")) return False, report else: obj = name recv = [(newmail, obj.meta.get("title"))] token = self.GenerateID(20) obj.data["token"] = token obj.data["tempcache"] = "verifymail:" + newmail obj.Commit(user=currentUser) app = self.app if mail == "default": mail = self.app.configuration.mailVerifyMail title = mail.title body = mail(user=obj, **kw) tool = app.GetTool("sendMail") if not tool: raise ConfigurationError, "Mail tool 'sendMail' not found" result, value = tool(body=body, title=title, recvmails=recv, force=1) if not result: report.append(_(u"The email could not be sent.")) return None, report report.append( _(u"The link to verify your new email has been sent by mail.")) return obj, report
def OldPwValidator(node, value): """ Validator which succeeds if the current password matches. """ user = node.widget.form.view.User(sessionuser=False) if not user.Authenticate(value): err = _(u"The old password does not match.") raise Invalid(node, err)
def MailUserPass(self, name, mail="default", newPassword=None, currentUser=None, **kw): """ Mails a new password or the current password in plain text. returns status and report list """ report = [] if not name: report.append(_(u"Please enter your email address or username.")) return False, report if isinstance(name, basestring): obj = self.GetUserByName(name) if not obj: report.append( _(u"No matching account found. Please try again.")) return False, report else: obj = name email = obj.data.get("email") title = obj.meta.get("title") if email == "": report.append(_("No email address found.")) return False, report recv = [(email, title)] if not newPassword: pwd = self.GenerateID(5) else: pwd = newPassword obj.data["password"] = pwd if mail == "default": try: mail = self.app.configuration.mailSendPass except AttributeError, e: raise ConfigurationError, str(e)
def PasswordValidator(node, value): """ Validator which succeeds if the username does not exist. Can be used for the name input field in a sign up form. """ Length(min=5,max=30)(node, value) chars = ''.join(set(value)) if len(chars)<5: err = _(u"Password is too simple. It should have at least 5 different characters.") raise Invalid(node, err)
def delete(self): ids = self.GetFormValue("ids") confirm = self.GetFormValue("confirm") users = [] msgs = [] root = self.context.dataroot if isinstance(ids, basestring): ids = (ids, ) elif not ids: ids = () for i in ids: u = root.GetUserByID(i, activeOnly=0) if not u: msgs.append( self.Translate( _(u"User not found. (id %(name)s)", mapping={"name": i}))) else: users.append(u) result = True if confirm: for u in users: name = u.data.name if not root.Delete(id=u.id, obj=u, user=self.User()): result = False msgs.append( self.Translate( _(u"Delete failed: User '%(name)s'", mapping={"name": u.meta.title}))) users = () if result: if len(ids) > 1: msgs.append(self.Translate(_(u"OK. Users deleted."))) else: msgs.append(self.Translate(_(u"OK. User deleted."))) return self.Redirect(self.Url(root), msgs) return { "ids": ids, "users": users, "result": result, "msgs": msgs, "confirm": confirm }
def PasswordValidator(node, value): """ Validator which succeeds if the username does not exist. Can be used for the name input field in a sign up form. """ Length(min=5, max=30)(node, value) chars = ''.join(set(value)) if len(chars) < 5: err = _( u"Password is too simple. It should have at least 5 different characters." ) raise Invalid(node, err)
def MailVerifyNewEmail(self, name, newmail, mail="default", currentUser=None, **kw): """ returns status and report list """ report=[] if not newmail: report.append(_(u"Please enter your new email address.")) return False, report if isinstance(name, basestring): obj = self.GetUserByName(name) if not obj: report.append(_(u"No matching account found.")) return False, report else: obj = name recv = [(newmail, obj.meta.get("title"))] token = self.GenerateID(20) obj.data["token"] = token obj.data["tempcache"] = "verifymail:"+newmail obj.Commit(user=currentUser) app = self.app if mail=="default": mail = self.app.configuration.mailVerifyMail title = mail.title body = mail(user=obj, **kw) tool = app.GetTool("sendMail") if not tool: raise ConfigurationError, "Mail tool 'sendMail' not found" result, value = tool(body=body, title=title, recvmails=recv, force=1) if not result: report.append(_(u"The email could not be sent.")) return None, report report.append(_(u"The link to verify your new email has been sent by mail.")) return obj, report
def DeleteUser(self, ident, currentUser=None): """ returns status and report list """ report = [] if not ident: report.append(_(u"Invalid user.")) return False, report elif isinstance(ident, basestring): if not ident: report.append(_(u"Invalid user.")) return False, report user = self.LookupUser(ident=ident, activeOnly=0) if not user: report.append(_(u"Invalid username.")) return False, report else: user = ident if IAdminUser.providedBy(user): report.append(_(u"You cannot delete the admin user.")) return False, report self.Logout(user) if not self.Delete(user.id, obj=user, user=currentUser): report.append(_(u"Sorry. An error occurred.")) return False, report report.append(_(u"User deleted.")) return True, report
def Activate(self, action, **kw): """ Form action: activate the mail in tempcache if token matches """ msgs = [] errors = [] result = False data = self.GetFormValue("token",method="ALL") if data: if data.find(u"token=")!=-1: data = data.split(u"token=")[-1] user = self.context.GetUserForToken(data, activeOnly=False) if user is not None: result = True user.Activate(currentUser=user) msgs = [self.context.app.configuration.get("activationMessage") or _(u"OK.")] else: result = False if not result: msgs = [_(u"The token is invalid. Please make sure it is complete.")] data = {"token": data or u""} return self._FinishFormProcessing(result, data, msgs, errors, **kw)
def EmailValidator(node, value): """ Validator which succeeds if the email does not exist. Can be used for the email input field in a sign up form. """ # validate email format Email()(node, value) if IsReservedUserName(value): err = _(u"Email '${name}' already in use. Please choose a different email.", mapping={'name':value}) raise Invalid(node, err) # lookup email in database r = node.widget.form.context.root() u = r.Select(pool_type=u"user", parameter={u"email": value}, fields=[u"id",u"name",u"email"], max=2, operators={u"email":u"="}) if not u: u = r.Select(pool_type=u"user", parameter={u"name": value}, fields=[u"id",u"name",u"email"], max=2, operators={u"name":u"="}) if u: # check if its the current user ctx = node.widget.form.context if len(u)==1 and ctx.id == u[0][0]: return err = _(u"Email '${name}' already in use. Please choose a different email.", mapping={'name':value}) raise Invalid(node, err)
def MailUserPass(self, name, mail="default", newPassword=None, currentUser=None, **kw): """ Mails a new password or the current password in plain text. returns status and report list """ report=[] if not name: report.append(_(u"Please enter your email address or username.")) return False, report if isinstance(name, basestring): obj = self.GetUserByName(name) if not obj: report.append(_(u"No matching account found. Please try again.")) return False, report else: obj = name email = obj.data.get("email") title = obj.meta.get("title") if email == "": report.append(_("No email address found.")) return False, report recv = [(email, title)] if not newPassword: pwd = self.GenerateID(5) else: pwd = newPassword obj.data["password"] = pwd if mail=="default": try: mail = self.app.configuration.mailSendPass except AttributeError, e: raise ConfigurationError, str(e)
def Login(self, name, password, raiseUnauthorized = 1): """ returns user/none and report list """ report = [] # session login user = self.GetUserByName(name) if not user: if raiseUnauthorized: raise Unauthorized, "Login failed" report.append(_(u"Sign in failed. Please check your username and password.")) return None, report if not user.Authenticate(password): if raiseUnauthorized: raise Unauthorized, "Login failed" report.append(_(u"Sign in failed. Please check your username and password.")) return None, report # call user user.Login() report.append(_(u"You are now signed in.")) return user, report
def Contact(self, action, **kw): """ Sends a email to the user 'receiver' :param action: :param kw: mail, receiver, replyToSender :return: """ result,data,errors = self.Validate(self.request) if not result: return result, self.Render(data, msgs=[], errors=errors) recv = kw.get("receiver") if not isinstance(recv, (list, tuple)): result = False msgs = (_(u"No receiver specified."),) return result, self.Render(data, msgs=msgs, errors=errors) replyTo = u"" user = self.view.User() if kw.get("replyToSender")==True: replyTo=user.data.email mail = kw.get("mail") or self.context.app.configuration.mailContact title = mail.title body = mail(sender=user, data=data, form=self, **kw) tool = self.context.app.GetTool("sendMail") if not tool: raise ConfigurationError, "Mail tool 'sendMail' not found" result, value = tool(body=body, title=title, recvmails=recv, replyTo=replyTo, force=1) if not result: msgs=(_(u"The email could not be sent."),) else: msgs = (_(u"The email has been sent."),) return self._FinishFormProcessing(result, data, msgs, None, **kw)
def SecureUpdate(self, data, user): """ Update existing user data. name, groups, pool_state cannot be changed """ readonly = ("name","email","groups","pool_state","pool_wfa","token","password",self.parent.identityField) for f in readonly: if f in data: del data[f] if not self.Update(data, user): return False, [_(u"Update failed.")] self.Commit(user) return True
def SecureUpdate(self, data, user): """ Update existing user data. name, groups, pool_state cannot be changed """ readonly = ("name", "email", "groups", "pool_state", "pool_wfa", "token", "password", self.parent.identityField) for f in readonly: if f in data: del data[f] if not self.Update(data, user): return False, [_(u"Update failed.")] self.Commit(user) return True
def UpdatePass(self, action, **kw): """ Form action: update password if current password matches """ user = self.view.User(sessionuser=False) if user is None: raise Unauthorized, "User not found." msgs = [] result,data,errors = self.Validate(self.request) if not result: return result, self.Render(data, msgs=msgs, errors=errors) result = user.UpdatePassword(data["password"], user) if result: msgs.append(_(u"OK. Password changed.")) return result, self.Render(data, msgs=msgs, errors=None, messagesOnly=True) return result, self.Render(data)
def logout(self): """ Logout action """ self.ResetFlashMessages() app = self.context.app user = self.UserName() a = self.context.root().Logout(user) app.ForgetLogin(self.request) redirect = self.GetFormValue(u"redirect") if not redirect: try: redirect = self.context.app.portal.configuration.logoutSuccessUrl except: redirect = self.context.app.portal.configuration.portalDefaultUrl if redirect: localizer = translator(self.request) self.Redirect(redirect, messages=[localizer(_(u"You have been logged out!"))]) return {}
def Update(self, action, **kw): """ Form action: safely update a user Pass additional user data as `values` in keywords. """ user = self.view.User(sessionuser=False) if not user: raise Unauthorized, "User not found." msgs = [] result,data,errors = self.Validate(self.request) if result: # add additional user values if passed in kws if kw.get("values"): data.update(kw["values"]) result = user.SecureUpdate(data, user) if result: msgs.append(_(u"OK.")) return self._FinishFormProcessing(result, data, msgs, errors, **kw)
from nive.definitions import AppConf, GroupConf, Conf from nive.definitions import implements, IUserDatabase, ILocalGroups from nive.security import Allow, Deny, Everyone, Authenticated, ALL_PERMISSIONS, remember, forget from nive.components.objects.base import ApplicationBase from nive.views import Mail from nive.components.reform.schema import Invalid from nive.components.reform.schema import Email from nive.components.reform.schema import Literal, Length from nive_userdb.i18n import _ #@nive_module configuration = AppConf( id="userdb", title=_(u"Users"), loginByEmail=True, # signup settings settings=Conf(groups=(), activate=1, generatePW=0, generateName=False), # contact system information #userAdmin = (u"*****@*****.**", u"Admin"), # non-db admin login #admin = {"name": "adminusername", "password": "******", "email": "u"*****@*****.**""}, # mails mailSignup=Mail(_(u"Signup confirmation"), "nive_userdb:userview/mails/signup.pt"), mailNotify=Mail(_(u"Signup notification"), "nive_userdb:userview/mails/notify.pt"), mailVerifyMail=Mail(_(u"Verify your new e-mail"),
def __init__(self, view=None, loadFromType=None, context=None, request=None, app=None, **kw): ObjectForm.__init__(self, view=view, loadFromType=loadFromType, context=context, request=request, app=app, **kw) self.actions = [ Conf(id="default", method="StartForm", name=u"Initialize", hidden=True), Conf(id="defaultEdit",method="LoadUser", name=u"Initialize", hidden=True), Conf(id="create", method="AddUser", name=_(u"Signup"), hidden=False), Conf(id="edit", method="Update", name=_(u"Confirm"), hidden=False), Conf(id="login", method="Login", name=_(u"Login"), hidden=False), ] self.subsets = { "create": { # loads fields from user configuration "actions": ["create"], "defaultAction": "default" }, "edit": { # loads fields from user configuration "actions": ["edit"], "defaultAction": "defaultEdit" }, "login": { "fields": [ FieldConf(id="name", name=_("Name"), datatype="string"), FieldConf(id="password", name=_("Password"), datatype="password", settings={"single": True}), FieldConf(id="redirect", datatype="string", size="500", name="redirect url", hidden=True), ], "actions": ["login"], "defaultAction": "default" }, "loginMail": { "fields": [ FieldConf(id="name", name=_("Name or email"), datatype="string"), FieldConf(id="password", name=_("Password"), datatype="password", settings={"single": True}), FieldConf(id="redirect", datatype="string", size="500", name="redirect url", hidden=True), ], "actions": ["login"], "defaultAction": "default" }, "activate": { "fields": [FieldConf(id="token", datatype="string", size="500", name="Activation token", required=True, hidden=False)], "actions": [Conf(id="activate", method="Activate", name=_(u"Activate"), hidden=False)], "defaultAction": "activate" }, "updatepass":{ "fields": [ FieldConf(id="oldpassword", datatype="password", size=100, default=u"", required=1, name=_(u"Old password"), settings={"single":True}, validator=OldPwValidator), "password" ], "actions": [Conf(id="updatepass", method="UpdatePass", name=_(u"Update password"), hidden=False)], "defaultAction": "default" }, "updatemail1": { "fields": [ FieldConf(id="newmail", datatype="email", size=255, default=u"", required=1, name=_(u"New email"), validator=EmailValidator) ], "actions": [Conf(id="updatemail", method="UpdateMail", name=_(u"Update email"), hidden=False)], "defaultAction": "default" }, "updatemail2": { "fields": [FieldConf(id="token", datatype="string", size="500", name="Activation token", required=True, hidden=False)], "actions": [Conf(id="updatemail_token", method="UpdateMailToken", name=_(u"Verify email"), hidden=False)], "defaultAction": "updatemail_token" }, "resetpass": { "fields": [FieldConf(id="name", name=_("Name"), datatype="string")], "actions": [Conf(id="resetpass", method="ResetPass", name=_(u"Reset password"), hidden=False)], "defaultAction": "default" }, "resetpassMail": { "fields": [FieldConf(id="name", name=_("Email"), datatype="string")], "actions": [Conf(id="resetpass", method="ResetPass", name=_(u"Reset password"), hidden=False)], "defaultAction": "default" }, "contact": { "fields": [FieldConf(id="message", name=_("Message"), datatype="text", required=True, size=3000)], "actions": [Conf(id="contact", method="Contact", name=_(u"Send message"), hidden=False)], "defaultAction": Conf(id="default", method="StartRequestPOST", name=_(u"Initialize"), hidden=True) }, } self.css_class = "smallform" self.settings = {}
def AddUser(self, data, activate=None, generatePW=None, generateName=None, mail="default", notifyMail="default", groups=None, currentUser=None, **kw): """ Create a new user with groups for login with name/password :: data: user data as dictionary. groups and pool_state are removed. activate: directly activate the user for login (pool_state=1) generatePW: generate a random password to be send by mail generateName: generate a unique id to be used as username mail: mail object template for confirmation mail notifyMail: mail object template for notify mail groups: initially assign groups to the user currentUser: the currently logged in user for pool_createdby and workflow returns tuple: the user object if succeeds and report list """ report = [] if generateName is None: generateName = self.app.configuration.settings.generateName if generateName: # generate a short uuid name name = self.GenerateID(15) exists = self.GetUserByName(name, activeOnly=0) while exists: name = self.GenerateID(15) exists = self.GetUserByName(name, activeOnly=0) data["name"] = name else: name = data.get("name") if not name or name == "": report.append(_(u"Please enter your username")) return None, report # check user with name exists user = self.GetUserByName(name, activeOnly=0) if user: report.append( _(u"Username '${name}' already in use. Please choose a different name.", mapping={u"name": name})) return None, report email = data.get("email") if email and self.app.configuration.get("loginByEmail"): user = self.GetUserByMail(email, activeOnly=0) if user: report.append( _(u"Email '${name}' already in use. ", mapping={'name': email})) return None, report if generatePW is None: generatePW = self.app.configuration.settings.generatePW if groups is None: groups = self.app.configuration.settings.groups if activate is None: activate = self.app.configuration.settings.activate if generatePW: pw = self.GeneratePassword() data["password"] = pw if groups: data["groups"] = groups if not "token" in data: token = self.GenerateID(30) data["token"] = token data["pool_type"] = u"user" data["pool_state"] = int(activate) data["pool_stag"] = StagUser if not currentUser: currentUser = User(name) obj = self.Create("user", data=data, user=currentUser) if not obj: report.append(_(u"Sorry. Account could not be created.")) return None, report #obj.Commit(currentUser) app = self.app if mail == "default": mail = app.configuration.mailSignup if mail: title = mail.title body = mail(user=obj, **kw) tool = app.GetTool("sendMail") if not tool: raise ConfigurationError, "Mail tool 'sendMail' not found" result, value = tool(body=body, title=title, recvids=[str(obj)], force=1) if not result: report.append(_(u"The email could not be sent.")) return None, report sysadmin = app.configuration.get("userAdmin") if sysadmin: if notifyMail == "default": notifyMail = self.app.configuration.mailNotify if notifyMail: title = notifyMail.title body = notifyMail(user=obj) tool = app.GetTool("sendMail") if not tool: raise ConfigurationError, "Mail tool 'sendMail' not found" result, value = tool(body=body, title=title, recvmails=[sysadmin], force=1) report.append(_(u"Account created.")) return obj, report
from pyramid.renderers import get_renderer, render, render_to_response from nive.definitions import ViewConf, ViewModuleConf, Conf, FieldConf from nive.definitions import IApplication, IUser from nive.components.reform.widget import RadioChoiceWidget from nive_userdb.i18n import _ # view module definition ------------------------------------------------------------------ #@nive_module configuration = ViewModuleConf("nive.adminview.view", id = "useradmin", name = _(u"User management"), containment = IApplication, context = "nive_userdb.useradmin.adminroot.adminroot", view = "nive_userdb.useradmin.view.UsermanagementView", templates = "nive_userdb.useradmin:", template = "nive.adminview:index.pt", permission = "manage users", # user interface configuration listfields = ("pool_state","name","email","groups","lastlogin","id"), addfields = ("name","password","email","groups"), editfields = (FieldConf(id="pool_state", name=_("Active"), datatype="bool", widget=RadioChoiceWidget(values=((u"true", _(u"Yes")),(u"false", _(u"No"))))), "name", FieldConf(id="password", name=_("Password"), datatype="password", settings={"update": True}), "email","groups") )
from nive.definitions import AppConf, GroupConf, Conf from nive.definitions import implements, IUserDatabase, ILocalGroups from nive.security import Allow, Deny, Everyone, Authenticated, ALL_PERMISSIONS, remember, forget from nive.components.objects.base import ApplicationBase from nive.views import Mail from nive.components.reform.schema import Invalid from nive.components.reform.schema import Email from nive.components.reform.schema import Literal, Length from nive_userdb.i18n import _ #@nive_module configuration = AppConf( id = "userdb", title = _(u"Users"), loginByEmail = True, # signup settings settings = Conf( groups=(), activate=1, generatePW=0, generateName=False ), # contact system information #userAdmin = (u"*****@*****.**", u"Admin"), # non-db admin login #admin = {"name": "adminusername", "password": "******", "email": "u"*****@*****.**""},
def AddUser(self, data, activate=None, generatePW=None, generateName=None, mail="default", notifyMail="default", groups=None, currentUser=None, **kw): """ Create a new user with groups for login with name/password :: data: user data as dictionary. groups and pool_state are removed. activate: directly activate the user for login (pool_state=1) generatePW: generate a random password to be send by mail generateName: generate a unique id to be used as username mail: mail object template for confirmation mail notifyMail: mail object template for notify mail groups: initially assign groups to the user currentUser: the currently logged in user for pool_createdby and workflow returns tuple: the user object if succeeds and report list """ report = [] if generateName is None: generateName = self.app.configuration.settings.generateName if generateName: # generate a short uuid name name = self.GenerateID(15) exists = self.GetUserByName(name, activeOnly=0) while exists: name = self.GenerateID(15) exists = self.GetUserByName(name, activeOnly=0) data["name"] = name else: name = data.get("name") if not name or name == "": report.append(_(u"Please enter your username")) return None, report # check user with name exists user = self.GetUserByName(name, activeOnly=0) if user: report.append(_(u"Username '${name}' already in use. Please choose a different name.", mapping={u"name":name})) return None, report email = data.get("email") if email and self.app.configuration.get("loginByEmail"): user = self.GetUserByMail(email, activeOnly=0) if user: report.append(_(u"Email '${name}' already in use. ", mapping={'name':email})) return None, report if generatePW is None: generatePW = self.app.configuration.settings.generatePW if groups is None: groups = self.app.configuration.settings.groups if activate is None: activate = self.app.configuration.settings.activate if generatePW: pw = self.GeneratePassword() data["password"] = pw if groups: data["groups"] = groups if not "token" in data: token = self.GenerateID(30) data["token"] = token data["pool_type"] = u"user" data["pool_state"] = int(activate) data["pool_stag"] = StagUser if not currentUser: currentUser = User(name) obj = self.Create("user", data=data, user=currentUser) if not obj: report.append(_(u"Sorry. Account could not be created.")) return None, report #obj.Commit(currentUser) app = self.app if mail=="default": mail = app.configuration.mailSignup if mail: title = mail.title body = mail(user=obj, **kw) tool = app.GetTool("sendMail") if not tool: raise ConfigurationError, "Mail tool 'sendMail' not found" result, value = tool(body=body, title=title, recvids=[str(obj)], force=1) if not result: report.append(_(u"The email could not be sent.")) return None, report sysadmin = app.configuration.get("userAdmin") if sysadmin: if notifyMail=="default": notifyMail = self.app.configuration.mailNotify if notifyMail: title = notifyMail.title body = notifyMail(user=obj) tool = app.GetTool("sendMail") if not tool: raise ConfigurationError, "Mail tool 'sendMail' not found" result, value = tool(body=body, title=title, recvmails=[sysadmin], force=1) report.append(_(u"Account created.")) return obj, report
""" if isinstance(groups, basestring): return groups in self.groups for g in groups: if g in self.groups: return True return False # user definition ------------------------------------------------------------------ from nive.definitions import StagUser, ObjectConf, FieldConf from nive_userdb.app import UsernameValidator, EmailValidator, PasswordValidator #@nive_module configuration = ObjectConf(id="user", name=_(u"User"), dbparam="users", context="nive_userdb.user.user", template="user.pt", selectTag=StagUser, container=False, description=__doc__) # split the fields up in system and extended data. Makes customizing easier. system = [ FieldConf(id="name", datatype="string", size=30, default=u"", required=1, name=_(u"User ID"),
# -*- coding: utf-8 -*- # Copyright 2012, 2013 Arndt Droullier, Nive GmbH. All rights reserved. # Released under GPL3. See license.txt # __doc__ = """ Root for context to run adminview """ from nive.definitions import RootConf from nive_userdb.root import root from nive_userdb.i18n import _ class adminroot(root): """ """ # Root definition ------------------------------------------------------------------ #@nive_module configuration = RootConf(id="usermanagement", context="nive_userdb.useradmin.adminroot.adminroot", default=False, subtypes="*", name=_(u"User listing"), description="")
from pyramid.renderers import get_renderer, render, render_to_response from nive.definitions import ViewConf, ViewModuleConf, Conf, FieldConf from nive.definitions import IApplication, IUser from nive.components.reform.widget import RadioChoiceWidget from nive_userdb.i18n import _ # view module definition ------------------------------------------------------------------ #@nive_module configuration = ViewModuleConf( "nive.adminview.view", id="useradmin", name=_(u"User management"), containment=IApplication, context="nive_userdb.useradmin.adminroot.adminroot", view="nive_userdb.useradmin.view.UsermanagementView", templates="nive_userdb.useradmin:", template="nive.adminview:index.pt", permission="manage users", # user interface configuration listfields=("pool_state", "name", "email", "groups", "lastlogin", "id"), addfields=("name", "password", "email", "groups"), editfields=(FieldConf( id="pool_state", name=_("Active"), datatype="bool", widget=RadioChoiceWidget(values=((u"true", _(u"Yes")), (u"false", _(u"No"))))), "name",
class root(RootBase): """ """ # field used as unique user identity internally in sessions and cache identityField = u"name" # User account handling ------------------------------------------------------------------------------------------------------ def AddUser(self, data, activate=None, generatePW=None, generateName=None, mail="default", notifyMail="default", groups=None, currentUser=None, **kw): """ Create a new user with groups for login with name/password :: data: user data as dictionary. groups and pool_state are removed. activate: directly activate the user for login (pool_state=1) generatePW: generate a random password to be send by mail generateName: generate a unique id to be used as username mail: mail object template for confirmation mail notifyMail: mail object template for notify mail groups: initially assign groups to the user currentUser: the currently logged in user for pool_createdby and workflow returns tuple: the user object if succeeds and report list """ report = [] if generateName is None: generateName = self.app.configuration.settings.generateName if generateName: # generate a short uuid name name = self.GenerateID(15) exists = self.GetUserByName(name, activeOnly=0) while exists: name = self.GenerateID(15) exists = self.GetUserByName(name, activeOnly=0) data["name"] = name else: name = data.get("name") if not name or name == "": report.append(_(u"Please enter your username")) return None, report # check user with name exists user = self.GetUserByName(name, activeOnly=0) if user: report.append( _(u"Username '${name}' already in use. Please choose a different name.", mapping={u"name": name})) return None, report email = data.get("email") if email and self.app.configuration.get("loginByEmail"): user = self.GetUserByMail(email, activeOnly=0) if user: report.append( _(u"Email '${name}' already in use. ", mapping={'name': email})) return None, report if generatePW is None: generatePW = self.app.configuration.settings.generatePW if groups is None: groups = self.app.configuration.settings.groups if activate is None: activate = self.app.configuration.settings.activate if generatePW: pw = self.GeneratePassword() data["password"] = pw if groups: data["groups"] = groups if not "token" in data: token = self.GenerateID(30) data["token"] = token data["pool_type"] = u"user" data["pool_state"] = int(activate) data["pool_stag"] = StagUser if not currentUser: currentUser = User(name) obj = self.Create("user", data=data, user=currentUser) if not obj: report.append(_(u"Sorry. Account could not be created.")) return None, report #obj.Commit(currentUser) app = self.app if mail == "default": mail = app.configuration.mailSignup if mail: title = mail.title body = mail(user=obj, **kw) tool = app.GetTool("sendMail") if not tool: raise ConfigurationError, "Mail tool 'sendMail' not found" result, value = tool(body=body, title=title, recvids=[str(obj)], force=1) if not result: report.append(_(u"The email could not be sent.")) return None, report sysadmin = app.configuration.get("userAdmin") if sysadmin: if notifyMail == "default": notifyMail = self.app.configuration.mailNotify if notifyMail: title = notifyMail.title body = notifyMail(user=obj) tool = app.GetTool("sendMail") if not tool: raise ConfigurationError, "Mail tool 'sendMail' not found" result, value = tool(body=body, title=title, recvmails=[sysadmin], force=1) report.append(_(u"Account created.")) return obj, report # Login/logout and user sessions ------------------------------------------------------------------------------------------------------ def Login(self, name, password, raiseUnauthorized=1): """ returns user/none and report list """ report = [] # session login user = self.GetUserByName(name) if not user: if raiseUnauthorized: raise Unauthorized, "Login failed" report.append( _(u"Sign in failed. Please check your username and password.")) return None, report if not user.Authenticate(password): if raiseUnauthorized: raise Unauthorized, "Login failed" report.append( _(u"Sign in failed. Please check your username and password.")) return None, report # call user user.Login() report.append(_(u"You are now signed in.")) return user, report def Logout(self, ident): """ Logout and delete session data """ user = self.GetUser(ident) if not user: return False if not IUser.providedBy(user): user = self.LookupUser(id=user.id) if user: user.Logout() return True # changing credentials -------------------------------------------------------------------- def MailVerifyNewEmail(self, name, newmail, mail="default", currentUser=None, **kw): """ returns status and report list """ report = [] if not newmail: report.append(_(u"Please enter your new email address.")) return False, report if isinstance(name, basestring): obj = self.GetUserByName(name) if not obj: report.append(_(u"No matching account found.")) return False, report else: obj = name recv = [(newmail, obj.meta.get("title"))] token = self.GenerateID(20) obj.data["token"] = token obj.data["tempcache"] = "verifymail:" + newmail obj.Commit(user=currentUser) app = self.app if mail == "default": mail = self.app.configuration.mailVerifyMail title = mail.title body = mail(user=obj, **kw) tool = app.GetTool("sendMail") if not tool: raise ConfigurationError, "Mail tool 'sendMail' not found" result, value = tool(body=body, title=title, recvmails=recv, force=1) if not result: report.append(_(u"The email could not be sent.")) return None, report report.append( _(u"The link to verify your new email has been sent by mail.")) return obj, report def MailUserPass(self, name, mail="default", newPassword=None, currentUser=None, **kw): """ Mails a new password or the current password in plain text. returns status and report list """ report = [] if not name: report.append(_(u"Please enter your email address or username.")) return False, report if isinstance(name, basestring): obj = self.GetUserByName(name) if not obj: report.append( _(u"No matching account found. Please try again.")) return False, report else: obj = name email = obj.data.get("email") title = obj.meta.get("title") if email == "": report.append(_("No email address found.")) return False, report recv = [(email, title)] if not newPassword: pwd = self.GenerateID(5) else: pwd = newPassword obj.data["password"] = pwd if mail == "default": try: mail = self.app.configuration.mailSendPass except AttributeError, e: raise ConfigurationError, str(e) title = mail.title body = mail(user=obj, password=pwd, **kw) tool = self.app.GetTool("sendMail") if not tool: raise ConfigurationError, "Mail tool 'sendMail' not found" result, value = tool(body=body, title=title, recvmails=recv, force=1) if not result: report.append(_(u"The email could not be sent.")) return False, report obj.Commit(user=currentUser) report.append( _(u"The new password has been sent to your email address. Please sign in and change it." )) return True, report
app = self.app if mail=="default": try: mail = self.app.configuration.mailResetPass except AttributeError, e: raise ConfigurationError, str(e) if not mail: raise ConfigurationError("Required mailtemplate is required") title = mail.title body = mail(user=obj, **kw) tool = app.GetTool("sendMail") if not tool: raise ConfigurationError, "Mail tool 'sendMail' not found" result, value = tool(body=body, title=title, recvmails=recv, force=1) if not result: report.append(_(u"The email could not be sent.")) return None, report report.append(_(u"The link to reset your password has been sent to your email address.")) return obj, report def DeleteUser(self, ident, currentUser=None): """ returns status and report list """ report = [] if not ident: report.append(_(u"Invalid user.")) return False, report elif isinstance(ident, basestring):
from nive.definitions import ConfigurationError from nive.definitions import IUser from nive.views import BaseView, Unauthorized, Mail from nive.forms import ObjectForm from nive_userdb.i18n import _ from nive_userdb.i18n import translator from nive_userdb.app import EmailValidator, UsernameValidator, OldPwValidator # view module definition ------------------------------------------------------------------ #@nive_module configuration = ViewModuleConf( id = "userview", name = _(u"User signup"), static = "nive_userdb.userview:static", containment = "nive_userdb.app.UserDB", context = "nive_userdb.root.root", view = "nive_userdb.userview.view.UserView", templates = "nive_userdb.userview:", template = "main.pt", permission = "view", assets = (), # form settings: additional slot to configure the forms used in the views form = {} ) t = configuration.templates configuration.views = [ # User Views ViewConf(name="login", attr="login", renderer=t+"loginpage.pt"),
# -*- coding: utf-8 -*- # Copyright 2012, 2013 Arndt Droullier, Nive GmbH. All rights reserved. # Released under GPL3. See license.txt # __doc__ = """ Root for context to run adminview """ from nive.definitions import RootConf from nive_userdb.root import root from nive_userdb.i18n import _ class adminroot(root): """ """ # Root definition ------------------------------------------------------------------ #@nive_module configuration = RootConf( id = "usermanagement", context = "nive_userdb.useradmin.adminroot.adminroot", default = False, subtypes = "*", name = _(u"User listing"), description = "" )
if isinstance(groups, basestring): return groups in self.groups for g in groups: if g in self.groups: return True return False # user definition ------------------------------------------------------------------ from nive.definitions import StagUser, ObjectConf, FieldConf from nive_userdb.app import UsernameValidator, EmailValidator, PasswordValidator #@nive_module configuration = ObjectConf( id = "user", name = _(u"User"), dbparam = "users", context = "nive_userdb.user.user", template = "user.pt", selectTag = StagUser, container = False, description = __doc__ ) # split the fields up in system and extended data. Makes customizing easier. system = [ FieldConf(id="name", datatype="string", size= 30, default=u"", required=1, name=_(u"User ID"), description=u"", validator=UsernameValidator), FieldConf(id="email", datatype="email", size=255, default=u"", required=1, name=_(u"Email"), description=u"", validator=EmailValidator), FieldConf(id="password", datatype="password", size=100, default=u"", required=1, name=_(u"Password"), description=u"",
app = self.app if mail == "default": try: mail = self.app.configuration.mailResetPass except AttributeError, e: raise ConfigurationError, str(e) if not mail: raise ConfigurationError("Required mailtemplate is required") title = mail.title body = mail(user=obj, **kw) tool = app.GetTool("sendMail") if not tool: raise ConfigurationError, "Mail tool 'sendMail' not found" result, value = tool(body=body, title=title, recvmails=recv, force=1) if not result: report.append(_(u"The email could not be sent.")) return None, report report.append( _(u"The link to reset your password has been sent to your email address." )) return obj, report def DeleteUser(self, ident, currentUser=None): """ returns status and report list """ report = [] if not ident: report.append(_(u"Invalid user.")) return False, report
def update(self): """ Renders and executes a web form based on the items configuration values. Form form setup requires the `subset` or list of fields to be used. If nothing is given it defaults to `create`. `subset` is the form identifier used in the items configuration as `form`. **Settings** - *form*: (dict) form definition inlcuding fields and form settings used for the form. - *values*: (dict) default values stored for the new user not include in the form. - *title*: (string) title displayed above the form **Request parameter** - *assets*: You can call `create?assets=only` to get the required css+js assets only. The form iteself will not be processed. **Return values** - *body*: This function returns rendered html code as body. - *X-Result header*: http header indicating whether the new item has been created or not. Form configuration lookup order : 1) Customized `create` view :: update = ViewConf( name="update", attr="update", ... settings={"form": {"fields": ("surname", "lastname")}} ) 2) The types' ObjectConf.forms settings for `newItem` :: user = ObjectConf( id = "user", ... forms = { "create": {"fields": ("email", "name", "password")}, "edit": {"fields": ("surname", "lastname")} }, ... ) defines the `newItem` form in both cases with 2 form fields and to use ajax submissions :: {"fields": ("surname", "lastname"), "use_ajax": True} """ user=self.User(sessionuser=False) subset = values = None title = u"" viewconf = self.GetViewConf() if viewconf and viewconf.get("settings"): subset = viewconf.settings.get("form") title = viewconf.settings.get("title",u"") values = viewconf.settings.get("values") form, subset = self._loadForm(subset, viewconf=viewconf, defaultsubset="edit") if self.GetFormValue("assets")=="only": self.AddHeader("X-Result", "true") return {"content": form.HTMLHead(ignore=[a[0] for a in self.configuration.assets])} if user and user.id == 0: self.AddHeader("X-Result", "false") return {u"content": _(u"Your current user can only be edited on file system level."), u"result": False, u"head": form.HTMLHead(ignore=[a[0] for a in self.configuration.assets]), u"title": title} form.Setup(subset=subset) try: result, data, action = form.Process(values=values) self.AddHeader("X-Result", str(result).lower()) return {u"content": data, u"result": result, u"head": form.HTMLHead(ignore=[a[0] for a in self.configuration.assets]), u"title": title} except Unauthorized: self.AddHeader("X-Result", "false") return {u"content": _(u"User not found"), u"result": False, u"head": form.HTMLHead(ignore=[a[0] for a in self.configuration.assets]), u"title": title}