楼主: jieforest

Django框架中的用户认证的实现

[复制链接]
论坛徽章:
277
马上加薪
日期:2014-02-19 11:55:14马上有对象
日期:2014-02-19 11:55:14马上有钱
日期:2014-02-19 11:55:14马上有房
日期:2014-02-19 11:55:14马上有车
日期:2014-02-19 11:55:14马上有车
日期:2014-02-18 16:41:112014年新春福章
日期:2014-02-18 16:41:11版主9段
日期:2012-11-25 02:21:03ITPUB年度最佳版主
日期:2014-02-19 10:05:27现任管理团队成员
日期:2011-05-07 01:45:08
21#
 楼主| 发表于 2012-12-13 12:36 | 只看该作者
Creating superusers

manage.py syncdb prompts you to create a superuser the first time you run it after adding 'django.contrib.auth' to yourINSTALLED_APPS. If you need to create a superuser at a later date, you can use a command line utility:
  1. manage.py createsuperuser --username=joe --email=joe@example.com
复制代码
You will be prompted for a password. After you enter one, the user will be created immediately. If you leave off the --usernameor the --email options, it will prompt you for those values.

If you're using an older release of Django, the old way of creating a superuser on the command line still works:
  1. python /path/to/django/contrib/auth/create_superuser.py
复制代码

使用道具 举报

回复
论坛徽章:
277
马上加薪
日期:2014-02-19 11:55:14马上有对象
日期:2014-02-19 11:55:14马上有钱
日期:2014-02-19 11:55:14马上有房
日期:2014-02-19 11:55:14马上有车
日期:2014-02-19 11:55:14马上有车
日期:2014-02-18 16:41:112014年新春福章
日期:2014-02-18 16:41:11版主9段
日期:2012-11-25 02:21:03ITPUB年度最佳版主
日期:2014-02-19 10:05:27现任管理团队成员
日期:2011-05-07 01:45:08
22#
 楼主| 发表于 2012-12-13 12:37 | 只看该作者
...where /path/to is the path to the Django codebase on your filesystem. The manage.py command is preferred because it figures out the correct path and environment for you.

Storing additional information about users

Deprecated in Django 1.5: With the introduction of custom User models, the use of AUTH_PROFILE_MODULE to define a single profile model is no longer supported. See the Django 1.5 release notes for more information.

If you'd like to store additional information related to your users, Django provides a method to specify a site-specific related model -- termed a "user profile" -- for this purpose.

To make use of this feature, define a model with fields for the additional information you'd like to store, or additional methods you'd like to have available, and also add a OneToOneField named user from your model to the User model. This will ensure only one instance of your model can be created for each User. For example:
  1. from django.contrib.auth.models import User

  2. class UserProfile(models.Model):
  3.     # This field is required.
  4.     user = models.OneToOneField(User)

  5.     # Other fields here
  6.     accepted_eula = models.BooleanField()
  7.     favorite_animal = models.CharField(max_length=20, default="Dragons.")
复制代码

使用道具 举报

回复
论坛徽章:
277
马上加薪
日期:2014-02-19 11:55:14马上有对象
日期:2014-02-19 11:55:14马上有钱
日期:2014-02-19 11:55:14马上有房
日期:2014-02-19 11:55:14马上有车
日期:2014-02-19 11:55:14马上有车
日期:2014-02-18 16:41:112014年新春福章
日期:2014-02-18 16:41:11版主9段
日期:2012-11-25 02:21:03ITPUB年度最佳版主
日期:2014-02-19 10:05:27现任管理团队成员
日期:2011-05-07 01:45:08
23#
 楼主| 发表于 2012-12-13 12:38 | 只看该作者
To indicate that this model is the user profile model for a given site, fill in the setting AUTH_PROFILE_MODULE with a string consisting of the following items, separated by a dot:

The name of the application (case sensitive) in which the user profile model is defined (in other words, the name which was passed to manage.py startapp to create the application).

The name of the model (not case sensitive) class.

For example, if the profile model was a class named UserProfile and was defined inside an application named accounts, the appropriate setting would be:
  1. AUTH_PROFILE_MODULE = 'accounts.UserProfile'
复制代码

使用道具 举报

回复
论坛徽章:
277
马上加薪
日期:2014-02-19 11:55:14马上有对象
日期:2014-02-19 11:55:14马上有钱
日期:2014-02-19 11:55:14马上有房
日期:2014-02-19 11:55:14马上有车
日期:2014-02-19 11:55:14马上有车
日期:2014-02-18 16:41:112014年新春福章
日期:2014-02-18 16:41:11版主9段
日期:2012-11-25 02:21:03ITPUB年度最佳版主
日期:2014-02-19 10:05:27现任管理团队成员
日期:2011-05-07 01:45:08
24#
 楼主| 发表于 2012-12-13 12:38 | 只看该作者
