Commits

Anonymous committed 7b5d323

[svn r2] - first import of project
- TODO: doc ...

Comments (0)

Files changed (19)

__init__.py

Empty file added.
+from django.contrib.auth.models import User
+from django.http import HttpResponseRedirect
+from django.utils.encoding import smart_str, iri_to_uri
+from django.utils.translation import ugettext as _
+from django.utils.http import urlquote_plus
+from django.core.urlresolvers import resolve,reverse
+
+from django_openidconsumer.views import get_url_host
+
+
+def username_test(view_func, view_name='django_authopenid.views.account_settings'):
+
+    def decorate(request, *args, **kwargs):
+        username = None
+        if 'username' in kwargs:
+            username = kwargs['username']
+
+        if not request.user.is_authenticated():
+            msg = _("In order to change settings for %s, you should be authenticated." % username)
+            redirect_to = "%s?next=%s&msg=%s" % (
+                reverse('django_authopenid.views.signin'), 
+                request.path, urlquote_plus(msg))
+            return HttpResponseRedirect(redirect_to)
+
+        if not username or username!=request.user.username: 
+            kwargs['username'] = request.user.username
+            redirect_to=iri_to_uri(reverse(view_name, kwargs=kwargs))
+            return HttpResponseRedirect(redirect_to)
+
+        return view_func(request, *args, **kwargs)
+    return decorate
+
+
+from django import newforms as forms
+from django.contrib.auth.models import User
+from django.contrib.auth import authenticate
+from django.utils.translation import ugettext as _
+
+import re
+
+attrs_dict = { 'class': 'required login' }
+username_re = re.compile(r'^\w+$')
+
+class OpenidAuthForm(forms.Form):
+    next = forms.CharField(max_length=255,widget=forms.HiddenInput(), required=False)
+    username = forms.CharField(max_length=30,  widget=forms.widgets.TextInput(attrs=attrs_dict))
+    password = forms.CharField(max_length=128, widget=forms.widgets.PasswordInput(attrs=attrs_dict))
+       
+    def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None):
+        super(OpenidAuthForm, self).__init__(data, files, auto_id, prefix, initial)
+        self.user_cache=None
+            
+    def clean_username(self):
+        if 'username' in self.cleaned_data and 'openid_url' not in self.cleaned_data:
+            if not username_re.search(self.cleaned_data['username']):
+                raise forms.ValidationError(_("Usernames can only contain letters, numbers and underscores"))
+            try:
+                user = User.objects.get(username__exact=self.cleaned_data['username'])
+            except User.DoesNotExist:
+                raise forms.ValidationError(_("This username don't exist in database. Please choose another."))
+            return self.cleaned_data['username']
+
+    def clean_password(self):
+        if 'username' in self.cleaned_data and 'password' in self.cleaned_data:
+            self.user_cache =  authenticate(username=self.cleaned_data['username'], password=self.cleaned_data['password'])
+            if self.user_cache is None:
+                raise forms.ValidationError(_("Please enter a correct username and password. Note that both fields are case-sensitive."))
+            elif self.user_cache.is_active == False:
+                raise forms.ValidationError(_("This account is inactive."))
+            return self.cleaned_data['password']
+
+    def clean_next(self):
+        if 'next' in self.cleaned_data and self.cleaned_data['next'] != "":
+            next_url_re = re.compile('^/[-\w/]+$')
+            if not next_url_re.match(self.cleaned_data['next']):
+                raise forms.ValidationError(_('next url "%s" is invalid' % self.cleaned_data['next']))
+            return self.cleaned_data['next']
+            
+    def get_user(self):
+        return self.user_cache
+            
+
+class OpenidRegisterForm(forms.Form):
+    next = forms.CharField(max_length=255,widget=forms.HiddenInput(), required=False)
+
+    username = forms.CharField(max_length=30, widget=forms.widgets.TextInput(attrs=attrs_dict))
+    email = forms.CharField(max_length=255, widget=forms.widgets.TextInput(attrs=attrs_dict))
+    
+    def clean_username(self):
+        if 'username' in self.cleaned_data:
+            if not username_re.search(self.cleaned_data['username']):
+                raise forms.ValidationError(_("Usernames can only contain letters, numbers and underscores"))
+            try:
+                user = User.objects.get(username__exact=self.cleaned_data['username'])
+            except User.DoesNotExist:
+                return self.cleaned_data['username']
+            raise forms.ValidationError(_("This username is already taken. Please choose another."))
+            
+    def clean_email(self):
+        """For security reason one unique email in database"""
+        if 'email' in self.cleaned_data:
+            try:
+                user = User.objects.get(email=self.cleaned_data['email'])
+            except User.DoesNotExist:
+                return self.cleaned_data['email']
+            raise forms.ValidationError(_("This email is already registered in our database. Please choose another."))
+ 
+    
+class OpenidVerifyForm(forms.Form):
+    next = forms.CharField(max_length=255,widget=forms.HiddenInput(), required=False)
+    username = forms.CharField(max_length=30, widget=forms.widgets.TextInput(attrs=attrs_dict))
+    password = forms.CharField(max_length=128, widget=forms.widgets.PasswordInput(attrs=attrs_dict))
+     
+    def clean_username(self):
+        if 'username' in self.cleaned_data:
+            if not username_re.search(self.cleaned_data['username']):
+                raise forms.ValidationError(_("Usernames can only contain letters, numbers and underscores"))
+            try:
+                user = User.objects.get(username__exact=self.cleaned_data['username'])
+            except User.DoesNotExist:
+                raise forms.ValidationError(_("This username don't exist. Please choose another."))
+            return self.cleaned_data['username']
+            
+    def clean_password(self):
+        if 'username' in self.cleaned_data and 'password' in self.cleaned_data:
+            self.user_cache =  authenticate(username=self.cleaned_data['username'], password=self.cleaned_data['password'])
+            if self.user_cache is None:
+                raise forms.ValidationError(_("Please enter a correct username and password. Note that both fields are case-sensitive."))
+            elif self.user_cache.is_active == False:
+                raise forms.ValidationError(_("This account is inactive."))
+            return self.cleaned_data['password']
+            
+    def get_user(self):
+        return self.user_cache
+
+
+attrs_dict = { 'class': 'required' }
+username_re = re.compile(r'^\w+$')
+
+class RegistrationForm(forms.Form):
+    next = forms.CharField(max_length=255,widget=forms.HiddenInput(), required=False)
+    username = forms.CharField(max_length=30,
+                               widget=forms.TextInput(attrs=attrs_dict),
+                               label=u'Username')
+    email = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict,
+                                                               maxlength=200)),
+                             label=u'Email address')
+    password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict),
+                                label=u'Password')
+    password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict),
+                                label=u'Password (again, to catch typos)')
+
+    def clean_username(self):
+        """
+        Validates that the username is alphanumeric and is not already
+        in use.
+        
+        """
+        if 'username' in self.cleaned_data:
+            if not username_re.search(self.cleaned_data['username']):
+                raise forms.ValidationError(u'Usernames can only contain letters, numbers and underscores')
+            try:
+                user = User.objects.get(username__exact=self.cleaned_data['username'])
+            except User.DoesNotExist:
+                return self.cleaned_data['username']
+            raise forms.ValidationError(u'This username is already taken. Please choose another.')
+
+    def clean_email(self):
+        if 'email' in self.cleaned_data:
+            try:
+                user = User.objects.get(email=self.cleaned_data['email'])
+            except:
+                return self.cleaned_data['email']
+            raise forms.ValidationError(u'This email is already registered in our database. Please choose another.')
+        return self.cleaned_data['email']
+    
+    def clean_password2(self):
+        """
+        Validates that the two password inputs match.
+        
+        """
+        if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data and \
+           self.cleaned_data['password1'] == self.cleaned_data['password2']:
+            return self.cleaned_data['password2']
+        raise forms.ValidationError(u'You must type the same password each time')
+
+
+class ChangepwForm(forms.Form):
+    username = forms.CharField(max_length=30,widget=forms.HiddenInput())
+    oldpw = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict))
+    password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict))
+    password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict))
+
+    def clean_oldpw(self):
+        if 'oldpw' in self.cleaned_data:
+            try:
+                u=User.objects.get(username=self.cleaned_data['username'])
+            except:
+                 raise forms.ValidationError(_("Incorrect username. What are you trying to do ..."))
+                 
+            if not u.check_password(self.cleaned_data['oldpw']):
+                raise forms.ValidationError(_("Old password is wrong. Please enter a valid password."))
+        return self.cleaned_data['oldpw']
+    
+    def clean_password2(self):
+        """
+        Validates that the two password inputs match.
+        
+        """
+        if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data and \
+           self.cleaned_data['password1'] == self.cleaned_data['password2']:
+            return self.cleaned_data['password2']
+        raise forms.ValidationError(_("new passwords do not match each other"))
+        
+        
+class ChangeemailForm(forms.Form):
+    username = forms.CharField(max_length=30,widget=forms.HiddenInput())
+    email = forms.CharField(max_length=255,widget=forms.TextInput(attrs={'class': "required validate-email" }))
+    password = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict))
+
+    def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None):
+        super(ChangeemailForm, self).__init__(data, files, auto_id, prefix, initial)
+        self.test_openid=False
+
+    def clean_password(self):
+        if 'password' in self.cleaned_data:
+            try:
+                u=User.objects.get(username=self.cleaned_data['username'])
+            except:
+                raise forms.ValidationError(_("Incorrect username."))
+                 
+            if not u.check_password(self.cleaned_data['password']):
+                self.test_openid=True
+        return self.cleaned_data['password']
+                
+class ChangeopenidForm(forms.Form):
+    username = forms.CharField(max_length=30,widget=forms.HiddenInput())
+    openid_url = forms.CharField(max_length=255,widget=forms.TextInput(attrs={'class': "required" }))
+
+
+class DeleteForm(forms.Form):
+    username = forms.CharField(max_length=30,widget=forms.HiddenInput())
+    confirm = forms.CharField(widget=forms.CheckboxInput(attrs=attrs_dict))
+    password = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict))
+
+    def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None):
+        super(DeleteForm, self).__init__(data, files, auto_id, prefix, initial)
+        self.test_openid=False
+
+    def clean_password(self):
+        if 'password' in self.cleaned_data:
+            try:
+                u=User.objects.get(username=self.cleaned_data['username'])
+            except:
+                raise forms.ValidationError(_("Incorrect username."))
+                 
+            if not u.check_password(self.cleaned_data['password']):
+                self.test_openid=True
+        return self.cleaned_data['password']
+
+
+class EmailPasswordForm(forms.Form):
+    username = forms.CharField(max_length=30,widget=forms.TextInput(attrs={'class': "required" }))
+
+    def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None):
+        super(EmailPasswordForm, self).__init__(data, files, auto_id, prefix, initial)
+        self.user_cache=None
+
+
+    def clean_username(self):
+        if 'username' in self.cleaned_data:
+            try:
+                self.user_cache=User.objects.get(username=self.cleaned_data['username'])
+            except:
+                raise forms.ValidationError(_("Incorrect username."))
+        return self.cleaned_data['username']
+from django.db import models
+from django.contrib.auth.models import User
+from django.conf import settings
+
+import md5, random, sys, os, time
+
+class UserAssociation(models.Model):
+    openid_url = models.CharField(blank=False, maxlength=255)
+    user = models.ForeignKey(User,unique=True)
+    
+    def __unicode__(self):
+        return "Openid %s with user %s" % (self.openid_url, self.user)
+        
+    class Admin:
+        pass
+
+
+class UserPasswordQueueManager(models.Manager):
+    def get_new_confirm_key(self):
+        "Returns key that isn't being used."
+        # The random module is seeded when this Apache child is created.
+        # Use SECRET_KEY as added salt.
+        while 1:
+            confirm_key = md5.new("%s%s%s%s" % (random.randint(0, sys.maxint - 1), os.getpid(), time.time(), settings.SECRET_KEY)).hexdigest()
+            try:
+                self.get(confirm_key=confirm_key)
+            except self.model.DoesNotExist:
+                break
+        return confirm_key
+
+
+class UserPasswordQueue(models.Model):
+    user = models.ForeignKey(User, unique=True)
+    new_password = models.CharField(maxlength=30)
+    confirm_key = models.CharField(max_length=40)
+
+    objects = UserPasswordQueueManager()
+
+
+    def __unicode__(self):
+        return self.user.username

