Files
the-littlest-jupyterhub/tljh/user.py
Matthias Bussonnier 552db9f74d Don't create home publicly readable
World-Readable seem to be a surprising default for many people,
especially in teaching context. Switch to a more reasonable rwxr-x---

We have to issue a chmod, as changing at creation time would require
changin /etc/adduser.conf DIR_MODE=0760 (or whatever), but that seem
unwise.

We do not set the exact permission in case the DIR_MODE is more
restrictive.

Closing #158
2018-08-29 14:38:38 -07:00

115 lines
2.0 KiB
Python

"""
User management for tljh.
Supports minimal user & group management
"""
import pwd
import grp
import subprocess
from os.path import expanduser
def ensure_user(username):
"""
Make sure a given user exists
"""
# Check if user exists
try:
pwd.getpwnam(username)
# User exists, nothing to do!
return
except KeyError:
# User doesn't exist, time to create!
pass
subprocess.check_call([
'useradd',
'--create-home',
username
])
subprocess.check_call([
'chmod',
'o-rwx',
expanduser('~{username}'.format(username=username))
])
def remove_user(username):
"""
Remove user from system if exists
"""
try:
pwd.getpwnam(username)
except KeyError:
# User doesn't exist, nothing to do
return
subprocess.check_call([
'deluser',
'--quiet',
username
])
def ensure_group(groupname):
"""
Ensure given group exists
"""
subprocess.check_call([
'groupadd',
'--force',
groupname
])
def remove_group(groupname):
"""
Remove group from system if exists
"""
try:
grp.getgrnam(groupname)
except KeyError:
# Group doesn't exist, nothing to do
return
subprocess.check_call([
'delgroup',
'--quiet',
groupname
])
def ensure_user_group(username, groupname):
"""
Ensure given user is member of given group
Group and User must already exist.
"""
group = grp.getgrnam(groupname)
if username in group.gr_mem:
return
subprocess.check_call([
'gpasswd',
'--add',
username,
groupname
])
def remove_user_group(username, groupname):
"""
Ensure given user is *not* a member of given group
"""
group = grp.getgrnam(groupname)
if username not in group.gr_mem:
return
subprocess.check_call([
'gpasswd',
'--delete',
username,
groupname
])