views.py 25.3 KB
Newer Older
1 2 3 4
"""
go/views.py
"""

5
# Future Imports
David Haynes's avatar
David Haynes committed
6 7
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)
8

David Haynes's avatar
David Haynes committed
9 10 11
# Python stdlib imports
from datetime import timedelta

12
# Django Imports
13
from django.conf import settings
David Haynes's avatar
David Haynes committed
14 15 16 17
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.decorators import login_required, user_passes_test
from django.core.exceptions import PermissionDenied  # ValidationError
from django.core.mail import EmailMessage, send_mail
18
from django.http import HttpResponseServerError  # Http404
19
from django.http import HttpResponseRedirect
David Haynes's avatar
David Haynes committed
20
from django.shortcuts import get_object_or_404, redirect, render
21
from django.utils import timezone
David Haynes's avatar
David Haynes committed
22 23

# Other imports
24
from ratelimit.decorators import ratelimit
25

26
# App Imports
27 28
from .forms import SignupForm, URLForm, EditForm
from .models import URL, RegisteredUser
David Haynes's avatar
David Haynes committed
29

30

David Haynes's avatar
David Haynes committed
31
def index(request):
32 33 34 35 36 37 38 39 40 41 42 43 44
    """
    If a user is logged in, this view displays all the information about all
    of their URLs. Otherwise, it will show the public landing page
    """

    # If the user is not authenticated, show them a public landing page.
    if not request.user.is_authenticated():
        return render(request, 'public_landing.html')
    # Do not display this page to unapproved users
    if not request.user.registereduser.approved:
        return render(request, 'not_registered.html')

    # Get the current domain info
45
    domain = "%ss://%s" % (request.scheme, request.META.get('HTTP_HOST')) + "/"
46 47 48 49

    # Grab a list of all the URL's that are currently owned by the user
    urls = URL.objects.filter(owner=request.user.registereduser)

50
    # Render my_links passing the list of URL's and Domain to the template
51 52 53 54
    return render(request, 'core/index.html', {
        'urls': urls,
        'domain': domain,
    })
Jean Michel Rouly's avatar
Jean Michel Rouly committed
55

56
@login_required
Zach Knox's avatar
Zach Knox committed
57
def new_link(request):
58
    """
David Haynes's avatar
David Haynes committed
59
    This view handles the homepage that the user is presented with when
60
    they request '/newLink'. If they're not logged in, they're redirected to
David Haynes's avatar
David Haynes committed
61 62 63
    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.
64 65
    """

David Haynes's avatar
David Haynes committed
66
    # If the user isn't approved, then display the you're not approved page.
67
    if not request.user.registereduser.approved:
68
        if request.user.registereduser.blocked:
Zosman's avatar
Zosman committed
69
            return render(request, 'banned.html')
70
        else:
Zosman's avatar
Zosman committed
71
            return render(request, 'not_registered.html')
72

73

David Haynes's avatar
David Haynes committed
74
    # Initialize a URL form
75
    url_form = URLForm(host=request.META.get('HTTP_HOST'))  # unbound form
76

David Haynes's avatar
David Haynes committed
77 78
    # If a POST request is received, then the user has submitted a form and it's
    # time to parse the form and create a new URL object
79
    if request.method == 'POST':
80 81
        # Now we initialize the form again but this time we have the POST
        # request
82
        url_form = URLForm(request.POST, host=request.META.get('HTTP_HOST'))
83 84 85

        # Django will check the form to make sure it's valid
        if url_form.is_valid():
86
            # Call our post method to assemble our new URL object
87
            res = post(request, url_form)
88

89 90
            # If there is a 500 error returned, handle it
            if res == 500:
91
                return HttpResponseServerError(render(request, '500.html'))
92

93
            # Redirect to the shiny new URL
94
            return redirect('view', res.short)
95

96 97 98
        # Else, there is an error, redisplay the form with the validation errors
        else:
            # Render index.html passing the form to the template
99
            return render(request, 'core/new_link.html', {
100
                'form': url_form,
101
            })
102

103

David Haynes's avatar
David Haynes committed
104
    # Render index.html passing the form to the template
Zach Knox's avatar
Zach Knox committed
105
    return render(request, 'core/new_link.html', {
106
        'form': url_form,
107
    })
Jean Michel Rouly's avatar
Jean Michel Rouly committed
108

