views.py 16.2 KB
Newer Older
1
# Django Imports
2
from django.conf import settings
3
from django.http import HttpResponseServerError  # Http404
4
from django.http import HttpResponseRedirect
5
from django.utils import timezone
6
from django.core.exceptions import PermissionDenied  # ValidationError
7
from django.core.mail import send_mail, EmailMessage
8
from django.contrib.auth import REDIRECT_FIELD_NAME
David Haynes's avatar
David Haynes committed
9
from django.contrib.auth.models import User
10
from django.contrib.auth.decorators import user_passes_test, login_required
Jean Michel Rouly's avatar
Jean Michel Rouly committed
11
from django.shortcuts import render, get_object_or_404, redirect
12

13
14
15
16
17
18
# App Imports
from go.models import URL, RegisteredUser
from go.forms import URLForm, SignupForm

# Other Imports
from datetime import timedelta
Jean Michel Rouly's avatar
Jean Michel Rouly committed
19

20
21
22
# requestObject = request.RegisteredUser.objects.get(user__username__exact=user)
# if requestObject.user.registereduser.blocked != False
#     raise PermissionDenied()
Zosman's avatar
draft 1    
Zosman committed
23
24


Jean Michel Rouly's avatar
Jean Michel Rouly committed
25
def index(request):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
26
27
28
29
30
31
32
    """
    This view handles the homepage that the user is presented with when
    they request '/'. If they're not logged in, they're redirected to
    login. If they're logged in but not registered, they're given the
    not_registered error page. If they are logged in AND registered, they
    get the URL registration form.
    """
Jean Michel Rouly's avatar
Jean Michel Rouly committed
33

34
    # If the user is blocked, redirect them to the blocked page.
35
    # If the user is not authenticated, show them a public landing page.
36
    if not request.user.is_authenticated():
Zosman's avatar
Zosman committed
37
        return render(request, 'public_landing.html')
38
39
    # If the user isn't approved, don't give them any leeway.
    elif not request.user.registereduser.approved:
40
        if request.user.registereduser.blocked:
Zosman's avatar
Zosman committed
41
            return render(request, 'banned.html')
42
        else:
Zosman's avatar
Zosman committed
43
            return render(request, 'not_registered.html')
44

45

46
    url_form = URLForm(host=request.META.get('HTTP_HOST'))  # unbound form
47
48

    if request.method == 'POST':
49
        url_form = URLForm(request.POST, host=request.META.get('HTTP_HOST'))  # bind dat form
50
51
        if url_form.is_valid():

Jean Michel Rouly's avatar
Jean Michel Rouly committed
52
53
            # We don't commit the url object yet because we need to add its
            # owner, and parse its date field.
54
            url = url_form.save(commit=False)
55
            url.owner = request.user.registereduser
56

Jean Michel Rouly's avatar
Jean Michel Rouly committed
57
            # If the user entered a short url, it's already been validated,
Jean Michel Rouly's avatar
Jean Michel Rouly committed
58
59
            # so accept it. If they did not, however, then generate a
            # random one and use that instead.
60
            short = url_form.cleaned_data.get('short').strip()
61
62
63
            if len(short) > 0:
                url.short = short
            else:
64
65
66
67
68
69
                # If the user didn't enter a short url, generate a random
                # one. However, if a random one can't be generated, return
                # a 500 server error.
                random_short = URL.generate_valid_short()
                if random_short is None:
                    return HttpResponseServerError(
David Haynes's avatar
David Haynes committed
70
                        render(request, 'admin/500.html', {})
71
72
73
                    )
                else:
                    url.short = random_short
74

Jean Michel Rouly's avatar
Jean Michel Rouly committed
75
76
77
            # Grab the expiration field value. It's currently an unsable
            # string value, so we need to parse it into a datetime object
            # relative to right now.
78
            expires = url_form.cleaned_data.get('expires')
79
80
81
82
83
84
85

            if expires == URLForm.DAY:
                url.expires = timezone.now() + timedelta(days=1)
            elif expires == URLForm.WEEK:
                url.expires = timezone.now() + timedelta(weeks=1)
            elif expires == URLForm.MONTH:
                url.expires = timezone.now() + timedelta(weeks=3)
Matthew Rodgers's avatar
Matthew Rodgers committed
86
87
            elif expires == URLForm.CUSTOM:
                url.expires = url_form.cleaned_data.get('expires_custom')
88
            else:
89
                pass  # leave the field NULL
90

Jean Michel Rouly's avatar
Jean Michel Rouly committed
91
92
            # Make sure that our new URL object is clean, then save it and
            # let's redirect to view this baby.
93
94
            url.full_clean()
            url.save()
Jean Michel Rouly's avatar
Jean Michel Rouly committed
95
            return redirect('view', url.short)
96

97
    return render(request, 'core/index.html', {
98
        'form': url_form,
Jean Michel Rouly's avatar
Jean Michel Rouly committed
99
100
101
    },
    )

Jean Michel Rouly's avatar
Jean Michel Rouly committed
102

Jean Michel Rouly's avatar
Jean Michel Rouly committed
103
def view(request, short):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
104
105
106
107
108
    """
    This view allows the user to view details about a URL. Note that they
    do not need to be logged in to view info.
    """

Nicholas Anderson's avatar
Nicholas Anderson committed
109
    domain = "%s://%s" % (request.scheme, request.META.get('HTTP_HOST')) + "/"
110

111
    url = get_object_or_404(URL, short__iexact=short)
112

Jean Michel Rouly's avatar
Jean Michel Rouly committed
113
    return render(request, 'view.html', {
114
        'url': url,
115
        'domain': domain,
116
117
118
    },
    )

Jean Michel Rouly's avatar
Jean Michel Rouly committed
119

120
@login_required
121
def my_links(request):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
122
123
124
125
126
    """
    This view displays all the information about all of your URLs. You
    obviously need to be logged in to view your URLs.
    """

127
    if not request.user.registereduser.approved:
128
        return render(request, 'not_registered.html')
Jean Michel Rouly's avatar
Jean Michel Rouly committed
129

130
    urls = URL.objects.filter(owner=request.user.registereduser)
131

132
    domain = "%s://%s" % (request.scheme, request.META.get('HTTP_HOST')) + "/"
133

134
    return render(request, 'my_links.html', {
135
136
        'urls': urls,
        'domain': domain,
137
138
139
    },
    )

Jean Michel Rouly's avatar
Jean Michel Rouly committed
140

141
@login_required
142
def delete(request, short):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
143
144
145
146
147
    """
    This view deletes a URL if you have the permission to. User must be
    logged in and registered, and must also be the owner of the URL.
    """

148
    if not request.user.registereduser.approved:
149
        return render(request, 'not_registered.html')
Jean Michel Rouly's avatar
Jean Michel Rouly committed
150

151
    url = get_object_or_404(URL, short__iexact=short)
152
    if url.owner == request.user.registereduser:
153
        url.delete()
154
155
        return redirect('my_links')
    else:
156
        raise PermissionDenied()
157

Jean Michel Rouly's avatar
Jean Michel Rouly committed
158

159
@login_required
Jean Michel Rouly's avatar
Jean Michel Rouly committed
160
def signup(request):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
161
    """
162
    This view presents the user with a registration form. You can register yourself.
Jean Michel Rouly's avatar
Jean Michel Rouly committed
163
    """
164
165
    # Do not display signup page to registered or approved users
    if request.user.registereduser.approved:
David Haynes's avatar
David Haynes committed
166
        return redirect('/')
167
    elif request.user.registereduser.registered:
David Haynes's avatar
David Haynes committed
168
        return redirect('registered')
169

170
171
172
    signup_form = SignupForm(request,
        initial={'full_name': request.user.first_name + " " + request.user.last_name})
    signup_form.fields['full_name'].widget.attrs['readonly'] = 'readonly'
Jean Michel Rouly's avatar
Jean Michel Rouly committed
173
174

    if request.method == 'POST':
175
176
177
        signup_form = SignupForm(request, request.POST, instance=request.user.registereduser,
            initial={'full_name': request.user.first_name + " " + request.user.last_name})
        signup_form.fields['full_name'].widget.attrs['readonly'] = 'readonly'
178

179
180
        if signup_form.is_valid():
            description = signup_form.cleaned_data.get('description')
181
            full_name = signup_form.cleaned_data.get('full_name')
182
            organization = signup_form.cleaned_data.get('organization')
183
            registered = signup_form.cleaned_data.get('registered')
184

185
186
            # Only send mail if we've defined the mailserver
            if settings.EMAIL_HOST and settings.EMAIL_PORT:
root's avatar
root committed
187
                user_mail = request.user.username + settings.EMAIL_DOMAIN
188
                # Email sent to notify Admins
