def testSessionHasRoleSessionNotInDbRoleNotInDb(self): conn = sqlite3.connect(":memory:") UserDatabase().createDatabase(conn) token = "hello" role = "admin" result = UserDatabase().sessionHasRole(token, role, conn) expectedResult = False self.assertEqual(expectedResult, result)
def testSendActivationEmail(self): conn = self.inMemoryDatabaseConnection(); userId = 3 email = "*****@*****.**" c = conn.cursor() c.execute("insert into user(id, email) values(?, ?)", (userId, email)) sender = DummyEmailSender() userDb = UserDatabase(emailSender=sender) userDb.sendActivationEmail(userId, conn) self.assertEquals([email], sender.messages[0].addressees)
def testSessionHasRoleSessionNotInDbRoleInDb(self): conn = sqlite3.connect(":memory:") UserDatabase().createDatabase(conn) token = "hello" role = "admin" c = conn.cursor() c.execute("insert into role (id, role) values (?, ?)", (1, role)) result = UserDatabase().sessionHasRole(token, role, conn) expectedResult = False self.assertEqual(expectedResult, result)
def testLoginConnectionNotSpecifiedIDNotFound(self): dbName = "users/users.db" database = UserDatabase(dbName) database.createDatabase(None, True) try: database.login("hello", "goodbye") self.fail("Should have thrown an exception") except UserException as ex: self.assertEquals(UserException.emailOrPasswordNotFound, ex.message) self.assertEquals(None, ex.cause)
def testSendActivationEmail(self): conn = self.inMemoryDatabaseConnection() userId = 3 email = "*****@*****.**" c = conn.cursor() c.execute("insert into user(id, email) values(?, ?)", (userId, email)) sender = DummyEmailSender() userDb = UserDatabase(emailSender=sender) userDb.sendActivationEmail(userId, conn) self.assertEquals([email], sender.messages[0].addressees)
def testActivateUserIdNotFoundConnectionNotSpecified(self): dbName = "users/users.db" database = UserDatabase(dbName) database.createDatabase(None, True) userId = 3 try: database.activateUser(userId) self.fail("Should have thrown an exception") except UserException as ex: self.assertEqual(UserException.userNotFound, ex.message) self.assertEqual(None, ex.cause)
def testActivateUserIdFoundAndInactive(self): conn = self.inMemoryDatabaseConnection(); userId = 3 c = conn.cursor() c.execute("insert into user(id, status) values(?, ?)", (userId, UserDatabase.inactiveStatus)) userDb = UserDatabase() userDb.emailSender = DummyEmailSender() userDb.activateUser(userId, conn) row = c.execute("select status from user where id = ?", (userId,)).fetchone() self.assertEquals((UserDatabase.activeStatus,), row) self.assertEquals([Settings.adminEmail], userDb.emailSender.messages[0].addressees)
def testRemindOfPasswordEmailExists(self): conn = self.inMemoryDatabaseConnection() email = "jeremy" password = "******" c = conn.cursor() c.execute("insert into user (id, email) values (?, ?)", (1, email)) c.execute("insert into password (id, password) values (?, ?)", (1, password)) userDb = UserDatabase() userDb.emailSender = DummyEmailSender() userDb.remindOfPassword(email, conn) self.assertEquals([email], userDb.emailSender.messages[0].addressees)
def testCheckSessionConnectionNotSpecifiedTokenDoesNotExist(self): token = "theToken" dbName = "users/users.db" database = UserDatabase(dbName) database.createDatabase(None, True) try: UserDatabase(dbName).checkSessionToken(token) self.fail("Should have thrown an exception") except UserException as ex: self.assertEquals(UserException.sessionExpired, ex.message) self.assertEquals(None, ex.cause)
def testRemindOfPasswordEmailDoesNotExist(self): conn = self.inMemoryDatabaseConnection() email = "jeremy" userDb = UserDatabase() userDb.emailSender = DummyEmailSender() try: userDb.remindOfPassword(email, conn) self.fail("Should have thrown an exception") except UserException as ex: self.assertEquals(UserException.emailNotFound, ex.message) self.assertEquals(None, ex.cause)
def testActivateUserIdFoundAndInactive(self): conn = self.inMemoryDatabaseConnection() userId = 3 c = conn.cursor() c.execute("insert into user(id, status) values(?, ?)", (userId, UserDatabase.inactiveStatus)) userDb = UserDatabase() userDb.emailSender = DummyEmailSender() userDb.activateUser(userId, conn) row = c.execute("select status from user where id = ?", (userId, )).fetchone() self.assertEquals((UserDatabase.activeStatus, ), row) self.assertEquals([Settings.adminEmail], userDb.emailSender.messages[0].addressees)
class UserActivation(Page): def __init__(self, pageId, params={}): Page.__init__(self, pageId, params) self.userDb = UserDatabase() def getTitle(self): answer = "SEHICL User Activation" return answer def getContent(self): answer = self.getActivationPage() return answer def getActivationPage(self): html = """ <h1>Activation successful</h1> <p>You have successfully activated the following account:</p> <ul> <li>Name: {user.name}</li> <li>E-mail: {user.email}</li> <li>Club: {user.club}</li> </ul> """ userId = self.allParams.get("user") try: userDetails = self.userDb.activateUser(userId) answer = html.format(user=userDetails) except UserException: answer = """ <h1>Activation failed</h1> <p>No user was found with the specified identity.</p> """ return answer
def testRegisterEmailDoesNotAlreadyExistClubNotSpecified(self): conn = self.inMemoryDatabaseConnection() email = "jeremy" name = "Jeremy" club = None password = "******" userDb = UserDatabase() userDb.emailSender = DummyEmailSender() result = userDb.registerUser(email, name, club, password, conn) c = conn.cursor() row = c.execute("select id, email, name, club, status from user").fetchone() self.assertEquals((result, email, name, club, UserDatabase.inactiveStatus), row) row = c.execute("select password from password where id = ?", (result,)).fetchone() self.assertEquals((password,), row) self.assertEquals([email], userDb.emailSender.messages[0].addressees) self.assertEquals([Settings.adminEmail], userDb.emailSender.messages[1].addressees)
def testRegisterBlocked(self): conn = self.inMemoryDatabaseConnection() email = "*****@*****.**" name = "Jeremy" club = None password = "******" userDb = UserDatabase() userDb.emailSender = DummyEmailSender() result = userDb.registerUser(email, name, club, password, conn) self.assertEquals(-1, result) c = conn.cursor() row = c.execute("select id, email, name, club, status from user").fetchone() self.assertEquals(None, row) row = c.execute("select password from password where id = ?", (result,)).fetchone() self.assertEquals(None, row) self.assertEquals([], userDb.emailSender.messages)
def testCheckSessionTokenExistsAndHasNotExpired(self): token = "theToken" conn = self.inMemoryDatabaseConnection() conn.cursor().execute( "insert into session(id, token, expiry) values(1, ?, datetime('now', '+2 minutes', 'localtime'))", (token, )) UserDatabase().checkSessionToken(token, conn)
def testRegisterEmailDoesNotAlreadyExistClubSpecifiedConnectionNotSpecified( self): dbName = "users/users.db" userDb = UserDatabase(dbName) userDb.emailSender = DummyEmailSender() userDb.createDatabase(None, True) email = "jeremy" name = "Jeremy" club = "Rotherham" password = "******" result = userDb.registerUser(email, name, club, password) conn = userDb.getConnection(None) c = conn.cursor() try: row = c.execute( "select id, email, name, club, status from user").fetchone() self.assertEquals( (result, email, name, club, UserDatabase.inactiveStatus), row) row = c.execute("select password from password where id = ?", (result, )).fetchone() self.assertEquals((password, ), row) finally: conn.close() self.assertEquals([email], userDb.emailSender.messages[0].addressees) self.assertEquals([Settings.adminEmail], userDb.emailSender.messages[1].addressees)
def testLoginUserIDNotFound(self): conn = self.inMemoryDatabaseConnection() try: UserDatabase().login("hello", "goodbye", conn) self.fail("Should have thrown an exception") except UserException as ex: self.assertEquals(UserException.emailOrPasswordNotFound, ex.message) self.assertEquals(None, ex.cause)
def testRegisterBlocked(self): conn = self.inMemoryDatabaseConnection() email = "*****@*****.**" name = "Jeremy" club = None password = "******" userDb = UserDatabase() userDb.emailSender = DummyEmailSender() result = userDb.registerUser(email, name, club, password, conn) self.assertEquals(-1, result) c = conn.cursor() row = c.execute( "select id, email, name, club, status from user").fetchone() self.assertEquals(None, row) row = c.execute("select password from password where id = ?", (result, )).fetchone() self.assertEquals(None, row) self.assertEquals([], userDb.emailSender.messages)
def testCheckSessionTokenDoesNotExist(self): token = "theToken" conn = self.inMemoryDatabaseConnection() try: UserDatabase().checkSessionToken(token, conn) self.fail("Should have thrown an exception") except UserException as ex: self.assertEquals(UserException.sessionExpired, ex.message) self.assertEquals(None, ex.cause)
def testRegisterEmailDoesNotAlreadyExistClubNotSpecified(self): conn = self.inMemoryDatabaseConnection() email = "jeremy" name = "Jeremy" club = None password = "******" userDb = UserDatabase() userDb.emailSender = DummyEmailSender() result = userDb.registerUser(email, name, club, password, conn) c = conn.cursor() row = c.execute( "select id, email, name, club, status from user").fetchone() self.assertEquals( (result, email, name, club, UserDatabase.inactiveStatus), row) row = c.execute("select password from password where id = ?", (result, )).fetchone() self.assertEquals((password, ), row) self.assertEquals([email], userDb.emailSender.messages[0].addressees) self.assertEquals([Settings.adminEmail], userDb.emailSender.messages[1].addressees)
def getContent(self, externalConn=None): action = self.allParams.get("action", None) if action is None: answer = self.getUserListPage(externalConn) elif action == "delete": answer = self.getUserDeleteConfirmationPage( self.allParams.get("user", None), externalConn) elif action == "togglestatus": currentStatus = self.allParams.get("status", None) UserDatabase().toggleUserStatus(self.allParams.get("user", None), currentStatus, externalConn) answer = self.getUserListPage(externalConn) elif action == "confirmdelete": UserDatabase().deleteUser(self.allParams.get("user", None), externalConn) answer = self.getUserListPage(externalConn) elif action == "canceldelete": answer = self.getUserListPage(externalConn) else: answer = action return answer
def testCheckSessionTokenExistsButHasExpired(self): token = "theToken" conn = self.inMemoryDatabaseConnection() conn.cursor().execute( "insert into session(id, token, expiry) values(1, ?, datetime('now', '-2 minutes', 'localtime'))", (token, )) try: UserDatabase().checkSessionToken(token, conn) self.fail("Should have thrown an exception") except UserException as ex: self.assertEquals(UserException.sessionExpired, ex.message) self.assertEquals(None, ex.cause)
def testClearExpiredSessions(self): conn = self.inMemoryDatabaseConnection() c = conn.cursor() now = datetime.now() for i in range(-3, 4, 2): date = now + timedelta(seconds=i) c.execute("insert into session(id, token, expiry) values(?, ?, ?)", (i + 12, "token{0}".format(i), date)) count = c.execute("select count(*) from session").fetchone()[0] self.assertEquals(4, count) UserDatabase().clearExpiredSessions(conn) count = c.execute("select count(*) from session").fetchone()[0] self.assertEquals(2, count)
def testRegisterEmailAlreadyExists(self): conn = self.inMemoryDatabaseConnection() email = "jeremy" name = "Jeremy" team = "Rotherham" password = "******" conn.cursor().execute("insert into user (email) values('jeremy')") try: UserDatabase().registerUser(email, name, team, password, conn) self.fail("Should have thrown an exception") except UserException as ex: self.assertEquals(UserException.emailAlreadyExists, ex.message) self.assertEquals(None, ex.cause)
def testLoginUserIDFoundPasswordCorrectUserInactive(self): conn = self.inMemoryDatabaseConnection() try: c = conn.cursor() c.execute("insert into user (name, email, status) values(?, ?, ?)", ("Jeremy", "hello", UserDatabase.inactiveStatus)) userId = c.execute("select last_insert_rowid()").fetchone()[0] c.execute("insert into password(id, password) values(?, ?)", (userId, "goodbye")) UserDatabase().login("hello", "goodbye", conn) self.fail("Should have thrown an exception") except UserException as ex: self.assertEquals(UserException.userNotActive, ex.message) self.assertEquals(None, ex.cause)
def getUsers(self, externalConn=None): html = """ <tr> <td class="userid">{user.userId}</td> <td class="name">{user.name}</td> <td class="email">{user.email}</td> <td class="club">{club}</td> <td class="status action">{user.status}</td> <td class="action"> {statusform} </td> <!-- <td class="failurecount">{user.failurecount}</td> --> <td class="roles">{roles}</td> <td class="action"> {deleteform} </td> <!-- <td class="action"> <form action="{thispage.url}" method="post"> <input type="hidden" name="action" value="addrole"> <input type="hidden" name="user" value="{user.userId}"> <input type="text" name="role"> <input type="submit" value="Add role"> </form> </td> --> </tr> """ answer = [] for user in UserDatabase().getUserList(externalConn): club = "" if user.club is None else user.club thisPage = PageLink(self.pageId, self) roles = string.join(user.roles, ",") deleteForm = self.getUserDeleteActionForm(user, thisPage) statusForm = self.getToggleUserStatusActionForm(user, thisPage) answer.append( html.format(user=user, club=club, roles=roles, thispage=thisPage, deleteform=deleteForm, statusform=statusForm)) return answer
def testLoginUserIDFoundPasswordCorrectUserActive(self): conn = self.inMemoryDatabaseConnection() c = conn.cursor() c.execute("insert into user (name, email, status) values(?, ?, ?)", ("Jeremy", "hello", UserDatabase.activeStatus)) userId = c.execute("select last_insert_rowid()").fetchone()[0] c.execute("insert into password(id, password) values(?, ?)", (userId, "goodbye")) random.seed(123) result = UserDatabase().login("hello", "goodbye", conn) expectedToken = "1D67B3" self.assertEquals(expectedToken, result) expiry, token = c.execute( "select s.expiry, s.token from session s, user u where s.id = u.id" ).fetchone() self.assertEquals(expectedToken, token) expectedDate = datetime.now() + timedelta(1) msg = "{0}, {1}".format(expectedDate, expiry) self.assertTrue( expectedDate - datetime.strptime(expiry, "%Y-%m-%d %H:%M:%S") < timedelta(0, 1), msg)
def getUserDeleteConfirmationPage(self, userId, externalConn=None): html = """ <h1>Please confirm</h1> <p>You have requested to delete the user with the following details:</p> <table> <tr><td>User ID: {user.userId}</td></tr> <tr><td>Name: {user.name}</td></tr> <tr><td>E-mail: {user.email}</td></tr> <tr><td>Club: {club}</td></tr> <tr><td>Roles: {roles}</td></tr> </table> <p>Press Delete to confirm and delete this user, or Cancel to cancel the deletion.</p> <table id="users"> <tr> <td class="action"> <form action="{thispage.url}" method="post"> <input type="hidden" name="action" value="confirmdelete"> <input type="hidden" name="user" value="{user.userId}"> <input type="submit" value="Delete"> </form> </td> <td> <form action="{thispage.url}" method="post"> <input type="hidden" name="action" value="canceldelete"> <input type="submit" value="Cancel"> </form> </td> </tr> </table> """ user = UserDatabase().getUserDetails(userId, externalConn) club = "" if user.club is None else user.club thisPage = PageLink(self.pageId, self) roles = string.join(user.roles, ",") answer = html.format(user=user, club=club, thispage=thisPage, roles=roles) return answer
def testRegisterEmailDoesNotAlreadyExistClubSpecifiedConnectionNotSpecified(self): dbName = "users/users.db" userDb = UserDatabase(dbName) userDb.emailSender = DummyEmailSender() userDb.createDatabase(None, True) email = "jeremy" name = "Jeremy" club = "Rotherham" password = "******" result = userDb.registerUser(email, name, club, password) conn = userDb.getConnection(None) c = conn.cursor() try: row = c.execute("select id, email, name, club, status from user").fetchone() self.assertEquals((result, email, name, club, UserDatabase.inactiveStatus), row) row = c.execute("select password from password where id = ?", (result,)).fetchone() self.assertEquals((password,), row) finally: conn.close() self.assertEquals([email], userDb.emailSender.messages[0].addressees) self.assertEquals([Settings.adminEmail], userDb.emailSender.messages[1].addressees)
import sqlite3 from userdb.userdb import UserDatabase from test.users.userdbtest import DummyEmailSender conn = sqlite3.connect("users/users.db") userDb = UserDatabase(emailSender=DummyEmailSender()) userDb.createDatabase(conn, True) userId = userDb.registerUser("*****@*****.**", "User Admin", None, "wceag1es", conn) userDb.activateUser(userId, conn) conn.cursor().execute("insert into role (id, role) values(?, 'admin')", (userId, )) conn.commit() conn.close()
class UserRegistration(Page): def __init__(self, pageId, params={}): Page.__init__(self, pageId, params) self.userDb = UserDatabase() def getTitle(self): answer = "SEHICL User Registration" return answer def getContent(self): if (self.allParams.get("displayed", None) == "true"): processingOutcome = self.processRegistrationData() if processingOutcome.valid: answer = self.getRegistrationConfirmationPage() else: answer = self.getRegistrationPage(processingOutcome) else: answer = self.getRegistrationPage() return answer def getRegistrationPage(self, validation=RegistrationValidation()): html = """ <h1>New user registration</h1> <p> Please fill in the fields below and press "Submit". All fields marked with "*" must be completed. </p> <form action="{submit.url}" method="post"> <input type="hidden" name="displayed" value="true"> <input type="hidden" name="forward" value="{forward}"> <table> <tr> <td>Name</td> <td>*</td> <td><input type="text" name="name" value="{valid.name}"></td> <td>{valid.nameMessage}</td> </tr> <tr> <td>Club</td> <td></td> <td><input type="text" name="club" value="{club}"></td> <td>{valid.clubMessage}</td> </tr> <tr> <td>E-mail address</td> <td>*</td> <td><input type="text" name="email" value="{valid.email}"></td> <td>{valid.emailMessage}</td> </tr> <tr> <td>Password</td> <td>*</td> <td><input type="password" name="password""></td> <td>{valid.passwordMessage}</td> </tr> <tr> <td>Confirm password</td> <td>*</td> <td><input type="password" name="passwordconf""></td> <td>{valid.passwordconfMessage}</td> </tr> </table> <p> By clicking the "Submit" button below, you agree that: <ul> <li> We may store the information you have supplied on a computer system, and we may use it only for the purpose of administering your rights as a registered user of this site. We will never give your details to any other party. </li> <li> You will treat all information to which your login gives you access with appropriate care and respect. In particular, where that information comprises other people's personal details, you may use it only for legitimate purposes connected with the League, unless you first gain the explicit consent of the person or persons concerned. </li> </ul> </p> <p> <input type="Submit" value="Submit"> </p> </form> """ submitLink = PageLink("register", self) club = "" if validation.club is None else validation.club forward = self.allParams.get("forward", PageLink(None, self).url) answer = html.format(submit=submitLink, valid=validation, forward=forward, club=club) return answer def processRegistrationData(self): answer = RegistrationValidation() answer.name = string.strip(self.allParams.get("name", "")) if answer.name == "": answer.valid = False answer.nameMessage = "Please specify your name." club = self.allParams.get("club", None) if club is not None: club = string.strip(club) if club == "": club = None answer.club = club answer.email = string.strip(self.allParams.get("email", "")) if answer.email == "": answer.valid = False answer.emailMessage = "Please specify your e-mail address." answer.password = string.strip(self.allParams.get("password", "")) if answer.password == "": answer.valid = False answer.passwordMessage = "Please specify your password." answer.passwordconf = string.strip( self.allParams.get("passwordconf", "")) if answer.passwordconf == "": answer.valid = False answer.passwordconfMessage = "Please confirm your password." elif answer.passwordconf != answer.password: answer.valid = False answer.passwordconfMessage = "Password and Confirm password must be the same." if answer.valid: try: self.userDb.registerUser(answer.email, answer.name, answer.club, answer.password) except UserException as ex: answer.valid = False answer.emailMessage = ex.message return answer def getRegistrationConfirmationPage(self): html = """ <h1>Registration successful</h1> <p>Thank you for registering. Your account has been set up, but needs to be activated.</p> <p>An e-mail has been sent to {email}. It contains a link, which you need to click in order to activate the account. Once you have done this the account will be active and you will be able to log in.</p> """ answer = html.format(email=self.allParams["email"]) return answer
class UserLogin(Page): msgKeyNoLogin = "******" msgKeyNoAuth = "noAuth" messages = {} messages[ msgKeyNoLogin] = "You must be logged in to view the requested page." messages[ msgKeyNoAuth] = "You do not have the necessary authority ('{role}') to view the requested page." def __init__(self, pageId, params={}): Page.__init__(self, pageId, params) self.userDb = UserDatabase() def getTitle(self): answer = "SEHICL User Login" return answer def getContent(self): if (self.allParams.get("displayed", None) == "true"): processingOutcome = self.processLoginData() if processingOutcome.valid: if processingOutcome.token is not None: self.allParams["session"] = processingOutcome.token pageLink = PageLink(self.allParams["forward"], self) raise RedirectException(pageLink) else: answer = self.getLoginPage(processingOutcome) else: answer = self.getLoginPage(processingOutcome) else: answer = self.getLoginPage() return answer def getLoginPage(self, validation=LoginValidation()): html = """ <h1>Login</h1> {message} <p> If you do not have a login, <a href="{register.url}">register here</a>.<br> Please note that if you registered for a login during the 2012-13 season, that login no longer works and you must re-register. </p> <p> If you have already registered, please fill in the fields below and press "Login". If you cannot remember your password, fill in the e-mail address and press "Remind"; if the e-mail address you specify is that of a registered user, a password reminder will be sent to that address. </p> <form action="{submit.url}" method="post"> <input type="hidden" name="displayed" value="true"> <table> <tr> <td>E-mail address</td> <td><input type="text" name="email" value="{valid.email}"></td> <td>{valid.emailMessage}</td> </tr> <tr> <td>Password</td> <td><input type="password" name="password" value="{valid.password}"></td> <td>{valid.passwordMessage}</td> </tr> </table> <p> <input name="button" type="Submit" value="Login"> <input name="button" type="Submit" value="Remind"> </p> </form> """ params = {} for k, v in self.allParams.items(): if k in ("message", "role", "forward"): params[k] = v submitLink = PageLink("login", self, params) registerLink = PageLink("register", self) msgKey = self.allParams.get("message", None) msgTemplate = self.messages.get(msgKey, "") message = msgTemplate.format(role=self.allParams.get("role", None)) answer = html.format(submit=submitLink, valid=validation, message=message, register=registerLink) return answer def processLoginData(self): answer = LoginValidation() buttonPressed = self.allParams.get("button", "") answer.email = string.strip(self.allParams.get("email", "")) if answer.email == "": answer.valid = False answer.emailMessage = "Please specify your e-mail address." if buttonPressed != "Remind": answer.password = string.strip(self.allParams.get("password", "")) if answer.password == "": answer.valid = False answer.passwordMessage = "Please specify your password." if answer.valid: try: if buttonPressed == "Remind": self.userDb.remindOfPassword(answer.email) answer.token = None answer.emailMessage = "A password reminder has been sent to this address." else: answer.token = self.userDb.login(answer.email, answer.password) except UserException as ex: answer.valid = False answer.emailMessage = ex.message return answer
def __init__(self, pageId, params={}): Page.__init__(self, pageId, params) self.userDb = UserDatabase()
class UserRegistration(Page): def __init__(self, pageId, params={}): Page.__init__(self, pageId, params) self.userDb = UserDatabase() def getTitle(self): answer = "SEHICL User Registration" return answer def getContent(self): if (self.allParams.get("displayed", None) == "true"): processingOutcome = self.processRegistrationData() if processingOutcome.valid: answer = self.getRegistrationConfirmationPage() else: answer = self.getRegistrationPage(processingOutcome) else: answer = self.getRegistrationPage() return answer def getRegistrationPage(self, validation=RegistrationValidation()): html = """ <h1>New user registration</h1> <p> Please fill in the fields below and press "Submit". All fields marked with "*" must be completed. </p> <form action="{submit.url}" method="post"> <input type="hidden" name="displayed" value="true"> <input type="hidden" name="forward" value="{forward}"> <table> <tr> <td>Name</td> <td>*</td> <td><input type="text" name="name" value="{valid.name}"></td> <td>{valid.nameMessage}</td> </tr> <tr> <td>Club</td> <td></td> <td><input type="text" name="club" value="{club}"></td> <td>{valid.clubMessage}</td> </tr> <tr> <td>E-mail address</td> <td>*</td> <td><input type="text" name="email" value="{valid.email}"></td> <td>{valid.emailMessage}</td> </tr> <tr> <td>Password</td> <td>*</td> <td><input type="password" name="password""></td> <td>{valid.passwordMessage}</td> </tr> <tr> <td>Confirm password</td> <td>*</td> <td><input type="password" name="passwordconf""></td> <td>{valid.passwordconfMessage}</td> </tr> </table> <p> By clicking the "Submit" button below, you agree that: <ul> <li> We may store the information you have supplied on a computer system, and we may use it only for the purpose of administering your rights as a registered user of this site. We will never give your details to any other party. </li> <li> You will treat all information to which your login gives you access with appropriate care and respect. In particular, where that information comprises other people's personal details, you may use it only for legitimate purposes connected with the League, unless you first gain the explicit consent of the person or persons concerned. </li> </ul> </p> <p> <input type="Submit" value="Submit"> </p> </form> """ submitLink = PageLink("register", self) club = "" if validation.club is None else validation.club forward = self.allParams.get("forward", PageLink(None, self).url) answer = html.format(submit=submitLink, valid=validation, forward=forward, club=club) return answer def processRegistrationData(self): answer = RegistrationValidation() answer.name = string.strip(self.allParams.get("name", "")) if answer.name == "": answer.valid = False answer.nameMessage = "Please specify your name." club = self.allParams.get("club", None) if club is not None: club = string.strip(club) if club == "": club = None answer.club = club answer.email = string.strip(self.allParams.get("email", "")) if answer.email == "": answer.valid = False answer.emailMessage = "Please specify your e-mail address." answer.password = string.strip(self.allParams.get("password", "")) if answer.password == "": answer.valid = False answer.passwordMessage = "Please specify your password." answer.passwordconf = string.strip(self.allParams.get("passwordconf", "")) if answer.passwordconf == "": answer.valid = False answer.passwordconfMessage = "Please confirm your password." elif answer.passwordconf != answer.password: answer.valid = False answer.passwordconfMessage = "Password and Confirm password must be the same." if answer.valid: try: self.userDb.registerUser(answer.email, answer.name, answer.club, answer.password) except UserException as ex: answer.valid = False answer.emailMessage = ex.message return answer def getRegistrationConfirmationPage(self): html = """ <h1>Registration successful</h1> <p>Thank you for registering. Your account has been set up, but needs to be activated.</p> <p>An e-mail has been sent to {email}. It contains a link, which you need to click in order to activate the account. Once you have done this the account will be active and you will be able to log in.</p> """ answer = html.format(email=self.allParams["email"]) return answer
class UserLogin(Page): msgKeyNoLogin = "******" msgKeyNoAuth = "noAuth" messages = {} messages[msgKeyNoLogin] = "You must be logged in to view the requested page." messages[msgKeyNoAuth] = "You do not have the necessary authority ('{role}') to view the requested page." def __init__(self, pageId, params={}): Page.__init__(self, pageId, params) self.userDb = UserDatabase() def getTitle(self): answer = "SEHICL User Login" return answer def getContent(self): if (self.allParams.get("displayed", None) == "true"): processingOutcome = self.processLoginData() if processingOutcome.valid: if processingOutcome.token is not None: self.allParams["session"] = processingOutcome.token pageLink = PageLink(self.allParams["forward"], self) raise RedirectException(pageLink) else: answer = self.getLoginPage(processingOutcome) else: answer = self.getLoginPage(processingOutcome) else: answer = self.getLoginPage() return answer def getLoginPage(self, validation=LoginValidation()): html = """ <h1>Login</h1> {message} <p> If you do not have a login, <a href="{register.url}">register here</a>.<br> Please note that if you registered for a login during the 2012-13 season, that login no longer works and you must re-register. </p> <p> If you have already registered, please fill in the fields below and press "Login". If you cannot remember your password, fill in the e-mail address and press "Remind"; if the e-mail address you specify is that of a registered user, a password reminder will be sent to that address. </p> <form action="{submit.url}" method="post"> <input type="hidden" name="displayed" value="true"> <table> <tr> <td>E-mail address</td> <td><input type="text" name="email" value="{valid.email}"></td> <td>{valid.emailMessage}</td> </tr> <tr> <td>Password</td> <td><input type="password" name="password" value="{valid.password}"></td> <td>{valid.passwordMessage}</td> </tr> </table> <p> <input name="button" type="Submit" value="Login"> <input name="button" type="Submit" value="Remind"> </p> </form> """ params = {} for k, v in self.allParams.items(): if k in ("message", "role", "forward"): params[k] = v submitLink = PageLink("login", self, params) registerLink = PageLink("register", self) msgKey = self.allParams.get("message", None) msgTemplate = self.messages.get(msgKey, "") message = msgTemplate.format(role=self.allParams.get("role", None)) answer = html.format(submit=submitLink, valid=validation, message=message, register=registerLink) return answer def processLoginData(self): answer = LoginValidation() buttonPressed = self.allParams.get("button", "") answer.email = string.strip(self.allParams.get("email", "")) if answer.email == "": answer.valid = False answer.emailMessage = "Please specify your e-mail address." if buttonPressed != "Remind": answer.password = string.strip(self.allParams.get("password", "")) if answer.password == "": answer.valid = False answer.passwordMessage = "Please specify your password." if answer.valid: try: if buttonPressed == "Remind": self.userDb.remindOfPassword(answer.email) answer.token = None answer.emailMessage = "A password reminder has been sent to this address." else: answer.token = self.userDb.login(answer.email, answer.password) except UserException as ex: answer.valid = False answer.emailMessage = ex.message return answer
def testGenerateToken(self): random.seed(123) result = UserDatabase().generateToken(12411) self.assertEquals("307BD67B3", result)
def inMemoryDatabaseConnection(self): dbName = ":memory:" conn = sqlite3.connect(dbName) UserDatabase().createDatabase(conn) return conn