109
@login_required
Zach Knox's avatar
Zach Knox committed
110
def my_links(request):
111 112 113 114 115 116 117 118 119 120
    """
    for compatibility, just in case
    shows the same thing as /, but requires login to be consistent with
    /newLink
    """
    if not request.user.registereduser.approved:
        if request.user.registereduser.blocked:
            return render(request, 'banned.html')
        else:
            return render(request, 'not_registered.html')
Zach Knox's avatar
Zach Knox committed
121 122
    return index(request)

David Haynes's avatar
David Haynes committed
123
# Rate limits are completely arbitrary
124 125
@ratelimit(key='user', rate='3/m', method='POST', block=True)
@ratelimit(key='user', rate='25/d', method='POST', block=True)
126
def post(request, url_form):
127
    """
128
    Helper function that handles POST requests for the URL creation
129 130
    """

131 132
    # We don't commit the url object yet because we need to add its
    # owner, and parse its date field.
133
    url = url_form.save(commit=False)
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
    url.owner = request.user.registereduser

    # If the user entered a short url, it's already been validated,
    # so accept it. If they did not, however, then generate a
    # random one and use that instead.
    short = url_form.cleaned_data.get('short').strip()

    # Check if a short URL was entered
    if len(short) > 0:
        url.short = short
    else:
        # 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 500
152
        else:
153 154 155 156 157 158 159 160 161
            url.short = random_short

    # 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.
    expires = url_form.cleaned_data.get('expires')

    # Determine what the expiration date is
    if expires == URLForm.DAY:
162
        url.expires = timezone.now() + timedelta(days=1)
163
    elif expires == URLForm.WEEK:
164
        url.expires = timezone.now() + timedelta(weeks=1)
165
    elif expires == URLForm.MONTH:
166
        url.expires = timezone.now() + timedelta(weeks=3)
167 168 169 170 171 172 173 174 175 176
    elif expires == URLForm.CUSTOM:
        url.expires = url_form.cleaned_data.get('expires_custom')
    else:
        pass  # leave the field NULL

    # Make sure that our new URL object is clean, then save it and
    # let's redirect to view this baby.
    url.full_clean()
    url.save()
    return url
177

David Haynes's avatar
David Haynes committed
178
def view(request, short):
179
    """
180 181
    This view allows the user to "view details" about a URL. Note that they
    do not need to be logged in to view this information.
182
    """
Jean Michel Rouly's avatar
Jean Michel Rouly committed
183

David Haynes's avatar
David Haynes committed
184
    # Get the current domain info
185
    domain = "%ss://%s" % (request.scheme, request.META.get('HTTP_HOST')) + "/"
186

David Haynes's avatar
David Haynes committed
187
    # Get the URL that is being requested
188
    url = get_object_or_404(URL, short__iexact=short)
189

David Haynes's avatar
David Haynes committed
190
    # Render view.html passing the specified URL and Domain to the template
Jean Michel Rouly's avatar
Jean Michel Rouly committed
191
    return render(request, 'view.html', {
192
        'url': url,
193
        'domain': domain,
194
    })
195

David Haynes's avatar
David Haynes committed
196
@login_required
David Haynes's avatar
David Haynes committed
197
def edit(request, short):
198
    """
David Haynes's avatar
David Haynes committed
199 200 201
    This view allows a logged in user to edit the details of a Go link that they
    own. They can modify any value that they wish. If `short` is modified then
    we will need to create a new link and copy over stats from the previous.
202
    """
Jean Michel Rouly's avatar
Jean Michel Rouly committed
203

David Haynes's avatar
David Haynes committed
204
    # Do not allow unapproved users to edit links
205
    if not request.user.registereduser.approved:
David Haynes's avatar
David Haynes committed
206 207 208 209
        if request.user.registereduser.blocked:
            return render(request, 'banned.html')
        else:
            return render(request, 'not_registered.html')
Jean Michel Rouly's avatar
Jean Michel Rouly committed
210

211

David Haynes's avatar
David Haynes committed
212 213
    # Get the URL that is going to be edited
    url = get_object_or_404(URL, short__iexact=short)
David Haynes's avatar
David Haynes committed
214

David Haynes's avatar
David Haynes committed
215 216
    # If the RegisteredUser is the owner of the URL
    if url.owner == request.user.registereduser:
217

218 219 220 221 222
        # If a POST request is received, then the user has submitted a form and it's
        # time to parse the form and edit that URL object
        if request.method == 'POST':
            # Now we initialize the form again but this time we have the POST
            # request
