0

I'm building an application and one of the packages manage multiple auth methods.

Now it supports LDAP and PAM but I want in the future it supports a few more.

I have a package with PAM.py and LDAP.py

for example PAM.py contents:

import pam

class pam_auth:

    def __init__(self, username=None, password=None):
        self.username=username
        self.password=password

    def login(self):        
        res_auth=pam.authenticate(username=self.username, password=password)
        return res_auth

and in another package I have the next class Login:

class Login:

    def __init__(self,method=None):
        self.authmethod=method

    def login(self):        
        res_login=self.authmethod.login()

        return res_login

Now i'm building my auth code like:

p=pam_auth()
p.username="pep"
p.password="just"

l=Login(method=p)
print l.login

And I believe that it is not the best way to do it, and thinking in multiples and different methods to auth. For Example may be something like?:

l=Login(method=PAM.pam_auth)
l.username="pep"
l.password="just"
print l.login()

¿What is that I must change in Login Class or PAM class to work in this way?

ManuParra
  • 1,471
  • 6
  • 18
  • 33

1 Answers1

0

For the change you mentioned, all you need to do is to instanciate the class inside Login's __init__:

class Login:
    def __init__(self,method):
        self.authmethod=method()

However, as Stefano Sanfilippo mentioned, this may actually hamper modularity, since suddenly Login must know the constructor parameters of the authentication method.


A couple more tips:

If you're writing python 2, you'll want to create new-style classes:

instead of

class Login:

use

class Login(object):

Also, if you're writing a general authentication layer, you probably don't want to deal explicitly with usernames and passwords: what will happen when you want to use third-factor, smartcard or biometric authentication in the future? You probably should deal with opaque "data", that the authentication method receives, unaltered.

Community
  • 1
  • 1
loopbackbee
  • 21,962
  • 10
  • 62
  • 97
  • And nothing more for example for the parameters from de PAM Class? – ManuParra Jan 14 '14 at 11:19
  • Yes my idea is that you can override a class and support, not only username or password, also each parameter related to the authentication method. As you say, biometrics, etc. don require usename, etc. – ManuParra Jan 14 '14 at 11:21
  • @ManuParra As I said, if you go for this approach, Login "must know the constructor parameters of the authentication method.". The big problem is that those constructor parameters will vary depending on the auth method. You could pass them as `*args, **kwargs`, but it's really best to just instantiate it outside Login and pass it a instance, as you're currently doing. – loopbackbee Jan 14 '14 at 11:29