Skip to content

Instantly share code, notes, and snippets.

@danielatdattrixdotcom
Created July 10, 2012 22:56
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save danielatdattrixdotcom/3086768 to your computer and use it in GitHub Desktop.
Save danielatdattrixdotcom/3086768 to your computer and use it in GitHub Desktop.
Django authentication backend using a Magento API
from django.contrib.auth.models import User
from magento import Customer
import hashlib
import random
# Requires magento - http://pypi.python.org/pypi/magento
# Note proper use of HTTP/HTTPS for your setup
# If you run multiple stores, set STORE_ID and WEBSITE_ID as-needed or adapt to your setup
class Magento:
URL = "https://127.0.0.1/"
USERNAME = 'MAGENTO_API_USER'
PASSWORD = 'MAGENTO_API_USER_PASSWORD'
STORE_ID = 1
WEBSITE_ID = 1
FORGOT_URL = '%scustomer/account/forgotpasswordpost/' % (URL)
def authenticate(self, username=None, password=None):
with Customer(self.URL, self.USERNAME, self.PASSWORD) as customer_api:
cust = customer_api.list({'email': {'eq': username}, 'store_id': {'eq': self.STORE_ID}})
if len(cust) == 1:
(hash_pass, salt) = cust[0]['password_hash'].split(':')
ph = '%s%s' % (salt, password)
ph = hashlib.md5(ph).hexdigest()
if ph == hash_pass:
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
user = User(username=username, password=random.getrandbits(128))
user.first_name = cust[0]['firstname']
user.last_name = cust[0]['lastname']
user.email = cust[0]['email']
user.is_staff = False
user.is_superuser = False
user.save()
return user
else:
return None
else:
return None
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
@staticmethod
def create_user(user_dict):
""" user_dict: Expects firstname, lastname, email, password """
with Customer(Magento.URL, Magento.USERNAME, Magento.PASSWORD) as customer_api:
cust = customer_api.list({'email': {'eq': user_dict['email']}, 'store_id': {'eq': Magento.STORE_ID}})
if len(cust) == 0:
user_dict['website_id'] = Magento.WEBSITE_ID
user_dict['store_id'] = Magento.STORE_ID
with Customer(Magento.URL, Magento.USERNAME, Magento.PASSWORD) as customer_api:
cust = customer_api.create(user_dict)
@staticmethod
def forgot_password(email):
data = urllib.urlencode({'email':email})
req = urllib2.Request(Magento.FORGOT_URL, data)
urllib2.urlopen(req)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment