OpenSlides/openslides/users/api.py

78 lines
2.0 KiB
Python
Raw Normal View History

from random import choice
2011-07-31 10:46:29 +02:00
from django.contrib.auth.models import Permission, Group
from django.contrib.contenttypes.models import ContentType
from .models import User
2011-09-03 17:17:29 +02:00
def gen_password():
"""
Generates a random passwort.
"""
chars = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789"
size = 8
return ''.join([choice(chars) for i in range(size)])
2011-09-03 17:17:29 +02:00
2011-07-31 10:46:29 +02:00
def gen_username(first_name, last_name):
"""
Generates a username from a first- and lastname.
"""
first_name = first_name.strip()
last_name = last_name.strip()
if first_name and last_name:
base_name = " ".join((first_name, last_name))
else:
base_name = first_name or last_name
if not base_name:
raise ValueError('Either \'first_name\' or \'last_name\' can not be '
'empty')
if not User.objects.filter(username=base_name).exists():
return base_name
counter = 0
2011-07-31 10:46:29 +02:00
while True:
counter += 1
test_name = "%s %d" % (base_name, counter)
if not User.objects.filter(username=test_name).exists():
return test_name
2013-03-12 20:58:22 +01:00
def get_registered_group():
"""
Returns the group 'Registered' (pk=2).
2013-03-12 20:58:22 +01:00
"""
return Group.objects.get(pk=2)
2013-06-16 12:00:57 +02:00
def create_or_reset_admin_user():
group_staff = Group.objects.get(pk=4)
try:
admin = User.objects.get(username="admin")
except User.DoesNotExist:
admin = User()
admin.username = 'admin'
admin.last_name = 'Administrator'
created = True
else:
created = False
2013-06-16 12:00:57 +02:00
admin.default_password = 'admin'
admin.set_password(admin.default_password)
admin.save()
admin.groups.add(group_staff)
return created
def get_protected_perm():
"""
Returns the permission to manage users. This function is a helper
function used to protect manager users from locking out themselves.
"""
return Permission.objects.get(
content_type=ContentType.objects.get(app_label='users', model='user'),
codename='can_manage')