Recipe 10.3. Authenticating Users by Means of a POP Server
Credit: Magnus Lyckå
Problem
You are writing a Python
application that must authenticate users. All of the users have
accounts on some POP servers, and you'd like to
reuse, for your own authentication, the user IDs and passwords that
your users have on those servers.
Solution
To log into the application, a user must provide the server, user ID
and password for his mail account. We try logging into that POP
server with these credentialsif that attempt succeeds, then
the user has authenticated successfully. (Of course, we
don't peek into the
user's mailbox!)
def popauth(popHost, user, passwd):
"" Log in and log out, only to verify user identity.
Raise exception in case of failure.
""
import poplib
try:
pop = poplib.POP3(popHost)
except:
raise RuntimeError("Could not establish connection "
"to %r for password check" % popHost)
try:
# Log in and perform a small sanity check
pop.user(user)
pop.pass_(passwd)
length, size = pop.stat( )
assert type(length) == type(size) == int
pop.quit( )
except:
raise RuntimeError("Could not verify identity. \n"
"User name %r or password incorrect." % user)
pop.quit( )
Discussion
To use this recipe, the application must store somewhere the list of
known users and either the single POP server they all share, or the
specific POP server on which each user authenticatesit need
not be the same POP server for all users. Either
a text file, or a simple table in any kind of database, will do just
fine for this purpose.This solution is neat, but it does have some weaknesses:
- Users must trust that any application implementing this
authentication system won't abuse their email
accounts. - POP passwords are, alas!, sent in plain text over the Internet.
- We have to trust that the POP server security isn't
compromised. - Logging in might take a few seconds if the POP server is slow.
- Logging in won't work if the POP server is down.
However, to offset all of these potential drawbacks is the
convenience of applications not having to store any passwords, nor
forcing a poor overworked system administrator to administer password
changes. It's also quite simple! In short, I
wouldn't use this approach for a bank system, but I
would have no qualms using it, for example, to give users rights to
edit web pages at a somewhat restricted WikiWiki, or similarly
low-risk applications.
See Also
Documentation of the standard library module
poplib in the Library
Reference and Python in a
Nutshell.