Commits

timger K committed e433d3d

add code

  • Participants

Comments (0)

Files changed (339)

__init__.py

Empty file added.

__init__.pyc

Binary file added.

account/.svn/entries

+10
+
+dir
+1095
+svn://guowee.com/guowee/code/trunk/account
+svn://guowee.com/guowee
+
+
+
+2011-04-25T03:36:05.598487Z
+1080
+zys
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+b6384a77-914e-427d-8adb-4b4a5a7eaa7e
+
+admin.py
+file
+
+
+
+
+2011-03-12T01:12:05.000000Z
+80e24eb5904e9a5fb6b2e769a5e92c9b
+2011-03-08T13:00:19.603495Z
+388
+zys
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+346
+
+views.py
+file
+
+
+
+
+2011-05-02T13:03:54.000000Z
+a089acf437a4829e04cac8226c3b50fc
+2011-04-25T03:36:05.598487Z
+1080
+zys
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+18156
+
+__init__.py
+file
+
+
+
+
+2011-03-12T01:12:05.000000Z
+d41d8cd98f00b204e9800998ecf8427e
+2011-02-28T13:45:57.807017Z
+153
+yishenggudou
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+0
+
+models.py
+file
+
+
+
+
+2011-04-05T05:33:50.000000Z
+7ac6ef9f4f62d2466aa33bb8d82f9adb
+2011-04-04T07:57:33.799033Z
+938
+zys
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+1440
+
+urls.py
+file
+
+
+
+
+2011-04-17T13:47:29.000000Z
+023fd186e396b81d46f0b4d719eaf6de
+2011-04-17T14:21:23.533867Z
+1059
+yishenggudou
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+943
+

account/.svn/text-base/__init__.py.svn-base

Empty file added.

account/.svn/text-base/admin.py.svn-base

+#! /usr/bin/python
+# -*- coding: utf-8 -*-
+
+from django.contrib import admin
+from models import UserProfile
+
+class UserProfileAdmin(admin.ModelAdmin):
+    list_display = ('id', 'user', 'nick_name', 'region', 'sex',
+                    'register_datetime',)
+    fields = ('nick_name', 'region')
+
+admin.site.register(UserProfile, UserProfileAdmin)

account/.svn/text-base/models.py.svn-base

+#! /usr/bin/python
+# -*- coding: utf-8 -*-
+
+import os
+
+from django.contrib.auth.models import User
+from django.db import models
+from django.conf import settings
+
+
+class UserProfile(models.Model):
+
+    id = models.AutoField('ID', primary_key=True)
+    user = models.ForeignKey(User, verbose_name='关联用户', null=False, unique=True)
+    nick_name = models.CharField('昵称', max_length=30, db_index=True)
+    region = models.CharField('地区', null=True, max_length=100)
+    register_datetime = models.DateTimeField('注册时间', auto_now_add=True)
+    sex = models.BooleanField('性别', default=True)
+    bio = models.TextField('简介', blank=True)
+
+    @property
+    def avatars(self):
+        dirname_big = '%s/%s/%s/' % ('avatars', 'b', self.user.id % 100)
+        dirname_small = '%s/%s/%s/' % ('avatars', 's', self.user.id % 100)
+        dirname_huge = '%s/%s/%s/' % ('avatars', 'h', self.user.id % 100)
+        filename_big = os.path.join(dirname_big, '%s.jpg' % self.user.id)
+        filename_small = os.path.join(dirname_small, '%s.jpg' % self.user.id)
+        filename_huge = os.path.join(dirname_huge, '%s.jpg' % self.user.id)
+        if os.path.isfile(os.path.join(settings.MEDIA_ROOT, filename_big)):
+            return filename_big, filename_small, filename_huge
+        else:
+            return 'avatars/default/avatar-big.png', 'avatars/default/avatar.png', ''
+
+    class Meta:
+        db_table = 'account_profile'

account/.svn/text-base/urls.py.svn-base

+# -*- coding:utf-8 -*-
+
+from django.conf.urls.defaults import *
+from django.contrib import admin
+
+admin.autodiscover()
+
+from views import (login,
+                   logout,
+                   register,
+                   send_mail,
+                   activate,
+                   test,
+                   reset_password,
+                   set_info,
+                   find_password,
+                   upload,
+                   save_avatars,
+                   avatars,
+                  )
+
+
+urlpatterns = patterns('',
+     (r'^test$', test),
+     (r'^login$', login),
+     (r'^logout$', logout),
+     (r'^register$', register),
+     (r'^actmail/(?P<user_id>\d+)$', send_mail),
+     (r'^activate/(?P<user_id>.*?)/(?P<code>.*)$', activate),
+     (r'^reset$', reset_password),
+     (r'^find-password$', find_password),
+     (r'^upload$', upload),
+     (r'^save_avatars$', save_avatars),
+     (r'^avatars$', avatars),
+     (r'^$', set_info),
+)

account/.svn/text-base/views.py.svn-base