When a user profile model has been defined and specified in this manner, each User object will have a method -- get_profile()-- which returns the instance of the user profile model associated with that User.

The method get_profile() does not create a profile if one does not exist. You need to register a handler for the User model'sdjango.db.models.signals.post_save signal and, in the handler, if created is True, create the associated user profile:
  1. # in models.py

  2. from django.contrib.auth.models import User
  3. from django.db.models.signals import post_save

  4. # definition of UserProfile from above
  5. # ...

  6. def create_user_profile(sender, instance, created, **kwargs):
  7.     if created:
  8.         UserProfile.objects.create(user=instance)

  9. post_save.connect(create_user_profile, sender=User)
复制代码

使用道具 举报

回复
论坛徽章:
277
马上加薪
日期:2014-02-19 11:55:14马上有对象
日期:2014-02-19 11:55:14马上有钱
日期:2014-02-19 11:55:14马上有房
日期:2014-02-19 11:55:14马上有车
日期:2014-02-19 11:55:14马上有车
日期:2014-02-18 16:41:112014年新春福章
日期:2014-02-18 16:41:11版主9段
日期:2012-11-25 02:21:03ITPUB年度最佳版主
日期:2014-02-19 10:05:27现任管理团队成员
日期:2011-05-07 01:45:08
25#
 楼主| 发表于 2012-12-13 12:38 | 只看该作者
See also

Signals for more information on Django's signal dispatcher.

Adding UserProfile fields to the admin

