/
nis.py
226 lines (174 loc) · 6.5 KB
/
nis.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
"""NIS authentication backend."""
from __future__ import annotations
import logging
from importlib import import_module
from types import ModuleType
from typing import Optional, TYPE_CHECKING, Tuple
from django.conf import settings
from django.contrib.auth.models import User
from django.utils.functional import cached_property
from django.utils.translation import gettext_lazy as _
from typing_extensions import TypeAlias
from reviewboard.accounts.backends.base import BaseAuthBackend
from reviewboard.accounts.forms.auth import NISSettingsForm
if TYPE_CHECKING:
from django.http import HttpRequest
logger = logging.getLogger(__name__)
#: A type alias for a NIS password entry.
#:
#: Version Added:
#: 6.0
_NISPasswdEntry: TypeAlias = Tuple[str, str, int, int, str, str, str]
class NISBackend(BaseAuthBackend):
"""Authenticate against a user on an NIS server."""
backend_id = 'nis'
name = _('NIS')
settings_form = NISSettingsForm
login_instructions = \
_('Use your standard NIS username and password.')
@cached_property
def nis(self) -> Optional[ModuleType]:
"""The nis module, used for interacting with NIS.
On first access, this will check if NIS is available, logging an
error if missing.
This safeguards against Python environments without NIS, and against
versions of Python >= 3.13.
Type:
module
"""
try:
return import_module('nis')
except ImportError:
logger.error('The nis module is not available on your version '
'of Python.')
return None
def authenticate(
self,
request: Optional[HttpRequest] = None,
*,
username: Optional[str] = None,
password: Optional[str] = None,
**kwargs,
) -> Optional[User]:
"""Authenticate the user.
This will attempt to authenticate the user against NIS. If the
username and password are valid, a user will be returned, and added
to the database if it doesn't already exist.
Version Changed:
6.0:
* ``request`` is now optional.
* ``username`` and ``password`` are technically optional, to
aid in consistency for type hints, but will result in a ``None``
result.
Version Changed:
4.0:
The ``request`` argument is now mandatory as the first positional
argument, as per requirements in Django.
Args:
request (django.http.HttpRequest):
The HTTP request from the caller. This may be ``None``.
username (str):
The username to authenticate.
password (str):
The password to authenticate.
**kwargs (dict, unused):
Additional keyword arguments.
Returns:
django.contrib.auth.models.User:
The authenticated user, or ``None`` if the user could not be
authenticated.
"""
if not username or not password:
logger.error('Attempted to authenticate NIS user without '
'supplying either a username or password parameter! '
'This may be a bug in Review Board. Please report '
'it.')
return None
nis = self.nis
if nis is None:
return None
username = username.strip()
import crypt
try:
passwd = self._nis_get_passwd(username)
except nis.error:
# The user does not exist, or there was an error communicating
# with NIS.
return None
original_crypted = passwd[1]
new_crypted = crypt.crypt(password, original_crypted)
if original_crypted == new_crypted:
return self.get_or_create_user(username=username,
request=request,
passwd=passwd)
return None
def get_or_create_user(
self,
username: str,
request: Optional[HttpRequest] = None,
passwd: Optional[_NISPasswdEntry] = None,
) -> Optional[User]:
"""Return an existing user, or create one if it does not exist.
If the user does not exist in the database, but does in the backend,
its information will be stored in the database for later lookup.
Args:
username (str):
The username of the user.
request (django.http.HttpRequest, optional):
The HTTP request from the client.
passwd (tuple, optional):
The parsed NIS passwd entry for the user.
Returns:
django.contrib.auth.models.User:
The existing or newly-created user, or ``None`` if an error was
encountered.
"""
nis = self.nis
if nis is None:
return None
username = username.strip()
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
if not passwd:
try:
passwd = self._nis_get_passwd(username)
except nis.error:
# The user does not exist, or there was an error
# communicating with NIS.
return None
names = passwd[4].split(',')[0].split(' ', 1)
first_name = names[0]
last_name = None
if len(names) > 1:
last_name = names[1]
email = '%s@%s' % (username, settings.NIS_EMAIL_DOMAIN)
user = User(username=username,
password='',
first_name=first_name,
last_name=last_name or '',
email=email)
user.is_staff = False
user.is_superuser = False
user.set_unusable_password()
user.save()
return user
def _nis_get_passwd(
self,
username: str,
) -> _NISPasswdEntry:
"""Return a passwd entry for a user.
Args:
username (str):
The username to fetch.
Returns:
tuple:
The parsed passwd entry.
Raises:
nis.error:
The user could not be found, or there was an error performing
the lookup.
"""
nis = self.nis
assert nis
return nis.match(username, 'passwd').split(':')