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
    """
    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():
40
        return render(request, 'landing.html')
41 42 43 44
    # 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
    # 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
71 72
    # Render my_links passing the list of URL's, Domain, and Sort Methods to
    # the template
73 74 75
    return render(request, 'core/index.html', {
        'urls': urls,
        'domain': domain,
76
        'sort_methods': SORT_METHODS
77
    })
Jean Michel Rouly's avatar
Jean Michel Rouly committed
78

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

232

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

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

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

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

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

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

                    # 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

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

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

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

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

David Haynes's avatar
David Haynes committed
338

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

David Haynes's avatar
David Haynes committed
652
    # Pass that list to the template
653
    return render(request, 'manage.html', {
654 655 656
        'need_approval': need_approval,
        'current_users': current_users,
        'blocked_users': blocked_users
David Haynes's avatar
David Haynes committed
657
    })