templates/account/changeemail.html

+{% load i18n %}
+{% extends "base.html" %}
+
+
+
+
+
+{% block content %}
+<h4 class="headblue">{% trans "Account: change email" %}</h4>
+
+<p class="settings-descr">{% blocktrans %}This is where you can change the email address associated with your account. Please keep this email address up to date so we can send you a password-reset email if you request one.{% endblocktrans %}</p>
+{% if form.errors %}
+<p class="errors">{% trans "Please correct errors below:" %}<br />
+	{% if form.email.errors %} 
+		<span class="error">{{ form.email.errors|join:", " }}</span>
+	{% endif %}
+	{% if form.password.errors %} 
+		<span class="error">{{ form.password.errors|join:", " }}</span>
+	{% endif %}
+</p>
+{% endif %}
+
+<div class="aligned">
+	<form action="{{ path }}" method="post" accept-charset="utf-8">
+
+		{{ form.username }}
+		<div id="form-row"><label for="id_email">{% trans "Email" %}</label>{{ form.email }}</div>
+		<div id="form-row"><label for="id_password">{% trans "Password" %}</label>{{ form.password }}</div>
+
+        <p><input type="submit" value="{% trans "Change email" %}"></p>
+
+	</form>
+	</div>
+{% endblock %}

templates/account/changeopenid.html

