本文整理汇总了Python中helios_auth.models.User类的典型用法代码示例。如果您正苦于以下问题:Python User类的具体用法?Python User怎么用?Python User使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了User类的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_user
def create_user(username, password, name = None):
from helios_auth.models import User
user = User.get_by_type_and_id('password', username)
if user:
raise Exception('user exists')
info = {'password' : password, 'name': name}
user = User.update_or_create(user_type='password', user_id=username, info = info)
user.save()
示例2: create_user
def create_user(username, password, name = None):
from helios_auth.models import User
from django.db import models
try:
user = User.get_by_type_and_id('password', username)
raise Exception('user exists')
except User.DoesNotExist:
pass
info = {'password' : password, 'name': name}
user = User.update_or_create(user_type='password', user_id=username, info = info)
user.save()
示例3: process
def process(self):
self.processing_started_at = datetime.datetime.utcnow()
self.save()
election = self.election
last_alias_num = election.last_alias_num
num_voters = 0
new_voters = []
for voter in self.itervoters():
# does voter for this user already exist
existing_voter = Voter.get_by_election_and_voter_id(election, voter['voter_id'])
# create the voter
if not existing_voter:
num_voters += 1
user = None
if 'user_type' in voter.keys():
if 'email' in voter.keys():
user = User.update_or_create(voter['user_type'], voter['voter_id'], voter['name'], {'email': voter['email']})
else:
user = User.update_or_create(voter['user_type'], voter['voter_id'], voter['name'], {})
voter_uuid = str(uuid.uuid4())
if 'email' in voter.keys():
new_voter = Voter(uuid=voter_uuid, user=user, voter_name=voter['name'], voter_email=voter['email'], election=election)
else:
new_voter = Voter(uuid=voter_uuid, user=user, voter_name=voter['name'], election=election)
new_voter.voter_login_id = voter['voter_id']
if not user:
new_voter.generate_password()
new_voters.append(new_voter)
new_voter.save()
if election.use_voter_aliases:
voter_alias_integers = range(last_alias_num + 1, last_alias_num + 1 + num_voters)
random.shuffle(voter_alias_integers)
for i, new_voter in enumerate(new_voters):
new_voter.alias = 'V%s' % voter_alias_integers[i]
new_voter.save()
self.num_voters = num_voters
self.processing_finished_at = datetime.datetime.utcnow()
self.save()
return num_voters
示例4: password_forgotten_view
def password_forgotten_view(request):
"""
forgotten password view and submit.
includes return_url
"""
from helios_auth.view_utils import render_template
from helios_auth.models import User
if request.method == "GET":
return render_template(request, 'password/forgot', {'return_url': request.GET.get('return_url', '')})
else:
username = request.POST['username']
return_url = request.POST['return_url']
try:
user = User.get_by_type_and_id('password', username)
except User.DoesNotExist:
return render_template(request, 'password/forgot', {'return_url': request.GET.get('return_url', ''), 'error': 'no such username'})
body = """
This is a password reminder:
Your username: %s
Your password: %s
--
%s
""" % (user.user_id, user.info['password'], settings.SITE_TITLE)
# FIXME: make this a task
send_mail('password reminder', body, settings.SERVER_EMAIL, ["%s <%s>" % (user.info['name'], user.info['email'])], fail_silently=False)
return HttpResponseRedirect(return_url)
示例5: password_login_view
def password_login_view(request):
from helios_auth.view_utils import render_template
from helios_auth.views import after
from helios_auth.models import User
error = None
if request.method == "GET":
form = LoginForm()
else:
form = LoginForm(request.POST)
# set this in case we came here straight from the multi-login chooser
# and thus did not have a chance to hit the "start/password" URL
request.session['auth_system_name'] = 'password'
if request.POST.has_key('return_url'):
request.session['auth_return_url'] = request.POST.get('return_url')
if form.is_valid():
username = form.cleaned_data['username'].strip()
password = form.cleaned_data['password'].strip()
try:
user = User.get_by_type_and_id('password', username)
if password_check(user, password):
request.session['password_user_id'] = user.user_id
return HttpResponseRedirect(reverse(after))
except User.DoesNotExist:
pass
error = 'Bad Username or Password'
return render_template(request, 'password/login', {'form': form, 'error': error})
示例6: load_eligible_voters
def load_eligible_voters(self):
"""
try to load voters by eligibility constraints
"""
if self.eligibility == None:
return
if self.openreg == False:
return
total_load = True
for eligibility_case in self.eligibility:
print eligibility_case
auth_system = eligibility_case['auth_system']
if not eligibility_case.has_key('constraint'):
total_load = False
else:
if hasattr(AUTH_SYSTEMS[auth_system], 'can_list_category_members'):
for constraint in eligibility_case['constraint']:
category_id = AUTH_SYSTEMS[auth_system].eligibility_category_id(constraint)
for u in AUTH_SYSTEMS[auth_system].list_category_members(category_id):
user = User.update_or_create(user_type = u['type'], user_id = u['id'], name = u['name'], info = u['info'], token = u['token'])
Voter.register_user_in_election(user, self)
else:
total_load = False
if total_load:
self.openreg = False
示例7: login_view
def login_view(request):
# imports are here because putting them in the header prevents
# initialization of the database
from helios_auth.view_utils import render_template
from helios_auth.views import after
from helios_auth.models import User
if request.method == "GET":
form = LoginForm()
else:
form = LoginForm(request.POST)
request.session['auth_system_name'] = 'dummy'
if request.POST.has_key('return_url'):
request.session['auth_return_url'] = request.POST.get('return_url')
if form.is_valid():
name = form.cleaned_data['username'].strip()
admin_p = form.cleaned_data['admin_p']
user_obj = User.update_or_create(user_type='dummy', user_id=name, name=name, info={})
if user_obj.admin_p != admin_p:
user_obj.admin_p = admin_p
user_obj.save()
request.session['dummy_user'] = name
return HttpResponseRedirect(reverse(after))
return render_template(request, 'dummy/login', {'form': form})
示例8: password_forgotten_view
def password_forgotten_view(request):
"""
forgotten password view and submit.
includes return_url
"""
from helios_auth.view_utils import render_template
from helios_auth.models import User
if request.method == "GET":
return render_template(request, "password/forgot", {"return_url": request.GET.get("return_url", "")})
else:
username = request.POST["username"]
return_url = request.POST["return_url"]
try:
user = User.get_by_type_and_id("password", username)
except User.DoesNotExist:
return render_template(
request,
"password/forgot",
{"return_url": request.GET.get("return_url", ""), "error": "no such username"},
)
body = """
This is a password reminder:
Your username: %s
Your password: %s
--
%s
""" % (
user.user_id,
user.info["password"],
settings.SITE_TITLE,
)
# FIXME: make this a task
send_mail(
"password reminder",
body,
settings.SERVER_EMAIL,
["%s <%s>" % (user.info["name"], user.info["email"])],
fail_silently=False,
)
return HttpResponseRedirect(return_url)
示例9: __init__
def __init__(self, *args, **kwargs):
super(Voter, self).__init__(*args, **kwargs)
# stub the user so code is not full of IF statements
if not self.user:
self.user = User(user_type='password', user_id=self.voter_email, name=self.voter_name)
示例10: Voter
class Voter(HeliosModel):
election = models.ForeignKey(Election)
# let's link directly to the user now
# FIXME: delete this as soon as migrations are set up
#name = models.CharField(max_length = 200, null=True)
#voter_type = models.CharField(max_length = 100)
#voter_id = models.CharField(max_length = 100)
uuid = models.CharField(max_length = 50)
# for users of type password, no user object is created
# but a dynamic user object is created automatically
user = models.ForeignKey('helios_auth.User', null=True)
# if user is null, then you need a voter login ID and password
voter_login_id = models.CharField(max_length = 100, null=True)
voter_password = models.CharField(max_length = 100, null=True)
voter_name = models.CharField(max_length = 200, null=True)
voter_email = models.CharField(max_length = 250, null=True)
voter_group = models.ForeignKey(VoterGroup, null=True)
# if election uses aliases
alias = models.CharField(max_length = 100, null=True)
# we keep a copy here for easy tallying
vote = LDObjectField(type_hint = 'legacy/EncryptedVote',
null=True)
vote_hash = models.CharField(max_length = 100, null=True)
cast_at = models.DateTimeField(auto_now_add=False, null=True)
class Meta:
unique_together = (('election', 'voter_login_id'))
def __init__(self, *args, **kwargs):
super(Voter, self).__init__(*args, **kwargs)
# stub the user so code is not full of IF statements
if not self.user:
self.user = User(user_type='password', user_id=self.voter_email, name=self.voter_name)
@classmethod
@transaction.commit_on_success
def register_user_in_election(cls, user, election):
voter_uuid = str(uuid.uuid4())
voter = Voter(uuid= voter_uuid, user = user, election = election)
# do we need to generate an alias?
if election.use_voter_aliases:
heliosutils.lock_row(Election, election.id)
alias_num = election.last_alias_num + 1
voter.alias = "V%s" % alias_num
voter.save()
return voter
@classmethod
def get_by_election(cls, election, cast=None, order_by='voter_login_id', after=None, limit=None):
"""
FIXME: review this for non-GAE?
"""
query = cls.objects.filter(election = election)
# the boolean check is not stupid, this is ternary logic
# none means don't care if it's cast or not
if cast == True:
query = query.exclude(cast_at = None)
elif cast == False:
query = query.filter(cast_at = None)
# little trick to get around GAE limitation
# order by uuid only when no inequality has been added
if cast == None or order_by == 'cast_at' or order_by =='-cast_at':
query = query.order_by(order_by)
# if we want the list after a certain UUID, add the inequality here
if after:
if order_by[0] == '-':
field_name = "%s__gt" % order_by[1:]
else:
field_name = "%s__gt" % order_by
conditions = {field_name : after}
query = query.filter (**conditions)
if limit:
query = query[:limit]
return query
@classmethod
def get_all_by_election_in_chunks(cls, election, cast=None, chunk=100):
return cls.get_by_election(election)
@classmethod
def get_by_election_and_voter_id(cls, election, voter_id):
try:
return cls.objects.get(election = election, voter_login_id = voter_id)
except cls.DoesNotExist:
return None
#.........这里部分代码省略.........
示例11: get_user_info_after_auth
def get_user_info_after_auth(request):
from helios_auth.models import User
user = User.get_by_type_and_id('password', request.session['password_user_id'])
del request.session['password_user_id']
return {'type': 'password', 'user_id' : user.user_id, 'name': user.name, 'info': user.info, 'token': None}
示例12: Voter
class Voter(HeliosModel):
election = models.ForeignKey(Election)
# let's link directly to the user now
# FIXME: delete this as soon as migrations are set up
#name = models.CharField(max_length = 200, null=True)
#voter_type = models.CharField(max_length = 100)
#voter_id = models.CharField(max_length = 100)
uuid = models.CharField(max_length = 50)
# for users of type password, no user object is created
# but a dynamic user object is created automatically
user = models.ForeignKey('helios_auth.User', null=True)
# if user is null, then you need a voter login ID and password
voter_login_id = models.CharField(max_length = 100, null=True)
voter_password = models.CharField(max_length = 100, null=True)
voter_name = models.CharField(max_length = 200, null=True)
voter_email = models.CharField(max_length = 250, null=True)
# if election uses aliases
alias = models.CharField(max_length = 100, null=True)
# we keep a copy here for easy tallying
vote = LDObjectField(type_hint = 'legacy/EncryptedVote',
null=True)
vote_hash = models.CharField(max_length = 100, null=True)
cast_at = models.DateTimeField(auto_now_add=False, null=True)
class Meta:
unique_together = (('election', 'voter_login_id'))
def __init__(self, *args, **kwargs):
super(Voter, self).__init__(*args, **kwargs)
# stub the user so code is not full of IF statements
if not self.user:
self.user = User(user_type='password', user_id=self.voter_email, name=self.voter_name)
def __unicode__(self):
return self.user.name
# DENIS - ultimo upload sobrescreve demais. Registros em helios_voter devem ser apagados de forma a constar somente os usuarios indicados no CSV carregado por
# ultimo. Atualiza helios_electionlog.
# TODO - na view acrescentar informacao: apagado(s) X eleitor(es), antes de informar novo processamento de CSV.
@classmethod
@transaction.commit_on_success
def unregister_voters_in_election(cls, election):
amount_voters = 0
if not election:
raise Exception("Eleicao nula, nao posso apagar eleitores do(s) arquivo(s) CSV previo(s) se existir(em)!")
else:
amount_voters = cls.objects.filter(election_id = election.id).count()
voters_to_del = cls.objects.filter(election_id = election.id)
voters_to_del.delete()
election.append_log(ElectionLog.PREVIOUS_VOTERS_REMOVED)
return amount_voters
@classmethod
@transaction.commit_on_success
def register_user_in_election(cls, user, election):
voter_uuid = str(uuid.uuid4())
voter = Voter(uuid= voter_uuid, user = user, election = election)
# do we need to generate an alias?
if election.use_voter_aliases:
heliosutils.lock_row(Election, election.id)
alias_num = election.last_alias_num + 1
voter.alias = "V%s" % alias_num
voter.save()
return voter
@classmethod
def get_by_election(cls, election, cast=None, order_by='voter_login_id', after=None, limit=None):
"""
FIXME: review this for non-GAE?
"""
query = cls.objects.filter(election = election)
# the boolean check is not stupid, this is ternary logic
# none means don't care if it's cast or not
if cast == True:
query = query.exclude(cast_at = None)
elif cast == False:
query = query.filter(cast_at = None)
# little trick to get around GAE limitation
# order by uuid only when no inequality has been added
if cast == None or order_by == 'cast_at' or order_by =='-cast_at':
query = query.order_by(order_by)
# if we want the list after a certain UUID, add the inequality here
if after:
if order_by[0] == '-':
field_name = "%s__gt" % order_by[1:]
else:
#.........这里部分代码省略.........