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

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

# Other Imports
from datetime import timedelta
Jean Michel Rouly's avatar
Jean Michel Rouly committed
17 18 19 20 21 22 23

##############################################################################
"""
Define useful helper methods here.
"""


24
def is_approved(user):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
25 26
    """
    This function checks if a user account has a corresponding RegisteredUser,
27
    thus checking if the user is approved.
Jean Michel Rouly's avatar
Jean Michel Rouly committed
28 29
    """

30
    try:
31
        registered = RegisteredUser.objects.get(username=user.username)
32
        return registered.approved
33 34 35
    except RegisteredUser.DoesNotExist:
        return False

Jean Michel Rouly's avatar
Jean Michel Rouly committed
36

37 38 39 40 41 42 43
def is_registered(user):
    """
    This function checks if a user account has a corresponding RegisteredUser,
    thus checking if the user is registered.
    """

    try:
44
        registered = RegisteredUser.objects.get(username=user.username)
45 46 47 48 49
        return True
    except RegisteredUser.DoesNotExist:
        return False


Jean Michel Rouly's avatar
Jean Michel Rouly committed
50 51 52 53 54 55
##############################################################################
"""
Define user views here.
"""


Jean Michel Rouly's avatar
Jean Michel Rouly committed
56
def index(request):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
57 58 59 60 61 62 63
    """
    This view handles the homepage that the user is presented with when
    they request '/'. If they're not logged in, they're redirected to
    login. If they're logged in but not registered, they're given the
    not_registered error page. If they are logged in AND registered, they
    get the URL registration form.
    """
Jean Michel Rouly's avatar
Jean Michel Rouly committed
64

65 66 67 68
    # If the user is not authenticated, show them a public landing page.
    if not request.user.is_authenticated():
        return render(request, 'public_landing.html')

Jean Michel Rouly's avatar
Jean Michel Rouly committed
69
    # If the user isn't registered, don't give them any leeway.
70
    if not is_approved(request.user):
71 72
        return render(request, 'not_registered.html')

73
    url_form = URLForm()  # unbound form
74 75

    if request.method == 'POST':
76
        url_form = URLForm(request.POST)  # bind dat form
77 78
        if url_form.is_valid():

Jean Michel Rouly's avatar
Jean Michel Rouly committed
79 80
            # We don't commit the url object yet because we need to add its
            # owner, and parse its date field.
81 82 83
            url = url_form.save(commit=False)
            url.owner = request.user

Jean Michel Rouly's avatar
Jean Michel Rouly committed
84
            # If the user entered a short url, it's already been validated,
Jean Michel Rouly's avatar
Jean Michel Rouly committed
85 86
            # so accept it. If they did not, however, then generate a
            # random one and use that instead.
87
            short = url_form.cleaned_data.get('short').strip()
88 89 90
            if len(short) > 0:
                url.short = short
            else:
91 92 93 94 95 96
                # If the user didn't enter a short url, generate a random
                # one. However, if a random one can't be generated, return
                # a 500 server error.
                random_short = URL.generate_valid_short()
                if random_short is None:
                    return HttpResponseServerError(
97
                        render(request, '500.html', {})
98 99 100
                    )
                else:
                    url.short = random_short
101

Jean Michel Rouly's avatar
Jean Michel Rouly committed
102 103 104
            # 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.
105
            expires = url_form.cleaned_data.get('expires')
106 107 108 109 110 111 112 113

            if expires == URLForm.DAY:
                url.expires = timezone.now() + timedelta(days=1)
            elif expires == URLForm.WEEK:
                url.expires = timezone.now() + timedelta(weeks=1)
            elif expires == URLForm.MONTH:
                url.expires = timezone.now() + timedelta(weeks=3)
            else:
114
                pass  # leave the field NULL
115

Jean Michel Rouly's avatar
Jean Michel Rouly committed
116 117
            # Make sure that our new URL object is clean, then save it and
            # let's redirect to view this baby.
118 119
            url.full_clean()
            url.save()
Jean Michel Rouly's avatar
Jean Michel Rouly committed
120
            return redirect('view', url.short)
121

122
    return render(request, 'core/index.html', {
123
        'form': url_form,
Jean Michel Rouly's avatar
Jean Michel Rouly committed
124 125 126
    },
    )

Jean Michel Rouly's avatar
Jean Michel Rouly committed
127

Jean Michel Rouly's avatar
Jean Michel Rouly committed
128
def view(request, short):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
129 130 131 132 133
    """
    This view allows the user to view details about a URL. Note that they
    do not need to be logged in to view info.
    """

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

136
    url = get_object_or_404(URL, short__iexact=short)