+{% load i18n %}
+{% extends "base.html" %}
+
+{% block content %}
+<h4 class="headblue">{% trans "Account: change openid url" %}</h4>
+
+<p>{% blocktrans %}This is where you can change your openid url used to connect to friendsnippets. Make sure you remember it!{% endblocktrans %}</p>
+{% if form.errors %}
+<p class="errors">{% trans "Please correct errors below:" %}<br />
+	{% if form.openid_url.errors %} 
+		<span class="error">{{ form.openid_url.errors|join:", " }}</span>
+	{% endif %}
+
+
+</p>
+{% endif %}
+{% if msg %}
+	<p class="errors">{{ msg }}</p>
+{% endif %}
+
+<div class="aligned">
+	<form action="." method="post" accept-charset="utf-8">
+
+		{{ form.username }}
+		<div id="form-row"><label for="id_openid_url">{% trans "OpenID url:" %}</label>{{ form.openid_url }}</div>
+        <p><input type="submit" value="{% trans "Change openid" %}"></p>
+
+	</form>
+	</div>
+{% endblock %}

templates/account/changepw.html

+{% load i18n %}
+{% extends "base.html" %}
+
+{% block head %}
+		
+{% endblock %}
+
+
+
+{% block content %}
+<h4 class="headblue">{% trans "Account: change password" %}</h4>
+
+<p>{% blocktrans %}This is where you can change your password. Make sure you remember it!{% endblocktrans %}</p>
+{% if form.errors %}
+<p class="errors">{% trans "Please correct errors below:" %}<br />
+{{ form.errors }}
+</p>
+{% endif %}
+
+<div class="aligned">
+	<form action="{{ path }}" method="post" accept-charset="utf-8">
+
+		{{ form.username }}
+		<div id="form-row"><label for="id_oldpw">{% trans "Old password" %}</label>{{ form.oldpw }}</div>
+		<div id="form-row"><label for="id_password1">{% trans "New password" %}</label>{{ form.password1 }}</div>
+		<div id="form-row"><label for="id_password2">{% trans "New password again" %}</label>{{ form.password2 }}</div>
+        <p><input type="submit" value="{% trans "Change password" %}"></p>
+
+	</form>
+	</div>
+{% endblock %}

templates/account/delete.html

+{% load i18n %}
+{% extends "base.html" %}
+
+
+
+{% block content %}
+<h4 class="headblue">{% trans "Account: delete account" %}</h4>
+
+<p class="settings-descr">{% blocktrans %}Note: After deleting your account, anyone will be able to register this username.{% endblocktrans %}</p>
+{% if form.errors %}
+<p class="errors">{% trans "Please correct errors below:" %}<br />
+	{% if form.confirm.errors %} 
+    <span class="error">{% trans "Check confirm box, if you want delete your account." %}</span><br />
+	{% endif %}
+	{% if form.password.errors %} 
+    <span class="error">{% trans "Password:" %} {{ form.password.errors|join:", " }}</span>
+	{% endif %}
+</p>
+{% endif %}
+{% if msg %}
+<p class="errors">{% trans "Please correct errors below:" %}<br />
+    <span class="error">{{ msg }}</span>
+    </p>
+{% endif %}
+<div class="aligned">
+	<form action="." method="post" accept-charset="utf-8">
+
+		{{ form.username }}
+        <div id="form-row"> {{ form.confirm }} {% trans "I am sure I want to delete my account." %}</div>
+        <div id="form-row"><label for="id_password">{% trans "Password/ OpenID URL" %}</label>{{ form.password }} {% trans "(required for your security)" %}</div>
+
+        <p><input type="submit" value="{% trans "delete account forever" %}"></p>
+
+	</form>
+	</div>
+{% endblock %}

templates/account/edit.html

+{% load i18n %}
+{% extends "base_3rows.html" %}
+
+{% block head %}
+	<link rel="stylesheet" href="/media/css/form.css" type="text/css" media="screen" title="no title" charset="utf-8">
+	<script type="text/javascript" src="http://yui.yahooapis.com/2.3.1/build/yahoo-dom-event/yahoo-dom-event.js"></script> 
+	<script language="javascript" src="/media/js/jsvalidate.js" type="text/javascript"></script>
+	
+{% endblock %}
+
+{% block info %}
+	<div id="metabar">
+	    <p>Settings, where you can make changes to your account</p>	
+	</div>
+{% endblock %}
+
+{% block content %}
+<h4 class="headblue">Account: edit profile</h4>
+
+<p class="settings-descr">If you choose to display this information, it will appear next to your username on your snippets page. It's a good way to give the readers of your snippets a little more information about you,</p>
+{% if form.errors %}
+<p class="errors">{% trans "Please correct errors below:" %}<br />
+	{% if form.homepage.errors %} 
+		<span class="error">{{ form.homepage.errors|join:", " }}</span>
+	{% endif %}
+</p>
+{% endif %}
+
+<div class="aligned">
+	<form action="{{ path }}" method="post" accept-charset="utf-8">
+
+        {{ form.username }}
+        <div id="form-row">{{ form.view_name }} show name and url on my bookmarks page?</div
+		<div id="form-row"><label for="id_name">{% trans "full name:" %}</label>{{ form.name }}</div>
+		<div id="form-row"><label for="id_password">{% trans "homepage:" %}</label>{{ form.homepage }}</div>
+
+        <p><input type="submit" value="{% trans "Edit profile" %}"></p>
+
+	</form>
+	</div>
+{% endblock %}

templates/account/sendpw.html

+{% load i18n %}
+{% extends "base.html" %}
+
+
+
+{% block content %}
+<h4 class="headblue">{% trans "Account: Send a new password" %}</h4>
+
+<p class="settings-descr">{% blocktrans %}Lost your password ? Here you can ask to reset your password. Enter the username you use  and you will get a confirm mail with your new password. This new password will be activated only after you clicked on the link you will find in the email{% endblocktrans %}</p>
+{% if form.errors %}
+<p class="errors">{% trans "Please correct errors below:" %}<br />
+	{% if form.username.errors %} 
+		<span class="error">{{ form.username.errors|join:", " }}</span>
+	{% endif %}
+</p>
+{% endif %}
+{% if msg %}
+<br /
+<span class="error">{{ msg }}</span>
+{% endif %}
+
+<div class="aligned">
+	<form action="." method="post" accept-charset="utf-8">
+		<div id="form-row"><label for="id_username">{% trans "Username" %}</label>{{ form.username }}</div>
+
+        <p><input type="submit" value="{% trans "Send new password" %}"></p>
+
+	</form>
+	</div>
+{% endblock %}

