-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathutils.py
More file actions
2681 lines (2200 loc) · 97 KB
/
utils.py
File metadata and controls
2681 lines (2200 loc) · 97 KB
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Utility functions for enterprise app.
"""
import datetime
import hashlib
import json
import os
import re
from collections import OrderedDict
from functools import reduce
from itertools import islice
from urllib.parse import parse_qs, quote, urlencode, urljoin, urlparse, urlsplit, urlunsplit
from uuid import UUID, uuid4
import bleach
import pytz
from edx_django_utils.cache import TieredCache
from edx_django_utils.cache import get_cache_key as get_django_cache_key
from slumber.exceptions import HttpClientError
from social_django.models import UserSocialAuth
from django.apps import apps
from django.conf import settings
from django.contrib import auth
from django.core import mail
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.core.validators import validate_email
from django.db import utils
from django.db.models import Q
from django.db.models.query import QuerySet
from django.forms.models import model_to_dict
from django.http import Http404
from django.shortcuts import get_object_or_404
from django.urls import reverse
from django.utils.dateparse import parse_datetime
from django.utils.html import format_html
from django.utils.text import slugify
from django.utils.translation import gettext as _
from django.utils.translation import ngettext
from enterprise.constants import (
ALLOWED_TAGS,
COURSE_MODE_SORT_ORDER,
DEFAULT_CATALOG_CONTENT_FILTER,
DEFAULT_USERNAME_ATTR,
LMS_API_DATETIME_FORMAT,
LMS_API_DATETIME_FORMAT_WITHOUT_TIMEZONE,
MAX_ALLOWED_TEXT_LENGTH,
PATHWAY_CUSTOMER_ADMIN_ENROLLMENT,
PROGRAM_TYPE_DESCRIPTION,
CourseModes,
)
from enterprise.logging import getEnterpriseLogger
try:
from openedx.features.enterprise_support.enrollments.utils import lms_update_or_create_enrollment
except ImportError:
lms_update_or_create_enrollment = None
try:
from openedx.core.djangoapps.course_groups.models import CourseUserGroup
from openedx.core.djangoapps.enrollments.errors import CourseEnrollmentError
except ImportError:
CourseUserGroup = None
CourseEnrollmentError = None
try:
from common.djangoapps.course_modes.models import CourseMode
except ImportError:
CourseMode = None
try:
from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers
except ImportError:
configuration_helpers = None
try:
from openedx.core.djangoapps.catalog.models import CatalogIntegration
except ImportError:
CatalogIntegration = None
try:
from lms.djangoapps.branding.api import get_logo_url
except ImportError:
get_logo_url = None
try:
from lms.djangoapps.branding.api import get_url
except ImportError:
get_url = None
# Only create manual enrollments if running in edx-platform
try:
from common.djangoapps.student.api import (
UNENROLLED_TO_ALLOWEDTOENROLL,
UNENROLLED_TO_ENROLLED,
create_manual_enrollment_audit,
)
except ImportError:
create_manual_enrollment_audit = None
UNENROLLED_TO_ENROLLED = None
UNENROLLED_TO_ALLOWEDTOENROLL = None
# For use with email templates
SELF_ENROLL_EMAIL_TEMPLATE_TYPE = 'SELF_ENROLL'
ADMIN_ENROLL_EMAIL_TEMPLATE_TYPE = 'ADMIN_ENROLL'
LOGGER = getEnterpriseLogger(__name__)
User = auth.get_user_model()
try:
from common.djangoapps.third_party_auth.provider import Registry
except ImportError as exception:
LOGGER.debug("Could not import Registry from common.djangoapps.third_party_auth.provider")
LOGGER.debug(exception)
Registry = None
try:
from common.djangoapps.track import segment
except ImportError as exception:
LOGGER.debug("Could not import segment from common.djangoapps.track")
LOGGER.debug(exception)
segment = None
try:
from openedx.core.djangoapps.user_api.models import UserPreference
except ImportError:
UserPreference = None
try:
from openedx.core.djangoapps.lang_pref import LANGUAGE_KEY
except ImportError:
LANGUAGE_KEY = 'pref-lang'
class ValidationMessages:
"""
Namespace class for validation messages.
"""
# Keep this alphabetically sorted
BOTH_FIELDS_SPECIFIED = _(
"Either \"Email or Username\" or \"CSV bulk upload\" must be specified, "
"but both were.")
BULK_LINK_FAILED = _(
"Error: Learners could not be added. Correct the following errors.")
COURSE_MODE_INVALID_FOR_COURSE = _(
"Enrollment track {course_mode} is not available for course {course_id}.")
COURSE_WITHOUT_COURSE_MODE = _(
"Select a course enrollment track for the given course(s).")
INVALID_COURSE_ID = _(
"Could not retrieve details for the course ID {course_id}. Specify "
"a valid ID.")
BOTH_COURSE_FIELDS_SPECIFIED = _(
"Either \"CSV bulk upload\" or a singular course ID may be used for manual enrollments, "
"but not both together."
)
INVALID_EMAIL = _(
"{argument} does not appear to be a valid email address.")
INVALID_EMAIL_OR_USERNAME = _(
"{argument} does not appear to be a valid email address or known "
"username")
MISSING_EXPECTED_COLUMNS = _(
"Expected a CSV file with [{expected_columns}] columns, but found "
"[{actual_columns}] columns instead."
)
MISSING_REASON = _(
"Reason field is required but was not filled."
)
NO_FIELDS_SPECIFIED = _(
"Either \"Email or Username\" or \"CSV bulk upload\" must be "
"specified, but neither were.")
USER_ALREADY_REGISTERED = _(
"User with email address {email} is already registered with Enterprise "
"Customer {ec_name}")
USER_NOT_LINKED = _("User is not linked with Enterprise Customer")
USER_NOT_EXIST = _("User with email address {email} doesn't exist.")
COURSE_NOT_EXIST_IN_CATALOG = _("Course ID {course_id} doesn't exist in Enterprise Customer's Catalog")
INVALID_CHANNEL_WORKER = _(
'Enterprise channel worker user with the username "{channel_worker_username}" was not found.'
)
INVALID_ENCODING = _(
"Unable to parse CSV file. Please make sure it is a CSV 'utf-8' encoded file."
)
INVALID_DISCOUNT = _(
'Discount percentage should be from 0 to 100.'
)
class NotConnectedToOpenEdX(Exception):
"""
Exception to raise when not connected to OpenEdX.
In general, this exception shouldn't be raised, because this package is
designed to be installed directly inside an existing OpenEdX platform.
"""
def __init__(self, *args, **kwargs):
"""
Log a warning and initialize the exception.
"""
LOGGER.warning('edx-enterprise unexpectedly failed as if not installed in an OpenEdX platform')
super().__init__(*args, **kwargs)
class CourseCatalogApiError(Exception):
"""
Exception to raise when we we received data from Course Catalog but it contained an error.
"""
class CourseEnrollmentDowngradeError(Exception):
"""
Exception to raise when an enrollment attempts to enroll the user in an unpaid mode when they are in a paid mode.
"""
class CourseEnrollmentPermissionError(Exception):
"""
Exception to raise when an enterprise attempts to use enrollment features it's not configured to use.
"""
def get_social_auth_from_idp(idp, user=None, user_idp_id=None):
"""
Return social auth entry of user for given enterprise IDP.
idp (EnterpriseCustomerIdentityProvider): EnterpriseCustomerIdentityProvider Object
user (User): User Object
user_idp_id (str): User id of user in third party LMS
"""
if idp:
tpa_provider = get_identity_provider(idp.provider_id)
filter_kwargs = {
'provider': tpa_provider.backend_name,
'uid__contains': tpa_provider.provider_id[5:]
}
if user_idp_id:
provider_slug = tpa_provider.provider_id[5:]
social_auth_uid = '{}:{}'.format(provider_slug, user_idp_id)
filter_kwargs['uid'] = social_auth_uid
else:
filter_kwargs['user'] = user
user_social_auth = UserSocialAuth.objects.select_related('user').filter(**filter_kwargs).first()
return user_social_auth if user_social_auth else None
return None
def get_user_valid_idp(user, enterprise_customer):
"""
Return the default idp if it has user social auth record else it
will return any idp with valid user social auth record
user (User): user object
enterprise_customer (EnterpriseCustomer): EnterpriseCustomer object
"""
valid_identity_provider = None
# If default idp provider has UserSocialAuth record then it has the highest priority.
if get_social_auth_from_idp(enterprise_customer.default_provider_idp, user=user):
valid_identity_provider = enterprise_customer.default_provider_idp
else:
for idp in enterprise_customer.identity_providers:
if get_social_auth_from_idp(idp, user=user):
valid_identity_provider = idp
break
return valid_identity_provider
def get_identity_provider(provider_id):
"""
Get Identity Provider with given id.
Return:
Instance of ProviderConfig or None.
"""
try:
return Registry and Registry.get(provider_id)
except ValueError:
return None
def get_idp_choices():
"""
Get a list of identity providers choices for enterprise customer.
Return:
A list of choices of all identity providers, None if it can not get any available identity provider.
"""
first = [("", "-" * 7)]
if Registry:
return first + [(idp.provider_id, idp.name) for idp in Registry.enabled() if not idp.disable_for_enterprise_sso]
return None
def get_all_field_names(model, excluded=None):
"""
Return all fields' names from a model. Filter out the field names present in `excluded`.
According to `Django documentation`_, ``get_all_field_names`` should become some monstrosity with chained
iterable ternary nested in a list comprehension. For now, a simpler version of iterating over fields and
getting their names work, but we might have to switch to full version in future.
.. _Django documentation: https://docs.djangoproject.com/en/1.8/ref/models/meta/
"""
excluded_fields = excluded or []
return [f.name for f in model._meta.get_fields() if f.name not in excluded_fields]
def get_oauth2authentication_class():
"""
Return oauth2 authentication class to authenticate REST APIs with Bearer token.
"""
try:
# pylint: disable=import-outside-toplevel
from openedx.core.lib.api.authentication import OAuth2AuthenticationAllowInactiveUser as OAuth2Authentication
except ImportError:
return None
return OAuth2Authentication
def get_catalog_admin_url(catalog_id):
"""
Get url to catalog details admin page.
Arguments:
catalog_id (int): Catalog id for which to return catalog details url.
Returns:
URL pointing to catalog details admin page for the give catalog id.
Example:
>>> get_catalog_admin_url_template(2)
"http://localhost:18381/admin/catalogs/catalog/2/change/"
"""
return get_catalog_admin_url_template().format(catalog_id=catalog_id)
def get_catalog_admin_url_template(mode='change'):
"""
Get template of catalog admin url.
URL template will contain a placeholder '{catalog_id}' for catalog id.
Arguments:
mode e.g. change/add.
Returns:
A string containing template for catalog url.
Example:
>>> get_catalog_admin_url_template('change')
"http://localhost:18381/admin/catalogs/catalog/{catalog_id}/change/"
"""
api_base_url = getattr(settings, "COURSE_CATALOG_API_URL", "")
# Extract FQDN (Fully Qualified Domain Name) from API URL.
match = re.match(r"^(?P<fqdn>(?:https?://)?[^/]+)", api_base_url)
if not match:
return ""
# Return matched FQDN from catalog api url appended with catalog admin path
if mode == 'change':
return match.group("fqdn").rstrip("/") + "/admin/catalogs/catalog/{catalog_id}/change/"
if mode == 'add':
return match.group("fqdn").rstrip("/") + "/admin/catalogs/catalog/add/"
return None
def get_notification_subject_line(course_name, template_configuration=None):
"""
Get a subject line for a notification email.
The method is designed to fail in a "smart" way; if we can't render a
database-backed subject line template, then we'll fall back to a template
saved in the Django settings; if we can't render _that_ one, then we'll
fall through to a friendly string written into the code.
One example of a failure case in which we want to fall back to a stock template
would be if a site admin entered a subject line string that contained a template
tag that wasn't available, causing a KeyError to be raised.
Arguments:
course_name (str): Course name to be rendered into the string
template_configuration: A database-backed object with a stored subject line template
"""
stock_subject_template = _('You\'ve been enrolled in {course_name}!')
default_subject_template = getattr(
settings,
'ENTERPRISE_ENROLLMENT_EMAIL_DEFAULT_SUBJECT_LINE',
stock_subject_template,
)
if template_configuration is not None and template_configuration.subject_line:
final_subject_template = template_configuration.subject_line
else:
final_subject_template = default_subject_template
try:
return final_subject_template.format(course_name=course_name)
except KeyError:
pass
try:
return default_subject_template.format(course_name=course_name)
except KeyError:
return stock_subject_template.format(course_name=course_name)
def find_enroll_email_template(enterprise_customer, template_type):
"""
Find email template from the template database represented by EnrollmentNotificationEmailTemplate model.
Arguments:
- enterprise_customer (EnterpriseCustomer): the customer model
- template_type (str): type of template to fetch, must be one of:
enterprise.utils.SELF_ENROLL_EMAIL_TEMPLATE_TYPE, or
enterprise.utils.ADMIN_ENROLL_EMAIL_TEMPLATE_TYPE
Returns:
Customer specific template if found.
Default template for the given type if found.
None if neither default template, nor per customer template found.
"""
enrollment_template = apps.get_model('enterprise', 'EnrollmentNotificationEmailTemplate')
if not enterprise_customer:
raise ValueError('Must provide a enterprise_customer argument')
if not template_type:
raise ValueError('Must provide a template_type argument')
# first try customer specific template for this type
try:
enterprise_template_config = enrollment_template.objects.filter(
enterprise_customer=enterprise_customer,
template_type=template_type,
).first()
except (ObjectDoesNotExist, AttributeError):
enterprise_template_config = None
if not enterprise_template_config:
# use the fallback template instead
enterprise_template_config = enrollment_template.objects.filter(
enterprise_customer=None,
template_type=template_type,
).first()
return enterprise_template_config
def is_pending_user(user):
"""
Returns true if pending_user attributes are detected
"""
return hasattr(user, 'user_email') and not hasattr(user, 'first_name')
def get_learner_portal_url(enterprise_customer):
"""
Learner portal url for enterprise_customer
"""
return get_configuration_value_for_site(
enterprise_customer.site,
'ENTERPRISE_LEARNER_PORTAL_BASE_URL',
settings.ENTERPRISE_LEARNER_PORTAL_BASE_URL
)
def serialize_notification_content(
enterprise_customer,
course_details,
course_id,
users,
admin_enrollment=False,
activation_links=None,
):
"""
Prepare serializable contents to send emails with (if using tasks to send emails)
Arguments:
enterprise_customer (enterprise.models.EnterpriseCustomer)
course_details (dict): With at least 'title', 'start' and 'course' keys
(usually obtained via CourseCatalogApiClient)
course_id (str)
users (list): list of users to enroll (each user should be a User or PendingEnterpriseCustomerUser)
activation_links (dict): a dictionary map of unactivated license user emails to license activation links
Returns: A list of dictionary objects that are of the form::
{
"user": user
"enrolled_in": {
'name': course_name,
'url': destination_url,
'type': 'course',
'start': course_start,
},
"dashboard_url": dashboard_url,
"enterprise_customer_uuid": self.uuid,
"admin_enrollment": admin_enrollment,
}
where user is one of
- 1: { 'first_name': name, 'username': user_name, 'email': email } (dict of User object)
- 2: { 'user_email' : user_email } (dict of PendingEnterpriseCustomerUser object)
"""
dashboard_url = None
course_name = course_details.get('title')
course_path = '/courses/{course_id}/course'.format(course_id=course_id)
params = {}
if admin_enrollment:
dashboard_url = get_learner_portal_url(enterprise_customer)
# add tpa_hint if there is only one IdP attached with enterprise_customer
if enterprise_customer.has_single_idp:
params = {'tpa_hint': enterprise_customer.identity_providers.first().provider_id}
elif enterprise_customer.has_multiple_idps and enterprise_customer.default_provider_idp:
params = {'tpa_hint': enterprise_customer.default_provider_idp.provider_id}
course_path = quote("{}?{}".format(course_path, urlencode(params)))
lms_root_url = get_configuration_value_for_site(
enterprise_customer.site,
'LMS_ROOT_URL',
settings.LMS_ROOT_URL
)
try:
course_start = parse_lms_api_datetime(course_details.get('start'))
except (TypeError, ValueError):
course_start = None
LOGGER.exception(
'None or empty value passed as course start date.\nCourse Details:\n{course_details}'.format(
course_details=course_details,
)
)
email_items = []
for user in users:
user_dict = model_to_dict(user, fields=['first_name', 'username', 'user_email', 'email'])
if 'email' in user_dict:
user_email = user_dict['email']
elif 'user_email' in user_dict:
user_email = user_dict['user_email']
else:
raise TypeError(_('`user` must have one of either `email` or `user_email`.'))
login_or_register = 'register' if is_pending_user(user) else 'login'
# if we have an activation link for a license, use that rather than the course URL
if activation_links is not None and activation_links.get(user_email) is not None:
destination_url = activation_links.get(user_email)
else:
destination_url = '{site}/{login_or_register}?next={course_path}'.format(
site=lms_root_url,
login_or_register=login_or_register,
course_path=course_path
)
email_items.append({
"user": user_dict,
"enrolled_in": {
'name': course_name,
'url': destination_url,
'type': 'course',
'start': course_start,
},
"dashboard_url": dashboard_url,
"enterprise_customer_uuid": enterprise_customer.uuid,
"admin_enrollment": admin_enrollment,
})
return email_items
def send_email_notification_message(
user,
enrolled_in,
dashboard_url,
enterprise_customer_uuid,
email_connection=None,
admin_enrollment=False,
):
"""
Send an email notifying a user about their enrollment in a course.
Arguments:
user: a dict with either of the following forms:
- 1: { 'first_name': name, 'username': user_name, 'email': email } (similar to a User object)
- 2: { 'user_email' : user_email } (similar to a PendingEnterpriseCustomerUser object)
enrolled_in (dict): The dictionary contains details of the enrollable object
(either course or program) that the user enrolled in. This MUST contain
a `name` key, and MAY contain the other following keys::
- url: A human-friendly link to the enrollable's home page
- type: Either `course` or `program` at present
- branding: A special name for what the enrollable "is"; for example,
"MicroMasters" would be the branding for a "MicroMasters Program"
- start: A datetime object indicating when the enrollable will be available.
dashboard_url: link to enterprise customer's unique homepage for user
enterprise_customer_uuid: The EnterpriseCustomer uuid that the enrollment was created using.
email_connection: An existing Django email connection that can be used without
creating a new connection for each individual message
admin_enrollment: If true, uses admin enrollment template instead of default ones.
"""
if 'first_name' in user and 'username' in user:
# PendingEnterpriseCustomerUsers don't have usernames or real names. We should
# template slightly differently to make sure weird stuff doesn't happen.
user_name = user['first_name']
if not user_name:
user_name = user['username']
else:
user_name = None
# User-like dicts have an `email` attribute; PendingEnterpriseCustomerUser-like have `user_email`.
if 'email' in user:
user_email = user['email']
elif 'user_email' in user:
user_email = user['user_email']
else:
raise TypeError(_('`user` must have one of either `email` or `user_email`.'))
enterprise_customer = get_enterprise_customer(enterprise_customer_uuid)
msg_context = {
'user_name': user_name,
'enrolled_in': enrolled_in,
'dashboard_url': dashboard_url,
'organization_name': enterprise_customer.name,
}
if admin_enrollment:
template_type = ADMIN_ENROLL_EMAIL_TEMPLATE_TYPE
else:
template_type = SELF_ENROLL_EMAIL_TEMPLATE_TYPE
enterprise_template_config = find_enroll_email_template(enterprise_customer, template_type)
if not enterprise_template_config:
LOGGER.warning(
'Cannot find email templates for %s, template_type: %s. '
'Not sending notification email.',
enterprise_customer.name, template_type
)
return None
plain_msg, html_msg = enterprise_template_config.render_all_templates(msg_context)
subject_line = get_notification_subject_line(enrolled_in['name'], enterprise_template_config)
from_email_address = get_configuration_value_for_site(
enterprise_customer.site,
'DEFAULT_FROM_EMAIL',
default=settings.DEFAULT_FROM_EMAIL
)
return mail.send_mail(
subject_line,
plain_msg,
from_email_address,
[user_email],
html_message=html_msg,
connection=email_connection
)
def enterprise_customer_model():
"""
Returns the ``EnterpriseCustomer`` class.
"""
return apps.get_model('enterprise', 'EnterpriseCustomer')
def enterprise_customer_sso_configuration_model():
"""
Returns the ``EnterpriseCustomerSsoConfiguration`` class.
"""
return apps.get_model('enterprise', 'EnterpriseCustomerSsoConfiguration')
def enterprise_enrollment_source_model():
"""
Returns the ``EnterpriseEnrollmentSource`` class.
"""
return apps.get_model('enterprise', 'EnterpriseEnrollmentSource')
def enterprise_customer_user_model():
"""
Returns the ``EnterpriseCustomerUser`` class.
"""
return apps.get_model('enterprise', 'EnterpriseCustomerUser')
def enterprise_course_enrollment_model():
"""
Returns the ``EnterpriseCourseEnrollment`` class.
"""
return apps.get_model('enterprise', 'EnterpriseCourseEnrollment')
def licensed_enterprise_course_enrollment_model():
"""
returns the ``LicensedEnterpriseCourseEnrollment`` class.
"""
return apps.get_model('enterprise', 'LicensedEnterpriseCourseEnrollment')
def subsidized_enterprise_course_enrollment_model():
"""
returns the ``LearnerCreditEnterpriseCourseEnrollment`` class.
"""
return apps.get_model('enterprise', 'LearnerCreditEnterpriseCourseEnrollment')
def enterprise_customer_invite_key_model():
"""
Returns the ``EnterpriseCustomerInviteKey`` class.
"""
return apps.get_model('enterprise', 'EnterpriseCustomerInviteKey')
def pending_enterprise_customer_admin_user_model():
"""
Returns the ``PendingEnterpriseCustomerAdminUser`` class.
"""
return apps.get_model('enterprise', 'PendingEnterpriseCustomerAdminUser')
def default_enterprise_enrollment_intention_model():
"""
Returns the ``DefaultEnterpriseEnrollmentIntention`` class.
"""
return apps.get_model('enterprise', 'DefaultEnterpriseEnrollmentIntention')
def default_enterprise_enrollment_realization_model():
"""
Returns the ``DefaultEnterpriseEnrollmentRealization`` class.
"""
return apps.get_model('enterprise', 'DefaultEnterpriseEnrollmentRealization')
def get_enterprise_customer(uuid):
"""
Get the ``EnterpriseCustomer`` instance associated with ``uuid``.
:param uuid: The universally unique ID of the enterprise customer.
:return: The ``EnterpriseCustomer`` instance, or ``None`` if it doesn't exist.
"""
EnterpriseCustomer = enterprise_customer_model()
try:
return EnterpriseCustomer.objects.get(uuid=uuid)
except (EnterpriseCustomer.DoesNotExist, ValidationError):
return None
def get_enterprise_uuids_for_user_and_course(auth_user, course_run_id, is_customer_active=None):
"""
Get the ``EnterpriseCustomer`` UUID(s) associated with a user and a course id``.
Some users are associated with an enterprise customer via `EnterpriseCustomerUser` model,
1. if given user is enrolled in a specific course via an enterprise customer enrollment,
return related enterprise customers as a list.
2. otherwise return empty list.
Arguments:
auth_user (contrib.auth.User): Django User
course_run_id (str): Course Run to lookup an enrollment against.
active: (boolean or None): Filter flag for returning active, inactive, or all uuids
Returns:
(list of str): enterprise customer uuids associated with the current user and course run or None
"""
return enterprise_course_enrollment_model().get_enterprise_uuids_with_user_and_course(
auth_user.id,
course_run_id,
is_customer_active=is_customer_active,
)
def get_enterprise_customer_for_user(auth_user):
"""
Return first found enterprise customer instance for given user.
Some users are associated with an enterprise customer via `EnterpriseCustomerUser` model,
1. if given user is associated with any enterprise customer, return first enterprise customer.
2. otherwise return `None`.
Arguments:
auth_user (contrib.auth.User): Django User
Returns:
(EnterpriseCustomer): enterprise customer associated with the current user.
"""
EnterpriseCustomerUser = apps.get_model('enterprise', 'EnterpriseCustomerUser')
try:
return EnterpriseCustomerUser.objects.get(user_id=auth_user.id).enterprise_customer
except EnterpriseCustomerUser.DoesNotExist:
return None
def get_enterprise_customer_user(user_id, enterprise_uuid):
"""
Return the object for EnterpriseCustomerUser.
Arguments:
user_id (str): user identifier
enterprise_uuid (UUID): Universally unique identifier for the enterprise customer.
Returns:
(EnterpriseCustomerUser): enterprise customer user record
"""
EnterpriseCustomerUser = apps.get_model('enterprise', 'EnterpriseCustomerUser')
try:
return EnterpriseCustomerUser.objects.get(
enterprise_customer__uuid=enterprise_uuid,
user_id=user_id
)
except EnterpriseCustomerUser.DoesNotExist:
return None
def get_course_track_selection_url(course_run, query_parameters):
"""
Return track selection url for the given course.
Arguments:
course_run (dict): A dictionary containing course run metadata.
query_parameters (dict): A dictionary containing query parameters to be added to course selection url.
Raises:
(KeyError): Raised when course run dict does not have 'key' key.
Returns:
(str): Course track selection url.
"""
try:
course_root = reverse('course_modes_choose', kwargs={'course_id': course_run['key']})
except KeyError:
LOGGER.exception(
"KeyError while parsing course run data.\nCourse Run: \n[%s]", course_run,
)
raise
url = '{}{}'.format(
settings.LMS_ROOT_URL,
course_root
)
course_run_url = update_query_parameters(url, query_parameters)
return course_run_url
def update_query_parameters(url, query_parameters):
"""
Return url with updated query parameters.
Arguments:
url (str): Original url whose query parameters need to be updated.
query_parameters (dict): A dictionary containing query parameters to be added to course selection url.
Returns:
(slug): slug identifier for the identity provider that can be used for identity verification of
users associated the enterprise customer of the given user.
"""
scheme, netloc, path, query_string, fragment = urlsplit(url)
url_params = parse_qs(query_string)
# Update url query parameters
url_params.update(query_parameters)
return urlunsplit(
(scheme, netloc, path, urlencode(sorted(url_params.items()), doseq=True), fragment),
)
def filter_audit_course_modes(enterprise_customer, course_modes):
"""
Filter audit course modes out if the enterprise customer has not enabled the 'Enable audit enrollment' flag.
Arguments:
enterprise_customer: The EnterpriseCustomer that the enrollment was created using.
course_modes: iterable with dictionaries containing a required 'mode' key
"""
audit_modes = getattr(settings, 'ENTERPRISE_COURSE_ENROLLMENT_AUDIT_MODES', ['audit'])
if not enterprise_customer.enable_audit_enrollment:
return [course_mode for course_mode in course_modes if course_mode['mode'] not in audit_modes]
return course_modes
def get_enterprise_customer_or_404(enterprise_uuid):
"""
Given an EnterpriseCustomer UUID, return the corresponding EnterpriseCustomer or raise a 404.
Arguments:
enterprise_uuid (str): The UUID (in string form) of the EnterpriseCustomer to fetch.
Returns:
(EnterpriseCustomer): The EnterpriseCustomer given the UUID.
"""
EnterpriseCustomer = enterprise_customer_model()
try:
if isinstance(enterprise_uuid, str):
enterprise_uuid_obj = UUID(enterprise_uuid)
else:
enterprise_uuid_obj = enterprise_uuid
return EnterpriseCustomer.objects.get(uuid=enterprise_uuid_obj)
except (TypeError, ValueError, EnterpriseCustomer.DoesNotExist) as no_customer_error:
LOGGER.error('Unable to find enterprise customer for UUID: [%s]', enterprise_uuid)
raise Http404 from no_customer_error
def get_enterprise_customer_by_slug_or_404(slug):
"""
Given an EnterpriseCustomer slug, return the corresponding EnterpriseCustomer or raise a 404.
Arguments:
slug (str): The unique slug (a string) identifying the customer.
Returns:
(EnterpriseCustomer): The EnterpriseCustomer given the slug.
"""
return get_object_or_404(
enterprise_customer_model(),
slug=slug,
)
def get_enterprise_customer_by_invite_key_or_404(invite_key_uuid):
"""
Given an EnterpriseCustomerInviteKey UUID, return the corresponding EnterpriseCustomer or raise a 404.
Arguments:
invite_key_uuid (str): The UUID identifying an EnterpriseCustomerInviteKey.
Returns:
(EnterpriseCustomer): The EnterpriseCustomer given the EnterpriseCustomerInviteKey UUID.
"""
customer_invite_key = get_object_or_404(
enterprise_customer_invite_key_model(),
uuid=invite_key_uuid,
)
return customer_invite_key.enterprise_customer
def clean_html_for_template_rendering(text):
"""
Given html text that will be rendered as a variable in a template, strip out characters that impact rendering.
Arguments:
text (str): The text to clean.
Returns:
(str): The cleaned text.
"""
# Sometimes there are random new lines between tags that don't render nicely.
return text.replace('>\\n<', '><')
def get_cache_key(**kwargs):
"""
Wrapper method on edx_django_utils get_cache_key utility.
"""
return get_django_cache_key(**kwargs)
def traverse_pagination(response, client, api_url):
"""
Traverse a paginated API response.
Extracts and concatenates "results" (list of dict) returned by DRF-powered
APIs.
Arguments:
response (Dict): Current response dict from service API;
client (requests.Session): either the OAuthAPIClient (from edx_rest_api_client) or requests.Session object;
api_url (str): API endpoint URL to call.