"""Defines website authentication helpers.
"""
import datetime
import rfc822
import time

import pytz
from aspen import Response
from gittip.orm import db
from gittip.models import User


BEGINNING_OF_EPOCH = rfc822.formatdate(0)
TIMEOUT = 60 * 60 * 24 * 7 # one week


def inbound(request):
    """Authenticate from a cookie.
    """
    if 'session' in request.headers.cookie:
        token = request.headers.cookie['session'].value
        user = User.from_session_token(token)
    else:
        user = User()
    request.context['user'] = user


def outbound(response):
    if 'user' in response.request.context:
        user = response.request.context['user']
        if not isinstance(user, User):
            raise Response(400, "If you define 'user' in a simplate it has to "
                                "be a User instance.")
    else:
        user = User()

    if user.ANON: # user is anonymous

        if 'session' not in response.request.headers.cookie:
            if 'username' not in response.request.headers.cookie:
                # no cookies in the request, don't set any on response
                return

        # expired cookies in the request, instruct browser to delete them
        response.headers.cookie['session'] = ''
        response.headers.cookie['username'] = ''
        expires = 0

    else: # user is authenticated
        user = User.from_session_token(user.session_token)
        response.headers['Expires'] = BEGINNING_OF_EPOCH # don't cache
        response.headers.cookie['session'] = user.session_token
        expires = time.time() + TIMEOUT
        user.session_expires = datetime.datetime.fromtimestamp(expires)\
                                                .replace(tzinfo=pytz.utc)
        db.session.add(user)
        db.session.commit()

        response.headers.cookie['username'] = user.username

    for cookie_name in ('username', 'session'):
        cookie = response.headers.cookie[cookie_name]
        # I am not setting domain, because it is supposed to default to what we
        # want: the domain of the object requested.
        #cookie['domain']
        cookie['path'] = '/'
        cookie['expires'] = rfc822.formatdate(expires)
        if cookie_name == 'session':
            cookie['httponly'] = "Yes, please."

@@ -903,17 +903,16 @@
 onymous%0A
-%0A
         
@@ -968,78 +968,8 @@
 ie:%0A
-            if 'username' not in response.request.headers.cookie:%0A    
     
@@ -983,25 +983,24 @@
  # no cookie
-s
  in the requ
@@ -1018,11 +1018,11 @@
 set 
-any
+one
  on 
@@ -1046,28 +1046,40 @@
     
- 
-   
 return%0A
-%0A
+        else:%0A   
         
 # ex
@@ -1074,16 +1074,17 @@
         
+ 
 # expire
@@ -1091,17 +1091,16 @@
 d cookie
-s
  in the 
@@ -1139,13 +1139,15 @@
 ete 
-them%0A
+it%0A    
     
@@ -1198,53 +1198,8 @@
     
-    response.headers.cookie%5B'username'%5D = ''%0A
     
@@ -1214,17 +1214,16 @@
 res = 0%0A
-%0A
     else
@@ -1691,121 +1691,8 @@
 ()%0A%0A
-        response.headers.cookie%5B'username'%5D = user.username%0A%0A    for cookie_name in ('username', 'session'):%0A    
     
@@ -1728,25 +1728,19 @@
 kie%5B
-cookie_name%5D%0A    
+'session'%5D%0A
     
@@ -1815,20 +1815,16 @@
  we%0A    
- 
-   
 # want: 
@@ -1863,20 +1863,16 @@
 ed.%0A    
-   
- 
 #cookie%5B
@@ -1881,20 +1881,16 @@
 omain'%5D%0A
-    
     cook
@@ -1906,28 +1906,24 @@
 %5D = '/'%0A    
- 
-   
 cookie%5B'expi
@@ -1961,53 +1961,8 @@
 es)%0A
-        if cookie_name == 'session':%0A        
     

Stop setting username in cookie