137

Jean Michel Rouly's avatar
Jean Michel Rouly committed
138
    return render(request, 'view.html', {
139
        'url': url,
140
        'domain': domain,
141 142 143
    },
    )

Jean Michel Rouly's avatar
Jean Michel Rouly committed
144

145
@login_required
146
def my_links(request):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
147 148 149 150 151
    """
    This view displays all the information about all of your URLs. You
    obviously need to be logged in to view your URLs.
    """

152
    if not is_approved(request.user):
153
        return render(request, 'not_registered.html')
Jean Michel Rouly's avatar
Jean Michel Rouly committed
154

155
    urls = URL.objects.filter(owner=request.user)
156

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

159
    return render(request, 'my_links.html', {
160 161
        'urls': urls,
        'domain': domain,
162 163 164
    },
    )

Jean Michel Rouly's avatar
Jean Michel Rouly committed
165

166
@login_required
167
def delete(request, short):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
168 169 170 171 172
    """
    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.
    """

173
    if not is_approved(request.user):
174
        return render(request, 'not_registered.html')
Jean Michel Rouly's avatar
Jean Michel Rouly committed
175

176
    url = get_object_or_404(URL, short__iexact=short)
177 178
    if url.owner == request.user:
        url.delete()
179 180
        return redirect('my_links')
    else:
181
        raise PermissionDenied()
182

Jean Michel Rouly's avatar
Jean Michel Rouly committed
183

184
@login_required
Jean Michel Rouly's avatar
Jean Michel Rouly committed
185
def signup(request):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
186 187 188 189 190
    """
    This view presents the user with a registration form. You can register
    yourself, or another person.

    """
191
    # Do not display signup page to registered or approved users (Staff can still see these pages)
192
    if is_registered(request.user) and not request.user.is_staff:
193
        return render(request, 'core/signup.html', {
194
            'registered': True,
195 196 197 198
            'approved': False,
        },
        )
    elif is_approved(request.user) and not request.user.is_staff:
199
        return render(request, 'core/signup.html', {
200 201
            'registered': True,
            'approved': True,
202 203 204
        },
        )

David Haynes's avatar
David Haynes committed
205 206
    signup_form = SignupForm(request, initial={'username': request.user.username})

207 208
    # Non-staff have the username field read-only and pre-filled
    if request.user.is_staff:
David Haynes's avatar
David Haynes committed
209
        signup_form = SignupForm(request)
210
    else:
David Haynes's avatar
David Haynes committed
211 212
        signup_form = SignupForm(request,
            initial={'username': request.user.username, 'full_name': request.user.first_name + " " + request.user.last_name})
213
        signup_form.fields['username'].widget.attrs['readonly'] = 'readonly'
Jean Michel Rouly's avatar
Jean Michel Rouly committed
214 215

    if request.method == 'POST':
David Haynes's avatar
David Haynes committed
216 217 218
        signup_form = SignupForm(request, request.POST,
            initial={'approved': False, 'username': request.user.username})
        signup_form.fields['username'].widget.attrs['readonly'] = 'readonly'
219

220
        if signup_form.is_valid():
221 222 223 224
            if not request.user.is_staff:
                username = request.user.username
            else:
                username = signup_form.cleaned_data.get('username')
225 226
            full_name = signup_form.cleaned_data.get('full_name')
            description = signup_form.cleaned_data.get('description')
227
            organization = signup_form.cleaned_data.get('organization')
228

229 230
            # Only send mail if we've defined the mailserver
            if settings.EMAIL_HOST and settings.EMAIL_PORT:
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
                user_mail = username + settings.EMAIL_DOMAIN
                # Email sent to notify Admins
                to_admin = (
                    'Signup from %s' % (request.user.username),
                    ######################
                    '%s signed up at %s\n\n'
                    'Username: %s\n'
                    'Organization: %s\n\n'
                    'Message: %s\n\n'
                    'Please head to go.gmu.edu/useradmin to approve or '
                    'deny this application.'
                    % (str(full_name), str(timezone.now()).strip(),
                    str(request.user.username), str(organization), str(description)),
                    ######################
                    settings.EMAIL_FROM,
                    [settings.EMAIL_TO]
                )
                # Confirmation email sent to Users
                to_user = (
                    'We have received your Go application!',
                    ######################
                    'Hey there %s,\n\n'
                    'The Go admins have received your application and are '
                    'currently in the process of reviewing it.\n\n'
                    'You will receive another email when you have been '
                    'approved.\n\n'
                    '- Go Admins'
                    % (str(full_name)),
                    ######################
                    settings.EMAIL_FROM,
                    [user_mail]
                )
                send_mass_mail((to_admin, to_user), fail_silently=False)