223
            url_form = EditForm(request.POST, host=request.META.get('HTTP_HOST'))
224

225 226 227 228 229
            # Make a copy of the old URL
            copy = url
            # Remove the old one
            url.delete()

230 231
            # Django will check the form to make sure it's valid
            if url_form.is_valid():
David Haynes's avatar
David Haynes committed
232 233
                # If the short changed then we need to create a new object and
                # migrate some data over
234
                if url_form.cleaned_data.get('short').strip() != copy.short:
David Haynes's avatar
David Haynes committed
235 236 237 238 239 240 241 242 243 244
                    # Parse the form and create a new URL object
                    res = post(request, url_form)

                    # If there is a 500 error returned, handle it
                    if res == 500:
                        return HttpResponseServerError(render(request, '500.html'))

                    # We can procede with the editing process
                    else:
                        # Migrate clicks data
245
                        res.clicks = copy.clicks
David Haynes's avatar
David Haynes committed
246 247
                        res.qrclicks = copy.qrclicks
                        res.socialclicks = copy.socialclicks
David Haynes's avatar
David Haynes committed
248 249 250 251 252 253 254 255 256

                        # Save the new URL
                        res.save()

                        # Redirect to the shiny new *edited URL
                        return redirect('view', res.short)

                # The short was not edited and thus, we can directly edit the url
                else:
257 258 259
                    if url_form.cleaned_data.get('target').strip() != copy.target:
                        copy.target = url_form.cleaned_data.get('target').strip()
                        copy.save()
David Haynes's avatar
David Haynes committed
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277

                    # 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.
                    expires = url_form.cleaned_data.get('expires')

                    # Determine what the expiration date is
                    if expires == URLForm.DAY:
                        edited_expires = timezone.now() + timedelta(days=1)
                    elif expires == URLForm.WEEK:
                        edited_expires = timezone.now() + timedelta(weeks=1)
                    elif expires == URLForm.MONTH:
                        edited_expires = timezone.now() + timedelta(weeks=3)
                    elif expires == URLForm.CUSTOM:
                        edited_expires = url_form.cleaned_data.get('expires_custom')
                    else:
                        pass  # leave the field NULL

278 279 280
                    if edited_expires != copy.expires:
                        copy.expires = edited_expires
                        copy.save()
David Haynes's avatar
David Haynes committed
281 282

                    # Redirect to the shiny new *edited URL
283
                    return redirect('view', copy.short)
284 285 286 287 288 289 290 291

            # Else, there is an error, redisplay the form with the validation errors
            else:
                # Render index.html passing the form to the template
                return render(request, 'core/edit_link.html', {
                    'form': url_form
                })
        else:
David Haynes's avatar
David Haynes committed
292 293 294
            # Initial data set here
            if url.expires != None:
                # Initialize a URL form with an expire date
295
                url_form = EditForm(host=request.META.get('HTTP_HOST'), initial={
David Haynes's avatar
David Haynes committed
296 297 298 299 300 301 302
                    'target': url.target,
                    'short': url.short,
                    'expires': 'Custom Date',
                    'expires_custom': url.expires
                })  # unbound form
            else:
                # Initialize a URL form without an expire date
303
                url_form = EditForm(host=request.META.get('HTTP_HOST'), initial={
David Haynes's avatar
David Haynes committed
304 305 306 307 308
                    'target': url.target,
                    'short': url.short,
                    'expires': 'Never',
                })  # unbound form

309 310 311 312
            # Render index.html passing the form to the template
            return render(request, 'core/edit_link.html', {
                'form': url_form
            })
David Haynes's avatar
David Haynes committed
313 314 315
    else:
        # do not allow them to edit
        raise PermissionDenied()
316

David Haynes's avatar
David Haynes committed
317

David Haynes's avatar
David Haynes committed
318 319
@login_required
def delete(request, short):
320
    """
David Haynes's avatar
David Haynes committed
321 322
    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.
323
    """
Jean Michel Rouly's avatar
Jean Michel Rouly committed
324

David Haynes's avatar
David Haynes committed
325
    # Do not allow unapproved users to delete links
326
    if not request.user.registereduser.approved:
327
        return render(request, 'not_registered.html')
Jean Michel Rouly's avatar
Jean Michel Rouly committed
328

David Haynes's avatar
David Haynes committed
329
    # Get the URL that is going to be deleted
330
    url = get_object_or_404(URL, short__iexact=short)