+#! /usr/bin/python
+# -*- coding: utf-8 -*-
+
+import hashlib
+import re
+import os
+import bsddb
+import datetime
+import uuid
+import json
+import traceback
+import uuid
+
+import PIL.Image
+
+from django.contrib.auth.models import User
+from django.contrib import auth
+from django.http import HttpResponse, HttpResponseRedirect, Http404
+from django.template import RequestContext
+from django.shortcuts import render_to_response
+from django.conf import settings
+from django.core.mail import send_mail as django_send_mail
+from django.contrib.auth.decorators import login_required
+
+
+from account.models import UserProfile
+from invitation.models import Invitation
+
+
+def test(request):
+
+    return render_to_response('account.html')
+
+
+
+def login(request):
+    '用户登陆, 要判断是否进行验证'
+
+    if request.method != 'POST':
+        return render_to_response('login.html', {'title': u'果味登陆'})
+
+    #POST
+    ######
+    username = request.POST['email']
+    password = request.POST['pwd1']
+
+    user = auth.authenticate(username=username, password=password)
+    if user is None:
+        waring = {
+            'main': u'验证失败',
+            'details': u'邮件地址或密码错误',
+            'helper': u'请重新',
+            'url': '/account/login/',
+            'url_text': u'登陆',
+        }
+        return render_to_response('my_waring.html', {'waring': waring,
+                                                     'title': u'登陆失败',})
+    if not user.is_active:
+        #未激活
+        if not user.is_active:
+            waring = {
+                'main': u'用户未激活',
+                'details': u'',
+                'helper': u'',
+                'url': '/account/actmail/%s/' % user.id,
+                'url_text': u'重新发送激活邮件',
+            }
+            return render_to_response('waring.html', {'waring': waring,
+                                                     'title': u'用户未激活',},
+                                      context_instance=RequestContext(request))
+
+        user.login(request, -1 if is_keep else None)
+
+    auth.login(request, user)
+
+    return HttpResponseRedirect(request.GET.get('next', '/'))
+
+
+def logout(request):
+    auth.logout(request)
+    return HttpResponseRedirect('/')
+
+
+def register(request):
+    '用户注册, 需要小心验证各字段值'
+
+    if request.method != 'POST':
+        code = request.GET.get('code', '')
+        email = request.GET.get('email', '')
+        return render_to_response('register.html', {'title': u'果味注册',
+                                                   'code': code,
+                                                   'email': email})
+
+    invitation = request.POST['invitation']
+    email = request.POST['email'].lower()
+    password = request.POST['pwd1']
+    password2 = request.POST['pwd2']
+    nick_name = request.POST['nick_name']
+
+    email_re = r'^[a-z0-9.+_-]+@[a-z0-9.-]{2,}\.[a-z]{2,}$'
+
+    waring = {
+        'main': u'注册失败',
+        'details': u'',
+        'helper': u'请重新',
+        'url': '/account/register',
+        'url_text': u'注册',
+    }
+
+    if re.match(email_re, email) is None:
+        waring['details'] = u'Email地址不正确'
+        return render_to_response('waring.html', {'waring': waring,
+                                                     'title': u'注册失败',})
+
+    if password != password2:
+        waring['details'] = u'您输入的两次密码不相同'
+        return render_to_response('waring.html', {'waring': waring,
+                                                     'title': u'注册失败',})
+
+    if len(password) < 5:
+        waring['details'] = u'密码至少5个字符'
+        return render_to_response('waring.html', {'waring': waring,
+                                                     'title': u'注册失败',})
+
+    if not 1 <= len(nick_name) <= 20:
+        waring['details'] = u'您输入的昵称格式不正确'
+        return render_to_response('waring.html', {'waring': waring,
+                                                     'title': u'注册失败',})
+
+    try:
+        invitation_obj = Invitation.objects.get(code=invitation)
+    except Invitation.DoesNotExist:
+        waring['details'] = u'非法的验证码'
+        return render_to_response('waring.html', {'waring': waring,
+                                                     'title': u'注册失败',})
+    else:
+        if invitation_obj.flag == 1:
+            waring['details'] = u'验证码已经被使用过了'
+            return render_to_response('waring.html', {'waring': waring,
+                                                         'title': u'注册失败',})
+
+        if invitation_obj.to_email.lower() != email:
+            waring['details'] = u'此邀请码不接受当前邮箱地址的注册'
+            return render_to_response('waring.html', {'waring': waring,
+                                                         'title': u'注册失败',})
+
+    try:
+        user = User.objects.create_user(username=email,
+                                        email='',
+                                        password=password,)
+
+        invitation_obj = Invitation.objects.get(code=invitation)
+        invitation_obj.to_email = email
+        invitation_obj.save()
+    except:
+        waring['details'] = u'此 Email 已经被注册了'
+        return render_to_response('waring.html', {'waring': waring,
+                                                     'title': u'注册失败',})
+
+    #注册成功直接变为登陆状态,不需要激活邮件了
+    user.is_active = True
+    user.save()
+
+    profile = UserProfile(user=user)
+    profile.nick_name = nick_name
+    profile.save()
+
+    invitation_obj.flag = 1
+    invitation_obj.save()
+
+    #登陆
+    auth_user = auth.authenticate(username=email, password=password)
+    auth.login(request, auth_user)
+
+    return render_to_response('register_ok.html')
+                                          
+
+
+def send_mail(request, user_id):
+    '给用户发激活信'
+
+    user = User.objects.only('is_active', 'username').get(id=user_id)
+    if user.is_active:
+        raise Http404
+
+    code = hashlib.md5(settings.SECRET_KEY + user_id).hexdigest()
+
+    activate_url = 'http://guowee.com/account/activate/%s/%s/' % (user_id, code)
+    email_content=settings.EMAIL_CONTEXT_ACTIVATION %(user.userprofile_set.all()[0].nick_name,activate_url)
+    django_send_mail('请激活你的帐号,完成注册', email_content,
+                     settings.DEFAULT_FROM_EMAIL, [user.username])
+
+    return render_to_response('register_ok.html', {'title': u'果味网账号激活邮件'})
+
+
+def activate(request, user_id, code):
+    '激活账号'
+
+    user = User.objects.only('username', 'is_active').get(id=user_id)
+    right_code = hashlib.md5(settings.SECRET_KEY + user_id).hexdigest()
+    if code == right_code and (not user.is_active):
+        user.is_active = True
+        user.save()
+        waring = {
+            'main': u'您的账号已经激活',
+            'details': u'',
+            'helper': '',
+            'url': '',
+            'url_text': '',
+        }
+
+        return render_to_response('waring.html', {'waring': waring,
+                                                     'title': u'果味网账号激活',},
+                                  context_instance=RequestContext(request))
+    else:
+        raise Http404
+
+
+@login_required
+def reset_password(request):
+    '重置密码'
+
+    if request.method != 'POST':
+        return render_to_response('resetpassword.html', {'title': u'重置密码'},
+                                  context_instance=RequestContext(request))
+
+    old_password = request.POST['pwd3']
+    password = request.POST['pwd1']
+    password2 = request.POST['pwd2']
+
+    waring = {
+        'main': u'重置密码失败',
+        'details': u'',
+        'helper': u'',
+        'url': '/account/reset',
+        'url_text': u'再试一次',
+    }
+
+    if password != password2:
+        waring['details'] = u'您输入的两次密码不相同'
+        return render_to_response('waring.html', {'waring': waring,
+                                                     'title': u'验证失败',},
+                                  context_instance=RequestContext(request))
+
+    if len(password) < 5:
+        waring['details'] = u'密码至少5个字符'
+        return render_to_response('waring.html', {'waring': waring,
+                                                     'title': u'验证失败',},
+                                  context_instance=RequestContext(request))
+
+    if password == old_password:
+        waring['details'] = u'新密码与旧密码相同, 不需要重置密码'
+        return render_to_response('waring.html', {'waring': waring,
+                                                     'title': u'验证失败',},
+                                  context_instance=RequestContext(request))
+
+    if not request.user.check_password(old_password):
+        waring['details'] = u'原密码不正确'
+        return render_to_response('waring.html', {'waring': waring,
+                                                     'title': u'验证失败',},
+                                  context_instance=RequestContext(request))
+    else:
+        request.user.set_password(password)
+        request.user.save()
+        #不用注销
+        #auth.logout(request)
+        return render_to_response('resetpassword_ok.html', {'title': u'重置密码成功',},
+                                  context_instance=RequestContext(request))
+
+
+def _save_avatar(user, file, type):
+    '''保存某用户的头像
+    根据用户的ID模100, 作一次目录hash.
+    返回四个临时文件的路径位置.
+    '''
+
+    dirname = '%s/%s/%s/%s' % (settings.MEDIA_ROOT, 'avatars', type, user.id % 100)
+    if not os.path.isdir(dirname):
+        os.makedirs(dirname)
+
+    file.open('r')
+    image = PIL.Image.open(file)
+    iw, ih = image.size
+    if iw>ih:
+        image=image.crop(((iw-ih)/2, 0, (iw-ih)/2+ih, ih))
+    elif ih > iw:
+        image=image.crop((0, (ih-iw)/2, iw, (ih-iw)/2+iw))
+    else:
+        pass
+    origin = os.path.join(dirname, '%s.jpg' % uuid.uuid4().hex)
+    image.save(origin)
+
+    image.thumbnail((500, 500),PIL.Image.ANTIALIAS)
+    huge = os.path.join(dirname, '%s.jpg' % uuid.uuid4().hex)
+    image.save(huge)
+
+    image.thumbnail((150, 150),PIL.Image.ANTIALIAS)
+    big = os.path.join(dirname, '%s.jpg' % uuid.uuid4().hex)
+    image.save(big)
+
+    image.thumbnail((50, 50),PIL.Image.ANTIALIAS)
+    small = os.path.join(dirname, '%s.jpg' % uuid.uuid4().hex)
+    image.save(small)
+
+
+    return (origin, huge, big, small)
+
+
+def _script_str(status, msg, user_id, origin, huge, big, small):
+    '返回给客户端的js执行段'
+    s = '''
+        <script type="text/javascript" charset="utf8">
+            function upload_callback(status, msg){
+                if(status){
+                    window.parent.after_upload("%(user_id)s", "%(origin)s", "%(huge)s", "%(big)s", "%(small)s");
+                } else {
+                    alert(msg);
+                }
+            }   
+
+            upload_callback(%(status)s, '%(msg)s');
+        </script>''' % {'user_id': user_id,
+                        'status': status,
+                        'msg': msg,
+                        'origin': origin,
+                        'big': big,
+                        'small': small,
+                        'huge': huge,}
+    return s
+
+
+@login_required
+def avatars(request):
+    '修改头像'
+
+    big, small, huge = request.user.get_profile().avatars
+    return render_to_response('face.html',
+                              {'avatar_b': '/static/' + big,
+                               'avatar_s': '/static/' + small,
+                               'title': u'头像修改',},
+                             context_instance=RequestContext(request))
+
+
+@login_required
+def upload(request):
+    '上传头像的原图'
+
+    try:
+        profile = request.user.get_profile()
+    except UserProfile.DoesNotExist:
+        profile = UserProfile(user=request.user, nick_name='')
+        profile.save()
+
+    file = request.FILES.get('img')
+    if file:
+        #最大400K
+        if request.FILES['img'].size > 1024 * 400:
+            return HttpResponse(json.dumps({'result': False, 'msg': u'图片最大为400K'}))
+
+        #格式检查
+        if file.content_type not in ['image/jpeg', 'image/png', 'image/gif']:
+            return HttpResponse(json.dumps({'result': False, 'msg': u'请上传jpeg, png, gif格式的图片'}))
+
+        #保存头像
+        origin, huge, big, small = _save_avatar(request.user, file, 'tmp')
+
+        origin = os.path.sep.join(origin.split(os.path.sep)[-2:])
+
+        huge = os.path.sep.join(huge.split(os.path.sep)[-2:])
+
+        big = os.path.sep.join(big.split(os.path.sep)[-2:])
+        small = os.path.sep.join(small.split(os.path.sep)[-2:])
+        return HttpResponse(_script_str('true', '', request.user.id, origin, huge, big, small))
+
+
+@login_required
+def save_avatars(request):
+    '保存头像, 把相关文件移动到相应位置'
+    big = request.POST['big']
+    small = request.POST['small']
+    huge = request.POST['huge']
+
+    big_file = '%s/%s/%s/%s/%s' % tuple([settings.MEDIA_ROOT, 'avatars', 'tmp']
+                                        + big.split('/')[-2:])
+    if not os.path.isfile(big_file):
+        return HttpResponse(json.dumps({'result': False, 'msg': u'头像文件不存在'}))
+
+    small_file = '%s/%s/%s/%s/%s' % tuple([settings.MEDIA_ROOT, 'avatars', 'tmp']
+                                          + small.split('/')[-2:])
+
+    huge_file = '%s/%s/%s/%s/%s' % tuple([settings.MEDIA_ROOT, 'avatars', 'tmp']
+                                          + huge.split('/')[-2:])
+
+    dirname = '%s/%s/%s/%s' % (settings.MEDIA_ROOT, 'avatars', 'b', request.user.id % 100)
+    if not os.path.isdir(dirname):
+        os.makedirs(dirname)
+    os.renames(big_file, '%s/%s.jpg' % (dirname, request.user.id))
+
+    dirname = '%s/%s/%s/%s' % (settings.MEDIA_ROOT, 'avatars', 's', request.user.id % 100)
+    if not os.path.isdir(dirname):
+        os.makedirs(dirname)
+    os.renames(small_file, '%s/%s.jpg' % (dirname, request.user.id))
+
+    dirname = '%s/%s/%s/%s' % (settings.MEDIA_ROOT, 'avatars', 'h', request.user.id % 100)
+    if not os.path.isdir(dirname):
+        os.makedirs(dirname)
+    os.renames(huge_file, '%s/%s.jpg' % (dirname, request.user.id))
+    
+    return HttpResponse(json.dumps({'result': True, 'msg': request.user.id}))
+        
+
+@login_required
+def set_info(request):
+    '修改用户的资料'
+
+    try:
+        profile = request.user.get_profile()
+    except UserProfile.DoesNotExist:
+        profile = UserProfile(user=request.user, nick_name='')
+        profile.save()
+
+    if request.method != 'POST':
+        return render_to_response('account.html',
+                  {'title': u'%s的信息' % profile.nick_name or request.user.username,
+                   'nick_name': profile.nick_name,
+                   'bio': profile.bio,
+                   'avatar': '/static/%s/%s/%s/%s.jpg' % ('avatars', 'b',
+                                                          request.user.id % 100, request.user.id),},
+                  context_instance=RequestContext(request))
+
+    nick_name = request.POST.get('nick_name') or profile.nick_name
+    bio = request.POST.get('bio') or profile.bio
+
+    profile.nick_name = nick_name
+    profile.bio = bio
+    profile.save()
+
+    waring = {
+        'main': u'资料修改成功',
+        'details': u'',
+        'helper': u'',
+        'url': '/',
+        'url_text': u'返回首页',
+    }
+
+    return render_to_response('my_waring.html', {'waring': waring,
+                                                 'title': u'资料修改成功',},
+                                              context_instance=RequestContext(request))
+
+def find_password(request):
+    '找回密码,生成一个随机密码,然后发到用户的邮箱当中'
+
+    waring = {
+        'main': u'验证失败',
+        'details': u'',
+        'helper': u'',
+        'url': '/account/find-password/',
+        'url_text': u'重试',
+    }
+
+    if request.user.is_authenticated():
+        waring['details'] = u'你现在处于登陆状态,不能执行此操作'
+        return render_to_response('waring.html', {'waring': waring,
+                                                     'title': u'忘记密码',},
+                                      context_instance=RequestContext(request))
+
+    if request.method != 'POST':
+        return render_to_response('forgetpassword.html',
+                                     {'title': u'忘记密码',},
+                                  context_instance=RequestContext(request))
+
+    email = request.POST.get('email', '.').lower()
+
+    email_re = r'^[a-z0-9.+]+@[a-z0-9]{2,}\.[a-z]{2,}$'
+
+    if re.match(email_re, email) is None:
+        waring['details'] = u'Email地址不正确'
+        return render_to_response('waring.html', {'waring': waring,
+                                                     'title': u'忘记密码',},
+                                  context_instance=RequestContext(request))
+
+    try:
+        user = User.objects.get(username=email)
+    except User.DoesNotExist:
+        waring['details'] = u'无此用户'
+        return render_to_response('waring.html', {'waring': waring,
+                                                     'title': u'忘记密码',},
+                                  context_instance=RequestContext(request))
+
+    password = uuid.uuid4().get_hex()[:6]
+    user.set_password(password)
+    user.save()
+
+    django_send_mail('果味网登陆密码', password,
+                     settings.DEFAULT_FROM_EMAIL, [email])
+
+    waring = {
+        'main': u'获取密码成功',
+        'details': u'我们已经将密码放送至您的注册邮箱,请注意查收',
+        'helper': u'',
+        'url': '',
+        'url_text': u'',
+    }
+
+    return render_to_response('waring.html', {'waring': waring,
+                                                 'title': u'忘记密码',},
+                                  context_instance=RequestContext(request))

