Newer
Older
data = self.get_sign_up_user_dict()
data["email"] = self.test_user.email
resp = self.post_sign_up(data=data, follow=False)
self.assertEqual(resp.status_code, 200)
self.assertNoNewUserCreated()
self.assertEqual(len(mail.outbox), 0)
self.assertAddMessageCalledWith(expected_msg)
expected_msg = (
"Email sent. Please check your email and click "
"the link.")
data = self.get_sign_up_user_dict()
resp = self.post_sign_up(data=data, follow=False)
self.assertRedirects(resp, reverse("relate-home"),
fetch_redirect_response=False)
sent_request = resp.wsgi_request
self.assertEqual(resp.status_code, 302)
self.assertNewUserCreated()
self.assertEqual(len(mail.outbox), 1)
new_user = get_user_model().objects.last()
sign_in_url = sent_request.build_absolute_uri(
reverse(
"relate-reset_password_stage2",
args=(new_user.id, new_user.sign_in_key,))
+ "?to_profile=1")
self.assertIn(sign_in_url, mail.outbox[0].body)
self.assertAddMessageCalledWith(expected_msg)
class SignOutTest(CoursesTestMixinBase, AuthTestMixin,
MockAddMessageMixing, TestCase):
with self.temporarily_switch_to_user(None):
expected_msg = "You've already signed out."
resp = self.get_sign_out(follow=False)
self.assertEqual(resp.status_code, 302)
self.assertRedirects(resp, reverse("relate-home"),
fetch_redirect_response=False)
self.assertSessionHasNoUserLoggedIn()
self.assertAddMessageCalledWith(expected_msg)
@override_settings(RELATE_SIGN_IN_BY_SAML2_ENABLED=False)
def test_sign_out_by_get(self):
with mock.patch("djangosaml2.views._get_subject_id") \
as mock_get_subject_id, \
mock.patch("djangosaml2.views.logout") as mock_saml2_logout:
mock_get_subject_id.return_value = "some_id"
with self.temporarily_switch_to_user(self.test_user):
resp = self.get_sign_out()
self.assertRedirects(resp, reverse("relate-home"),
target_status_code=200,
fetch_redirect_response=False)
self.assertSessionHasNoUserLoggedIn()
self.assertEqual(mock_saml2_logout.call_count, 0)
@override_settings(RELATE_SIGN_IN_BY_SAML2_ENABLED=False)
def test_sign_out_by_post(self):
with mock.patch("djangosaml2.views._get_subject_id") \
as mock_get_subject_id, \
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
mock.patch("djangosaml2.views.logout") as mock_saml2_logout:
mock_get_subject_id.return_value = "some_id"
with self.temporarily_switch_to_user(self.test_user):
resp = self.post_sign_out({})
self.assertRedirects(resp, reverse("relate-home"),
target_status_code=200,
fetch_redirect_response=False)
self.assertSessionHasNoUserLoggedIn()
self.assertEqual(mock_saml2_logout.call_count, 0)
@override_settings(RELATE_SIGN_IN_BY_SAML2_ENABLED=False)
def test_sign_out_with_redirect_to(self):
with self.temporarily_switch_to_user(self.test_user):
resp = self.get_sign_out(redirect_to="/some_where/")
self.assertRedirects(resp, "/some_where/",
target_status_code=200,
fetch_redirect_response=False)
self.assertSessionHasNoUserLoggedIn()
@override_settings(RELATE_SIGN_IN_BY_SAML2_ENABLED=True)
def test_sign_out_with_saml2_enabled_no_subject_id(self):
with mock.patch("djangosaml2.views._get_subject_id") \
as mock_get_subject_id, \
mock.patch("djangosaml2.views.logout") as mock_saml2_logout:
mock_get_subject_id.return_value = None
with self.temporarily_switch_to_user(self.test_user):
resp = self.get_sign_out()
self.assertEqual(resp.status_code, 302)
self.assertSessionHasNoUserLoggedIn()
self.assertEqual(mock_saml2_logout.call_count, 0)
@override_settings(RELATE_SIGN_IN_BY_SAML2_ENABLED=True)
def test_sign_out_with_saml2_enabled_with_subject_id(self):
self.c.force_login(self.test_user)
with mock.patch("djangosaml2.views._get_subject_id") \
as mock_get_subject_id, \
mock.patch("djangosaml2.views.logout") as mock_saml2_logout:
mock_get_subject_id.return_value = "some_id"
mock_saml2_logout.return_value = HttpResponse()
resp = self.get_sign_out()
self.assertEqual(resp.status_code, 200)
self.assertEqual(mock_saml2_logout.call_count, 1)
def test_sign_out_confirmation_anonymous(self):
with self.temporarily_switch_to_user(None):
expected_msg = "You've already signed out."
resp = self.get_sign_out_confirmation(follow=False)
self.assertEqual(resp.status_code, 302)
self.assertRedirects(resp, reverse("relate-home"),
fetch_redirect_response=False)
self.assertSessionHasNoUserLoggedIn()
self.assertAddMessageCalledWith(expected_msg)
@override_settings(RELATE_SIGN_IN_BY_SAML2_ENABLED=True)
def test_sign_out_confirmation(self):
with self.temporarily_switch_to_user(self.test_user):
resp = self.get_sign_out_confirmation(follow=False)
self.assertEqual(resp.status_code, 200)
@override_settings(RELATE_SIGN_IN_BY_SAML2_ENABLED=True)
def test_sign_out_confirmation_with_redirect_to(self):
with self.temporarily_switch_to_user(self.test_user):
redirect_to = "/some_where/"
resp = self.get_sign_out_confirmation(
redirect_to=redirect_to, follow=False)
self.assertEqual(resp.status_code, 200)
self.assertIn(
self.concatenate_redirect_url(
self.get_sign_out_view_url(), redirect_to
),
resp.content.decode())
class UserProfileTest(CoursesTestMixinBase, AuthTestMixin,
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
def setUp(self):
super(UserProfileTest, self).setUp()
self.rf = RequestFactory()
def generate_profile_data(self, **kwargs):
profile_data = {
"first_name": "",
"last_name": "",
"institutional_id": "",
"editor_mode": "default"}
profile_data.update(kwargs)
return profile_data
def post_profile_by_request_factory(self, data, query_string_dict=None):
data.update({"submit_user": [""]})
url = self.get_profile_view_url()
if query_string_dict is not None:
url = (
"%s?%s" % (
url,
"&".join(["%s=%s" % (k, v)
for k, v in six.iteritems(query_string_dict)])))
request = self.rf.post(url, data)
request.user = self.test_user
request.session = mock.MagicMock()
from course.auth import user_profile
response = user_profile(request)
return response
def get_profile_by_request_factory(self):
request = self.rf.get(self.get_profile_view_url())
request.user = self.test_user
request.session = mock.MagicMock()
from course.auth import user_profile
response = user_profile(request)
return response
def generate_profile_form_data(self, **kwargs):
form_data = {
"first_name": "",
"last_name": "",
"institutional_id": "",
"institutional_id_confirm": "",
"no_institutional_id": True,
"editor_mode": "default"}
form_data.update(kwargs)
return form_data
def test_not_authenticated(self):
with self.temporarily_switch_to_user(None):
resp = self.get_profile()
self.assertTrue(resp.status_code, 403)
data = self.generate_profile_form_data()
resp = self.post_profile(data)
self.assertTrue(resp.status_code, 403)
def test_get_profile(self):
with self.temporarily_switch_to_user(self.test_user):
resp = self.get_profile()
self.assertTrue(resp.status_code, 200)
def test_post_profile_without_submit_user(self):
# Only POST with 'submit_user' works
with self.temporarily_switch_to_user(self.test_user):
resp = self.get_profile()
self.assertTrue(resp.status_code, 200)
data = self.generate_profile_form_data(first_name="foo")
# No 'submit_user' in POST
resp = self.c.post(self.get_profile_view_url(), data)
self.test_user.refresh_from_db()
self.assertEqual(self.test_user.first_name, "")
def update_profile_by_post_form(self, user_profile_dict=None,
update_profile_dict=None,
query_string_dict=None):
if user_profile_dict:
assert isinstance(user_profile_dict, dict)
else:
user_profile_dict = {}
if update_profile_dict:
assert isinstance(update_profile_dict, dict)
else:
update_profile_dict = {}
user_profile = self.generate_profile_data(**user_profile_dict)
get_user_model().objects.filter(pk=self.test_user.pk).update(**user_profile)
self.test_user.refresh_from_db()
form_data = self.generate_profile_form_data(**update_profile_dict)
return self.post_profile_by_request_factory(form_data, query_string_dict)
@skipIf(six.PY2, "Python2 doesn't support subTest")
def test_update_profile_with_different_settings(self):
disabled_inst_id_html_pattern = (
'<input type="text" name="institutional_id" value="%s" '
'class="textinput textInput form-control" id="id_institutional_id" '
'maxlength="100" disabled />')
enabled_inst_id_html_pattern = (
'<input type="text" name="institutional_id" value="%s" '
'class="textinput textInput form-control" id="id_institutional_id" '
'maxlength="100" />')
expected_success_msg = "Profile data updated."
expected_unchanged_msg = "No change was made on your profile."
from collections import namedtuple
Conf = namedtuple(
'Conf', [
'id',
'override_settings_dict',
'user_profile_dict',
'update_profile_dict',
'expected_result_dict',
'assert_in_html_kwargs_list',
'expected_msg',
])
test_confs = (
# {{{ basic test
Conf("basic_1",
{EDITABLE_INST_ID_BEFORE_VERI: True, SHOW_INST_ID_FORM: True}, {},
{}, {}, [], expected_unchanged_msg),
Conf("basic_2",
{EDITABLE_INST_ID_BEFORE_VERI: True, SHOW_INST_ID_FORM: False}, {},
{}, {}, [], expected_unchanged_msg),
Conf("basic_3",
{EDITABLE_INST_ID_BEFORE_VERI: False, SHOW_INST_ID_FORM: True}, {},
{}, {}, [], expected_unchanged_msg),
Conf("basic_4",
{EDITABLE_INST_ID_BEFORE_VERI: False, SHOW_INST_ID_FORM: False},
{}, {}, {}, [], expected_unchanged_msg),
# }}}
# {{{ update first_name
Conf("first_name_1",
{},
{"first_name": "foo", "name_verified": False},
{"first_name": "bar"},
{"first_name": "bar"},
[],
expected_success_msg),
Conf("first_name_2", {},
{"first_name": "foo", "name_verified": True},
{"first_name": "bar"},
{"first_name": "foo"},
[],
expected_unchanged_msg),
# test strip
Conf("first_name_3", {},
{"first_name": "foo", "name_verified": False},
{"first_name": " bar "},
{"first_name": "bar"},
[],
expected_success_msg),
# }}}
# {{{ update last_name
Conf("last_name_1", {},
{"last_name": "foo", "name_verified": False},
{"last_name": "bar"},
{"last_name": "bar"},
[],
expected_success_msg),
Conf("last_name_2", {},
{"last_name": "foo", "name_verified": True},
{"last_name": "bar"},
{"last_name": "foo"},
[],
expected_unchanged_msg),
# test strip
Conf("last_name_3", {},
{"last_name": "foo", "name_verified": False},
{"last_name": " bar "},
{"last_name": "bar"},
[],
expected_success_msg),
# }}}
# {{{ update institutional_id update
Conf("institutional_id_update_1",
{EDITABLE_INST_ID_BEFORE_VERI: True, SHOW_INST_ID_FORM: True},
{"institutional_id": "1234", "institutional_id_verified": False},
{"institutional_id": "1234", "institutional_id_confirm": "1234"},
{"institutional_id": "1234"},
[{"needle": enabled_inst_id_html_pattern % "1234", "count": 1}],
expected_unchanged_msg),
Conf("institutional_id_update_2",
{EDITABLE_INST_ID_BEFORE_VERI: True, SHOW_INST_ID_FORM: True},
{"institutional_id": "1234", "institutional_id_verified": False},
{"institutional_id": "123", "institutional_id_confirm": "123"},
{"institutional_id": "123"},
[{"needle": enabled_inst_id_html_pattern % "123", "count": 1}],
expected_success_msg),
Conf("institutional_id_update_3",
{EDITABLE_INST_ID_BEFORE_VERI: True, SHOW_INST_ID_FORM: False},
{"institutional_id": "1234", "institutional_id_verified": False},
{"institutional_id": "1234", "institutional_id_confirm": "1234"},
{"institutional_id": "1234"},
[],
expected_unchanged_msg),
Conf("institutional_id_update_4",
{EDITABLE_INST_ID_BEFORE_VERI: True, SHOW_INST_ID_FORM: False},
{"institutional_id": "1234", "institutional_id_verified": False},
{"institutional_id": "123", "institutional_id_confirm": "123"},
{"institutional_id": "123"},
[],
expected_success_msg),
Conf("institutional_id_update_5",
{EDITABLE_INST_ID_BEFORE_VERI: True, SHOW_INST_ID_FORM: True},
{"institutional_id": "1234", "institutional_id_verified": True},
{"institutional_id": "1234", "institutional_id_confirm": "1234"},
{"institutional_id": "1234"},
[{"needle": disabled_inst_id_html_pattern % "1234", "count": 1}],
expected_unchanged_msg),
Conf("institutional_id_update_6",
{EDITABLE_INST_ID_BEFORE_VERI: True, SHOW_INST_ID_FORM: True},
{"institutional_id": "1234", "institutional_id_verified": True},
{"institutional_id": "123", "institutional_id_confirm": "123"},
{"institutional_id": "1234"},
[{"needle": disabled_inst_id_html_pattern % "1234", "count": 1}],
expected_unchanged_msg),
Conf("institutional_id_update_7",
{EDITABLE_INST_ID_BEFORE_VERI: True, SHOW_INST_ID_FORM: False},
{"institutional_id": "1234", "institutional_id_verified": True},
{"institutional_id": "1234", "institutional_id_confirm": "1234"},
{"institutional_id": "1234"},
[],
expected_unchanged_msg),
Conf("institutional_id_update_8",
{EDITABLE_INST_ID_BEFORE_VERI: True, SHOW_INST_ID_FORM: False},
{"institutional_id": "1234", "institutional_id_verified": True},
{"institutional_id": "123", "institutional_id_confirm": "123"},
{"institutional_id": "1234"},
[{"needle": enabled_inst_id_html_pattern % "1234", "count": 0}],
expected_unchanged_msg),
Conf("institutional_id_update_9",
{EDITABLE_INST_ID_BEFORE_VERI: False, SHOW_INST_ID_FORM: True},
{"institutional_id": "1234", "institutional_id_verified": False},
{"institutional_id": "1234", "institutional_id_confirm": "1234"},
{"institutional_id": "1234"},
[{"needle": disabled_inst_id_html_pattern % "1234", "count": 1}],
expected_unchanged_msg),
Conf("institutional_id_update_10",
{EDITABLE_INST_ID_BEFORE_VERI: False, SHOW_INST_ID_FORM: True},
{"institutional_id": "1234", "institutional_id_verified": False},
{"institutional_id": "123", "institutional_id_confirm": "123"},
{"institutional_id": "1234"},
[{"needle": disabled_inst_id_html_pattern % "1234", "count": 1}],
expected_unchanged_msg),
# }}}
# {{{ institutional_id clean
Conf("institutional_id_clean_1",
{EDITABLE_INST_ID_BEFORE_VERI: True, SHOW_INST_ID_FORM: True},
{"institutional_id": "1234", "institutional_id_verified": False},
{"institutional_id": "123", "institutional_id_confirm": "1234"},
{"institutional_id": "1234"},
[{"needle": "Inputs do not match.", "count": 1}],
None),
Conf("institutional_id_clean_2",
{EDITABLE_INST_ID_BEFORE_VERI: True, SHOW_INST_ID_FORM: True},
{"institutional_id": "1234", "institutional_id_verified": False},
{"institutional_id": "123"},
{"institutional_id": "1234"},
[{"needle": "This field is required.", "count": 1}],
None),
# }}}
# Update with blank value
# https://github.com/inducer/relate/pull/145
Conf("clear_institutional_id",
{EDITABLE_INST_ID_BEFORE_VERI: True, SHOW_INST_ID_FORM: True},
{"institutional_id": "1234", "institutional_id_verified": False},
{"institutional_id": "", "institutional_id_confirm": ""},
{"institutional_id": None},
[],
expected_success_msg),
# test post value with leading/trailing spaces (striped when saving)
Conf("strip_institutional_id",
{EDITABLE_INST_ID_BEFORE_VERI: True, SHOW_INST_ID_FORM: True},
{},
{"institutional_id": "123 ",
{"institutional_id": "123"},
[],
expected_success_msg),
)
for conf in test_confs:
with self.subTest(conf.id):
with override_settings(**conf.override_settings_dict):
resp = self.update_profile_by_post_form(
conf.user_profile_dict,
conf.update_profile_dict)
self.assertTrue(resp.status_code, 200)
self.test_user.refresh_from_db()
for k, v in six.iteritems(conf.expected_result_dict):
self.assertEqual(self.test_user.__dict__[k], v)
if conf.assert_in_html_kwargs_list:
kwargs_list = conf.assert_in_html_kwargs_list
for kwargs in kwargs_list:
self.assertInHTML(haystack=resp.content.decode(),
**kwargs)
if conf.expected_msg is not None:
self.assertAddMessageCalledWith(conf.expected_msg)
def test_profile_page_hide_institutional_id_or_editor_mode(self):
"""
Test whether the response content contains <input type="hidden"
for specific field
"""
field_div_with_id_pattern = (
".*(<div\s+[^\>]*id\s*=\s*['\"]div_id_%s['\"][^>]*\/?>).*")
def assertFieldDiv(field_name, exist=True): # noqa
resp = self.get_profile_by_request_factory()
self.assertEqual(resp.status_code, 200)
pattern = field_div_with_id_pattern % field_name
if exist:
self.assertRegex(resp.content.decode(), pattern,
msg=("Field Div of '%s' is expected to exist."
% field_name))
else:
self.assertNotRegex(resp.content.decode(), pattern,
msg=("Field Div of '%s' is not expected "
"to exist." % field_name))
with override_settings(
RELATE_SHOW_INST_ID_FORM=True, RELATE_SHOW_EDITOR_FORM=True):
assertFieldDiv("institutional_id", True)
assertFieldDiv("editor_mode", True)
with override_settings(
RELATE_SHOW_INST_ID_FORM=False, RELATE_SHOW_EDITOR_FORM=True):
assertFieldDiv("institutional_id", False)
assertFieldDiv("editor_mode", True)
with override_settings(
RELATE_SHOW_INST_ID_FORM=True, RELATE_SHOW_EDITOR_FORM=False):
assertFieldDiv("institutional_id", True)
assertFieldDiv("editor_mode", False)
with override_settings(
RELATE_SHOW_INST_ID_FORM=False, RELATE_SHOW_EDITOR_FORM=False):
assertFieldDiv("institutional_id", False)
assertFieldDiv("editor_mode", False)
def test_update_profile_for_first_login(self):
data = self.generate_profile_data(first_name="foo")
expected_msg = "Profile data updated."
resp = self.post_profile_by_request_factory(
data, query_string_dict={"first_login": "1"})
self.assertRedirects(resp, reverse("relate-home"),
fetch_redirect_response=False)
self.assertAddMessageCalledWith(expected_msg)
def test_update_profile_for_referer(self):
data = self.generate_profile_data(first_name="foo")
expected_msg = "Profile data updated."
resp = self.post_profile_by_request_factory(
data, query_string_dict={"referer": "/some/where/",
"set_inst_id": "1"})
self.assertRedirects(resp, "/some/where/",
fetch_redirect_response=False)
self.assertAddMessageCalledWith(expected_msg)
def test_update_profile_for_referer_wrong_spell(self):
data = self.generate_profile_data(first_name="foo")
# "Wrong" spell of referer, no redirect
resp = self.post_profile_by_request_factory(
data, query_string_dict={"referrer": "/some/where/",
"set_inst_id": "1"})
self.assertTrue(resp.status_code, 200)
self.assertAddMessageCalledWith(expected_msg)
class ResetPasswordStageOneTest(CoursesTestMixinBase, MockAddMessageMixing,
LocmemBackendTestsMixin, TestCase):
@classmethod
def setUpTestData(cls): # noqa
super(ResetPasswordStageOneTest, cls).setUpTestData()
cls.user_email = "a_very_looooooong_email@somehost.com"
cls.user_inst_id = "1234"
cls.user = factories.UserFactory.create(email=cls.user_email,
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
institutional_id=cls.user_inst_id)
def setUp(self):
super(ResetPasswordStageOneTest, self).setUp()
self.registration_override_setting = override_settings(
RELATE_REGISTRATION_ENABLED=True)
self.registration_override_setting.enable()
self.addCleanup(self.registration_override_setting.disable)
self.user.refresh_from_db()
self.c.logout()
def test_reset_get(self):
resp = self.get_reset_password()
self.assertEqual(resp.status_code, 200)
resp = self.get_reset_password(use_instid=True)
self.assertEqual(resp.status_code, 200)
@override_settings(RELATE_REGISTRATION_ENABLED=False)
def test_reset_with_registration_disabled(self):
resp = self.get_reset_password()
self.assertEqual(resp.status_code, 400)
resp = self.get_reset_password(use_instid=True)
self.assertEqual(resp.status_code, 400)
resp = self.post_reset_password(data={})
self.assertEqual(resp.status_code, 400)
resp = self.post_reset_password(use_instid=True, data={})
self.assertEqual(resp.status_code, 400)
def test_reset_form_invalid(self):
resp = self.post_reset_password(
data={"email": "some/email"})
self.assertTrue(resp.status_code, 200)
self.assertFormErrorLoose(resp, "Enter a valid email address.")
self.assertEqual(len(mail.outbox), 0)
def test_reset_by_email_non_exist(self):
expected_msg = (
"That %s doesn't have an "
"associated user account. Are you "
"sure you've registered?" % "email address")
resp = self.post_reset_password(
data={"email": "some_email@example.com"})
self.assertTrue(resp.status_code, 200)
self.assertAddMessageCalledWith(expected_msg)
self.assertEqual(len(mail.outbox), 0)
def test_reset_by_instid_non_exist(self):
expected_msg = (
"That %s doesn't have an "
"associated user account. Are you "
"sure you've registered?" % "institutional ID")
resp = self.post_reset_password(
data={"instid": "2345"}, use_instid=True)
self.assertTrue(resp.status_code, 200)
self.assertAddMessageCalledWith(expected_msg)
self.assertEqual(len(mail.outbox), 0)
self.assertEqual(resp.status_code, 200)
def test_reset_user_has_no_email(self):
self.user.email = ""
self.user.save()
expected_msg = (
"The account with that institution ID "
"doesn't have an associated email.")
resp = self.post_reset_password(data={"instid": self.user_inst_id},
use_instid=True)
self.assertTrue(resp.status_code, 200)
self.assertAddMessageCalledWith(expected_msg)
self.assertEqual(len(mail.outbox), 0)
self.assertEqual(resp.status_code, 200)
def test_reset_by_email_have_multiple_user_with_same_email(self):
with mock.patch("accounts.models.User.objects.get") as mock_get_user:
from django.core.exceptions import MultipleObjectsReturned
mock_get_user.side_effect = MultipleObjectsReturned()
expected_msg = (
"Failed to send an email: multiple users were "
"unexpectedly using that same "
"email address. Please "
"contact site staff.")
resp = self.post_reset_password(
data={"email": "some_email@example.com"})
self.assertTrue(resp.status_code, 200)
self.assertAddMessageCalledWith(expected_msg)
self.assertEqual(len(mail.outbox), 0)
def test_reset_by_email_post_success(self):
expected_msg = (
"Email sent. Please check your email and "
"click the link."
)
resp = self.post_reset_password(data={"email": self.user_email})
self.assertTrue(resp.status_code, 200)
self.assertAddMessageCallCount(1)
self.assertAddMessageCalledWith(expected_msg)
self.assertEqual(len(mail.outbox), 1)
self.assertTemplateUsed("course/sign-in-email.txt", count=1)
def test_reset_by_istid_post_success(self):
from course.auth import masked_email
masked = masked_email(self.user_email)
self.assertNotEqual(masked, self.user_email)
with mock.patch("course.auth.masked_email") as mock_mask_email:
expected_msg = (
"Email sent. Please check your email and "
"click the link."
)
resp = self.post_reset_password(data={"instid": self.user_inst_id},
use_instid=True)
self.assertTrue(resp.status_code, 200)
self.assertAddMessageCallCount(2)
self.assertAddMessageCalledWith(
"'The email address associated with that account is",
reset=False)
self.assertAddMessageCalledWith(expected_msg)
self.assertEqual(mock_mask_email.call_count, 1)
self.assertEqual(len(mail.outbox), 1)
self.assertTemplateUsed("course/sign-in-email.txt", count=1)
class ResetPasswordStageTwoTest(CoursesTestMixinBase, MockAddMessageMixing,
LocmemBackendTestsMixin, TestCase):
@classmethod
def setUpTestData(cls): # noqa
super(ResetPasswordStageTwoTest, cls).setUpTestData()
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
cls.c.logout()
with override_settings(RELATE_REGISTRATION_ENABLED=True):
cls.post_reset_password(data={"email": user.email})
user.refresh_from_db()
assert user.sign_in_key is not None
cls.user = user
def setUp(self):
super(ResetPasswordStageTwoTest, self).setUp()
self.registration_override_setting = override_settings(
RELATE_REGISTRATION_ENABLED=True)
self.registration_override_setting.enable()
self.addCleanup(self.registration_override_setting.disable)
self.c.logout()
self.user.refresh_from_db()
def assertHasUserLoggedIn(self, user): # noqa
self.assertEqual(self.get_logged_in_user(), user)
def assertHasNoUserLoggedIn(self): # noqa
self.assertIsNone(self.get_logged_in_user())
@override_settings(RELATE_REGISTRATION_ENABLED=False)
def test_reset_stage2_with_registration_disabled(self):
resp = self.get_reset_password_stage2(self.user.pk, self.user.sign_in_key)
self.assertEqual(resp.status_code, 400)
resp = self.post_reset_password_stage2(
self.user.pk, self.user.sign_in_key, data={})
self.assertEqual(resp.status_code, 400)
self.assertHasNoUserLoggedIn()
def test_reset_stage2_invalid_user(self):
expected_msg = ("Account does not exist.")
resp = self.get_reset_password_stage2(user_id=1000, # no exist
sign_in_key=self.user.sign_in_key)
self.assertTrue(resp.status_code, 403)
self.assertAddMessageCallCount(1)
self.assertAddMessageCalledWith(expected_msg)
self.assertHasNoUserLoggedIn()
resp = self.post_reset_password_stage2(
user_id=1000, # no exist
sign_in_key=self.user.sign_in_key,
data={})
self.assertTrue(resp.status_code, 403)
self.assertAddMessageCallCount(1)
self.assertAddMessageCalledWith(expected_msg)
self.assertHasNoUserLoggedIn()
expected_msg = ("Invalid sign-in token. Perhaps you've used an "
"old token email?")
resp = self.get_reset_password_stage2(user_id=self.user.id,
sign_in_key="some_invalid_token")
self.assertTrue(resp.status_code, 403)
self.assertAddMessageCallCount(1)
self.assertAddMessageCalledWith(expected_msg)
self.assertHasNoUserLoggedIn()
resp = self.post_reset_password_stage2(
user_id=self.user.id,
sign_in_key="some_invalid_token", data={})
self.assertTrue(resp.status_code, 403)
self.assertAddMessageCallCount(1)
self.assertAddMessageCalledWith(expected_msg)
self.assertHasNoUserLoggedIn()
def test_reset_stage2_get_sucess(self):
resp = self.get_reset_password_stage2(self.user.id, self.user.sign_in_key)
self.assertEqual(resp.status_code, 200)
self.assertHasNoUserLoggedIn()
def test_reset_stage2_post_form_not_valid(self):
data = {"password": "my_pass", "password_repeat": ""}
resp = self.post_reset_password_stage2(self.user.id,
self.user.sign_in_key, data)
self.assertEqual(resp.status_code, 200)
self.assertFormErrorLoose(resp, "This field is required.")
self.assertFormErrorLoose(resp, "The two password fields didn't match.")
self.assertHasNoUserLoggedIn()
def test_reset_stage2_post_success_redirect_profile_no_real_name(self):
assert not (self.user.first_name or self.user.last_name)
expected_msg = ("Successfully signed in. "
"Please complete your registration information below.")
data = {"password": "my_pass", "password_repeat": "my_pass"}
resp = self.post_reset_password_stage2(self.user.id,
self.user.sign_in_key, data)
self.assertRedirects(resp,
self.get_profile_view_url() + "?first_login=1",
fetch_redirect_response=False)
self.assertAddMessageCallCount(1)
self.assertAddMessageCalledWith(expected_msg)
self.assertHasUserLoggedIn(self.user)
def test_reset_stage2_post_success_redirect_profile_no_full_name(self):
self.user.first_name = "testuser"
self.user.save()
expected_msg = ("Successfully signed in. "
"Please complete your registration information below.")
data = {"password": "my_pass", "password_repeat": "my_pass"}
resp = self.post_reset_password_stage2(self.user.id,
self.user.sign_in_key, data)
self.assertRedirects(resp,
self.get_profile_view_url() + "?first_login=1",
fetch_redirect_response=False)
self.assertAddMessageCallCount(1)
self.assertAddMessageCalledWith(expected_msg)
self.assertHasUserLoggedIn(self.user)
def test_reset_stage2_post_success_redirect_home(self):
self.user.first_name = "test"
self.user.last_name = "user"
self.user.save()
expected_msg = ("Successfully signed in.")
data = {"password": "my_pass", "password_repeat": "my_pass"}
resp = self.post_reset_password_stage2(self.user.id,
self.user.sign_in_key, data)
self.assertEqual(resp.status_code, 302)
self.assertAddMessageCallCount(1)
self.assertAddMessageCalledWith(expected_msg)
self.assertHasUserLoggedIn(self.user)
def test_reset_stage2_post_success_redirect_profile_requesting_profile(self):
self.user.first_name = "testuser"
self.user.last_name = "user"
self.user.save()
expected_msg = ("Successfully signed in. "
"Please complete your registration information below.")
data = {"password": "my_pass", "password_repeat": "my_pass"}
resp = self.post_reset_password_stage2(self.user.id,
self.user.sign_in_key, data,
querystring={"to_profile": "-1"})
self.assertRedirects(resp,
self.get_profile_view_url() + "?first_login=1",
fetch_redirect_response=False)
self.assertAddMessageCallCount(1)
self.assertAddMessageCalledWith(expected_msg)
self.assertHasUserLoggedIn(self.user)
def test_reset_stage2_post_user_not_active(self):
self.user.is_active = False
self.user.save()
expected_msg = ("Account disabled.")
data = {"password": "my_pass", "password_repeat": "my_pass"}
resp = self.post_reset_password_stage2(self.user.id,
self.user.sign_in_key, data)
self.assertEqual(resp.status_code, 403)
self.assertAddMessageCallCount(1)
self.assertAddMessageCalledWith(expected_msg)
self.assertHasNoUserLoggedIn()
def test_reset_stage2_invalid_token_when_post_form(self):
with mock.patch("django.contrib.auth.authenticate") as mock_auth:
mock_auth.return_value = None
data = {"password": "my_pass", "password_repeat": "my_pass"}
expected_msg = ("Invalid sign-in token. Perhaps you've used an "
"old token email?")
resp = self.post_reset_password_stage2(self.user.id,
self.user.sign_in_key, data)
self.assertTrue(resp.status_code, 403)
self.assertAddMessageCallCount(1)
self.assertAddMessageCalledWith(expected_msg)
class EmailedTokenBackendTest(CoursesTestMixinBase, TestCase):
def test_authenticate(self):
self.c.logout()
with override_settings(RELATE_REGISTRATION_ENABLED=True):
self.post_reset_password(data={"email": user.email})
user.refresh_from_db()
assert user.sign_in_key is not None
backend = EmailedTokenBackend()
self.assertEqual(
backend.authenticate(user.pk, token=user.sign_in_key), user)
self.assertIsNone(
backend.authenticate(user.pk, token="non_exist_sign_in_key"))
def test_get_user(self):
self.c.logout()
backend = EmailedTokenBackend()
self.assertEqual(backend.get_user(user.pk), user)
self.assertIsNone(backend.get_user(10000))
class LogoutConfirmationRequiredDecoratorTest(unittest.TestCase):
def setUp(self):
def test_logout_confirmation_required_as_callable(self):
from course.auth import logout_confirmation_required
self.assertTrue(callable(logout_confirmation_required()))
self.assertTrue(logout_confirmation_required()(self.user))
from django.contrib.auth.models import AnonymousUser
self.assertTrue(logout_confirmation_required()(AnonymousUser))
class TestSaml2Backend(TestCase):
def test_update_user(self):
user = factories.UserFactory(first_name="", last_name="",
institutional_id="",
institutional_id_verified=False,
name_verified=False,
status=constants.user_status.unconfirmed)
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
backend = Saml2Backend()
saml_attribute_mapping = {
'PrincipalName': ('username',),
'iTrustUIN': ('institutional_id',),
'mail': ('email',),
'givenName': ('first_name',),
'sn': ('last_name',),
}
user_attribute = {
'PrincipalName': (user.username,),
}
with mock.patch("accounts.models.User.save") as mock_save:
# no changes
user = backend.update_user(user, user_attribute, saml_attribute_mapping)
self.assertEqual(mock_save.call_count, 0)
self.assertEqual(user.first_name, "")
self.assertEqual(user.last_name, "")
self.assertFalse(user.name_verified)
self.assertEqual(user.status, constants.user_status.unconfirmed)
self.assertFalse(user.institutional_id_verified)
expected_first = "my_first"
expected_last = "my_last"
expected_inst_id = "123321"
user_attribute = {
'PrincipalName': (user.username,),
'iTrustUIN': (expected_inst_id,),
'givenName': (expected_first,),
'sn': (expected_last,),
}
with mock.patch("accounts.models.User.save") as mock_save:
user = backend.update_user(user, user_attribute, saml_attribute_mapping)
self.assertEqual(mock_save.call_count, 1)
user = backend.update_user(user, user_attribute, saml_attribute_mapping)
self.assertEqual(user.first_name, expected_first)
self.assertEqual(user.last_name, expected_last)
self.assertTrue(user.name_verified)
self.assertEqual(user.status, constants.user_status.unconfirmed)
self.assertTrue(user.institutional_id_verified)
user_attribute = {
'PrincipalName': (user.username,),
'iTrustUIN': (expected_inst_id,),
'mail': (user.email,),
'givenName': (expected_first,),
'sn': (expected_last,),
}
user = backend.update_user(user, user_attribute, saml_attribute_mapping)
self.assertEqual(user.first_name, expected_first)
self.assertEqual(user.last_name, expected_last)
self.assertTrue(user.name_verified)
self.assertEqual(user.status, constants.user_status.active)
self.assertTrue(user.institutional_id_verified)
with mock.patch("accounts.models.User.save") as mock_save:
# no changes
backend.update_user(user, user_attribute, saml_attribute_mapping)
self.assertEqual(mock_save.call_count, 0)