-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathviews.py
268 lines (224 loc) · 9.05 KB
/
views.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
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
"""
ui views
"""
import json
import logging
from urllib.parse import urlencode
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.urls import reverse
from django.shortcuts import Http404, redirect, render
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View, TemplateView
from rolepermissions.permissions import available_perm_status
from rolepermissions.checkers import has_role
from cms.util import get_coupon_code
from courses.models import Program, Course
from ecommerce.models import Coupon
from micromasters.utils import webpack_dev_server_host
from micromasters.serializers import serialize_maybe_user
from profiles.permissions import CanSeeIfNotPrivate
from roles.models import Instructor, Staff
from ui.decorators import require_mandatory_urls
from ui.templatetags.render_bundle import public_path
log = logging.getLogger(__name__)
class ReactView(View):
"""
Abstract view for templates using React
"""
template_name = "dashboard.html"
def get_context(self, request):
"""
Get the context for the view
Args:
request (Request): the incoming request
Returns:
dict: the context object as a dictionary
"""
user = request.user
roles = []
if not user.is_anonymous:
roles = [
{
'program': role.program.id,
'role': role.role,
'permissions': [perm for perm, value in available_perm_status(user).items() if value is True]
} for role in user.role_set.all()
]
js_settings = {
"gaTrackingID": settings.GA_TRACKING_ID,
"reactGaDebug": settings.REACT_GA_DEBUG,
"host": webpack_dev_server_host(request),
"edx_base_url": settings.EDXORG_CALLBACK_URL,
"mitxonline_base_url": settings.MITXONLINE_CALLBACK_URL,
"mitxonline_url": settings.MITXONLINE_URL,
"roles": roles,
"release_version": settings.VERSION,
"environment": settings.ENVIRONMENT,
"sentry_dsn": settings.SENTRY_DSN,
"search_url": reverse('search_api', kwargs={"opensearch_url": ""}),
"support_email": settings.EMAIL_SUPPORT,
"user": serialize_maybe_user(request.user),
"es_page_size": settings.OPENSEARCH_DEFAULT_PAGE_SIZE,
"public_path": public_path(request),
"FEATURES": {
"PROGRAM_LEARNERS": settings.FEATURES.get('PROGRAM_LEARNERS_ENABLED', False),
"DISCUSSIONS_POST_UI": settings.FEATURES.get('OPEN_DISCUSSIONS_POST_UI', False),
"DISCUSSIONS_CREATE_CHANNEL_UI": settings.FEATURES.get('OPEN_DISCUSSIONS_CREATE_CHANNEL_UI', False),
"PROGRAM_RECORD_LINK": settings.FEATURES.get('PROGRAM_RECORD_LINK', False),
"ENABLE_PROGRAM_LETTER": settings.FEATURES.get('ENABLE_PROGRAM_LETTER', False),
},
"open_discussions_redirect_url": settings.OPEN_DISCUSSIONS_REDIRECT_URL,
}
return {
"has_zendesk_widget": True,
"is_public": False,
"google_maps_api": False,
"js_settings_json": json.dumps(js_settings),
"ga_tracking_id": "",
"support_email": settings.EMAIL_SUPPORT,
}
def get(self, request, *args, **kwargs): # pylint: disable=unused-argument
"""
Handle GET requests to templates using React
"""
return render(
request,
self.template_name,
context=self.get_context(request),
)
def post(self, request, *args, **kwargs): # pylint: disable=unused-argument
"""Redirect to GET. This assumes there's never any good reason to POST to these views."""
return redirect(request.build_absolute_uri())
@method_decorator(require_mandatory_urls, name='dispatch')
@method_decorator(login_required, name='dispatch')
@method_decorator(csrf_exempt, name='dispatch')
class DashboardView(ReactView):
"""
Wrapper for dashboard view which asserts certain logged in requirements
"""
class UsersView(ReactView):
"""
View for learner pages. This gets handled by the dashboard view like all other
React handled views, but we also want to return a 404 if the user does not exist.
"""
def get(self, request, *args, **kwargs):
"""
Handle GET requests
"""
user = kwargs.pop('user')
if user is not None:
if not CanSeeIfNotPrivate().has_permission(request, self):
raise Http404
elif request.user.is_anonymous:
# /learner/ redirects to logged in user's page, but user is not logged in here
raise Http404
return super().get(request, *args, **kwargs)
class SignInView(ReactView):
"""Sign In view"""
template_name = "signin.html"
def get_context(self, request):
"""
Get the context for the view
Args:
request (Request): the incoming request
Returns:
dict: the context object as a dictionary
"""
context = super().get_context(request)
program_id = request.GET.get('program', None)
next_url = request.GET.get('next', None)
mitxonline_enabled = settings.FEATURES.get("MITXONLINE_LOGIN", False)
program = Program.objects.filter(id=program_id[0]).first() if mitxonline_enabled and program_id else None
params = {"next": next_url}
return {
**context,
"program": program,
"login_qs": f"?{urlencode(params)}" if next_url else '',
}
def get(self, request, *args, **kwargs): # pylint: disable=unused-argument
"""
Handle GET requests to templates using React
"""
context = self.get_context(request)
coupon_code = get_coupon_code(request)
# if we didn't get a program in the context, look it up via the coupon code
if (
settings.FEATURES.get("MITXONLINE_LOGIN", False)
and coupon_code
and context["program"] is None
):
program = None
coupon = Coupon.objects.filter(coupon_code=coupon_code).first()
if coupon is not None:
if isinstance(coupon.content_object, Program):
program = coupon.content_object
elif isinstance(coupon.content_object, Course):
program = coupon.content_object.program
if program:
params = request.GET.copy()
params["program"] = program.id
return redirect(
f"{reverse('signin')}?{params.urlencode()}",
)
return render(
request,
self.template_name,
context=context,
)
def standard_error_page(request, status_code, template_filename):
"""
Returns an error page with a given template filename and provides necessary context variables
"""
name = request.user.profile.preferred_name if not request.user.is_anonymous else ""
authenticated = not request.user.is_anonymous
response = render(
request,
template_filename,
context={
"has_zendesk_widget": True,
"is_public": True,
"js_settings_json": json.dumps({
"release_version": settings.VERSION,
"environment": settings.ENVIRONMENT,
"sentry_dsn": settings.SENTRY_DSN,
"user": serialize_maybe_user(request.user),
}),
"authenticated": authenticated,
"name": name,
"username": request.user.username,
"is_staff": has_role(request.user, [Staff.ROLE_ID, Instructor.ROLE_ID]),
"support_email": settings.EMAIL_SUPPORT,
"sentry_dsn": settings.SENTRY_DSN,
}
)
response.status_code = status_code
return response
def page_404(request, *args, **kwargs): # pylint: disable=unused-argument
"""
Overridden handler for the 404 error pages.
"""
return standard_error_page(request, 404, "404.html")
def page_500(request, *args, **kwargs): # pylint: disable=unused-argument
"""
Overridden handler for the 404 error pages.
"""
return standard_error_page(request, 500, "500.html")
def need_verified_email(request, *args, **kwargs): # pylint: disable=unused-argument
"""
Returns error page for unverified email on edX
"""
return standard_error_page(request, 401, "verify_email.html")
def oauth_maintenance(request, *args, **kwargs): # pylint: disable=unused-argument
"""
Returns maintenance page during oauth downtime
"""
return standard_error_page(request, 200, "oauth_maintenance.html")
class BackgroundImagesCSSView(TemplateView):
"""
Pass a CSS file through Django's template system, so that we can make
the URLs point to a CDN.
"""
template_name = "background-images.css"
content_type = "text/css"