account/__init__.py

Empty file added.

account/__init__.pyc

Binary file added.
+#! /usr/bin/python
+# -*- coding: utf-8 -*-
+
+from django.contrib import admin
+from models import UserProfile
+
+class UserProfileAdmin(admin.ModelAdmin):
+    list_display = ('id', 'user', 'nick_name', 'region', 'sex',
+                    'register_datetime',)
+    fields = ('nick_name', 'region')
+
+admin.site.register(UserProfile, UserProfileAdmin)

account/admin.pyc

Binary file added.

account/models.py

+#! /usr/bin/python
+# -*- coding: utf-8 -*-
+
+import os
+
+from django.contrib.auth.models import User
+from django.db import models
+from django.conf import settings
+
+
+class UserProfile(models.Model):
+
+    id = models.AutoField('ID', primary_key=True)
+    user = models.ForeignKey(User, verbose_name='关联用户', null=False, unique=True)
+    nick_name = models.CharField('昵称', max_length=30, db_index=True)
+    region = models.CharField('地区', null=True, max_length=100)
+    register_datetime = models.DateTimeField('注册时间', auto_now_add=True)
+    sex = models.BooleanField('性别', default=True)
+    bio = models.TextField('简介', blank=True)
+
+    @property
+    def avatars(self):
+        dirname_big = '%s/%s/%s/' % ('avatars', 'b', self.user.id % 100)
+        dirname_small = '%s/%s/%s/' % ('avatars', 's', self.user.id % 100)
+        dirname_huge = '%s/%s/%s/' % ('avatars', 'h', self.user.id % 100)
+        filename_big = os.path.join(dirname_big, '%s.jpg' % self.user.id)
+        filename_small = os.path.join(dirname_small, '%s.jpg' % self.user.id)
+        filename_huge = os.path.join(dirname_huge, '%s.jpg' % self.user.id)
+        if os.path.isfile(os.path.join(settings.MEDIA_ROOT, filename_big)):
+            return filename_big, filename_small, filename_huge
+        else:
+            return 'avatars/default/avatar-big.png', 'avatars/default/avatar.png', ''
+
+    class Meta:
+        db_table = 'account_profile'

