2015-01-28 17:51:25 +00:00
|
|
|
import time
|
|
|
|
import jwt
|
|
|
|
import uuid
|
|
|
|
|
2015-01-08 20:55:24 +00:00
|
|
|
from datetime import timedelta
|
2015-01-28 17:51:25 +00:00
|
|
|
|
2015-01-08 20:55:24 +00:00
|
|
|
from django.utils import timezone
|
|
|
|
from openid_provider.models import *
|
|
|
|
|
|
|
|
|
|
|
|
def create_id_token_dic(user, iss, aud):
|
2015-01-28 17:51:25 +00:00
|
|
|
"""
|
2015-01-08 20:55:24 +00:00
|
|
|
Receives a user object, iss (issuer) and aud (audience).
|
|
|
|
Then creates the id_token dic.
|
|
|
|
See: http://openid.net/specs/openid-connect-core-1_0.html#IDToken
|
|
|
|
|
|
|
|
Return a dic.
|
2015-01-28 17:51:25 +00:00
|
|
|
"""
|
2015-01-08 20:55:24 +00:00
|
|
|
expires_in = 60*10
|
|
|
|
|
|
|
|
now = timezone.now()
|
|
|
|
|
|
|
|
# Convert datetimes into timestamps.
|
|
|
|
iat_time = time.mktime(now.timetuple())
|
|
|
|
exp_time = time.mktime((now + timedelta(seconds=expires_in)).timetuple())
|
|
|
|
user_auth_time = time.mktime(user.last_login.timetuple())
|
|
|
|
|
|
|
|
dic = {
|
2015-01-16 13:37:47 +00:00
|
|
|
'iss': iss,
|
2015-01-08 20:55:24 +00:00
|
|
|
'sub': user.id,
|
|
|
|
'aud': aud,
|
|
|
|
'exp': exp_time,
|
|
|
|
'iat': iat_time,
|
|
|
|
'auth_time': user_auth_time,
|
|
|
|
}
|
|
|
|
|
|
|
|
return dic
|
|
|
|
|
2015-01-28 17:51:25 +00:00
|
|
|
|
2015-01-08 20:55:24 +00:00
|
|
|
def encode_id_token(id_token_dic, client_secret):
|
2015-01-28 17:51:25 +00:00
|
|
|
"""
|
2015-01-08 20:55:24 +00:00
|
|
|
Represent the ID Token as a JSON Web Token (JWT).
|
|
|
|
|
|
|
|
Return a hash.
|
2015-01-28 17:51:25 +00:00
|
|
|
"""
|
2015-01-08 20:55:24 +00:00
|
|
|
id_token_hash = jwt.encode(id_token_dic, client_secret)
|
|
|
|
|
|
|
|
return id_token_hash
|
|
|
|
|
2015-01-28 17:51:25 +00:00
|
|
|
|
2015-01-08 20:55:24 +00:00
|
|
|
def create_token(user, client, id_token_dic, scope):
|
2015-01-28 17:51:25 +00:00
|
|
|
"""
|
2015-01-08 20:55:24 +00:00
|
|
|
Create and populate a Token object.
|
|
|
|
|
|
|
|
Return a Token object.
|
2015-01-28 17:51:25 +00:00
|
|
|
"""
|
2015-01-08 20:55:24 +00:00
|
|
|
token = Token()
|
|
|
|
token.user = user
|
|
|
|
token.client = client
|
|
|
|
token.access_token = uuid.uuid4().hex
|
|
|
|
|
|
|
|
token.id_token = id_token_dic
|
|
|
|
|
|
|
|
token.refresh_token = uuid.uuid4().hex
|
2015-01-28 17:51:25 +00:00
|
|
|
token.expires_at = timezone.now() + timedelta(seconds=60*60) # TODO: Add this into settings.
|
2015-01-08 20:55:24 +00:00
|
|
|
token.scope = scope
|
|
|
|
|
|
|
|
return token
|