2018-10-13 10:44:01 -05:00
|
|
|
from django.contrib.auth.models import Permission, Group, User
|
2018-02-16 03:25:26 -06:00
|
|
|
from users.models import Token
|
|
|
|
|
|
|
|
from ruamel.yaml import YAML
|
2018-12-19 07:25:58 -06:00
|
|
|
from pathlib import Path
|
|
|
|
import sys
|
2018-02-16 03:25:26 -06:00
|
|
|
|
2018-12-19 07:25:58 -06:00
|
|
|
file = Path('/opt/netbox/initializers/users.yml')
|
|
|
|
if not file.is_file():
|
|
|
|
sys.exit()
|
|
|
|
|
|
|
|
with file.open('r') as stream:
|
2018-02-16 03:25:26 -06:00
|
|
|
yaml=YAML(typ='safe')
|
|
|
|
users = yaml.load(stream)
|
|
|
|
|
|
|
|
if users is not None:
|
|
|
|
for username, user_details in users.items():
|
|
|
|
if not User.objects.filter(username=username):
|
|
|
|
user = User.objects.create_user(
|
|
|
|
username = username,
|
|
|
|
password = user_details.get('password', 0) or User.objects.make_random_password)
|
|
|
|
|
|
|
|
print("👤 Created user ",username)
|
|
|
|
|
|
|
|
if user_details.get('api_token', 0):
|
|
|
|
Token.objects.create(user=user, key=user_details['api_token'])
|
2018-10-13 10:44:01 -05:00
|
|
|
|
2019-12-05 09:41:11 -06:00
|
|
|
yaml_permissions = user_details.get('permissions', [])
|
|
|
|
permission_object = user
|
|
|
|
if yaml_permissions:
|
|
|
|
permission_object.permissions.clear()
|
|
|
|
for yaml_permission in yaml_permissions:
|
2019-12-11 10:14:38 -06:00
|
|
|
if '*' in yaml_permission:
|
|
|
|
permission_codename_function = 'codename__iregex'
|
|
|
|
permission_codename = '^' + yaml_permission.replace('*','.*') + '$'
|
2019-12-05 09:41:11 -06:00
|
|
|
else:
|
|
|
|
permission_codename_function = 'codename'
|
2019-12-11 10:14:38 -06:00
|
|
|
permission_codename = yaml_permission
|
|
|
|
|
|
|
|
# supports non-unique permission codenames
|
|
|
|
for permission in eval('Permission.objects.filter(' + permission_codename_function + '=permission_codename)'):
|
|
|
|
permission_object.permissions.add(permission)
|
2019-12-05 09:41:11 -06:00
|
|
|
|
|
|
|
permission_object.save()
|