<file_sep>from django.contrib import admin
from .models import acount account

# Register your models here.
class accountAdmin(admin.ModelAdmin):
    list_display= ['username', '<PASSWORD>', 'email']


admin.site.register(accountAdmin, account)
<file_sep>from django.db import models
from django.contrib.auth.models import (AbstractBaseUser, PermissionsMixin,
                                        BaseUserManager, AnonymousUser) 
from django.core import validators
from django.utils import timezone
from django.core.mail import send_mail
from .signals import account_signed_up, account_activate
import datetime
from django.shortcuts import render_to_string
from django.core.email import EmailMultiAlternatives

SEX_CHOICE = (
    ('M', u'男'),
    ('F', u'女'),
 )

class accountManager(models.Manager):
    def _create_account(self, username, password, email, nickname, sex,
                        activation_key, is_active=False, is_staff=False,
                        is_super=False, **extra_fields):
        now = timezone.now()
        if not username:
            raise ValueError('The given username must be set')
        email = self.normalize_email(email)
        user = self.model(username=username, email=email, nickname=nickname, sex=sex,
                          activation_key=activation_key, is_super=is_super, 
                          is_staff=is_staff, is_active=is_active, join_date=now,
                          update=now, **extra_fields)
        user.set_password(<PASSWORD>)
        user.save(using=self._db)
        return user

    def create_account(self, username, password, email, nickname, sex=None, 
                       activation_key, **extra_fields):
        account =  self._create_account(username, password, email, 
                                    nickname, sex, activation_key, **extra_fields)
        retrun account
    
    def create_superuser(self, username, password, email, 
                         nickname, sex, **extra_fields):
        return self._create_account(username, password, email, nickname, sex, 
                                    'ACTIVATE', True, True, True, **extra_fields)


class account(AnonymousUser, PermissionsMixin):
    username = models.CharField(u'用户名', max_length=30, unique=True,
                                 validators=[validators.RegexValidator(
                                 re.compile('^[\w.@+-]+$'),
                                 _('Enter a valid username.'), _('invalid'))] ))
    password = models.CharField(u'密码', max_length=30)
    state = models.CharField(u'状态', max_length=10,default='unlock')
    email = models.EmailField(u'邮箱')
    is_active = models.BooleanField(u'激活状态', max_length=10, default=False)
    join_date = models.DateTimeField(u'注册时间', max_length=10, default=timezone.now)
    update = models.DateTimeField(u'上次登陆时间')
    is_staff = models.BooleanField(u'职员身份', default=False)
    is_super = models.BooleanField(u'超级管理员', default=False)
    activation_key = models.CharField(u'激活码', max_length=40)
    
    objects = accountManager()
    
    USERNAME_FIELD = 'username'
    REQUIRED_FIELD = ['email', ]

    def __unicode__(self):
        return self.username,

    def is_active(self):
        return self.is_active 

    def activate_account(self):
        self.is_active = True
        self.save(using self._db)

    def get_full_name(self):
        return self.username

   def get_short_name(self):
        return self.username

    def get_points(self): 
        return self.points

    def is_superuser(self):
        return is_super

    def get_state(self):
        return self.state
    
    def set_state(self, state):
        self.state = state
        self.save(using self._db)
    
    def is_activate_expired(self):
        expired_day = self.join_date + datetime.timedelta(days = \
             setting.ACCOUNT_ACTIVATION_DAYS)
        return self.activation_key=='ACCEPT' or datetime.now() <=  expired_day


class profile(models.Model):
    ueser = OneToOneField(account, unique=True)
    nickname = models.CharField(u'昵称', max_length=30)
    sex = models.CharField(u'性别', max_length=1, choices=SEX_CHOICE,
                           null=True, blank=True)
    level = models.DecimalField(u'等级',default=0)
    money = models.DecimalField(u'金币', default=0)
    state = models.CharField(u'状态', max_length=10,default='unlock')
    points  = models.DecimalField(u'积分', default=100)
    
    
def handle_signed_up(sender, **kwargs):
    account = kwargs.get('account')
    email = account.email
    if isinstance(email, unicode):
        email = email.encode('utf-8')
    ctx_dict = {
    'activation_key' :  account.activation_key,
    'expiration_days' : settings.ACCOUNT_ACTIVATION_DAYS,
    'site':site,
    }
    html_content = render_to_string('send_email.html', ctx_dict})
    text_content = '这是forum论坛注册激活邮件，点击激活'
    subject = 'forum论坛注册激活邮件',
    message = 'message',
    from_mail = '<EMAIL>'  
    msg = EmailMultiAlternatives(subject, text_content, from_mail, email)
    msg.attach_alternative(html_content, "text/html")
    msg.send()
    return True

        
#signals for signup    
account_signed_up.connect(handle_signed_up, dispatch_uid='account_signed_up_id')