David Haynes's avatar
David Haynes committed
331 332

    # If the RegisteredUser is the owner of the URL
David Haynes's avatar
David Haynes committed
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
    if url.owner == request.user.registereduser:
        # There are some instances where this request header does not exist, in
        # this case we fallback to the insecure method
        if request.META.get('HTTP_REFERER') is not None:
            # Make sure that the requestee is from the same domain (go.gmu.edu)
            if request.META.get('HTTP_REFERER') == request.META.get('HTTP_HOST'):
                # remove the URL
                url.delete()
                # redirect to my_links
                return redirect('my_links')
            else:
                raise PermissionDenied()
        # Fallback and delete
        else:
            # remove the URL
            url.delete()
            # redirect to my_links
            return redirect('my_links')
351
    else:
David Haynes's avatar
David Haynes committed
352
        # do not allow them to delete
353
        raise PermissionDenied()
354

David Haynes's avatar
David Haynes committed
355

356
@login_required
Jean Michel Rouly's avatar
Jean Michel Rouly committed
357
def signup(request):
358
    """
359 360
    This view presents the user with a registration form. You can register
    yourself.
361 362
    """

363
    # Do not display signup page to registered or approved users
364
    if request.user.registereduser.blocked:
365
        return render(request, 'banned.html')
366
    elif request.user.registereduser.approved:
David Haynes's avatar
David Haynes committed
367
        return redirect('/')
368
    elif request.user.registereduser.registered:
David Haynes's avatar
David Haynes committed
369
        return redirect('registered')
370

David Haynes's avatar
David Haynes committed
371
    # Initialize our signup form
372 373 374 375 376 377
    signup_form = SignupForm(
        request,
        initial={
            'full_name': request.user.first_name + " " + request.user.last_name
        }
    )
David Haynes's avatar
David Haynes committed
378 379

    # Set the full_name field to readonly since CAS will fill that in for them
380
    signup_form.fields['full_name'].widget.attrs['readonly'] = 'readonly'
Jean Michel Rouly's avatar
Jean Michel Rouly committed
381

David Haynes's avatar
David Haynes committed
382 383
    # If a POST request is received, then the user has submitted a form and it's
    # time to parse the form and create a new RegisteredUser
Jean Michel Rouly's avatar
Jean Michel Rouly committed
384
    if request.method == 'POST':
David Haynes's avatar
David Haynes committed
385 386
        # Now we initialize the form again but this time we have the POST
        # request
387 388 389 390 391 392
        signup_form = SignupForm(
            request, request.POST, instance=request.user.registereduser,
            initial={
                'full_name': request.user.first_name + " " + request.user.last_name
            }
        )
David Haynes's avatar
David Haynes committed
393 394

        # set the readonly flag again for good measure
395
        signup_form.fields['full_name'].widget.attrs['readonly'] = 'readonly'
396

David Haynes's avatar
David Haynes committed
397
        # Django will check the form to make sure it's valid
398
        if signup_form.is_valid():
David Haynes's avatar
David Haynes committed
399
            # Grab data from the form and store into variables
400
            description = signup_form.cleaned_data.get('description')
401
            full_name = signup_form.cleaned_data.get('full_name')
402
            organization = signup_form.cleaned_data.get('organization')
403

404 405
            # Only send mail if we've defined the mailserver
            if settings.EMAIL_HOST and settings.EMAIL_PORT:
root's avatar
root committed
406
                user_mail = request.user.username + settings.EMAIL_DOMAIN
407
                # Email sent to notify Admins
408
                to_admin = EmailMessage(
409
                    'Signup from %s' % (request.user.registereduser.user),
410 411 412 413 414
                    ######################
                    '%s signed up at %s\n\n'
                    'Username: %s\n'
                    'Organization: %s\n\n'
                    'Message: %s\n\n'
415 416
                    'You can contact the user directly by replying to this email or '
                    'reply all to contact the user and notfiy the mailing list.\n'
417 418
                    'Please head to go.gmu.edu/useradmin to approve or '
                    'deny this application.'
419 420 421 422 423
                    %(
                        str(full_name), str(timezone.now()).strip(),
                        str(request.user.registereduser.user), str(organization),
                        str(description)
                    ),
424 425
                    ######################
                    settings.EMAIL_FROM,
426
                    [settings.EMAIL_TO],
427 428 429
                    reply_to=[user_mail]
                )
                to_admin.send()
430
                # Confirmation email sent to Users
431
                send_mail(
432 433 434 435 436 437 438 439 440 441 442 443 444
                    '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]
                )
445

David Haynes's avatar
David Haynes committed
446 447
            # Make sure that our new RegisteredUser object is clean, then save
            # it and let's redirect to tell the user they have registered.
448
            signup_form.save()
449
            return redirect('registered')
Jean Michel Rouly's avatar
Jean Michel Rouly committed
450

David Haynes's avatar
David Haynes committed
451 452
    # render signup.html passing along the form and the current registered
    # status
453
    return render(request, 'core/signup.html', {
454
        'form': signup_form,
455
        'registered': False,
456
    })
Jean Michel Rouly's avatar
Jean Michel Rouly committed
457

David Haynes's avatar
David Haynes committed
458
def redirection(request, short):
459
    """
David Haynes's avatar
David Haynes committed
460
    This view redirects a user based on the short URL they requested.
461
    """
Jean Michel Rouly's avatar
Jean Michel Rouly committed
462

David Haynes's avatar
David Haynes committed
463 464
    # Get the current domain info
    domain = "%s://%s" % (request.scheme, request.META.get('HTTP_HOST')) + "/"
Eyad Hasan's avatar
Eyad Hasan committed
465
    
David Haynes's avatar
David Haynes committed
466
    # Get the URL object that relates to the requested Go link
467
    url = get_object_or_404(URL, short__iexact=short)
David Haynes's avatar
David Haynes committed
468 469
    # Increment our clicks by one
    url.clicks += 1
Eyad Hasan's avatar
Eyad Hasan committed
470 471 472 473 474
    # Get the URL short link
    doesExist = URL.objects.get(short__iexact=short)
    # Checks to see if the link exists, if not we 404 the user.
    if doesExist.target is None:
        return redirect('go/404.html')
David Haynes's avatar
David Haynes committed
475
    # If the user is trying to make a Go link to itself, we 404 them
476
    if url.target == domain + short:
477
        return redirect('404.html')
478

David Haynes's avatar
David Haynes committed
479
    # If the user is coming from a QR request then increment qrclicks
480 481 482
    if 'qr' in request.GET:
        url.qrclicks += 1

David Haynes's avatar
David Haynes committed
483
    # If the user is coming from a social media request then increment qrclicks
484 485 486
    if 'social' in request.GET:
        url.socialclicks += 1

David Haynes's avatar
David Haynes committed
487
    # Save our data and redirect the user towards thier destination
Jean Michel Rouly's avatar
Jean Michel Rouly committed
488
    url.save()
489
    return redirect(url.target)
Jean Michel Rouly's avatar
Jean Michel Rouly committed
490

491 492
def staff_member_required(view_func, redirect_field_name=REDIRECT_FIELD_NAME, login_url='/'):
    """
David Haynes's avatar
David Haynes committed
493 494
    Decorator function for views that checks that the user is logged in and is
    a staff member, displaying the login page if necessary.
495 496
    """

497 498
    return user_passes_test(
        lambda u: u.is_active and u.is_staff,
499 500
        login_url=login_url,
        redirect_field_name=redirect_field_name
501 502
    )(view_func)

David Haynes's avatar
David Haynes committed
503 504
@staff_member_required
def useradmin(request):
505
    """
David Haynes's avatar
David Haynes committed
506 507
    This view is a simplified admin panel, so that staff don't need to log in
    to approve links
508
    """
David Haynes's avatar
David Haynes committed
509 510

    # If we receive a POST request
511
    if request.POST:
David Haynes's avatar
David Haynes committed
512
        # Get a list of the potential victims (users)
513
        userlist = request.POST.getlist('username')
David Haynes's avatar
David Haynes committed
514
        # If we're approving users
515
        if '_approve' in request.POST:
516
            for name in userlist:
517 518 519
                to_approve = RegisteredUser.objects.get(user__username__exact=name)
                to_approve.approved = True
                to_approve.save()
David Haynes's avatar
David Haynes committed
520 521

                # Send an email letting them know they are approved
522
                if settings.EMAIL_HOST and settings.EMAIL_PORT:
523
                    user_mail = to_approve.user.username + settings.EMAIL_DOMAIN
524 525 526 527 528 529 530 531
                    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'
532
                        % (str(to_approve.full_name)),
533 534 535 536
                        ######################
                        settings.EMAIL_FROM,
                        [user_mail]
                    )
Zosman's avatar
Zosman committed
537

David Haynes's avatar
David Haynes committed
538
        # If we're denying users
539
        elif '_deny' in request.POST:
540
            for name in userlist:
541
                to_deny = RegisteredUser.objects.get(user__username__exact=name)
542
                if settings.EMAIL_HOST and settings.EMAIL_PORT:
543
                    user_mail = to_deny.user.username + settings.EMAIL_DOMAIN
David Haynes's avatar
David Haynes committed
544
                    # Send an email letting them know they are denied
545 546 547 548 549 550 551 552 553
                    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'
554
                        % (str(to_deny.full_name)),
555 556 557 558
                        ######################
                        settings.EMAIL_FROM,
                        [user_mail]
                    )
David Haynes's avatar
David Haynes committed
559
                # Delete their associated RegisteredUsers
560
                to_deny.user.delete()
561
                return HttpResponseRedirect('useradmin')
Zosman's avatar
Zosman committed
562

563
        # If we're blocking users
Zosman's avatar
draft 1  
Zosman committed
564 565
        elif '_block' in request.POST:
            for name in userlist:
566
                to_block = RegisteredUser.objects.get(user__username__exact=name)
Zosman's avatar
draft 1  
Zosman committed
567
                if settings.EMAIL_HOST and settings.EMAIL_PORT:
568
                    user_mail = to_block.user.username + settings.EMAIL_DOMAIN
Zosman's avatar
draft 1  
Zosman committed
569 570 571 572 573 574 575 576 577
                    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'
578
                        % (str(to_block.full_name)),
Zosman's avatar
draft 1  
Zosman committed
579 580 581 582
                        ######################
                        settings.EMAIL_FROM,
                        [user_mail]
                    )
583 584 585 586
                to_block.blocked = True
                to_block.approved = False
                to_block.registered = False
                to_block.save()
Zosman's avatar
Zosman committed
587

588
        # If we're un-blocking users
589 590
        elif '_unblock' in request.POST:
            for name in userlist:
591
                to_un_block = RegisteredUser.objects.get(user__username__exact=name)
592
                if settings.EMAIL_HOST and settings.EMAIL_PORT:
593
                    user_mail = to_un_block.user.username + settings.EMAIL_DOMAIN
594
                    send_mail(
595
                        'Your Account has been Un-Blocked!',
596 597 598
                        ######################
                        'Hey there %s,\n\n'
                        'The Go admins have reviewed your application and have '
599
                        'Un-Blocked you from using Go.\n\n'
600
                        'If you wish to continue Go use please register again. \n\n'
601 602
                        'Congratulations! '
                        '- Go Admins'
603
                        % (str(to_un_block.full_name)),
604 605 606 607
                        ######################
                        settings.EMAIL_FROM,
                        [user_mail]
                    )
608 609
                to_un_block.blocked = False
                to_un_block.save()
610
                return HttpResponseRedirect('useradmin')
611

612
        # If we're removing existing users
613 614
        elif '_remove' in request.POST:
            for name in userlist:
615
                to_remove = RegisteredUser.objects.get(user__username__exact=name)
616
                if settings.EMAIL_HOST and settings.EMAIL_PORT:
617
                    user_mail = to_remove.user.username + settings.EMAIL_DOMAIN
618 619 620 621 622 623 624 625
                    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'
626
                        % (str(to_remove.full_name)),
627 628 629 630
                        ######################
                        settings.EMAIL_FROM,
                        [user_mail]
                    )
631
                to_remove.user.delete()
632
                return HttpResponseRedirect('useradmin')
633

634
    # Get a list of all RegisteredUsers that need to be approved
635 636
    need_approval = RegisteredUser.objects.filter(registered=True).filter(
        approved=False).filter(blocked=False)
Zosman's avatar
Zosman committed
637
    # Get a list of all RegisteredUsers that are currently users
638 639
    current_users = RegisteredUser.objects.filter(approved=True).filter(
        registered=True).filter(blocked=False)
Zosman's avatar
Zosman committed
640
    # Get a list of all RegisteredUsers that are blocked
641
    blocked_users = RegisteredUser.objects.filter(blocked=True)
642

David Haynes's avatar
David Haynes committed
643
    # Pass that list to the template
644
    return render(request, 'admin/useradmin.html', {
645 646 647
        'need_approval': need_approval,
        'current_users': current_users,
        'blocked_users': blocked_users
David Haynes's avatar
David Haynes committed
648
    })