views.py 11.1 KB
Newer Older
1
from go.models import URL, RegisteredUser
Jean Michel Rouly's avatar
Jean Michel Rouly committed
2
from go.forms import URLForm, SignupForm
3
from datetime import timedelta
4
from django.conf import settings
5
from django.http import HttpResponseServerError  # Http404
6
from django.utils import timezone
7 8
# from django.contrib.auth.models import User
from django.core.exceptions import PermissionDenied  # ValidationError
9
from django.core.mail import send_mail
10 11
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
12
from django.shortcuts import render, get_object_or_404, redirect
13
# import os
14

Jean Michel Rouly's avatar
Jean Michel Rouly committed
15 16 17 18 19 20 21

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


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

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

Jean Michel Rouly's avatar
Jean Michel Rouly committed
34

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

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


Jean Michel Rouly's avatar
Jean Michel Rouly committed
48 49 50 51 52 53
##############################################################################
"""
Define error page handling here.
"""


54
def error_404(request):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
55 56 57 58
    """
    Error 404 view, in case a url is not found.
    """

59
    return render(request, '404.html', {
60 61 62
    },
    )

63

64
def error_500(request):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
65 66 67 68
    """
    Error 500 view, in case a server error occurs.
    """

69
    return render(request, '500.html', {
70 71 72
    },
    )

Jean Michel Rouly's avatar
Jean Michel Rouly committed
73 74 75 76 77 78
##############################################################################
"""
Define user views here.
"""


Jean Michel Rouly's avatar
Jean Michel Rouly committed
79
def index(request):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
80 81 82 83 84 85 86
    """
    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
87

88 89 90 91
    # 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
92
    # If the user isn't registered, don't give them any leeway.
93
    if not is_approved(request.user):
94 95
        return render(request, 'not_registered.html')

96
    url_form = URLForm()  # unbound form
97 98

    if request.method == 'POST':
99
        url_form = URLForm(request.POST)  # bind dat form
100 101
        if url_form.is_valid():

Jean Michel Rouly's avatar
Jean Michel Rouly committed
102 103
            # We don't commit the url object yet because we need to add its
            # owner, and parse its date field.
104 105 106
            url = url_form.save(commit=False)
            url.owner = request.user

Jean Michel Rouly's avatar
Jean Michel Rouly committed
107
            # If the user entered a short url, it's already been validated,
Jean Michel Rouly's avatar
Jean Michel Rouly committed
108 109
            # so accept it. If they did not, however, then generate a
            # random one and use that instead.
110
            short = url_form.cleaned_data.get('short').strip()
111 112 113
            if len(short) > 0:
                url.short = short
            else:
114 115 116 117 118 119
                # 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(
120
                        render(request, '500.html', {})
121 122 123
                    )
                else:
                    url.short = random_short
124

Jean Michel Rouly's avatar
Jean Michel Rouly committed
125 126 127
            # 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.
128
            expires = url_form.cleaned_data.get('expires')
129 130 131 132 133 134 135 136

            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:
137
                pass  # leave the field NULL
138

Jean Michel Rouly's avatar
Jean Michel Rouly committed
139 140
            # Make sure that our new URL object is clean, then save it and
            # let's redirect to view this baby.
141 142
            url.full_clean()
            url.save()
Jean Michel Rouly's avatar
Jean Michel Rouly committed
143
            return redirect('view', url.short)
144

145
    return render(request, 'core/index.html', {
146
        'form': url_form,
Jean Michel Rouly's avatar
Jean Michel Rouly committed
147 148 149
    },
    )

Jean Michel Rouly's avatar
Jean Michel Rouly committed
150

Jean Michel Rouly's avatar
Jean Michel Rouly committed
151
def view(request, short):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
152 153 154 155 156
    """
    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
157
    domain = "%s://%s" % (request.scheme, request.META.get('HTTP_HOST')) + "/"
158

159
    url = get_object_or_404(URL, short__iexact=short)
160

Jean Michel Rouly's avatar
Jean Michel Rouly committed
161
    return render(request, 'view.html', {
162
        'url': url,
163
        'domain': domain,
164 165 166
    },
    )

Jean Michel Rouly's avatar
Jean Michel Rouly committed
167

168
@login_required
169
def my_links(request):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
170 171 172 173 174
    """
    This view displays all the information about all of your URLs. You
    obviously need to be logged in to view your URLs.
    """

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

178
    urls = URL.objects.filter(owner=request.user)
179

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

182
    return render(request, 'my_links.html', {
183 184
        'urls': urls,
        'domain': domain,
185 186 187
    },
    )

Jean Michel Rouly's avatar
Jean Michel Rouly committed
188

189
@login_required
190
def delete(request, short):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
191 192 193 194 195
    """
    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.
    """

196
    if not is_approved(request.user):
197
        return render(request, 'not_registered.html')
