本文整理汇总了Python中django.contrib.auth.authenticate方法的典型用法代码示例。如果您正苦于以下问题:Python auth.authenticate方法的具体用法?Python auth.authenticate怎么用?Python auth.authenticate使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.contrib.auth
的用法示例。
在下文中一共展示了auth.authenticate方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: site_login
# 需要导入模块: from django.contrib import auth [as 别名]
# 或者: from django.contrib.auth import authenticate [as 别名]
def site_login(request):
"""
Logs in current user
:param request:
:return render:
"""
if request.method == "POST":
user = None
user_login = request.POST['login']
user_password = request.POST['password']
print("Login tryout by "+user_login)
if user_login != "" and user_password != "":
user = authenticate(username=user_login, password=user_password)
if user is not None:
login(request, user)
return HttpResponseRedirect(reverse('public_gate:home'))
else:
# User.objects.create_user(user_login, '', user_password).save()
return render(request, 'public_gate/home.html', {"error_message": "Wrong login/password combination"})
return render(request, 'public_gate/home.html', {"error_message": "One or more fields are empty"})
示例2: test_01_login
# 需要导入模块: from django.contrib import auth [as 别名]
# 或者: from django.contrib.auth import authenticate [as 别名]
def test_01_login(self):
"""Verify user creation"""
user = authenticate(username='demo', password='demo123')
self.assertTrue(user is not None)
self.assertTrue(user.is_active == True)
user = authenticate(username='demo', password='demo122')
self.assertTrue(user is None)
user = authenticate(username='demo', password='')
self.assertTrue(user is None)
user = authenticate(username='demo1', password='demo123')
self.assertTrue(user is None)
user = authenticate(username='', password='demo123')
self.assertTrue(user is None)
示例3: form_valid
# 需要导入模块: from django.contrib import auth [as 别名]
# 或者: from django.contrib.auth import authenticate [as 别名]
def form_valid(self, form):
user_email = form.cleaned_data['email'].lower().strip()
password = form.cleaned_data['password']
user = authenticate(email=user_email, password=password)
if user and user.is_active:
login(self.request, user)
return redirect(self.get_success_url())
else:
try:
user = User.objects.get(email__iexact=user_email)
if not check_password(password, user.password):
form._errors['password'] = ErrorList([u'That is not the correct Password.'])
except User.DoesNotExist:
form._errors['email'] = ErrorList([u'This email is not registered with us.'])
context = self.get_context_data(form=form)
return self.render_to_response(context)
示例4: login_view
# 需要导入模块: from django.contrib import auth [as 别名]
# 或者: from django.contrib.auth import authenticate [as 别名]
def login_view(request):
request_json = json.loads(request.body)
if not request_json.get('email'):
return create_json_response({}, status=400, reason='Email is required')
if not request_json.get('password'):
return create_json_response({}, status=400, reason='Password is required')
users = User.objects.filter(email__iexact=request_json['email'])
if users.count() != 1:
return create_json_response({}, status=401, reason='Invalid credentials')
u = authenticate(username=users.first().username, password=request_json['password'])
if not u:
return create_json_response({}, status=401, reason='Invalid credentials')
login(request, u)
return create_json_response({'success': True})
示例5: set_password
# 需要导入模块: from django.contrib import auth [as 别名]
# 或者: from django.contrib.auth import authenticate [as 别名]
def set_password(request, username):
user = User.objects.get(username=username)
request_json = json.loads(request.body)
if not request_json.get('password'):
return create_json_response({}, status=400, reason='Password is required')
user.set_password(request_json['password'])
user.first_name = request_json.get('firstName') or ''
user.last_name = request_json.get('lastName') or ''
user.save()
u = authenticate(username=username, password=request_json['password'])
login(request, u)
return create_json_response({'success': True})
示例6: test_log_out_the_user_if_the_id_token_is_not_valid
# 需要导入模块: from django.contrib import auth [as 别名]
# 或者: from django.contrib.auth import authenticate [as 别名]
def test_log_out_the_user_if_the_id_token_is_not_valid(self, rf):
request = rf.get('/oidc/cb/', {'state': 'state', 'code': 'authcode', })
SessionMiddleware().process_request(request)
request.session.save()
backend = OIDCAuthBackend()
user = backend.authenticate(request, 'nonce')
request.session['oidc_auth_id_token_exp_timestamp'] = \
(tz.now() - dt.timedelta(minutes=1)).timestamp()
request.session['oidc_auth_refresh_token'] = 'this_is_a_refresh_token'
auth.login(request, user)
request.user = user
httpretty.register_uri(
httpretty.POST, oidc_rp_settings.PROVIDER_TOKEN_ENDPOINT,
body=json.dumps({
'id_token': 'badidtoken', 'access_token': 'accesstoken',
'refresh_token': 'refreshtoken', }),
content_type='text/json')
middleware = OIDCRefreshIDTokenMiddleware(lambda r: 'OK')
middleware(request)
assert not request.user.is_authenticated
示例7: test_log_out_the_user_if_the_refresh_token_is_expired
# 需要导入模块: from django.contrib import auth [as 别名]
# 或者: from django.contrib.auth import authenticate [as 别名]
def test_log_out_the_user_if_the_refresh_token_is_expired(self, rf):
request = rf.get('/oidc/cb/', {'state': 'state', 'code': 'authcode', })
SessionMiddleware().process_request(request)
request.session.save()
backend = OIDCAuthBackend()
user = backend.authenticate(request, 'nonce')
request.session['oidc_auth_id_token_exp_timestamp'] = \
(tz.now() - dt.timedelta(minutes=1)).timestamp()
request.session['oidc_auth_refresh_token'] = 'this_is_a_refresh_token'
auth.login(request, user)
request.user = user
httpretty.register_uri(
httpretty.POST, oidc_rp_settings.PROVIDER_TOKEN_ENDPOINT,
body=json.dumps({'error': 'yes'}),
content_type='text/json', status=400)
middleware = OIDCRefreshIDTokenMiddleware(lambda r: 'OK')
middleware(request)
assert not request.user.is_authenticated
示例8: post
# 需要导入模块: from django.contrib import auth [as 别名]
# 或者: from django.contrib.auth import authenticate [as 别名]
def post(self, request):
username = request.POST.get("username", None)
password = request.POST.get("password", None)
user = authenticate(username=username, password=password)
if user:
if hasattr(user, "userprofile") is not True:
models.UserProfile.objects.create(user=user)
userDict = JSONSerializer().serializeToPython(user)
userDict["password"] = None
userDict["is_reviewer"] = user_is_resource_reviewer(user)
userDict["viewable_nodegroups"] = user.userprofile.viewable_nodegroups
userDict["editable_nodegroups"] = user.userprofile.editable_nodegroups
userDict["deletable_nodegroups"] = user.userprofile.deletable_nodegroups
response = JSONResponse(userDict)
else:
response = Http401Response()
return response
示例9: clean
# 需要导入模块: from django.contrib import auth [as 别名]
# 或者: from django.contrib.auth import authenticate [as 别名]
def clean(self):
username = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')
message = ERROR_MESSAGE
if username and password:
self.user_cache = authenticate(
username=username, password=password)
if self.user_cache is None:
if u'@' in username:
User = get_user_model()
# Mistakenly entered e-mail address instead of username? Look it up.
try:
user = User.objects.get(email=username)
except (User.DoesNotExist, User.MultipleObjectsReturned):
# Nothing to do here, moving along.
pass
else:
if user.check_password(password):
message = _("Your e-mail address is not your username."
" Try '%s' instead.") % user.username
raise forms.ValidationError(message)
elif not self.user_cache.is_active or not self.user_cache.is_staff:
raise forms.ValidationError(message)
return self.cleaned_data
示例10: welcome_staff
# 需要导入模块: from django.contrib import auth [as 别名]
# 或者: from django.contrib.auth import authenticate [as 别名]
def welcome_staff(request):
"""Allow to create a staff user if None exists yet."""
if user_model.objects.filter(is_staff=True).exists():
return HttpResponseRedirect('/')
if request.method == 'POST':
form = CreateStaffForm(request.POST)
if form.is_valid():
user = form.save()
user = authenticate(serial=user.serial,
password=request.POST['password'])
login(request, user)
msg = _(u'Welcome to {}, {}!').format(
get_config('server', 'site-name'), user)
messages.add_message(request, messages.SUCCESS, msg)
return HttpResponseRedirect('/')
else:
form = CreateStaffForm()
return render(request, 'ideascube/welcome_staff.html', {'form': form})
示例11: myLogin
# 需要导入模块: from django.contrib import auth [as 别名]
# 或者: from django.contrib.auth import authenticate [as 别名]
def myLogin(request):
errors = []
data = ''
next = request.GET.get('next') or request.GET.get('redirect_to') or '/'
if request.method == 'POST':
username = request.POST.get('username', '')
password = request.POST.get('password', '')
if not request.POST.get('username',''):
errors.append('Enter a user')
if not request.POST.get('password',''):
errors.append('Enter a passwd')
if not errors:
user = auth.authenticate(username=username,password=password)
if user is not None and user.is_active:
auth.login(request,user)
return redirect('%s' % next)
else:
data = '登陆失败,请核对信息'
print(errors)
return render(request, 'login2.html', {'errors': errors, 'data': data},)
示例12: clean
# 需要导入模块: from django.contrib import auth [as 别名]
# 或者: from django.contrib.auth import authenticate [as 别名]
def clean(self):
username = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')
if username and password:
self.user_cache = authenticate(username=username,
password=password)
if self.user_cache is None:
raise forms.ValidationError(
self.error_messages['invalid_login'],
code='invalid_login',
params={'username': self.username_field.verbose_name},
)
else:
self.confirm_login_allowed(self.user_cache)
return self.cleaned_data
示例13: _make_submission_w_attachment
# 需要导入模块: from django.contrib import auth [as 别名]
# 或者: from django.contrib.auth import authenticate [as 别名]
def _make_submission_w_attachment(self, path, attachment_path):
with open(path) as f:
a = open(attachment_path)
post_data = {'xml_submission_file': f, 'media_file': a}
url = '/%s/submission' % self.user.username
auth = DigestAuth('bob', 'bob')
self.factory = APIRequestFactory()
request = self.factory.post(url, post_data)
request.user = authenticate(username='bob',
password='bob')
self.response = submission(request,
username=self.user.username)
if auth and self.response.status_code == 401:
request.META.update(auth(request.META, self.response))
self.response = submission(request,
username=self.user.username)
示例14: filter_queryset
# 需要导入模块: from django.contrib import auth [as 别名]
# 或者: from django.contrib.auth import authenticate [as 别名]
def filter_queryset(self, queryset):
project = self.kwargs.get('pk', None)
if project:
queryset = queryset.filter(
user__user_roles__project__id = project,
user__is_active=True).order_by('user__first_name')
return queryset
try:
org = self.request.user.user_profile.organization
queryset = queryset.filter(organization = org,user__is_active=True).order_by('user__first_name')
except:
queryset = []
return queryset
# def web_authenticate(username=None, password=None):
# # returns User , Email_correct, Password_correct
# try:
# user = User.objects.get(email__iexact=username)
# if user.check_password(password):
# return authenticate(username=user.username, password=password)
# else:
# return None, True, False
# except User.DoesNotExist:
# return None, False, True
示例15: form_list_xml
# 需要导入模块: from django.contrib import auth [as 别名]
# 或者: from django.contrib.auth import authenticate [as 别名]
def form_list_xml(url, request, **kwargs):
response = requests.Response()
factory = RequestFactory()
req = factory.get(url.path)
req.user = authenticate(username='bob', password='bob')
req.user.profile.require_auth = False
req.user.profile.save()
id_string = 'transportation_2011_07_25'
if url.path.endswith('formList'):
res = formList(req, username='bob')
elif url.path.endswith('form.xml'):
res = download_xform(req, username='bob', id_string=id_string)
elif url.path.find('xformsManifest') > -1:
res = xformsManifest(req, username='bob', id_string=id_string)
elif url.path.find('formid-media') > -1:
data_id = url.path[url.path.rfind('/') + 1:]
res = download_media_data(
req, username='bob', id_string=id_string, data_id=data_id)
response._content = get_streaming_content(res)
else:
res = formList(req, username='bob')
response.status_code = 200
if not response._content:
response._content = res.content
return response