<file_sep># -*- coding: utf-8 -*-
"""
"""

from django.conf.urls import patterns, url

urlpatterns = patterns(
    'forum.account.views',
    url('r^signup/$', 'signup', name='signup'),
    url('r^login/$', 'login', name='login'),
    url('r^logout/$', 'logout', name='logout'),
    url('r^activate_account/(P<activation_key>\w+>)/$', 'activate_account',
        name='activate'),
    url('r^reset_passwort/(P<activation_key>\w+>)/$', 'activate_account',
        name='reset_passwort'),
    url('r^change_password/(P<activation_key>\w+>)/$', 'activate_account',
        name='change_password'),
)
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
"""

from django import forms
from django.contrib import auth
from .models import account

class loginForm(forms.Form):
    username = form.CharField(required=True, label='用户名',error_message={
                              'required': u'请正确填写您的用户名',
                              'invalid': u'请正确填写您的用户名'})
    password  = form.CharField(required=True, label='密码',
                               widget=forms.PasswordInput(render_value=False)
                               error_messages={'required': 
                                               u'请正确填写您的用户名和密码'})
    
    def clean(self):
        username = self.cleaned_data.get['username']
        password = self.cleaned_data.get['password']
        if username and password:
            self.user_cache = auth.authenticate(
                username=username,
                password=<PASSWORD>)
        if self.user_cache is None:
            raise forms.ValidationError(
                self.error_message['invalid_login'],
                code = 'invalid_login',
                parms={'username':username})
        elif not self.user.is_active:
            raise forms.ValidationError(
                self.error_message['inactivate'],
                code = 'inactivate',)
        return self.cleaned_data


class signupForm(forms.Form):
    username = form.CharField(required=True, label='用户名',max_length=30,
                              regex='^[\w.@+-]+$',
                              error_messages={'invalid':'格式错误'})
    
    password1 = form.CharField(required=True, label='密码',
                               widget=forms.PasswordInput(render_value=False))
    password2 = form.CharField(required=True, label='密码',
                               widget=forms.PasswordInput(render_value=False))
    
    email = form.CharField(required=True, label='',error_messages={
                           'required': u'请填写有效的电子邮箱',
                           'invalid': u'请正确填写您的电子邮箱'})

    def clean_password2(self):
        password1 = self.cleaned_data['password1']
        password2 = self.cleaned_data['password2']
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError(
                self.error_messages[''],
                code = 'password_dismatch',)
        return password2

    def clean_username(self):
        username = self.cleaned_data['username']
        try:
            user = account.objects.get(username=username)
            except User.DoesNotExist:
                return username
            raise form.ValidationError(
                  self.error_messages['用户名已存在'],
                  code='duplicate_username')
    
    def clean_email(self):
        email = self.cleaned_data['email']
        try:
            user = account.objects.get(email=email)
            except User.DoesNotExist:
                return email
            raise form.ValidationError(
                  self.error_messages['用户名已存在'],
                  code='duplicate_username')

    
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''
'''

from django.dispatch import Signal

account_signed_up = Signal(providing_args='account')
<file_sep>#! /usr/bin/env python
# -*- coding: utf-8 -*-

from django.shortcuts import render, render_to_response
# -*-coding:utf-8 -*-

import hashlib
import random
from forum import settings
from django.template import RequestContext
from django.contrid import messages
from django.contrid import auth
from .form import loginForm, signupForm
from .account import account
from .signals import account_signed_up, account_activate


def login(request):
    if request.user.is_authenticated():
        return redirect('home')
    context = RequestContext(request)
    if request.method = 'POST':
        form = loginForm(request.POST)
        if form.is_valid():
            auth.login(request, form.user_cache)
            return redirect('home')
    else:
        form = loginForm()
        return render_to_response('', context_instance=context)


def logout(request):
    auth.logout(request)
    return redirect('home')


def signup(request):
    context = RequestContext(request)
    if requests.method = 'POST' 
        form = signupForm(requests.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = <PASSWORD>.<PASSWORD>_data['<PASSWORD>']
            email = form.cleaned_data['email']
            nickname = form.cleaned_data['nickname']
            salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
            activate_key = hashlib.sha1(salt+username).hexdigest()
            print '--------> activate_key', activate_key
            user = account.objects.create_account(username, password, email,
                                                  nickname, None, activate_key)
            if user not None:
                account_signed_up.send(sender=signupForm, accout=user)
                return redirect('home')
    else:
        form = signupForm()
        return render_to_response('',context_instance=context)
    return 


def activate_account(request, activation_key):
    account = request.get('user')
    if account.is_active():
        return 
    if account.activation_key == activation_key and account.is_activate_expired():
        account.activate_account()
        account.activate_key = 'ACCEPT'
        return 
    return 