Jean Michel Rouly's avatar
Jean Michel Rouly committed
198

199
    url = get_object_or_404(URL, short__iexact=short)
200 201
    if url.owner == request.user:
        url.delete()
202 203
        return redirect('my_links')
    else:
204
        raise PermissionDenied()
205

Jean Michel Rouly's avatar
Jean Michel Rouly committed
206

207
@login_required
Jean Michel Rouly's avatar
Jean Michel Rouly committed
208
def signup(request):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
209 210 211 212 213
    """
    This view presents the user with a registration form. You can register
    yourself, or another person.

    """
214
    # Do not display signup page to registered or approved users (Staff can still see these pages)
215
    if is_registered(request.user) and not request.user.is_staff:
216
        return render(request, 'core/signup.html', {
217
            'registered': True,
218 219 220 221
            'approved': False,
        },
        )
    elif is_approved(request.user) and not request.user.is_staff:
222
        return render(request, 'core/signup.html', {
223 224
            'registered': True,
            'approved': True,
225 226 227
        },
        )

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

230 231
    # Non-staff have the username field read-only and pre-filled
    if request.user.is_staff:
David Haynes's avatar
David Haynes committed
232
        signup_form = SignupForm(request)
233
    else:
David Haynes's avatar
David Haynes committed
234 235
        signup_form = SignupForm(request,
            initial={'username': request.user.username, 'full_name': request.user.first_name + " " + request.user.last_name})
236
        signup_form.fields['username'].widget.attrs['readonly'] = 'readonly'
Jean Michel Rouly's avatar
Jean Michel Rouly committed
237 238

    if request.method == 'POST':
David Haynes's avatar
David Haynes committed
239 240 241
        signup_form = SignupForm(request, request.POST,
            initial={'approved': False, 'username': request.user.username})
        signup_form.fields['username'].widget.attrs['readonly'] = 'readonly'
242

243
        if signup_form.is_valid():
244 245 246 247
            if not request.user.is_staff:
                username = request.user.username
            else:
                username = signup_form.cleaned_data.get('username')
248 249
            full_name = signup_form.cleaned_data.get('full_name')
            description = signup_form.cleaned_data.get('description')
250 251
            organization = signup_form.cleaned_data.get('organization')
            
252 253
            # Only send mail if we've defined the mailserver
            if settings.EMAIL_HOST and settings.EMAIL_PORT:
David Haynes's avatar
David Haynes committed
254 255
                # TODO rewrite see #14
                send_mail('Signup from %s' % (request.user.username), '%s signed up at %s\n'
256 257
                          'Username: %s\nMessage: %s\nPlease attend to this request at '
                          'your earliest convenience.' % (str(full_name),
David Haynes's avatar
David Haynes committed
258
                          str(timezone.now()).strip(), str(request.user.username), str(description)),
259
                          settings.EMAIL_FROM, [settings.EMAIL_TO])
260

261 262
            signup_form.save()

263
            return redirect('registered')
Jean Michel Rouly's avatar
Jean Michel Rouly committed
264

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

Jean Michel Rouly's avatar
Jean Michel Rouly committed
271

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

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

    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
286
    url.save()
287

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

293 294
    from piwikapi.tracking import PiwikTracker
    from django.conf import settings
295
    # First, if PIWIK variables are undefined, don't try to push
296
    if settings.PIWIK_SITE_ID != "" and settings.PIWIK_URL != "":
297 298 299 300 301 302 303
        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
304

305
    return redirect(url.target)
Jean Michel Rouly's avatar
Jean Michel Rouly committed
306 307


308 309 310 311 312 313 314 315 316 317 318 319 320
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
321
def useradmin(request):
322 323 324 325 326
    """
    This view is a simplified admin panel, so that staff don't need to log in
    to approve links
    """
    if request.POST:
327
        userlist = request.POST.getlist('username')
328
        if '_approve' in request.POST:
329 330 331 332
            for name in userlist:
                toapprove = RegisteredUser.objects.get(username=name)
                toapprove.approved = True
                toapprove.save()
333
        elif '_deny' in request.POST:
334 335 336
            for name in userlist:
                todeny = RegisteredUser.objects.get(username=name)
                todeny.delete()
337
    need_approval = RegisteredUser.objects.filter(approved=False)
338
    return render(request, 'admin/useradmin.html', {
339 340 341 342 343
        'need_approval': need_approval
    },
    )


Jean Michel Rouly's avatar
Jean Michel Rouly committed
344 345 346 347 348 349 350
##############################################################################
"""
Define static user views here.
"""


def about(request):
351
    return render(request, 'core/about.html', {
Jean Michel Rouly's avatar
Jean Michel Rouly committed
352 353 354
    },
    )

355

356 357 358 359
def registered(request):
    return render(request, 'registered.html', {
    },
    )