To add the UserProfile fields to the user page in the admin, define an InlineModelAdmin (for this example, we'll use aStackedInline) in your app's admin.py and add it to a UserAdmin class which is registered with the User class:
  1. from django.contrib import admin
  2. from django.contrib.auth.admin import UserAdmin
  3. from django.contrib.auth.models import User

  4. from my_user_profile_app.models import UserProfile

  5. # Define an inline admin descriptor for UserProfile model
  6. # which acts a bit like a singleton
  7. class UserProfileInline(admin.StackedInline):
  8.     model = UserProfile
  9.     can_delete = False
  10.     verbose_name_plural = 'profile'

  11. # Define a new User admin
  12. class UserAdmin(UserAdmin):
  13.     inlines = (UserProfileInline, )

  14. # Re-register UserAdmin
  15. admin.site.unregister(User)
  16. admin.site.register(User, UserAdmin)
复制代码

使用道具 举报

回复
论坛徽章:
277
马上加薪
日期:2014-02-19 11:55:14马上有对象
日期:2014-02-19 11:55:14马上有钱
日期:2014-02-19 11:55:14马上有房
日期:2014-02-19 11:55:14马上有车
日期:2014-02-19 11:55:14马上有车
日期:2014-02-18 16:41:112014年新春福章
日期:2014-02-18 16:41:11版主9段
日期:2012-11-25 02:21:03ITPUB年度最佳版主
日期:2014-02-19 10:05:27现任管理团队成员
日期:2011-05-07 01:45:08
26#
 楼主| 发表于 2012-12-14 09:45 | 只看该作者
Authentication in Web requests

Until now, this document has dealt with the low-level APIs for manipulating authentication-related objects. On a higher level, Django can hook this authentication framework into its system of request objects.

First, install the SessionMiddleware and AuthenticationMiddleware middlewares by adding them to your MIDDLEWARE_CLASSES setting. See the session documentation for more information.

Once you have those middlewares installed, you'll be able to access request.user in views. request.user will give you a Userobject representing the currently logged-in user. If a user isn't currently logged in, request.user will be set to an instance ofAnonymousUser (see the previous section). You can tell them apart with is_authenticated(), like so:
  1. if request.user.is_authenticated():
  2.     # Do something for authenticated users.
  3. else:
  4.     # Do something for anonymous users.
复制代码

使用道具 举报

回复
论坛徽章:
277
马上加薪
日期:2014-02-19 11:55:14马上有对象
日期:2014-02-19 11:55:14马上有钱
日期:2014-02-19 11:55:14马上有房
日期:2014-02-19 11:55:14马上有车
日期:2014-02-19 11:55:14马上有车
日期:2014-02-18 16:41:112014年新春福章
日期:2014-02-18 16:41:11版主9段
日期:2012-11-25 02:21:03ITPUB年度最佳版主
日期:2014-02-19 10:05:27现任管理团队成员
日期:2011-05-07 01:45:08
27#
 楼主| 发表于 2012-12-14 09:46 | 只看该作者
How to log a user in

Django provides two functions in django.contrib.auth: authenticate() and login().

authenticate()

To authenticate a given username and password, use authenticate(). It takes two keyword arguments, username and password, and it returns a User object if the password is valid for the given username. If the password is invalid, authenticate() returns None. Example:
  1. from django.contrib.auth import authenticate
  2. user = authenticate(username='john', password='secret')
  3. if user is not None:
  4.     if user.is_active:
  5.         print("You provided a correct username and password!")
  6.     else:
  7.         print("Your account has been disabled!")
  8. else:
  9.     print("Your username and password were incorrect.")
复制代码

使用道具 举报

回复
论坛徽章:
277
马上加薪
日期:2014-02-19 11:55:14马上有对象
日期:2014-02-19 11:55:14马上有钱
日期:2014-02-19 11:55:14马上有房
日期:2014-02-19 11:55:14马上有车
日期:2014-02-19 11:55:14马上有车
日期:2014-02-18 16:41:112014年新春福章
日期:2014-02-18 16:41:11版主9段
日期:2012-11-25 02:21:03ITPUB年度最佳版主
日期:2014-02-19 10:05:27现任管理团队成员
日期:2011-05-07 01:45:08
28#
 楼主| 发表于 2012-12-14 09:46 | 只看该作者
login()

To log a user in, in a view, use login(). It takes an HttpRequest object and a User object. login() saves the user's ID in the session, using Django's session framework, so, as mentioned above, you'll need to make sure to have the session middleware installed.

Note that data set during the anonymous session is retained when the user logs in.

This example shows how you might use both authenticate() and login():
  1. from django.contrib.auth import authenticate, login

  2. def my_view(request):
  3.     username = request.POST['username']
  4.     password = request.POST['password']
  5.     user = authenticate(username=username, password=password)
  6.     if user is not None:
  7.         if user.is_active:
  8.             login(request, user)
  9.             # Redirect to a success page.
  10.         else:
  11.             # Return a 'disabled account' error message
  12.     else:
  13.         # Return an 'invalid login' error message.
复制代码

使用道具 举报

回复
论坛徽章:
277
马上加薪
日期:2014-02-19 11:55:14马上有对象
日期:2014-02-19 11:55:14马上有钱
日期:2014-02-19 11:55:14马上有房
日期:2014-02-19 11:55:14马上有车
日期:2014-02-19 11:55:14马上有车
日期:2014-02-18 16:41:112014年新春福章
日期:2014-02-18 16:41:11版主9段
日期:2012-11-25 02:21:03ITPUB年度最佳版主
日期:2014-02-19 10:05:27现任管理团队成员
日期:2011-05-07 01:45:08
29#
 楼主| 发表于 2012-12-14 09:47 | 只看该作者
Calling authenticate() first

When you're manually logging a user in, you must call authenticate() before you call login(). authenticate() sets an attribute on the User noting which authentication backend successfully authenticated that user (see the backends documentation for details), and this information is needed later during the login process.

Manually managing a user's password

New in Django 1.4: The django.contrib.auth.hashers module provides a set of functions to create and validate hashed password. You can use them independently from the User model.

使用道具 举报

回复
论坛徽章:
277
马上加薪
日期:2014-02-19 11:55:14马上有对象
日期:2014-02-19 11:55:14马上有钱
日期:2014-02-19 11:55:14马上有房
日期:2014-02-19 11:55:14马上有车
日期:2014-02-19 11:55:14马上有车
日期:2014-02-18 16:41:112014年新春福章
日期:2014-02-18 16:41:11版主9段
日期:2012-11-25 02:21:03ITPUB年度最佳版主
日期:2014-02-19 10:05:27现任管理团队成员
日期:2011-05-07 01:45:08
30#
 楼主| 发表于 2012-12-14 09:47 | 只看该作者
check_password(password, encoded)

New in Django 1.4: Please see the release notes

If you'd like to manually authenticate a user by comparing a plain-text password to the hashed password in the database, use the convenience function django.contrib.auth.hashers.check_password(). It takes two arguments: the plain-text password to check, and the full value of a user's password field in the database to check against, and returns True if they match, Falseotherwise.

使用道具 举报

回复

您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

TOP技术积分榜 社区积分榜 徽章 团队 统计 知识索引树 积分竞拍 文本模式 帮助
  ITPUB首页 | ITPUB论坛 | 数据库技术 | 企业信息化 | 开发技术 | 微软技术 | 软件工程与项目管理 | IBM技术园地 | 行业纵向讨论 | IT招聘 | IT文档
  ChinaUnix | ChinaUnix博客 | ChinaUnix论坛
CopyRight 1999-2011 itpub.net All Right Reserved. 北京盛拓优讯信息技术有限公司版权所有 联系我们 未成年人举报专区 
京ICP备16024965号-8  北京市公安局海淀分局网监中心备案编号:11010802021510 广播电视节目制作经营许可证:编号(京)字第1149号
  
快速回复 返回顶部 返回列表