account/models.pyc

Binary file added.
+# -*- coding:utf-8 -*-
+
+from django.conf.urls.defaults import *
+from django.contrib import admin
+
+admin.autodiscover()
+
+from views import (login,
+                   logout,
+                   register,
+                   send_mail,
+                   activate,
+                   test,
+                   reset_password,
+                   set_info,
+                   find_password,
+                   upload,
+                   save_avatars,
+                   avatars,
+                  )
+
+
+urlpatterns = patterns('',
+     (r'^test$', test),
+     (r'^login$', login),
+     (r'^logout$', logout),
+     (r'^register$', register),
+     (r'^actmail/(?P<user_id>\d+)$', send_mail),
+     (r'^activate/(?P<user_id>.*?)/(?P<code>.*)$', activate),
+     (r'^reset$', reset_password),
+     (r'^find-password$', find_password),
+     (r'^upload$', upload),
+     (r'^save_avatars$', save_avatars),
+     (r'^avatars$', avatars),
+     (r'^$', set_info),
+)

account/urls.pyc

Binary file added.
+#! /usr/bin/python
+# -*- coding: utf-8 -*-
+
+import hashlib
+import re
+import os
+import bsddb
+import datetime
+import uuid
+import json
+import traceback
+import uuid
+
+import PIL.Image
+
+from django.contrib.auth.models import User
+from django.contrib import auth
+from django.http import HttpResponse, HttpResponseRedirect, Http404
+from django.template import RequestContext
+from django.shortcuts import render_to_response
+from django.conf import settings
+from django.core.mail import send_mail as django_send_mail
+from django.contrib.auth.decorators import login_required
+
+
+from account.models import UserProfile
+from invitation.models import Invitation
+
+
+def test(request):
+
+    return render_to_response('account.html')
+
+
+
+def login(request):
+    '用户登陆, 要判断是否进行验证'
+
+    if request.method != 'POST':
+        return render_to_response('login.html', {'title': u'果味登陆'})
+
+    #POST
+    ######
+    username = request.POST['email']
+    password = request.POST['pwd1']
+
+    user = auth.authenticate(username=username, password=password)
+    if user is None:
+        waring = {
+            'main': u'验证失败',
+            'details': u'邮件地址或密码错误',
+            'helper': u'请重新',
+            'url': '/account/login/',
+            'url_text': u'登陆',
+        }
+        return render_to_response('waring.html', {'waring': waring,
+                                                     'title': u'登陆失败',})
+    if not user.is_active:
+        #未激活
+        if not user.is_active:
+            waring = {
+                'main': u'用户未激活',
+                'details': u'',
+                'helper': u'',
+                'url': '/account/actmail/%s/' % user.id,
+                'url_text': u'重新发送激活邮件',
+            }
+            return render_to_response('waring.html', {'waring': waring,
+                                                     'title': u'用户未激活',},
+                                      context_instance=RequestContext(request))
+
+        user.login(request, -1 if is_keep else None)
+
+    auth.login(request, user)
+
+    return HttpResponseRedirect(request.GET.get('next', '/'))
+
+
+def logout(request):
+    auth.logout(request)
+    return HttpResponseRedirect('/')
+
+
+def register(request):
+    '用户注册, 需要小心验证各字段值'
+
+    if request.method != 'POST':
+        code = request.GET.get('code', '')
+        email = request.GET.get('email', '')
+        return render_to_response('register.html', {'title': u'果味注册',
+                                                   'code': code,
+                                                   'email': email})
+
+    invitation = request.POST['invitation']
+    email = request.POST['email'].lower()
+    password = request.POST['pwd1']
+    password2 = request.POST['pwd2']
+    nick_name = request.POST['nick_name']
+
+    email_re = r'^[a-z0-9.+_-]+@[a-z0-9.-]{2,}\.[a-z]{2,}$'
+
+    waring = {
+        'main': u'注册失败',
+        'details': u'',
+        'helper': u'请重新',
+        'url': '/account/register',
+        'url_text': u'注册',
+    }
+
+    if re.match(email_re, email) is None:
+        waring['details'] = u'Email地址不正确'
+        return render_to_response('waring.html', {'waring': waring,
+                                                     'title': u'注册失败',})
+
+    if password != password2:
+        waring['details'] = u'您输入的两次密码不相同'
+        return render_to_response('waring.html', {'waring': waring,
+                                                     'title': u'注册失败',})
+
+    if len(password) < 5:
+        waring['details'] = u'密码至少5个字符'
+        return render_to_response('waring.html', {'waring': waring,
+                                                     'title': u'注册失败',})
+
+    if not 1 <= len(nick_name) <= 20:
+        waring['details'] = u'您输入的昵称格式不正确'
+        return render_to_response('waring.html', {'waring': waring,
+                                                     'title': u'注册失败',})
+
+    try:
+        invitation_obj = Invitation.objects.get(code=invitation)
+    except Invitation.DoesNotExist:
+        waring['details'] = u'非法的验证码'
+        return render_to_response('waring.html', {'waring': waring,
+                                                     'title': u'注册失败',})
+    else:
+        if invitation_obj.flag == 1:
+            waring['details'] = u'验证码已经被使用过了'
+            return render_to_response('waring.html', {'waring': waring,
+                                                         'title': u'注册失败',})
+
+        if invitation_obj.to_email.lower() != email:
+            waring['details'] = u'此邀请码不接受当前邮箱地址的注册'
+            return render_to_response('waring.html', {'waring': waring,
+                                                         'title': u'注册失败',})
+
+    try:
+        user = User.objects.create_user(username=email,
+                                        email='',
+                                        password=password,)
+
+        invitation_obj = Invitation.objects.get(code=invitation)
+        invitation_obj.to_email = email
+        invitation_obj.save()
+    except:
+        waring['details'] = u'此 Email 已经被注册了'
+        return render_to_response('waring.html', {'waring': waring,
+                                                     'title': u'注册失败',})
+
+    #注册成功直接变为登陆状态,不需要激活邮件了
+    user.is_active = True
+    user.save()
+
+    profile = UserProfile(user=user)
+    profile.nick_name = nick_name
+    profile.save()
+
+    invitation_obj.flag = 1
+    invitation_obj.save()
+
+    #登陆
+    auth_user = auth.authenticate(username=email, password=password)
+    auth.login(request, auth_user)
+
+    return render_to_response('register_ok.html')
+                                          
+
+
+def send_mail(request, user_id):
+    '给用户发激活信'
+
+    user = User.objects.only('is_active', 'username').get(id=user_id)
+    if user.is_active:
+        raise Http404
+
+    code = hashlib.md5(settings.SECRET_KEY + user_id).hexdigest()
+
+    activate_url = 'http://guowee.com/account/activate/%s/%s/' % (user_id, code)
+    email_content=settings.EMAIL_CONTEXT_ACTIVATION %(user.userprofile_set.all()[0].nick_name,activate_url)
+    django_send_mail('请激活你的帐号,完成注册', email_content,
+                     settings.DEFAULT_FROM_EMAIL, [user.username])
+
+    return render_to_response('register_ok.html', {'title': u'果味网账号激活邮件'})
+
+
+def activate(request, user_id, code):
+    '激活账号'
+
+    user = User.objects.only('username', 'is_active').get(id=user_id)
+    right_code = hashlib.md5(settings.SECRET_KEY + user_id).hexdigest()
+    if code == right_code and (not user.is_active):
+        user.is_active = True
+        user.save()
+        waring = {
+            'main': u'您的账号已经激活',
+            'details': u'',
+            'helper': '',
+            'url': '',
+            'url_text': '',
+        }
+
+        return render_to_response('waring.html', {'waring': waring,
+                                                     'title': u'果味网账号激活',},
+                                  context_instance=RequestContext(request))
+    else:
+        raise Http404
+
+
+@login_required
+def reset_password(request):
+    '重置密码'
+
+    if request.method != 'POST':
+        return render_to_response('resetpassword.html', {'title': u'重置密码'},
+                                  context_instance=RequestContext(request))
+
+    old_password = request.POST['pwd3']
+    password = request.POST['pwd1']
+    password2 = request.POST['pwd2']
+
+    waring = {
+        'main': u'重置密码失败',
+        'details': u'',
+        'helper': u'',
+        'url': '/account/reset',
+        'url_text': u'再试一次',
+    }
+
+    if password != password2:
+        waring['details'] = u'您输入的两次密码不相同'
+        return render_to_response('waring.html', {'waring': waring,
+                                                     'title': u'验证失败',},
+                                  context_instance=RequestContext(request))
+
+    if len(password) < 5:
+        waring['details'] = u'密码至少5个字符'
+        return render_to_response('waring.html', {'waring': waring,
+                                                     'title': u'验证失败',},
+                                  context_instance=RequestContext(request))
+
+    if password == old_password:
+        waring['details'] = u'新密码与旧密码相同, 不需要重置密码'
+        return render_to_response('waring.html', {'waring': waring,
+                                                     'title': u'验证失败',},
+                                  context_instance=RequestContext(request))
+
+    if not request.user.check_password(old_password):
+        waring['details'] = u'原密码不正确'
+        return render_to_response('waring.html', {'waring': waring,
+                                                     'title': u'验证失败',},
+                                  context_instance=RequestContext(request))
+    else:
+        request.user.set_password(password)
+        request.user.save()
+        #不用注销
+        #auth.logout(request)
+        return render_to_response('resetpassword_ok.html', {'title': u'重置密码成功',},
+                                  context_instance=RequestContext(request))
+
+
+def _save_avatar(user, file, type):
+    '''保存某用户的头像
+    根据用户的ID模100, 作一次目录hash.
+    返回四个临时文件的路径位置.
+    '''
+
+    dirname = '%s/%s/%s/%s' % (settings.MEDIA_ROOT, 'avatars', type, user.id % 100)
+    if not os.path.isdir(dirname):
+        os.makedirs(dirname)
+
+    file.open('r')
+    image = PIL.Image.open(file)
+    iw, ih = image.size
+    if iw>ih:
+        image=image.crop(((iw-ih)/2, 0, (iw-ih)/2+ih, ih))
+    elif ih > iw:
+        image=image.crop((0, (ih-iw)/2, iw, (ih-iw)/2+iw))
+    else:
+        pass
+    origin = os.path.join(dirname, '%s.jpg' % uuid.uuid4().hex)
+    image.save(origin)
+
+    image.thumbnail((500, 500),PIL.Image.ANTIALIAS)
+    huge = os.path.join(dirname, '%s.jpg' % uuid.uuid4().hex)
+    image.save(huge)
+
+    image.thumbnail((150, 150),PIL.Image.ANTIALIAS)
+    big = os.path.join(dirname, '%s.jpg' % uuid.uuid4().hex)
+    image.save(big)
+
+    image.thumbnail((50, 50),PIL.Image.ANTIALIAS)
+    small = os.path.join(dirname, '%s.jpg' % uuid.uuid4().hex)
+    image.save(small)
+
+
+    return (origin, huge, big, small)
+
+
+def _script_str(status, msg, user_id, origin, huge, big, small):
+    '返回给客户端的js执行段'
+    s = '''
+        <script type="text/javascript" charset="utf8">
+            function upload_callback(status, msg){
+                if(status){
+                    window.parent.after_upload("%(user_id)s", "%(origin)s", "%(huge)s", "%(big)s", "%(small)s");
+                } else {
+                    alert(msg);
+                }
+            }   
+
+            upload_callback(%(status)s, '%(msg)s');
+        </script>''' % {'user_id': user_id,
+                        'status': status,
+                        'msg': msg,
+                        'origin': origin,
+                        'big': big,
+                        'small': small,
+                        'huge': huge,}
+    return s
+
+
+@login_required
+def avatars(request):
+    '修改头像'
+
+    big, small, huge = request.user.get_profile().avatars
+    return render_to_response('face.html',
+                              {'avatar_b': '/static/' + big,
+                               'avatar_s': '/static/' + small,
+                               'title': u'头像修改',},
+                             context_instance=RequestContext(request))
+
+
+@login_required
+def upload(request):
+    '上传头像的原图'
+
+    try:
+        profile = request.user.get_profile()
+    except UserProfile.DoesNotExist:
+        profile = UserProfile(user=request.user, nick_name='')
+        profile.save()
+
+    file = request.FILES.get('img')
+    if file:
+        #最大400K
+        if request.FILES['img'].size > 1024 * 400:
+            return HttpResponse(json.dumps({'result': False, 'msg': u'图片最大为400K'}))
+
+        #格式检查
+        if file.content_type not in ['image/jpeg', 'image/png', 'image/gif']:
+            return HttpResponse(json.dumps({'result': False, 'msg': u'请上传jpeg, png, gif格式的图片'}))
+
+        #保存头像
+        origin, huge, big, small = _save_avatar(request.user, file, 'tmp')
+
+        origin = os.path.sep.join(origin.split(os.path.sep)[-2:])
+
+        huge = os.path.sep.join(huge.split(os.path.sep)[-2:])
+
+        big = os.path.sep.join(big.split(os.path.sep)[-2:])
+        small = os.path.sep.join(small.split(os.path.sep)[-2:])
+        return HttpResponse(_script_str('true', '', request.user.id, origin, huge, big, small))
+
+
+@login_required
+def save_avatars(request):
+    '保存头像, 把相关文件移动到相应位置'
+    big = request.POST['big']
+    small = request.POST['small']
+    huge = request.POST['huge']
+
+    big_file = '%s/%s/%s/%s/%s' % tuple([settings.MEDIA_ROOT, 'avatars', 'tmp']
+                                        + big.split('/')[-2:])
+    if not os.path.isfile(big_file):
+        return HttpResponse(json.dumps({'result': False, 'msg': u'头像文件不存在'}))
+
+    small_file = '%s/%s/%s/%s/%s' % tuple([settings.MEDIA_ROOT, 'avatars', 'tmp']
+                                          + small.split('/')[-2:])
+
+    huge_file = '%s/%s/%s/%s/%s' % tuple([settings.MEDIA_ROOT, 'avatars', 'tmp']
+                                          + huge.split('/')[-2:])
+
+    dirname = '%s/%s/%s/%s' % (settings.MEDIA_ROOT, 'avatars', 'b', request.user.id % 100)
+    if not os.path.isdir(dirname):
+        os.makedirs(dirname)
+    os.renames(big_file, '%s/%s.jpg' % (dirname, request.user.id))
+
+    dirname = '%s/%s/%s/%s' % (settings.MEDIA_ROOT, 'avatars', 's', request.user.id % 100)
+    if not os.path.isdir(dirname):
+        os.makedirs(dirname)
+    os.renames(small_file, '%s/%s.jpg' % (dirname, request.user.id))
+
+    dirname = '%s/%s/%s/%s' % (settings.MEDIA_ROOT, 'avatars', 'h', request.user.id % 100)
+    if not os.path.isdir(dirname):
+        os.makedirs(dirname)
+    os.renames(huge_file, '%s/%s.jpg' % (dirname, request.user.id))
+    
+    return HttpResponse(json.dumps({'result': True, 'msg': request.user.id}))
+        
+
+@login_required
+def set_info(request):
+    '修改用户的资料'
+
+    try:
+        profile = request.user.get_profile()
+    except UserProfile.DoesNotExist:
+        profile = UserProfile(user=request.user, nick_name='')
+        profile.save()
+
+    if request.method != 'POST':
+        return render_to_response('account.html',
+                  {'title': u'%s的信息' % profile.nick_name or request.user.username,
+                   'nick_name': profile.nick_name,
+                   'bio': profile.bio,
+                   'avatar': '/static/%s/%s/%s/%s.jpg' % ('avatars', 'b',
+                                                          request.user.id % 100, request.user.id),},
+                  context_instance=RequestContext(request))
+
+    nick_name = request.POST.get('nick_name') or profile.nick_name
+    bio = request.POST.get('bio') or profile.bio
+
+    profile.nick_name = nick_name
+    profile.bio = bio
+    profile.save()
+
+    waring = {
+        'main': u'资料修改成功',
+        'details': u'',
+        'helper': u'',
+        'url': '/',
+        'url_text': u'返回首页',
+    }
+
+    return render_to_response('waring.html', {'waring': waring,
+                                                 'title': u'资料修改成功',},
+                                              context_instance=RequestContext(request))
+
+def find_password(request):
+    '找回密码,生成一个随机密码,然后发到用户的邮箱当中'
+
+    waring = {
+        'main': u'验证失败',
+        'details': u'',
+        'helper': u'',
+        'url': '/account/find-password/',
+        'url_text': u'重试',
+    }
+
+    if request.user.is_authenticated():
+        waring['details'] = u'你现在处于登陆状态,不能执行此操作'
+        return render_to_response('waring.html', {'waring': waring,
+                                                     'title': u'忘记密码',},
+                                      context_instance=RequestContext(request))
+
+    if request.method != 'POST':
+        return render_to_response('forgetpassword.html',
+                                     {'title': u'忘记密码',},
+                                  context_instance=RequestContext(request))
+
+    email = request.POST.get('email', '.').lower()
+
+    email_re = r'^[a-z0-9.+]+@[a-z0-9]{2,}\.[a-z]{2,}$'
+
+    if re.match(email_re, email) is None:
+        waring['details'] = u'Email地址不正确'
+        return render_to_response('waring.html', {'waring': waring,
+                                                     'title': u'忘记密码',},
+                                  context_instance=RequestContext(request))
+
+    try:
+        user = User.objects.get(username=email)
+    except User.DoesNotExist:
+        waring['details'] = u'无此用户'
+        return render_to_response('waring.html', {'waring': waring,
+                                                     'title': u'忘记密码',},
+                                  context_instance=RequestContext(request))
+
+    password = uuid.uuid4().get_hex()[:6]
+    user.set_password(password)
+    user.save()
+
+    django_send_mail('果味网登陆密码', password,
+                     settings.DEFAULT_FROM_EMAIL, [email])
+
+    waring = {
+        'main': u'获取密码成功',
+        'details': u'我们已经将密码放送至您的注册邮箱,请注意查收',
+        'helper': u'',
+        'url': '',
+        'url_text': u'',
+    }
+
+    return render_to_response('waring.html', {'waring': waring,
+                                                 'title': u'忘记密码',},
+                                  context_instance=RequestContext(request))

