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

David Haynes's avatar
David Haynes committed
4 5 6
The functions that handle a request to a given URL. Get some data, manipulate
it, and return a rendered template.
"""
7
# Future Imports
David Haynes's avatar
David Haynes committed
8 9
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)
10

David Haynes's avatar
David Haynes committed
11 12 13
# Python stdlib imports
from datetime import timedelta

14
# Django Imports
15
from django.conf import settings
David Haynes's avatar
David Haynes committed
16 17 18 19
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
20
from django.http import HttpResponseServerError  # Http404
21
from django.http import HttpResponseRedirect
David Haynes's avatar
David Haynes committed
22
from django.shortcuts import get_object_or_404, redirect, render
23
from django.utils import timezone
David Haynes's avatar
David Haynes committed
24 25

# Other imports
26
from ratelimit.decorators import ratelimit
27

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

David Haynes's avatar
David Haynes committed
32
def index(request):
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')

45 46
    # List of sort methods and their display name "Column" : "Name"
    SORT_METHODS = {
David Haynes's avatar
David Haynes committed
47
        "-date_created": "Most Recent",
48
        "date_created": "Oldest",
David Haynes's avatar
David Haynes committed
49 50 51 52 53
        "short": "Alphabetical (A-Z)",
        "-short": "Alphabetical (Z-A)",
        "-clicks": "Most Popular",
        "clicks": "Least Popular",
        "-expires": "Expiring Soon"
54
    }
David Haynes's avatar
David Haynes committed
55

56 57 58
    # Get the requested sort method, default to "-date_created" : "Most Recent"
    sort_method = request.GET.get('sort', '-date_created')

59
    # Get the current domain info
60
    domain = "%ss://%s" % (request.scheme, request.META.get('HTTP_HOST')) + "/"
61 62 63 64

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

65 66 67 68 69 70 71
    # Check if provided sort method is valid, otherwise default
    if sort_method in SORT_METHODS:
        urls = urls.order_by(sort_method)
    else:
        urls = urls.order_by("-date_created")

    # Render my_links passing the list of URL's, Domain, and Sort Methods to the template
72 73 74
    return render(request, 'core/index.html', {
        'urls': urls,
        'domain': domain,
75
        'sort_methods': SORT_METHODS
76
    })
Jean Michel Rouly's avatar
Jean Michel Rouly committed
77

78
@login_required
Zach Knox's avatar
Zach Knox committed
79
def new_link(request):
80
    """
David Haynes's avatar
David Haynes committed
81
    This view handles the homepage that the user is presented with when
82
    they request '/newLink'. If they're not logged in, they're redirected to
David Haynes's avatar
David Haynes committed
83 84 85
    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.
86
    """
David Haynes's avatar
David Haynes committed
87
    # If the user isn't approved, then display the you're not approved page.
88
    if not request.user.registereduser.approved:
89
        if request.user.registereduser.blocked:
Zosman's avatar
Zosman committed
90
            return render(request, 'banned.html')
91
        else:
Zosman's avatar
Zosman committed
92
            return render(request, 'not_registered.html')
93

David Haynes's avatar
David Haynes committed
94
    # Initialize a URL form
95
    url_form = URLForm(host=request.META.get('HTTP_HOST'))  # unbound form
96

David Haynes's avatar
David Haynes committed
97 98
    # 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
99
    if request.method == 'POST':
100 101
        # Now we initialize the form again but this time we have the POST
        # request
102
        url_form = URLForm(request.POST, host=request.META.get('HTTP_HOST'))
103 104 105

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

David Haynes's avatar
David Haynes committed
109
            # 500 error
110
            if res == 500:
111
                return HttpResponseServerError(render(request, '500.html'))
112

113
            # Redirect to the shiny new URL
114
            return redirect('view', res.short)
115

116 117 118
        # Else, there is an error, redisplay the form with the validation errors
        else:
            # Render index.html passing the form to the template
119
            return render(request, 'core/new_link.html', {
120
                'form': url_form,
121
            })
122

David Haynes's avatar
David Haynes committed
123
    # Render index.html passing the form to the template
Zach Knox's avatar
Zach Knox committed
124
    return render(request, 'core/new_link.html', {
125
        'form': url_form,
126
    })
Jean Michel Rouly's avatar
Jean Michel Rouly committed
127

128
@login_required
Zach Knox's avatar
Zach Knox committed
129
def my_links(request):
130 131 132 133 134 135 136 137 138 139
    """
    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
140 141
    return index(request)

David Haynes's avatar
David Haynes committed
142
# Rate limits are completely arbitrary
143 144
@ratelimit(key='user', rate='3/m', method='POST', block=True)
@ratelimit(key='user', rate='25/d', method='POST', block=True)
145
def post(request, url_form):
146
    """
147
    Helper function that handles POST requests for the URL creation
148 149
    """

150 151
    # We don't commit the url object yet because we need to add its
    # owner, and parse its date field.
152
    url = url_form.save(commit=False)
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
    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
171
        else:
172 173 174 175 176 177 178 179 180
            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:
181
        url.expires = timezone.now() + timedelta(days=1)
182
    elif expires == URLForm.WEEK:
183
        url.expires = timezone.now() + timedelta(weeks=1)
184
    elif expires == URLForm.MONTH:
185
        url.expires = timezone.now() + timedelta(weeks=3)
186 187 188 189 190 191 192 193 194 195
    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
196

David Haynes's avatar
David Haynes committed
197
def view(request, short):
198
    """
199 200
    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.
201
    """
Jean Michel Rouly's avatar
Jean Michel Rouly committed
202

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

David Haynes's avatar
David Haynes committed
206
    # Get the URL that is being requested
207
    url = get_object_or_404(URL, short__iexact=short)
208

David Haynes's avatar
David Haynes committed
209
    # Render view.html passing the specified URL and Domain to the template
Jean Michel Rouly's avatar
Jean Michel Rouly committed
210
    return render(request, 'view.html', {
211
        'url': url,
212
        'domain': domain,
213
    })
214

David Haynes's avatar
David Haynes committed
215
@login_required
David Haynes's avatar
David Haynes committed
216
def edit(request, short):
217
    """
David Haynes's avatar
David Haynes committed
218 219 220
    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.
221
    """
Jean Michel Rouly's avatar
Jean Michel Rouly committed
222

David Haynes's avatar
David Haynes committed
223
    # Do not allow unapproved users to edit links
224
    if not request.user.registereduser.approved:
David Haynes's avatar
David Haynes committed
225 226 227 228
        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
229

230

David Haynes's avatar
David Haynes committed
231 232
    # 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
233

David Haynes's avatar
David Haynes committed
234 235
    # If the RegisteredUser is the owner of the URL
    if url.owner == request.user.registereduser:
236

237 238 239 240 241
        # 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
242
            url_form = EditForm(request.POST, host=request.META.get('HTTP_HOST'))
243

244 245 246 247 248
            # Make a copy of the old URL
            copy = url
            # Remove the old one
            url.delete()

249 250
            # Django will check the form to make sure it's valid
            if url_form.is_valid():
David Haynes's avatar
David Haynes committed
251 252
                # If the short changed then we need to create a new object and
                # migrate some data over
253
                if url_form.cleaned_data.get('short').strip() != copy.short:
David Haynes's avatar
David Haynes committed
254 255 256 257 258 259 260 261 262 263
                    # 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
264
                        res.clicks = copy.clicks
David Haynes's avatar
David Haynes committed
265 266
                        res.qrclicks = copy.qrclicks
                        res.socialclicks = copy.socialclicks
David Haynes's avatar
David Haynes committed
267 268 269 270 271 272 273 274 275

                        # 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:
276 277 278
                    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
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296

                    # 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

297 298 299
                    if edited_expires != copy.expires:
                        copy.expires = edited_expires
                        copy.save()
David Haynes's avatar
David Haynes committed
300 301

                    # Redirect to the shiny new *edited URL
302
                    return redirect('view', copy.short)
303 304 305 306 307 308 309 310

            # 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
311 312 313
            # Initial data set here
            if url.expires != None:
                # Initialize a URL form with an expire date
314
                url_form = EditForm(host=request.META.get('HTTP_HOST'), initial={
David Haynes's avatar
David Haynes committed
315 316 317 318 319 320 321
                    'target': url.target,
                    'short': url.short,
                    'expires': 'Custom Date',
                    'expires_custom': url.expires
                })  # unbound form
            else:
                # Initialize a URL form without an expire date
322
                url_form = EditForm(host=request.META.get('HTTP_HOST'), initial={
David Haynes's avatar
David Haynes committed
323 324 325 326 327
                    'target': url.target,
                    'short': url.short,
                    'expires': 'Never',
                })  # unbound form

328 329 330 331
            # 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
332 333 334
    else:
        # do not allow them to edit
        raise PermissionDenied()
335

David Haynes's avatar
David Haynes committed
336

David Haynes's avatar
David Haynes committed
337 338
@login_required
def delete(request, short):
339
    """
David Haynes's avatar
David Haynes committed
340 341
    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.
342
    """
David Haynes's avatar
David Haynes committed
343
    # Do not allow unapproved users to delete links
344
    if not request.user.registereduser.approved:
345
        return render(request, 'not_registered.html')
Jean Michel Rouly's avatar
Jean Michel Rouly committed
346

David Haynes's avatar
David Haynes committed
347
    # Get the URL that is going to be deleted
348
    url = get_object_or_404(URL, short__iexact=short)
David Haynes's avatar
David Haynes committed
349 350

    # If the RegisteredUser is the owner of the URL
David Haynes's avatar
David Haynes committed
351
    if url.owner == request.user.registereduser:
David Haynes's avatar
David Haynes committed
352 353 354 355
        # remove the URL
        url.delete()
        # redirect to my_links
        return redirect('my_links')
356
    else:
David Haynes's avatar
David Haynes committed
357
        # do not allow them to delete
358
        raise PermissionDenied()
359

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

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

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

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

David Haynes's avatar
David Haynes committed
386 387
    # 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
388
    if request.method == 'POST':
David Haynes's avatar
David Haynes committed
389 390
        # Now we initialize the form again but this time we have the POST
        # request
391 392 393 394 395 396
        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
397 398

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

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

408 409
            # Only send mail if we've defined the mailserver
            if settings.EMAIL_HOST and settings.EMAIL_PORT:
root's avatar
root committed
410
                user_mail = request.user.username + settings.EMAIL_DOMAIN
411
                # Email sent to notify Admins
412
                to_admin = EmailMessage(
413
                    'Signup from %s' % (request.user.registereduser.user),
414
                    ######################
David Haynes's avatar
David Haynes committed
415 416 417 418 419 420 421 422 423 424 425 426
                    """
                    %s signed up at %s\n\n

                    Username: %s\n
                    Organization: %s\n\n

                    Message: %s\n\n

                    You can contact the user directly by replying to this email or reply all to contact the user and notify the mailing list.\n
                    Please head to go.gmu.edu/manage to approve or deny this application.'
                    """
                    % (
427 428 429 430
                        str(full_name), str(timezone.now()).strip(),
                        str(request.user.registereduser.user), str(organization),
                        str(description)
                    ),
431 432
                    ######################
                    settings.EMAIL_FROM,
433
                    [settings.EMAIL_TO],
434 435 436
                    reply_to=[user_mail]
                )
                to_admin.send()
437
                # Confirmation email sent to Users
438
                send_mail(
439 440
                    'We have received your Go application!',
                    ######################
David Haynes's avatar
David Haynes committed
441 442 443 444 445 446 447 448 449
                    """
                    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
                    """
450 451 452 453 454
                    % (str(full_name)),
                    ######################
                    settings.EMAIL_FROM,
                    [user_mail]
                )
455

David Haynes's avatar
David Haynes committed
456 457
            # Make sure that our new RegisteredUser object is clean, then save
            # it and let's redirect to tell the user they have registered.
458
            signup_form.save()
459
            return redirect('registered')
Jean Michel Rouly's avatar
Jean Michel Rouly committed
460

David Haynes's avatar
David Haynes committed
461 462
    # render signup.html passing along the form and the current registered
    # status
463
    return render(request, 'core/signup.html', {
464
        'form': signup_form,
465
        'registered': False,
466
    })
Jean Michel Rouly's avatar
Jean Michel Rouly committed
467

David Haynes's avatar
David Haynes committed
468
def redirection(request, short):
469
    """
David Haynes's avatar
David Haynes committed
470
    This view redirects a user based on the short URL they requested.
471
    """
Jean Michel Rouly's avatar
Jean Michel Rouly committed
472

David Haynes's avatar
David Haynes committed
473 474
    # Get the current domain info
    domain = "%s://%s" % (request.scheme, request.META.get('HTTP_HOST')) + "/"
David Haynes's avatar
David Haynes committed
475

David Haynes's avatar
David Haynes committed
476
    # Get the URL object that relates to the requested Go link
477
    url = get_object_or_404(URL, short__iexact=short)
David Haynes's avatar
David Haynes committed
478 479
    # Increment our clicks by one
    url.clicks += 1
Eyad Hasan's avatar
Eyad Hasan committed
480 481 482 483 484
    # 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
485
    # If the user is trying to make a Go link to itself, we 404 them
486
    if url.target == domain + short:
487
        return redirect('404.html')
488

David Haynes's avatar
David Haynes committed
489
    # If the user is coming from a QR request then increment qrclicks
490 491 492
    if 'qr' in request.GET:
        url.qrclicks += 1

David Haynes's avatar
David Haynes committed
493
    # If the user is coming from a social media request then increment qrclicks
494 495 496
    if 'social' in request.GET:
        url.socialclicks += 1

David Haynes's avatar
David Haynes committed
497
    # Save our data and redirect the user towards their destination
Jean Michel Rouly's avatar
Jean Michel Rouly committed
498
    url.save()
499
    return redirect(url.target)
Jean Michel Rouly's avatar
Jean Michel Rouly committed
500

501 502
def staff_member_required(view_func, redirect_field_name=REDIRECT_FIELD_NAME, login_url='/'):
    """
David Haynes's avatar
David Haynes committed
503 504
    Decorator function for views that checks that the user is logged in and is
    a staff member, displaying the login page if necessary.
505
    """
506 507
    return user_passes_test(
        lambda u: u.is_active and u.is_staff,
508 509
        login_url=login_url,
        redirect_field_name=redirect_field_name
510 511
    )(view_func)

David Haynes's avatar
David Haynes committed
512 513
@staff_member_required
def useradmin(request):
514
    """
David Haynes's avatar
David Haynes committed
515 516
    This view is a simplified admin panel, so that staff don't need to log in
    to approve links
517
    """
David Haynes's avatar
David Haynes committed
518 519

    # If we receive a POST request
520
    if request.POST:
David Haynes's avatar
David Haynes committed
521
        # Get a list of the potential victims (users)
522
        userlist = request.POST.getlist('username')
David Haynes's avatar
David Haynes committed
523
        # If we're approving users
524
        if '_approve' in request.POST:
525
            for name in userlist:
526 527 528
                to_approve = RegisteredUser.objects.get(user__username__exact=name)
                to_approve.approved = True
                to_approve.save()
David Haynes's avatar
David Haynes committed
529 530

                # Send an email letting them know they are approved
531
                if settings.EMAIL_HOST and settings.EMAIL_PORT:
532
                    user_mail = to_approve.user.username + settings.EMAIL_DOMAIN
533 534 535 536 537 538 539 540
                    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'
541
                        % (str(to_approve.full_name)),
542 543 544 545
                        ######################
                        settings.EMAIL_FROM,
                        [user_mail]
                    )
Zosman's avatar
Zosman committed
546

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

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

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

621
        # If we're removing existing users
622 623
        elif '_remove' in request.POST:
            for name in userlist:
624
                to_remove = RegisteredUser.objects.get(user__username__exact=name)
625
                if settings.EMAIL_HOST and settings.EMAIL_PORT:
626
                    user_mail = to_remove.user.username + settings.EMAIL_DOMAIN
627 628 629 630 631 632 633 634
                    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'
635
                        % (str(to_remove.full_name)),
636 637 638 639
                        ######################
                        settings.EMAIL_FROM,
                        [user_mail]
                    )
640
                to_remove.user.delete()
David Haynes's avatar
David Haynes committed
641
                return HttpResponseRedirect('manage')
642

643
    # Get a list of all RegisteredUsers that need to be approved
David Haynes's avatar
David Haynes committed
644
    need_approval = RegisteredUser.objects.filter(registered=True).filter(approved=False).filter(blocked=False)
Zosman's avatar
Zosman committed
645
    # Get a list of all RegisteredUsers that are currently users
David Haynes's avatar
David Haynes committed
646
    current_users = RegisteredUser.objects.filter(approved=True).filter(registered=True).filter(blocked=False)
Zosman's avatar
Zosman committed
647
    # Get a list of all RegisteredUsers that are blocked
648
    blocked_users = RegisteredUser.objects.filter(blocked=True)
649

David Haynes's avatar
David Haynes committed
650
    # Pass that list to the template
651
    return render(request, 'admin/useradmin.html', {
652 653 654
        'need_approval': need_approval,
        'current_users': current_users,
        'blocked_users': blocked_users
David Haynes's avatar
David Haynes committed
655
    })