Merge "update the huawei's lab"
[pharos.git] / tools / pharos-dashboard / 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     Activate the timezone from request.user.userprofile if user is authenticated,
20     deactivate the timezone otherwise and use default (UTC)
21     """
22     def process_request(self, request):
23         if request.user.is_authenticated:
24             try:
25                 tz = request.user.userprofile.timezone
26                 timezone.activate(tz)
27             except UserProfile.DoesNotExist:
28                 UserProfile.objects.create(user=request.user)
29                 tz = request.user.userprofile.timezone
30                 timezone.activate(tz)
31         else:
32             timezone.deactivate()