templates/account/sendpw_email.txt

+Someone ask to reset your password on {{ site_url }}. 
+If it's not you, please ignore this email. 
+
+Your new account details are:
+
+Username: {{ username }}
+New password: {{ password }}
+
+To confirm reset of your password go on this url:
+{{ site_url }}{{ url_confirm }}?key={{ confirm_key }}
+
+See you,
+

templates/account/settings.html

+{% load i18n %}
+{% extends "base.html" %}
+
+{% block head %}
+<style type="text/css" media="screen">
+	dt, dd { padding:0 0 0.35em 0; }
+	dt { float: left; width: 21ex;  }
+	dd { margin-left: 23ex;  }
+	
+	#settings-options, #settings-intro { padding: 4em 1.5em;}
+	#settings-options { min-height: 300px; border-left: 1px solid #333;}
+	
+	#settings-options h5 { font-weight: bold;}
+</style>
+{% endblock %}
+
+{% block content %}
+<div id="settings-intro">
+	
+
+
+    <h4><strong>{{ user.username }}</strong> {% trans "Settings" %}</h4>
+    {% blocktrans %}
+    <p>This is where you can make changes to your account.</p>
+
+    {% endblocktrans %}
+</div>
+
+<div id="settings-options">
+	{% if msg %}
+		<p class="error">{{ msg }}</p>
+	{% endif %}
+    <h5>{% trans "Account" %}</h5>
+	<dl>
+        <dt>» <a href="{{ settings_path }}changepw">{% trans "change password" %}</a></dt>
+        <dd>{% trans "Give your  account a new password." %}</dd>
+        <dt>» <a href="{{ settings_path }}changeemail">{% trans "change email" %}</a></dt>
+        <dd>{% trans "Add or update the email address associated with your account." %}</dd>
+        {% if is_openid %}
+        <dt>» <a href="{{ settings_path }}changeopenid">{% trans "change openid url" %}</a></dt>
+        <dd>{% trans "Change openid associated to your account" %}</dd>
+        {% endif %}
+        
+        <dt>» <a href="{{ settings_path }}delete">{% trans "delete account" %}</a></dt>
+        <dd>{% trans "Erase your username and all your data from website" %}</dd>
+	</dl>
+</div>
+{% endblock %}

templates/authopenid/complete.html

+{% load i18n %}
+
+{% extends "base.html" %}
+
+{% block head %}{% endblock %}
+
+
+{% block content %}
+
+	<div id="completetxt">
+	<h1>{% trans "Your OpenID is verified! " %}</h1>
+	{% blocktrans %}
+	<p>Your OpenID can now be associated with a new or existing membership. You can change the association later in your preferences</p>
+	{% endblocktrans %}
+	<br /><br />
+	<h2>{% trans "Associate your OpenID" %}</h2>
+	{% blocktrans %}
+	<p>If you're joining <strong>Sitename</strong>, associate your OpenID with a new account. If you're already a member, associate with your existing account.</p>
+	{% endblocktrans %}
+	</div>
+
+		
+	
+	{% if form1.errors %}
+	<p class="errors">{% trans "Please correct errors below:" %}<br />
+		{% if form1.username.errors %} 
+			<span class="error">{{ form1.username.errors|join:", " }}</span>
+		{% endif %}
+		{% if form1.email.errors %} 
+			<span class="error">{{ form1.email.errors|join:", " }}</span>
+		{% endif %}
+	</p>
+	{% endif %}
+	{% if form2.errors %}
+	<p class="errors">{% trans "Please correct errors below:" %}<br />
+		{% if form2.username.errors %} 
+			<span class="error">{{ form2.username.errors|join:", " }}</span>
+		{% endif %}
+		{% if form2.password.errors %} 
+			<span class="error">{{ form2.password.errors|join:", " }}</span>
+		{% endif %}
+	</p>
+	{% endif %}
+
+	<div class="login">
+        <form name="fregister" action="{{ action }}" method="POST">
+            {{ form.next }}
+			<fieldset>
+				<legend>{% trans "A new account" %}</legend>
+				<div class="form-row"><label for "id_username">{% trans "Screen name" %}</label><br />{{ form1.username }}</div>
+				<div class="form-row"><label for "id_email">{% trans "Email" %}</label><br />{{ form1.email }}</div>
+				<div class="submit-row"><input type="submit" name="bnewaccount" value="CREATE MY ACCOUNT"></div>
+				<hr class="clear" />
+            	</fieldset>
+		</form>
+	</div>
+
+	
+
+	<div class="login">
+		<h3></h3>
+        <form name="fverify" action="{{ action }}" method="POST">
+            {{ form.next }}
+			<fieldset>
+				<legend>{% trans "An exisiting account" %}</legend>
+				<div class="form-row"><label for "id_username">{% trans "Screen name" %}</label><br />{{ form2.username }}</div>
+				<div class="form-row"><label for "id_passwordl">{% trans "Password" %}</label><br />{{ form2.password }}</div>
+				<div class="submit-row"><input type="submit" name="bverify" value="VERIFY"></div>
+			</fieldset>
+		</form>
+	</div>
+{% endblock %}
+
+	
+

templates/authopenid/confirm_email.txt

+Thank you for registering. 
+
+Your account details are:
+
+Username: {{ username }}
+Password: {{ password }}
+
+
+You could sign in  with this url:
+{{ site_url }}signin/
+
+

templates/authopenid/failure.html

+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+  "http://www.w3.org/TR/html4/strict.dtd">
+<html>
+<head>
+  <title>OpenID failed</title>
+</head>
+<body>
+<h1>OpenID failed</h1>
+
+<p>{{ message|escape }}</p>
+
+</body>
+</html>

templates/authopenid/signin.html