account/views.pyc

Binary file added.

account/views.py~

+#! /usr/bin/python
+# -*- coding: utf-8 -*-
+
+import hashlib
+import re
+import os
+import bsddb
+import datetime
+import uuid
+import json
+import traceback
+import uuid
+
+import PIL.Image
+
+from django.contrib.auth.models import User
+from django.contrib import auth
+from django.http import HttpResponse, HttpResponseRedirect, Http404
+from django.template import RequestContext
+from django.shortcuts import render_to_response
+from django.conf import settings
+from django.core.mail import send_mail as django_send_mail
+from django.contrib.auth.decorators import login_required
+
+
+from account.models import UserProfile
+from invitation.models import Invitation
+
+
+def test(request):
+
+    return render_to_response('account.html')
+
+
+
+def login(request):
+    '用户登陆, 要判断是否进行验证'
+
+    if request.method != 'POST':
+        return render_to_response('login.html', {'title': u'果味登陆'})
+
+    #POST
+    ######
+    username = request.POST['email']
+    password = request.POST['pwd1']
+
+    user = auth.authenticate(username=username, password=password)
+    if user is None:
+        waring = {
+            'main': u'验证失败',
+            'details': u'邮件地址或密码错误',
+            'helper': u'请重新',
+            'url': '/account/login/',
+            'url_text': u'登陆',
+        }
+        return render_to_response('waring.html', {'waring': waring,
+                                                     'title': u'登陆失败',})
+    if not user.is_active:
+        #未激活
+        if not user.is_active:
+            waring = {
+                'main': u'用户未激活',
+                'details': u'',
+                'helper': u'',
+                'url': '/account/actmail/%s/' % user.id,
+                'url_text': u'重新发送激活邮件',
+            }
+            return render_to_response('waring.html', {'waring': waring,
+                                                     'title': u'用户未激活',},
+                                      context_instance=RequestContext(request))
+
+        user.login(request, -1 if is_keep else None)
+
+    auth.login(request, user)
+
+    return HttpResponseRedirect(request.GET.get('next', '/'))
+
+
+def logout(request):
+    auth.logout(request)
+    return HttpResponseRedirect('/')
+
+
+def register(request):
+    '用户注册, 需要小心验证各字段值'
+
+    if request.method != 'POST':
+        code = request.GET.get('code', '')
+        email = request.GET.get('email', '')
+        return render_to_response('register.html', {'title': u'果味注册',
+                                                   'code': code,
+                                                   'email': email})
+
+    invitation = request.POST['invitation']
+    email = request.POST['email'].lower()
+    password = request.POST['pwd1']
+    password2 = request.POST['pwd2']
+    nick_name = request.POST['nick_name']
+
+    email_re = r'^[a-z0-9.+_-]+@[a-z0-9.-]{2,}\.[a-z]{2,}$'
+
+    waring = {
+        'main': u'注册失败',
+        'details': u'',
+        'helper': u'请重新',
+        'url': '/account/register',
+        'url_text': u'注册',
+    }
+
+    if re.match(email_re, email) is None:
+        waring['details'] = u'Email地址不正确'
+        return render_to_response('waring.html', {'waring': waring,
+                                                     'title': u'注册失败',})
+
+    if password != password2:
+        waring['details'] = u'您输入的两次密码不相同'
+        return render_to_response('waring.html', {'waring': waring,
+                                                     'title': u'注册失败',})
+
+    if len(password) < 5:
+        waring['details'] = u'密码至少5个字符'
+        return render_to_response('waring.html', {'waring': waring,
+                                                     'title': u'注册失败',})
+
+    if not 1 <= len(nick_name) <= 20:
+        waring['details'] = u'您输入的昵称格式不正确'
+        return render_to_response('waring.html', {'waring': waring,
+                                                     'title': u'注册失败',})
+
+    try:
+        invitation_obj = Invitation.objects.get(code=invitation)
+    except Invitation.DoesNotExist:
+        waring['details'] = u'非法的验证码'
+        return render_to_response('waring.html', {'waring': waring,
+                                                     'title': u'注册失败',})
+    else:
+        if invitation_obj.flag == 1:
+            waring['details'] = u'验证码已经被使用过了'
+            return render_to_response('waring.html', {'waring': waring,
+                                                         'title': u'注册失败',})
+
+        if invitation_obj.to_email.lower() != email:
+            waring['details'] = u'此邀请码不接受当前邮箱地址的注册'
+            return render_to_response('waring.html', {'waring': waring,
+                                                         'title': u'注册失败',})
+
+    try:
+        user = User.objects.create_user(username=email,
+                                        email='',
+                                        password=password,)
+
+        invitation_obj = Invitation.objects.get(code=invitation)
+        invitation_obj.to_email = email
+        invitation_obj.save()
+    except:
+        waring['details'] = u'此 Email 已经被注册了'
+        return render_to_response('waring.html', {'waring': waring,
+                                                     'title': u'注册失败',})
+
+    #注册成功直接变为登陆状态,不需要激活邮件了
+    user.is_active = True
+    user.save()
+
+    profile = UserProfile(user=user)
+    profile.nick_name = nick_name
+    profile.save()
+
+    invitation_obj.flag = 1
+    invitation_obj.save()
+
+    #登陆
+    auth_user = auth.authenticate(username=email, password=password)
+    auth.login(request, auth_user)
+
+    return render_to_response('register_ok.html')
+                                          
+
+
+def send_mail(request, user_id):
+    '给用户发激活信'
+
+    user = User.objects.only('is_active', 'username').get(id=user_id)
+    if user.is_active:
+        raise Http404
+
+    code = hashlib.md5(settings.SECRET_KEY + user_id).hexdigest()
+
+    activate_url = 'http://guowee.com/account/activate/%s/%s/' % (user_id, code)
+    email_content=settings.EMAIL_CONTEXT_ACTIVATION %(user.userprofile_set.all()[0].nick_name,activate_url)
+    django_send_mail('请激活你的帐号,完成注册', email_content,
+                     settings.DEFAULT_FROM_EMAIL, [user.username])
+
+    return render_to_response('register_ok.html', {'title': u'果味网账号激活邮件'})
+
+
+def activate(request, user_id, code):
+    '激活账号'
+
+    user = User.objects.only('username', 'is_active').get(id=user_id)
+    right_code = hashlib.md5(settings.SECRET_KEY + user_id).hexdigest()
+    if code == right_code and (not user.is_active):
+        user.is_active = True
+        user.save()
+        waring = {
+            'main': u'您的账号已经激活',
+            'details': u'',
+            'helper': '',
+            'url': '',
+            'url_text': '',
+        }
+
+        return render_to_response('waring.html', {'waring': waring,
+                                                     'title': u'果味网账号激活',},
+                                  context_instance=RequestContext(request))
+    else:
+        raise Http404
+
+
+@login_required