-
Notifications
You must be signed in to change notification settings - Fork 3
/
auth.py
103 lines (70 loc) · 2.67 KB
/
auth.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# Copyright (C) 2012 SCS srl <[email protected]>
""" This module contains all authentication related functions. It imports the authentication application basic
functionalities to create and validate the authentication tickets. """
import urllib2
try:
import json
except ImportError:
import simplejson as json
from functools import wraps
from flask import request, Response
MI_API_URL = "https://portal.vph-share.eu/api/"
def checkAuthentication(username, password):
""" This function is called to check if a username password combination is valid.
Arguments:
username (string): the user identifier
password (string): the user password
Returns:
boolean. True if the authentication check is successful, False otherwise
"""
# get the ticket
if getAuthTicket(username, password) is not None:
return True
return False
def getAuthTicket(username, password):
""" Returns the authentication ticket for given username.
Arguments:
secret (string): the secret key to be used to produce the authentication ticket
username (string): the username the ticket has to be produced for
Returns:
string. The authentication ticket as a string
"""
resp = urllib2.urlopen('%s/auth/user_login?domain=VPHSHARE&username=%s&password=%s' % (MI_API_URL, username, password))
ticket = resp.read()
if resp.code != 200:
return None
return ticket
def extractUserFromTicket(ticket):
""" Extracts the user dictionary from the given authentication ticket.
Arguments:
ticket (string): the authentication ticket
Returns:
dictionary. the extracted user attributes as a dictionary
"""
try:
resp = urllib2.urlopen('%s/validatetkt/?ticket=%s' % (MI_API_URL, ticket))
user_dict = json.loads(resp.read())
return user_dict
except BaseException, e:
pass
return None
def authenticate():
"""Sends a 401 response that enables basic auth"""
return Response(
'Could not verify your access level for that URL.\n'
'You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'})
def requiresAuthentication(f):
""" Function decorator. User must be logged in order to call the decorated method.
Arguments:
f (function): the function to be decorated
Returns:
function. Retursn the decorated function
"""
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not checkAuthentication(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated