views.py 25.2 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.
"""
David Haynes's avatar
David Haynes committed
7 8 9
# Python stdlib imports
from datetime import timedelta

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

# Other imports
22
from ratelimit.decorators import ratelimit
23

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

David Haynes's avatar
David Haynes committed
28
def index(request):
29 30
    """
    If a user is logged in, this view displays all the information about all
David Haynes's avatar
David Haynes committed
31
    of their URLs. Otherwise, it will show the public landing page.
32
    """
David Haynes's avatar
David Haynes committed
33
    if not request.user.is_authenticated:
34
        return render(request, 'landing.html')
35 36 37
    if not request.user.registereduser.approved:
        return render(request, 'not_registered.html')

38 39
    # List of sort methods and their display name "Column" : "Name"
    SORT_METHODS = {
David Haynes's avatar
David Haynes committed
40
        "-date_created": "Most Recent",
41
        "date_created": "Oldest",
David Haynes's avatar
David Haynes committed
42 43 44 45 46
        "short": "Alphabetical (A-Z)",
        "-short": "Alphabetical (Z-A)",
        "-clicks": "Most Popular",
        "clicks": "Least Popular",
        "-expires": "Expiring Soon"
47
    }
David Haynes's avatar
David Haynes committed
48

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

52
    # Get the current domain info
53
    domain = "%ss://%s" % (request.scheme, request.META.get('HTTP_HOST')) + "/"
54

David Haynes's avatar
David Haynes committed
55
    # Grab a list of all the URLs that are currently owned by the user
56 57
    urls = URL.objects.filter(owner=request.user.registereduser)

58 59 60 61 62 63
    # 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")

David Haynes's avatar
David Haynes committed
64
    # Render my_links passing the list of URLs, Domain, and Sort Methods to
David Haynes's avatar
David Haynes committed
65
    # the template
66 67 68
    return render(request, 'core/index.html', {
        'urls': urls,
        'domain': domain,
69
        'sort_methods': SORT_METHODS
70
    })
Jean Michel Rouly's avatar
Jean Michel Rouly committed
71

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

David Haynes's avatar
David Haynes committed
88
    # Initialize a URL form
89
    url_form = URLForm(host=request.META.get('HTTP_HOST'))  # unbound form
90

David Haynes's avatar
David Haynes committed
91 92
    # 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
93
    if request.method == 'POST':
94 95
        # Now we initialize the form again but this time we have the POST
        # request
96
        url_form = URLForm(request.POST, host=request.META.get('HTTP_HOST'))
97 98 99

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

David Haynes's avatar
David Haynes committed
103
            # 500 error
104
            if res == 500:
105
                return HttpResponseServerError(render(request, '500.html'))
106

107
            # Redirect to the shiny new URL
108
            return redirect('view', res.short)
109

David Haynes's avatar
David Haynes committed
110 111
        # Else, there is an error, redisplay the form with the validation
        # errors
112 113
        else:
            # Render index.html passing the form to the template
David Haynes's avatar
David Haynes committed
114
            return render(request, 'core/new.html', {
115
                'form': url_form,
116
            })
117

David Haynes's avatar
David Haynes committed
118
    # Render index.html passing the form to the template
David Haynes's avatar
David Haynes committed
119
    return render(request, 'core/new.html', {
120
        'form': url_form,
121
    })
Jean Michel Rouly's avatar
Jean Michel Rouly committed
122

123
@login_required
Zach Knox's avatar
Zach Knox committed
124
def my_links(request):
125 126 127 128 129 130 131 132 133 134
    """
    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
135 136
    return index(request)

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

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

David Haynes's avatar
David Haynes committed
192
def view(request, short):
193
    """
194 195
    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.
196
    """
Jean Michel Rouly's avatar
Jean Michel Rouly committed
197

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

David Haynes's avatar
David Haynes committed
201
    # Get the URL that is being requested
202
    url = get_object_or_404(URL, short__iexact=short)
203

David Haynes's avatar
David Haynes committed
204
    # Render view.html passing the specified URL and Domain to the template
Jean Michel Rouly's avatar
Jean Michel Rouly committed
205
    return render(request, 'view.html', {
206
        'url': url,
207
        'domain': domain,
208
    })
209

David Haynes's avatar
David Haynes committed
210
@login_required
David Haynes's avatar
David Haynes committed
211
def edit(request, short):
212
    """
David Haynes's avatar
David Haynes committed
213 214 215
    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.
216
    """
Jean Michel Rouly's avatar
Jean Michel Rouly committed
217

David Haynes's avatar
David Haynes committed
218
    # Do not allow unapproved users to edit links
219
    if not request.user.registereduser.approved:
David Haynes's avatar
David Haynes committed
220 221 222 223
        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
224

225

David Haynes's avatar
David Haynes committed
226 227
    # 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
228

David Haynes's avatar
David Haynes committed
229 230
    # If the RegisteredUser is the owner of the URL
    if url.owner == request.user.registereduser:
231

232 233 234 235 236
        # 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
237
            url_form = EditForm(request.POST, host=request.META.get('HTTP_HOST'))
238

239 240 241 242 243
            # Make a copy of the old URL
            copy = url
            # Remove the old one
            url.delete()

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

                        # 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:
271 272 273
                    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
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291

                    # 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

292 293 294
                    if edited_expires != copy.expires:
                        copy.expires = edited_expires
                        copy.save()
David Haynes's avatar
David Haynes committed
295 296

                    # Redirect to the shiny new *edited URL
297
                    return redirect('view', copy.short)
298 299 300 301 302 303 304 305

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

323 324 325 326
            # 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
327 328 329
    else:
        # do not allow them to edit
        raise PermissionDenied()
330

David Haynes's avatar
David Haynes committed
331

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

David Haynes's avatar
David Haynes committed
342
    # Get the URL that is going to be deleted
343
    url = get_object_or_404(URL, short__iexact=short)
David Haynes's avatar
David Haynes committed
344 345

    # If the RegisteredUser is the owner of the URL
David Haynes's avatar
David Haynes committed
346
    if url.owner == request.user.registereduser:
David Haynes's avatar
David Haynes committed
347 348 349 350
        # 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

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

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

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

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

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

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

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

403 404
            # Only send mail if we've defined the mailserver
            if settings.EMAIL_HOST and settings.EMAIL_PORT:
root's avatar
root committed
405
                user_mail = request.user.username + settings.EMAIL_DOMAIN
406
                # Email sent to notify Admins
407
                to_admin = EmailMessage(
408
                    'Signup from %s' % (request.user.registereduser.user),
409
                    ######################
David Haynes's avatar
David Haynes committed
410 411 412 413 414 415 416 417 418 419 420 421
                    """
                    %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.'
                    """
                    % (
422 423 424 425
                        str(full_name), str(timezone.now()).strip(),
                        str(request.user.registereduser.user), str(organization),
                        str(description)
                    ),
426 427
                    ######################
                    settings.EMAIL_FROM,
428
                    [settings.EMAIL_TO],
429 430 431
                    reply_to=[user_mail]
                )
                to_admin.send()
432
                # Confirmation email sent to Users
433
                send_mail(
434 435
                    'We have received your Go application!',
                    ######################
David Haynes's avatar
David Haynes committed
436 437 438 439 440 441 442 443 444
                    """
                    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
                    """
445 446 447 448 449
                    % (str(full_name)),
                    ######################
                    settings.EMAIL_FROM,
                    [user_mail]
                )
450

David Haynes's avatar
David Haynes committed
451 452
            # Make sure that our new RegisteredUser object is clean, then save
            # it and let's redirect to tell the user they have registered.
453
            signup_form.save()
454
            return redirect('registered')
Jean Michel Rouly's avatar
Jean Michel Rouly committed
455

David Haynes's avatar
David Haynes committed
456 457
    # render signup.html passing along the form and the current registered
    # status
458
    return render(request, 'core/signup.html', {
459
        'form': signup_form,
460
        'registered': False,
461
    })
Jean Michel Rouly's avatar
Jean Michel Rouly committed
462

David Haynes's avatar
David Haynes committed
463
def redirection(request, short):
464
    """
David Haynes's avatar
David Haynes committed
465
    This view redirects a user based on the short URL they requested.
466
    """
Jean Michel Rouly's avatar
Jean Michel Rouly committed
467

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

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

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

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

David Haynes's avatar
David Haynes committed
492
    # Save our data and redirect the user towards their destination
Jean Michel Rouly's avatar
Jean Michel Rouly committed
493
    url.save()
494
    return redirect(url.target)
Jean Michel Rouly's avatar
Jean Michel Rouly committed
495

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

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

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

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

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

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

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

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

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

David Haynes's avatar
David Haynes committed
645
    # Pass that list to the template
646
    return render(request, 'manage.html', {
647 648 649
        'need_approval': need_approval,
        'current_users': current_users,
        'blocked_users': blocked_users
David Haynes's avatar
David Haynes committed
650
    })