189
                to_admin = EmailMessage(
190
                    'Signup from %s' % (request.user.registereduser.user),
191
192
193
194
195
                    ######################
                    '%s signed up at %s\n\n'
                    'Username: %s\n'
                    'Organization: %s\n\n'
                    'Message: %s\n\n'
196
197
                    'You can contact the user directly by replying to this email or '
                    'reply all to contact the user and notfiy the mailing list.\n'
198
199
200
                    'Please head to go.gmu.edu/useradmin to approve or '
                    'deny this application.'
                    % (str(full_name), str(timezone.now()).strip(),
201
                    str(request.user.registereduser.user), str(organization), str(description)),
202
203
                    ######################
                    settings.EMAIL_FROM,
204
205
                    [settings.EMAIL_TO],
                    reply_to=[user_mail]
206
                ).send()
207
                # Confirmation email sent to Users
208
                send_mail(
209
210
211
212
213
214
215
216
217
218
219
220
221
                    'We have received your Go application!',
                    ######################
                    'Hey there %s,\n\n'
                    'The Go admins have received your application and are '
                    'currently in the process of reviewing it.\n\n'
                    'You will receive another email when you have been '
                    'approved.\n\n'
                    '- Go Admins'
                    % (str(full_name)),
                    ######################
                    settings.EMAIL_FROM,
                    [user_mail]
                )
222

223
            signup_form.save()
224
            return redirect('registered')
Jean Michel Rouly's avatar
Jean Michel Rouly committed
225

226
    return render(request, 'core/signup.html', {
227
        'form': signup_form,
228
        'registered': False,
Jean Michel Rouly's avatar
Jean Michel Rouly committed
229
230
    },
    )
Jean Michel Rouly's avatar
Jean Michel Rouly committed
231

Jean Michel Rouly's avatar
Jean Michel Rouly committed
232

Jean Michel Rouly's avatar
Jean Michel Rouly committed
233
def redirection(request, short):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
234
235
236
    """
    This view redirects a user based on the short URL they requested.
    """
Jean Michel Rouly's avatar
Jean Michel Rouly committed
237

238
    url = get_object_or_404(URL, short__iexact=short)
Jean Michel Rouly's avatar
Jean Michel Rouly committed
239
    url.clicks = url.clicks + 1
240

241
242
    domain = "%s://%s" % (request.scheme, request.META.get('HTTP_HOST')) + "/"
    if url.target == domain + short:
David Haynes's avatar
David Haynes committed
243
        return redirect('admin/404.html')
244

245
246
247
248
249
250
    if 'qr' in request.GET:
        url.qrclicks += 1

    if 'social' in request.GET:
        url.socialclicks += 1

Jean Michel Rouly's avatar
Jean Michel Rouly committed
251
    url.save()
252

Jean Michel Rouly's avatar
Jean Michel Rouly committed
253
254
255
256
257
    """
    Include server-side tracking because there is no template displayed to
    the user which would include javascript tracking.
    """

258
259
    from piwikapi.tracking import PiwikTracker
    from django.conf import settings
260
    # First, if PIWIK variables are undefined, don't try to push
261
    if settings.PIWIK_SITE_ID != "" and settings.PIWIK_URL != "":
262
263
264
265
266
267
268
        try:
            piwiktracker = PiwikTracker(settings.PIWIK_SITE_ID, request)
            piwiktracker.set_api_url(settings.PIWIK_URL)
            piwiktracker.do_track_page_view('Redirect to %s' % url.target)
        # Second, if we do get an error, don't let that keep us from redirecting
        except:
            pass
269

270
    return redirect(url.target)
Jean Michel Rouly's avatar
Jean Michel Rouly committed
271
272


273
def staff_member_required(view_func, redirect_field_name=REDIRECT_FIELD_NAME, login_url='/'):
274
275
276
277
278
279
280
281
282
283
284
285
    """
    Decorator for views that checks that the user is logged in and is a staff
    member, displaying the login page if necessary.
    """
    return user_passes_test(
        lambda u: u.is_active and u.is_staff,
        login_url=login_url,
        redirect_field_name=redirect_field_name
    )(view_func)


@staff_member_required
Chris Reffett's avatar
Chris Reffett committed
286
def useradmin(request):
287
288
289
290
291
    """
    This view is a simplified admin panel, so that staff don't need to log in
    to approve links
    """
    if request.POST:
292
        userlist = request.POST.getlist('username')
293
        if '_approve' in request.POST:
294
            for name in userlist:
295
                toapprove = RegisteredUser.objects.get(user__username__exact=name)
296
297
                toapprove.approved = True
                toapprove.save()
298
                if settings.EMAIL_HOST and settings.EMAIL_PORT:
root's avatar
root committed
299
                    user_mail = toapprove.user.username + settings.EMAIL_DOMAIN