264
            signup_form.save()
265
            return redirect('registered')
Jean Michel Rouly's avatar
Jean Michel Rouly committed
266

267
    return render(request, 'core/signup.html', {
268
        'form': signup_form,
269
        'registered': False,
Jean Michel Rouly's avatar
Jean Michel Rouly committed
270 271
    },
    )
Jean Michel Rouly's avatar
Jean Michel Rouly committed
272

Jean Michel Rouly's avatar
Jean Michel Rouly committed
273

Jean Michel Rouly's avatar
Jean Michel Rouly committed
274
def redirection(request, short):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
275 276 277
    """
    This view redirects a user based on the short URL they requested.
    """
Jean Michel Rouly's avatar
Jean Michel Rouly committed
278

279
    url = get_object_or_404(URL, short__iexact=short)
Jean Michel Rouly's avatar
Jean Michel Rouly committed
280
    url.clicks = url.clicks + 1
281 282 283 284 285 286 287

    if 'qr' in request.GET:
        url.qrclicks += 1

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

Jean Michel Rouly's avatar
Jean Michel Rouly committed
288
    url.save()
289

Jean Michel Rouly's avatar
Jean Michel Rouly committed
290 291 292 293 294
    """
    Include server-side tracking because there is no template displayed to
    the user which would include javascript tracking.
    """

295 296
    from piwikapi.tracking import PiwikTracker
    from django.conf import settings
297
    # First, if PIWIK variables are undefined, don't try to push
298
    if settings.PIWIK_SITE_ID != "" and settings.PIWIK_URL != "":
299 300 301 302 303 304 305
        try:
            piwiktracker = PiwikTracker(settings.PIWIK_SITE_ID, request)
            piwiktracker.set_api_url(settings.PIWIK_URL)
            piwiktracker.do_track_page_view('Redirect to %s' % url.target)
        # Second, if we do get an error, don't let that keep us from redirecting
        except:
            pass
306

307
    return redirect(url.target)
Jean Michel Rouly's avatar
Jean Michel Rouly committed
308 309


310 311 312 313 314 315 316 317 318 319 320 321 322
def staff_member_required(view_func, redirect_field_name=REDIRECT_FIELD_NAME, login_url='about'):
    """
    Decorator for views that checks that the user is logged in and is a staff
    member, displaying the login page if necessary.
    """
    return user_passes_test(
        lambda u: u.is_active and u.is_staff,
        login_url=login_url,
        redirect_field_name=redirect_field_name
    )(view_func)


@staff_member_required
Chris Reffett's avatar
Chris Reffett committed
323
def useradmin(request):
324 325 326 327 328
    """
    This view is a simplified admin panel, so that staff don't need to log in
    to approve links
    """
    if request.POST:
329
        userlist = request.POST.getlist('username')
330
        if '_approve' in request.POST:
331 332 333 334
            for name in userlist:
                toapprove = RegisteredUser.objects.get(username=name)
                toapprove.approved = True
                toapprove.save()
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
                if settings.EMAIL_HOST and settings.EMAIL_PORT:
                    user_mail = toapprove.username + settings.EMAIL_DOMAIN
                    send_mail(
                        'Your Account has been Approved!',
                        ######################
                        'Hey there %s,\n\n'
                        'The Go admins have reviewed your application and have '
                        'approved you to use Go!\n\n'
                        'Head over to go.gmu.edu to create your first address.\n\n'
                        '- Go Admins'
                        % (str(toapprove.full_name)),
                        ######################
                        settings.EMAIL_FROM,
                        [user_mail]
                    )
350
        elif '_deny' in request.POST:
351 352
            for name in userlist:
                todeny = RegisteredUser.objects.get(username=name)
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
                if settings.EMAIL_HOST and settings.EMAIL_PORT:
                    user_mail = todeny.username + settings.EMAIL_DOMAIN
                    send_mail(
                        'Your Account has been Denied!',
                        ######################
                        'Hey there %s,\n\n'
                        'The Go admins have reviewed your application and have '
                        'decided to not approve you to use Go.\n\n'
                        'Please reach out to srct@gmu.edu to appeal '
                        'this decision.\n\n'
                        '- Go Admins'
                        % (str(todeny.full_name)),
                        ######################
                        settings.EMAIL_FROM,
                        [user_mail]
                    )
369
                todeny.delete()
370
    need_approval = RegisteredUser.objects.filter(approved=False)
371
    return render(request, 'admin/useradmin.html', {
372 373 374
        'need_approval': need_approval
    },
    )