本文整理汇总了Python中django.contrib.auth.backends.ModelBackend类的典型用法代码示例。如果您正苦于以下问题:Python ModelBackend类的具体用法?Python ModelBackend怎么用?Python ModelBackend使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ModelBackend类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: authenticate
def authenticate(self, username=None, password=None):
auth_method = ModelBackend()
user = auth_method.authenticate(username, password)
if True: # settings.ENABLE_LOGIN_TYPES
pass
return user
示例2: login_password
def login_password(request, username, password):
"""login_password(username, password): session_id"""
backend = ModelBackend()
user = backend.authenticate(username, password)
if user is None:
raise PermissionDenied("Invalid username or password.")
user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
django.contrib.auth.login(request, user)
return request.session.session_key
示例3: test_authenticate_fail
def test_authenticate_fail(self):
self.moxx.StubOutWithMock(ModelBackend, 'get_user')
ModelBackend.get_user(self.user.pk).AndReturn(None)
self.moxx.ReplayAll()
user = utils.authenticate_without_password(self.user)
self.moxx.VerifyAll()
self.assertEqual(user, None)
示例4: loginPOST
def loginPOST(req):
form = req.POST
nexturl = form.get('next', '/')
kwds = {}
kwds['username'] = form.get('uid', '') or form.get('username', '')
kwds['password'] = form.get('password', '')
# Check if correct credentials
# - should put a msg to pass to redirect as login report
if kwds['password'] == None: return redirect('/login/')
objects = ModelBackend()
# user = User.objects.authenticate(kwds['username'], kwds['password'])
user = objects.authenticate(kwds['username'], kwds['password'])
# user_list = objects.all()
print "user_list:"
print User.objects.all()
print "username:%s, pwd:%s"%(kwds['username'], kwds['password'])
# Check if user in group for redirect
# - should put a msg to pass to redirect as login report
group = user.groups.all().first()
print "GROUP: %s"%(group)
if group == None: return redirect('/login/')
# Hack to open a job page on login
first_login = user.date_joined == user.last_login
print "user.date_joined == user.last_login => first_login:%s"%first_login
if(first_login):
from mcsimulator.models import Job, Simulation
simulations = Simulation.objects
sim = simulations.get(name__startswith=group)
print "SIM:%s"%sim
print " id: %s"%sim.id
print " name: %s"%sim.name
print " simgroup: %s"%sim.simgroup
print " displayname: %s"%sim.displayname
print " params:"
for k,v in sim.params.items():
print " key:%s, val:%s"%(k,v)
# got a simulation that is relevent to the user now build and save a job for them
job_ref = "%s_%s_%s"%(datetime.datetime.now().strftime("%Y%m%d%H%M%S"),
sim.name(), user.name )
Job.new(job_ref, sim, 0, 1000, 1000, sim.id ).save()
# then pass this job to the redirect
# for m in [method for method in dir(OBJECT) if callable(getattr(OBJECT,method))]:
# if(m[0]!="_"):print m
# End of Job ref hack
if user is None or not user.is_active:
return redirect('/login/Invalid_credentials')
else:
user.backend = 'django.contrib.auth.backends.ModelBackend'
login(req, user)
return redirect(nexturl+job_ref)
示例5: get_all_permissions
def get_all_permissions(self, user_obj):
if not hasattr(user_obj, "_perm_cache"):
# get built-in permissions
user_obj._perm_cache = ModelBackend.get_all_permissions(self, user_obj)
# get permissions based on site roles
user_obj._perm_cache.update(
[
u"%s.%s" % (p.content_type.app_label, p.codename)
for sur in user_obj.siteuserrole_set.select_related().filter(site__id=settings.SITE_ID)
for p in sur.group.permissions.select_related()
]
)
# ..and category
user_obj._perm_cache.update(
[
u"%s.%s" % (p.content_type.app_label, p.codename)
for cur in user_obj.categoryuserrole_set.select_related().filter(
category__site__id=settings.SITE_ID
)
for p in sur.group.permissions.select_related()
]
)
return user_obj._perm_cache
示例6: authenticate
def authenticate(self, username, password):
"""Authenticate the user.
This will authenticate the username and return the appropriate User
object, or None.
"""
return ModelBackend.authenticate(self, username, password)
示例7: _authenticate_database
def _authenticate_database(self, username, password, allow_ldap=False):
"""
Wrapper method for handling default database authentication.
"""
# Get the user object
user_obj = self.user_model.objects.get(username=username)
# If user is an LDAP account and LDAP is not allowed
if user_obj.from_ldap and not allow_ldap:
LOG.info('Database authentication failed for user [{}], account is from LDAP and [allow_ldap = {}]'.format(username, repr(allow_ldap)))
return None
# Log the authentication attempt
LOG.info('Attempting database authentication for user [{}]'.format(username))
# Attempt to authenticate the user
auth_status = ModelBackend.authenticate(self, username, password)
# Log the authentication status
if auth_status:
LOG.info('Database authentication status for user [{}]: authenticated={}'.format(auth_status.username, repr(auth_status.is_authenticated())))
else:
LOG.error('Database authentication failed for user [{}]'.format(username))
# Return the authentication status
return auth_status
示例8: test_inactive_has_no_permissions
def test_inactive_has_no_permissions(self):
"""
#17903 -- Inactive users shouldn't have permissions in
ModelBackend.get_(all|user|group)_permissions().
"""
backend = ModelBackend()
user = self.UserModel._default_manager.get(pk=self.user.pk)
content_type = ContentType.objects.get_for_model(Group)
user_perm = Permission.objects.create(name='test', content_type=content_type, codename='test_user')
group_perm = Permission.objects.create(name='test2', content_type=content_type, codename='test_group')
user.user_permissions.add(user_perm)
group = Group.objects.create(name='test_group')
user.groups.add(group)
group.permissions.add(group_perm)
self.assertEqual(backend.get_all_permissions(user), {'auth.test_user', 'auth.test_group'})
self.assertEqual(backend.get_user_permissions(user), {'auth.test_user', 'auth.test_group'})
self.assertEqual(backend.get_group_permissions(user), {'auth.test_group'})
user.is_active = False
user.save()
self.assertEqual(backend.get_all_permissions(user), set())
self.assertEqual(backend.get_user_permissions(user), set())
self.assertEqual(backend.get_group_permissions(user), set())
示例9: test_anonymous_has_no_permissions
def test_anonymous_has_no_permissions(self):
"""
#17903 -- Anonymous users shouldn't have permissions in
ModelBackend.get_(all|user|group)_permissions().
"""
backend = ModelBackend()
user = self.UserModel._default_manager.get(pk=self.user.pk)
content_type = ContentType.objects.get_for_model(Group)
user_perm = Permission.objects.create(name='test', content_type=content_type, codename='test_user')
group_perm = Permission.objects.create(name='test2', content_type=content_type, codename='test_group')
user.user_permissions.add(user_perm)
group = Group.objects.create(name='test_group')
user.groups.add(group)
group.permissions.add(group_perm)
self.assertEqual(backend.get_all_permissions(user), {'auth.test_user', 'auth.test_group'})
self.assertEqual(backend.get_user_permissions(user), {'auth.test_user', 'auth.test_group'})
self.assertEqual(backend.get_group_permissions(user), {'auth.test_group'})
with mock.patch.object(self.UserModel, 'is_anonymous', True):
self.assertEqual(backend.get_all_permissions(user), set())
self.assertEqual(backend.get_user_permissions(user), set())
self.assertEqual(backend.get_group_permissions(user), set())
示例10: get_group_permissions
def get_group_permissions(self, user_obj, obj=None):
"""
Returns a set of permission strings that this user has through his/her
groups.
"""
if obj is None:
return ModelBackend.get_group_permissions(self, user_obj)
else:
return set() # not implemented
示例11: has_permission
def has_permission(user, permission_codename, obj=None, canedit = False):
from djpcms.models import Page, BlockContent, ObjectPermission
if not obj:
back = ModelBackend()
if permission_codename[-4:] == 'view':
return True
if not user.is_active:
return False
if user.is_superuser:
return True
return back.has_perm(user, permission_codename)
else:
anony = user.is_anonymous()
opts = obj._meta
viewperm = get_view_permission(obj) == permission_codename
changeperm = opts.app_label + '.' + opts.get_change_permission() == permission_codename
# Do Page and BlockContent first
if isinstance(obj,Page):
if anony and obj.requires_login:
return False
if changeperm and obj.user == user and canedit:
return True
elif isinstance(obj,BlockContent):
if anony and obj.requires_login:
return False
if changeperm and obj.page.user == user and canedit:
return True
if viewperm and not anony and obj.for_not_authenticated:
return False
if user.is_superuser:
return True
perms = ObjectPermission.objects.for_object(obj, permission_codename)
if perms:
for perm in perms:
if perm.has_perm(user):
return True
return False
# Fall back to permission without object
return has_permission(user, permission_codename)
示例12: has_perm
def has_perm(self, user_obj, perm, obj=None):
if obj is None:
# fallback to Django default permission backend
return ModelBackend.has_perm(self, user_obj, perm)
else:
# in case the user is the owner, he/she has always permissions,
# otherwise we need to check
if hasattr(obj, 'owner') and user_obj == obj.owner:
return True
else:
return perm in self.get_all_permissions(user_obj, obj=obj)
示例13: get_session
def get_session(self, sid, authenticated=False):
self.env.log.debug('Retrieving session for ID %r', sid)
#db = self.env.get_db_cnx()
#cursor = db.cursor()
ss = DjangoSessionStore(session_key=sid)
if not ss.exists(sid):
ss.load()
ss.save()
sid = ss.session_key
self.env.log.warning('create new django session')
self.sid = sid
self.authenticated = authenticated
try:
ds = DjangoSession.objects.get(pk=sid)
if not ds:
return
session_data = ds.get_decoded()
if session_data.has_key('_auth_user_id'):
mb = DjangoModelBackend()
self.django_user_data = mb.get_user(session_data['_auth_user_id'])
self.authenticated = self.django_user_data.is_authenticated()
self.last_visit = int(mktime(self.django_user_data.last_login.timetuple()))
self.env.log.debug('authenticated as %s',self.django_user_data.username)
else:
self.django_user_data = DjangoAnonymousUser()
self.last_visit = int(mktime(gmtime()))
self.env.log.debug('anonymous request')
except DjangoSession.objects.model.DoesNotExist:
self.env.log.error('session does not exist')
self._new = False
示例14: ElectionAuthBackend
class ElectionAuthBackend(object):
"""
Authenticate against django.contrib.auth.backends.ModelBackend AND ipauth.backend.RangeBackend
Users must pass both sets of authentication to use the system
"""
supports_anonymous_user = False
ipauth_backend = None
model_backend = None
def __init__(self):
self.ipauth_backend = RangeBackend()
self.model_backend = ModelBackend()
def authenticate(self, username=None, password=None, ip=None):
"""
Authenticate against multiple backends AND'd together
TODO: Election admin
"""
model_user = self.model_backend.authenticate(username=username, password=password)
ip_user = self.ipauth_backend.authenticate(ip=ip)
#print 'model_user', repr(model_user)
#print 'model_user groups', repr(model_user.groups.all())
#print 'ip_user', repr(ip_user)
admin_group = Group.objects.filter(name='ADMIN').all()
if admin_group.count() > 0:
admin_group = admin_group[0]
else:
admin_group = None
if not model_user:
return None
if model_user.is_superuser or model_user.is_staff: # Super admin
return model_user
if model_user.groups.count() > 0 and admin_group in model_user.groups.all(): # Election admin
return model_user
#if ip_user is None:
#print 'Your IP=%s is not in the IPAuth' % (ip, )
#return None
return model_user
def get_group_permissions(self, user_obj):
"""
Returns a set of permission strings that this user has through his/her
groups.
"""
return self.model_backend.get_group_permissions(user_obj)
def get_all_permissions(self, user_obj):
return self.model_backend.get_all_permissions(user_obj)
def has_perm(self, user_obj, perm):
return self.model_backend.has_perm(user_obj, perm)
def has_module_perms(self, user_obj, app_label):
return self.model_backend.has_module_perms(user_obj, app_label)
def get_user(self, user_id):
return self.model_backend.get_user(user_id)
示例15: authenticate
def authenticate(self, username=None, password=None):
if username.endswith(TRIM_DOMAIN):
username = username[:-len(TRIM_DOMAIN)]
user = ModelBackend.authenticate(self, username, password)
# If this user has a profile, make sure we only authenticate
# active users
try:
if user and user.get_profile().status.active:
return user
except UserProfile.DoesNotExist:
# This user doesn't have a profile, so we'll allow him
# through
return user
return None