6a46dfe8801465c8d3c55f0b58c75d6d990e64a8
[laas.git] / src / account / middleware.py
1 ##############################################################################
2 # Copyright (c) 2016 Max Breitenfeldt and others.
3 #
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
9
10
11 from django.utils import timezone
12 from django.utils.deprecation import MiddlewareMixin
13
14 from account.models import UserProfile
15
16
17 class TimezoneMiddleware(MiddlewareMixin):
18     """
19     Manage user's Timezone preference.
20
21     Activate the timezone from request.user.userprofile if user is authenticated,
22     deactivate the timezone otherwise and use default (UTC)
23     """
24
25     def process_request(self, request):
26         if request.user.is_authenticated:
27             try:
28                 tz = request.user.userprofile.timezone
29                 timezone.activate(tz)
30             except UserProfile.DoesNotExist:
31                 UserProfile.objects.create(user=request.user)
32                 tz = request.user.userprofile.timezone
33                 timezone.activate(tz)
34         else:
35             timezone.deactivate()