+{% extends "base.html" %}
+{% load i18n %}
+
+{% block head %}
+
+
+{% endblock %}
+
+
+{% block content %}
+{% if msg %}
+<br />
+	<p class="warning">{{ msg }}</p>
+{% endif %}
+{% if form1.errors %}
+<p class="errors">{% trans "Please correct errors below:" %}<br />
+	{% if form1.username.errors %} 
+		<span class="error">{{ form1.username.errors|join:", " }}</span>
+	{% endif %}
+	{% if form1.password.errors %} 
+		<span class="error">{{ form1.password.errors|join:", " }}</span>
+	{% endif %}
+</p>
+{% endif %}
+<div class="login">
+
+    <form name="fauth" action="{{ action }}" method="post">
+        {{ form.next }}
+	<fieldset>
+		<legend>{% trans "Sign In Using Your Account ID" %}</legend>
+		<div class="form-row"><label for="id_username">{% trans "Username:" %}</label><br />{{ form1.username }}</div>
+		<div class="form-row"><label for="id_password">{% trans "Password" %}</label><br />{{ form1.password }}</div>
+        <div class="submit-row"><input type="submit" name="blogin" value="{% trans "Sign in" %}"> </div>
+        <div>&nbsp;&nbsp;<a href="{{ sendpw_url }}">{% trans "Lost your password ?" %}</a></div>
+	</fieldset>	
+</form>
+
+<br />
+<form name="fopenid" action="{{ action }}" method="post">
+    {{ form.next }}
+	<fieldset>
+		<legend>{% trans "Sign In Using Your OpenID" %}</legend>
+        <div class="form-row"><label for="id_openid_ul">{% trans "OpenId URL :" %}</label><br />{{ form2.openid_url }}</div>
+        <div class="submit-row "><input name="bsignin" type="submit" value="{% trans "Sign in with OPENID" %}"></div>
+		
+	</fieldset>
+</form>	
+</div>	
+{% endblock %}
+

templates/authopenid/signup.html