300
301
302
303
304
305
306
307
308
309
310
311
312
                    send_mail(
                        'Your Account has been Approved!',
                        ######################
                        'Hey there %s,\n\n'
                        'The Go admins have reviewed your application and have '
                        'approved you to use Go!\n\n'
                        'Head over to go.gmu.edu to create your first address.\n\n'
                        '- Go Admins'
                        % (str(toapprove.full_name)),
                        ######################
                        settings.EMAIL_FROM,
                        [user_mail]
                    )
313
        elif '_deny' in request.POST:
314
            for name in userlist:
315
                todeny = RegisteredUser.objects.get(user__username__exact=name)
316
                if settings.EMAIL_HOST and settings.EMAIL_PORT:
David Haynes's avatar
David Haynes committed
317
                    user_mail = todeny.user.username + settings.EMAIL_DOMAIN
318
319
320
321
322
323
324
325
326
327
328
329
330
331
                    send_mail(
                        'Your Account has been Denied!',
                        ######################
                        'Hey there %s,\n\n'
                        'The Go admins have reviewed your application and have '
                        'decided to not approve you to use Go.\n\n'
                        'Please reach out to srct@gmu.edu to appeal '
                        'this decision.\n\n'
                        '- Go Admins'
                        % (str(todeny.full_name)),
                        ######################
                        settings.EMAIL_FROM,
                        [user_mail]
                    )
332
                todeny.user.delete()
333
                return HttpResponseRedirect('useradmin')
Zosman's avatar
draft 1    
Zosman committed
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
        elif '_block' in request.POST:
            for name in userlist:
                toblock = RegisteredUser.objects.get(user__username__exact=name)
                if settings.EMAIL_HOST and settings.EMAIL_PORT:
                    user_mail = toblock.user.username + settings.EMAIL_DOMAIN
                    send_mail(
                        'Your Account has been Blocked!',
                        ######################
                        'Hey there %s,\n\n'
                        'The Go admins have reviewed your application and have '
                        'blocked you from using Go.\n\n'
                        'Please reach out to srct@gmu.edu to appeal '
                        'this decision.\n\n'
                        '- Go Admins'
                        % (str(toblock.full_name)),
                        ######################
                        settings.EMAIL_FROM,
                        [user_mail]
                    )
                # toblock.user.delete()
354
355
                toblock.blocked = True
                toblock.approved = False
356
                toblock.registered = False
357
358
359
360
361
362
363
364
365
366
367
368
                toblock.save()
        elif '_unblock' in request.POST:
            for name in userlist:
                toUNblock = RegisteredUser.objects.get(user__username__exact=name)
                if settings.EMAIL_HOST and settings.EMAIL_PORT:
                    user_mail = toUNblock.user.username + settings.EMAIL_DOMAIN
                    send_mail(
                        'Your Account has been Blocked!',
                        ######################
                        'Hey there %s,\n\n'
                        'The Go admins have reviewed your application and have '
                        'unblocked you from using Go.\n\n'
369
                        'If you wish to continue Go use please register again. \n\n'
370
371
372
373
374
375
376
                        'Congratulations! '
                        '- Go Admins'
                        % (str(toblock.full_name)),
                        ######################
                        settings.EMAIL_FROM,
                        [user_mail]
                    )
377
                toUNblock.user.delete()
378
                return HttpResponseRedirect('useradmin')
379
380
381
                # toUNblock.blocked = False
                # toUNblock.approved = False
                # toUNblock.save()
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
        elif '_remove' in request.POST:
            for name in userlist:
                toremove = RegisteredUser.objects.get(user__username__exact=name)
                if settings.EMAIL_HOST and settings.EMAIL_PORT:
                    user_mail = toremove.user.username + settings.EMAIL_DOMAIN
                    send_mail(
                        'Your Account has been Deleted!',
                        ######################
                        'Hey there %s,\n\n'
                        'The Go admins have decided to remove you from Go. \n\n'
                        'Please reach out to srct@gmu.edu to appeal '
                        'this decision.\n\n'
                        '- Go Admins'
                        % (str(toremove.full_name)),
                        ######################
                        settings.EMAIL_FROM,
                        [user_mail]
                    )
                toremove.user.delete()
401
                return HttpResponseRedirect('useradmin')
402

403
    need_approval = RegisteredUser.objects.filter(registered=True).filter(approved=False).filter(blocked=False)
404
405
    current_users = RegisteredUser.objects.filter(approved=True).filter(registered=True)
    blocked_users = RegisteredUser.objects.filter(blocked=True)
406
    return render(request, 'admin/useradmin.html', {
407
408
409
        'need_approval': need_approval,
        'current_users': current_users,
        'blocked_users': blocked_users
410
411
    },
    )