+{% load i18n %}
+
+{% extends "base.html" %}
+
+{% block content %}
+
+<div class="jointxt">
+    {% blocktrans %}
+    <h1>Join</h1>
+    <p>There are two ways to join: with an email + screen name, or with OpenID.<br />Enter information only for the type of sign up you want to do.</p>
+    {% endblocktrans %}
+	<br />
+	<br />
+    <h2 class="signup">{% trans "Regular Signup" %}</h2>
+    {% if form.errors %}
+    <p class="errors">{% trans "Please correct errors below:" %}<br />
+    {% if form.username.errors %} 
+    <span class="error">{{ form.username.errors|join:", " }}</span>
+    {% endif %}
+    {% if form.email.errors %} 
+    <span class="error">{{ form.email.errors|join:", " }}</span>
+    {% endif %}
+    {% if form.password2.errors %} 
+    <span class="error">{{ form.password2.errors|join:", " }}</span>
+    {% endif %}
+    </p>
+    {% endif %}
+</div>
+    <form action="{{ action }}" method="post" accept-charset="utf-8">	
+        <div class="form-row"><label for="id_username">{% trans "Choose a Screen Name:" %}</label><br />{{ form.username }}</div>
+
+        <div class="form-row"><label for="id_email">{% trans "Enter Your Email Address:" %}</label><br />{{ form.email }}</div>
+        <div class="form-row"><label for="id_password1">{% trans "Choose a Password:" %}</label><br />{{ form.password1 }}</div>
+        <div class="form-row"><label for="id_password2">{% trans "Confirm Your Password:" %}</label><br />{{ form.password2 }}</div>
+
+        <div class="submit-row"><input type="submit" value="{% trans "JOIN FREE" %}" /></div>
+        <br />
+    </form>
+<br />
+    <h2 class="signup">{% trans "OpenID Signup" %}</h2>
+    <form name="fopenid" action="{{ action_signin }}" method="post">
+        <div class="form-row">{{ form2.openid_url }}</div>
+        <div class="submit-row "><input name="bsignin" type="submit" value="{% trans "Sign in with OPENID" %}"></div>
+    </form>
+{% endblock %}
+from django.conf.urls.defaults import patterns
+
+urlpatterns = patterns('',
+     # manage account registration
+    (r'^signin/$', 'django_authopenid.views.signin'),
+    (r'^signout/$', 'django_authopenid.views.signout'),
+    (r'^complete/$', 'django_authopenid.views.complete_signin'),
+    (r'^register/$', 'django_authopenid.views.register'),
+    (r'^signup/$', 'django_authopenid.views.signup'),
+    (r'^signup/$', 'django_authopenid.views.signup'),
+    ('^sendpw/$', 'django_authopenid.views.sendpw'),
+
+    # manage account settings
+    (r'^(?P<username>\w+)/$', 'django_authopenid.views.account_settings'),
+    (r'^$', 'django_authopenid.views.account_settings'),
+    (r'^(?P<username>\w+)/changepw/$', 'django_authopenid.views.changepw'),
+    (r'^(?P<username>\w+)/changeemail/$', 'django_authopenid.views.changeemail'),
+    (r'^(?P<username>\w+)/changeopenid/$', 'django_authopenid.views.changeopenid'),
+    (r'^(?P<username>\w+)/delete/$', 'django_authopenid.views.delete'),
+    (r'^sendpw/confirm/$', 'django_authopenid.views.confirmchangepw'),
+
+)
+from django.http import HttpResponse, HttpResponseRedirect, get_host
+from django.shortcuts import render_to_response as render
+from django.template import RequestContext, loader, Context
+from django.conf import settings
+from django.contrib.auth.models import User
+from django.contrib.auth import authenticate,login,logout
+from django.core.urlresolvers import reverse
+from django.utils.html import escape
+from django.utils.translation import ugettext as _
+from django.contrib.sites.models import Site
+from django.utils.encoding import smart_str
+from django.utils.http import urlquote_plus, urlquote
+
+from openid.consumer.consumer import Consumer
+from openid.consumer.discover import DiscoveryFailure
+from yadis import xri
+
+import urllib
+
+from django_openidconsumer.util import OpenID, DjangoOpenIDStore, from_openid_response
+from django_openidconsumer.views import complete, is_valid_next_url, get_url_host
+from django_openidconsumer.forms import OpenidSigninForm
+
+from models import UserAssociation, UserPasswordQueue
+from forms import OpenidAuthForm, OpenidRegisterForm, OpenidVerifyForm, RegistrationForm, ChangepwForm, ChangeemailForm, ChangeopenidForm, DeleteForm, EmailPasswordForm
+from decorators import username_test
+
+
+def signin(request):
+    on_failure = signin_failure
+    extension_args = {}
+    next = ''
+
+
+    if request.GET.get('next') and is_valid_next_url(request.GET['next']):
+        next = request.GET.get('next', '').strip()
+    if not next or not is_valid_next_url(next):
+        next = getattr(settings, 'OPENID_REDIRECT_NEXT', '/')
+
+    if request.user.is_authenticated():
+        return HttpResponseRedirect(next)
+
+
+    form_signin = OpenidSigninForm(initial={'next':next})
+    form_auth = OpenidAuthForm(initial={'next':next})
+
+    if request.POST:   
+        if 'bsignin' in request.POST.keys():
+            form_signin = OpenidSigninForm(request.POST)
+            if form_signin.is_valid():
+                next = form_signin.cleaned_data['next']
+                if not next:
+                    next = getattr(settings, 'OPENID_REDIRECT_NEXT', '/')
+
+                extension_args['sreg.optional'] = 'email,nickname'
+
+                trust_root = getattr(
+                    settings, 'OPENID_TRUST_ROOT', get_url_host(request) + '/'
+                )
+
+                redirect_to = "%s?next=%s" % (get_url_host(request) + reverse('django_authopenid.views.complete_signin'), urllib.urlencode({'next':next}))
+
+                consumer = Consumer(request.session, DjangoOpenIDStore())
+                try:
+                    auth_request = consumer.begin(form_signin.cleaned_data['openid_url'])
+                except DiscoveryFailure:
+                    return on_failure(request, _("The OpenID %s was invalid") % form_signin.cleaned_data['openid_url'])
+
+                # Add extension args (for things like simple registration)
+                for name, value in extension_args.items():
+                    namespace, key = name.split('.', 1)
+                    auth_request.addExtensionArg(namespace, key, value)
+
+                redirect_url = auth_request.redirectURL(trust_root, redirect_to)
+                return HttpResponseRedirect(redirect_url)
+        elif 'blogin' in request.POST.keys():
+            # perform normal django authentification
+            form_auth = OpenidAuthForm(request.POST)
+            if form_auth.is_valid():
+                user = form_auth.get_user()
+                login(request, user)
+
+                next = form_auth.cleaned_data['next']
+                if not next:
+                    next = getattr(settings, 'OPENID_REDIRECT_NEXT', '/')
+                return HttpResponseRedirect(next)
+
+
+    return render('authopenid/signin.html', {
+        'form1': form_auth,
+        'form2': form_signin,
+        'action': request.path,
+        'msg':  request.GET.get('msg',''),
+        'sendpw_url': reverse('django_authopenid.views.sendpw'),
+    })
+
+def complete_signin(request):
+    return complete(request, signin_success, signin_failure)
+
+
+def signin_success(request, identity_url, openid_response):
+    request.session['openids'] = []
+    openid=from_openid_response(openid_response)
+    request.session['openids'].append(openid)
+
+    try:
+        rel = UserAssociation.objects.get(openid_url__exact=str(openid))
+    except:
+        # try to register this new user
+        return register(request)
+    user = rel.user
+    if user.is_active:
+        user.backend = "django.contrib.auth.backends.ModelBackend"
+        login(request,user)
+
+    next = request.GET.get('next', '').strip()
+    if not next or not is_valid_next_url(next):
+        next = getattr(settings, 'OPENID_REDIRECT_NEXT', '/')
+    
+    return HttpResponseRedirect(next)
+
+def is_association_exist(openid_url):
+    is_exist=True
+    try:
+        o=UserAssociation.objects.get(openid_url__exact=openid_url)
+    except:
+        is_exist=False
+    return is_exist
+
+def register(request):
+    is_redirect = False
+    next = request.GET.get('next', '').strip()
+    if not next or not is_valid_next_url(next):
+        next = getattr(settings, 'OPENID_REDIRECT_NEXT', '/')
+
+
+    openids = request.session.get('openids', [])
+    if openids and len(openids)>0:
+        openid = openids[-1] # Last authenticated OpenID
+    else:
+         return HttpResponseRedirect(reverse('django_authopenid.views.signin') + next)
+
+    nickname = openid.sreg.get('nickname', '')
+    email = openid.sreg.get('email', '')
+    
+    form1 = OpenidRegisterForm(initial={
+        'next': next,
+        'username': nickname,
+        'email': email,
+    }) 
+    form2 = OpenidVerifyForm(initial={
+        'next': next,
+        'username': nickname,
+    })
+    
+    if request.POST:
+        just_completed=False
+        if 'bnewaccount' in request.POST.keys():
+            form1 = OpenidRegisterForm(request.POST)
+            if form1.is_valid():
+                next = form1.cleaned_data['next']
+                if not next:
+                    next = getattr(settings, 'OPENID_REDIRECT_NEXT', '/')
+                is_redirect = True
+                tmp_pwd = User.objects.make_random_password()
+                user = User.objects.create_user(form1.cleaned_data['username'],form1.cleaned_data['email'], tmp_pwd)
+                
+                # make association with openid
+                ua = UserAssociation(openid_url=str(openid),user_id=user.id)
+                ua.save()
+                    
+                # login 
+                user.backend = "django.contrib.auth.backends.ModelBackend"
+                login(request, user)
+        elif 'bverify' in request.POST.keys():
+            form2 = OpenidVerifyForm(request.POST)
+            if form2.is_valid():
+                is_redirect = True
+                next = form2.cleaned_data['next']
+                if not next:
+                    next = getattr(settings, 'OPENID_REDIRECT_NEXT', '/')
+                user = form2.get_user()
+
+                ua = UserAssociation(openid_url=str(openid),user_id=user.id)
+                ua.save()
+                login(request, user)
+        
+        # redirect, can redirect only if forms are valid.
+        if is_redirect:
+            return HttpResponseRedirect(next)
+    
+    
+    
+    return render('authopenid/complete.html', {
+        'form1': form1,
+        'form2': form2,
+        'action': reverse('django_authopenid.views.register'),
+        'nickname': nickname,
+        'email': email
+    }, context_instance=RequestContext(request))
+
+def signin_failure(request, message):
+    request_path=reverse('friendsnippets.django_authopenid.views.signin')
+    if request.GET.get('next'):
+        request_path += '?' + urllib.urlencode({
+            'next': request.GET['next']
+        })
+
+    form_signin = OpenidSigninForm(initial={'next':next})
+    form_auth = OpenidAuthForm(initial={'next':next})
+
+    return render('authopenid/openid.html', {
+        'msg': message,
+        'form1': form_auth,
+        'form2': form_signin,
+    })
+
+
+def signup(request):
+    action_signin = reverse('django_authopenid.views.signin')
+
+    next = request.GET.get('next', '/')
+    form = RegistrationForm(initial={'next':next})
+    form_signin = OpenidSigninForm(initial={'next':next})
+
+    if request.user.is_authenticated():
+        return HttpResponseRedirect(next)
+    
+    if request.POST:
+        form = RegistrationForm(request.POST)
+        if form.is_valid():
+
+            next = form.cleaned_data['next']
+            if not next: next = '/'
+
+            user = User.objects.create_user(form.cleaned_data['username'],form.cleaned_data['email'], form.cleaned_data['password1'])
+           
+            user.backend = "django.contrib.auth.backends.ModelBackend"
+            login(request, user)
+            
+            # send email
+            current_domain = Site.objects.get_current().domain
+            subject = _("Welcome")
+            message_template = loader.get_template('authopenid/confirm_email.txt')
+            message_context = Context({ 'site_url': 'http://%s/' % current_domain,
+                                        'username': form.cleaned_data['username'],
+                                        'password': form.cleaned_data['password1'] })
+            message = message_template.render(message_context)
+            send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [user.email])
+            
+            return HttpResponseRedirect(next)
+    
+    return render('authopenid/signup.html', {
+        'form': form,
+        'form2': form_signin,
+        'action': request.path,
+        'action_signin': action_signin,
+        },context_instance=RequestContext(request))
+
+    
+def signout(request):
+    request.session['openids'] = []
+    next = request.GET.get('next', '/')
+    if not is_valid_next_url(next):
+        next = '/'
+
+    logout(request)
+    
+    return HttpResponseRedirect(next)
+
+
+
+def account_settings(request,username=None):
+    msg = request.GET.get('msg', '')
+    is_openid = True
+
+    try:
+        o=UserAssociation.objects.get(user__username__exact=username)
+    except:
+        is_openid = False
+
+
+    return render('account/settings.html',
+            {'msg': msg, 'settings_path': request.path, 'is_openid': is_openid},
+            context_instance=RequestContext(request))
+account_settings = username_test(settings, 'django_authopenid.views.account_settings')
+
+
+def changepw(request,username):
+    try:
+        u=User.objects.get(username=username)
+    except:
+        raise Http404
+
+    if request.POST:
+        form = ChangepwForm(request.POST)
+        if form.is_valid():
+            u.set_password(form.cleaned_data['password1'])
+            u.save()
+            msg=_("Password changed.") 
+            redirect="%s?msg=%s" % (reverse('django_authopenid.views.account_settings',kwargs={'username': request.user.username}),urlquote_plus(msg))
+            return HttpResponseRedirect(redirect)
+    else:
+        form=ChangepwForm(initial={'username':request.user.username})
+
+    return render('account/changepw.html', {'form': form },
+                                context_instance=RequestContext(request))
+
+changepw = username_test(changepw, 'django_authopenid.views.changepw')
+
+
+def ask_openid(request, openid_url, redirect_to, on_failure=None, extension_args=None):
+    on_failure = on_failure or signin_failure
+    extension_args = extension_args or {}
+
+    trust_root = getattr(
+        settings, 'OPENID_TRUST_ROOT', get_url_host(request) + '/'
+    )
+    if xri.identifierScheme(openid_url) == 'XRI' and getattr(
+            settings, 'OPENID_DISALLOW_INAMES', False
+    ):
+        msg = _("i-names are not supported")
+        return on_failure(request,msg)
+    consumer = Consumer(request.session, DjangoOpenIDStore())
+    try:
+        auth_request = consumer.begin(openid_url)
+    except DiscoveryFailure:
+        msg =_("The OpenID %s was invalid" % openid_url)
+        return on_failure(request,msg)
+
+    # Add extension args (for things like simple registration)
+    for name, value in extension_args.items():
+        namespace, key = name.split('.', 1)
+        auth_request.addExtensionArg(namespace, key, value)
+    redirect_url = auth_request.redirectURL(trust_root, redirect_to)
+    return HttpResponseRedirect(redirect_url)
+
+
+def changeemail(request,username):
+    extension_args = {}
+ 
+    try:
+        u=User.objects.get(username=username)
+    except:
+        raise Http404
+     
+    if request.POST:
+        form = ChangeemailForm(request.POST)
+        if form.is_valid():
+            if not form.test_openid:
+                u.email = form.cleaned_data['email']
+                u.save()
+                msg=_("Email changed.") 
+                redirect="%s?msg=%s" % (reverse('django_authopenid.views.account_settings', kwargs={'username': request.user.username}),urlquote_plus(msg))
+                return HttpResponseRedirect(redirect)
+            else:
+                redirect_to = "%s?new_email=%s" % (get_url_host(request) + reverse('django_authopenid.views.changeemail',kwargs={'username':username}),form.cleaned_data['email'])
+                
+                return ask_openid(request, form.cleaned_data['password'], redirect_to, on_failure=emailopenid_failure)    
+    elif not request.POST and 'openid.mode' in request.GET:
+        return complete(request, emailopenid_success, emailopenid_failure) 
+    else:
+        form = ChangeemailForm(initial={
+                                        'email': u.email,
+                                        'username':request.user.username
+                                        })
+    
+    return render('account/changeemail.html', 
+            {'form': form }, context_instance=RequestContext(request))
+changeemail = username_test(changeemail, 'django_authopenid.views.changeemail')
+
+def emailopenid_success(request, identity_url, openid_response):
+    openid=from_openid_response(openid_response)
+
+    try:
+        u=User.objects.get(username=request.user.username)
+    except:
+        raise Http404
+
+    try:
+        o=UserAssociation.objects.get(openid_url__exact=identity_url)
+    except:
+        return emailopenid_failure(request, _("No openid % associated in our database" % identity_url))
+
+    if o.user.username != request.user.username:
+        return emailopenid_failure(request, _("The openid %s isn't associated to current logged user" % identity_url))
+    
+    new_email=request.GET.get('new_email', '')
+    if new_email:
+        u.email=new_email
+        u.save()
+    msg=_("Email Changed.")
+
+    redirect="%s?msg=%s" % (reverse('django_authopenid.views.account_settings',kwargs={'username': request.user.username}),urlquote_plus(msg))
+    return HttpResponseRedirect(redirect)
+    
+
+def emailopenid_failure(request, message):
+    redirect_to="%s?msg=%s" % (reverse('django_authopenid.views.changeemail',kwargs={'username':request.user.username}), urlquote_plus(message))
+
+    return HttpResponseRedirect(redirect_to)
+ 
+
+
+def changeopenid(request, username):
+    extension_args = {}
+    openid_url=''
+    has_openid=True
+    msg = request.GET.get('msg', '')
+        
+    try:
+        u=User.objects.get(username=username)
+    except:
+        raise Http404
+        
+    try:
+        uopenid=UserAssociation.objects.get(user=u)
+        openid_url = uopenid.openid_url
+    except:
+        has_openid=False
+         
+    if request.POST and has_openid:
+        form=ChangeopenidForm(request.POST)
+        if form.is_valid():
+            redirect_to = get_url_host(request) + reverse('django_authopenid.views.changeopenid',kwargs={'username':username})
+            return ask_openid(request, form.cleaned_data['openid_url'], redirect_to, on_failure=changeopenid_failure)
+    elif not request.POST and has_openid:
+        if 'openid.mode' in request.GET:
+            return complete(request, changeopenid_success, changeopenid_failure)    
+
+    form = ChangeopenidForm(initial={'openid_url': openid_url, 'username':request.user.username })
+    return render('account/changeopenid.html', {'form': form,
+        'has_openid': has_openid, 'msg': msg }, context_instance=RequestContext(request))
+
+changeopenid = username_test(changeopenid, 'django_authopenid.views.changeopenid')
+
+def changeopenid_success(request, identity_url, openid_response):
+    openid=from_openid_response(openid_response)
+    is_exist=True
+    try:
+        o=UserAssociation.objects.get(openid_url__exact=identity_url)
+    except:
+        is_exist=False
+        
+    if not is_exist:
+        try:
+            o=UserAssociation.objects.get(user__username__exact=request.user.username)
+            o.openid_url=identity_url
+            o.save()
+        except:
+            o=UserAssociation(user=request.user,openid_url=identity_url)
+            o.save()
+    elif o.user.username != request.user.username:
+        return changeopenid_failure(request, _('This openid is already associated with another account.'))
+
+    request.session['openids'] = []
+    request.session['openids'].append(openid)
+
+    msg=_("Openid %s associated with your account." % identity_url) 
+    redirect="%s?msg=%s" % (reverse('django_authopenid.views.account_settings', kwargs={'username':request.user.username}), urlquote_plus(msg))
+    return HttpResponseRedirect(redirect)
+    
+
+def changeopenid_failure(request, message):
+    redirect_to="%s?msg=%s" % (reverse('django_authopenid.views.changeopenid',kwargs={'username':request.user.username}), urlquote_plus(message))
+    return HttpResponseRedirect(redirect_to)
+    
+def delete(request,username):
+    extension_args={}
+    try:
+        u=User.objects.get(username=username)
+    except:
+        raise Http404
+
+    if request.POST:
+        form = DeleteForm(request.POST)
+        if form.is_valid():
+            if not form.test_openid:
+                u.delete()
+                from friendsnippets.django_openidconsumer.views import signout
+                return signout(request)
+            else:
+                redirect_to = get_url_host(request) + reverse('django_authopenid.views.delete',kwargs={'username':username})
+                return ask_openid(request, form.cleaned_data['password'], redirect_to, on_failure=deleteopenid_failure)
+    elif not request.POST and 'openid.mode' in request.GET:
+        return complete(request, deleteopenid_success, deleteopenid_failure) 
+    
+    form = DeleteForm(initial={'username': username})
+
+    msg = request.GET.get('msg','')
+    return render('account/delete.html', {'form': form, 'msg': msg, },
+                                        context_instance=RequestContext(request))
+
+delete = username_test(delete, 'django_authopenid.views.delete')
+
+def deleteopenid_success(request, identity_url, openid_response):
+    openid=from_openid_response(openid_response)
+
+    try:
+        u=User.objects.get(username=request.user.username)
+    except:
+        raise Http404
+
+    try:
+        o=UserAssociation.objects.get(openid_url__exact=identity_url)
+    except:
+        return deleteopenid_failure(request, _("No openid % associated in our database" % identity_url))
+
+    if o.user.username == request.user.username:
+        u.delete()
+        return signout(request)
+    else:
+        return deleteopenid_failure(request, _("The openid %s isn't associated to current logged user" % identity_url))
+    
+    msg=_("Account deleted.") 
+    redirect="/?msg=%s" % (urlquote_plus(msg))
+    return HttpResponseRedirect(redirect)
+    
+
+def deleteopenid_failure(request, message):
+    redirect_to="%s?msg=%s" % (reverse('django_authopenid.views.delete',kwargs={'username':request.user.username}), urlquote_plus(message))
+
+    return HttpResponseRedirect(redirect_to)
+
+
+def sendpw(request):
+    msg = request.GET.get('msg','')
+    if request.POST:
+        form = EmailPasswordForm(request.POST)
+        if form.is_valid():
+            new_pw = User.objects.make_random_password()
+            confirm_key = UserPasswordQueue.objects.get_new_confirm_key()
+            try:
+                q=UserPasswordQueue.objects.get(user=form.user_cache)
+            except:
+                q=UserPasswordQueue(user=form.user_cache)
+            q.new_password=new_pw
+            q.confirm_key = confirm_key
+            q.save()
+            # send email
+            from django.core.mail import send_mail
+            current_domain = Site.objects.get_current().domain
+            subject = _("Request for a new password")
+            message_template = loader.get_template('account/sendpw_email.txt')
+            message_context = Context({ 'site_url': 'http://%s' % current_domain,
+                'confirm_key': confirm_key,
+                'username': form.user_cache.username,
+                'password': new_pw,
+                'url_confirm': reverse('django_authopenid.views.confirmchangepw'),
+            })
+            message = message_template.render(message_context)
+            send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [form.user_cache.email])
+            msg=_("A new password has been sent to your email")
+    else:
+        form = EmailPasswordForm()
+        
+    return render('account/sendpw.html', {'form': form,
+            'msg': msg, },
+            context_instance=RequestContext(request))
+
+
+def confirmchangepw(request):
+    confirm_key = request.GET.get('key', '')
+    if not confirm_key:
+        return HttpResponseRedirect('/')
+
+    try:
+        q = UserPasswordQueue.objects.get(confirm_key__exact=confirm_key)
+    except:
+        msg=_("Can not change password. Confirmation key '%s' isn't registered." % confirm_key) 
+        redirect="%s?msg=%s" % (reverse('django_authopenid.views.sendpw'),urlquote_plus(msg))
+        return HttpResponseRedirect(redirect)
+
+    try:
+        user = User.objects.get(id=q.user.id)
+    except:
+        msg=_("Can not change password. User don't exist anymore in our database.") 
+        redirect="%s?msg=%s" % (reverse('django_authopenid.views.sendpw'),urlquote_plus(msg))
+        return HttpResponseRedirect(redirect)
+
+    user.set_password(q.new_password)
+    user.save()
+    q.delete()
+    msg=_("Password changed for %s. You could now sign-in" % user.username) 
+    redirect="%s?msg=%s" % (reverse('django_authopenid.views.signin'), 
+                                        urlquote_plus(msg))
+
+    return HttpResponseRedirect(redirect)
+
+       
+
+    
+    
+
+
+    
+
+
+
+
+
+