root / social / apps / pyramid_app / utils.py @ a0a04c0a
History | View | Annotate | Download (2.3 kB)
1 |
import warnings |
---|---|
2 |
|
3 |
from functools import wraps |
4 |
|
5 |
from pyramid.threadlocal import get_current_registry |
6 |
from pyramid.httpexceptions import HTTPNotFound, HTTPForbidden |
7 |
|
8 |
from social.utils import setting_name, module_member |
9 |
from social.strategies.utils import get_strategy |
10 |
from social.backends.utils import get_backend, user_backends_data |
11 |
|
12 |
|
13 |
DEFAULTS = { |
14 |
'STORAGE': 'social.apps.pyramid_app.models.PyramidStorage', |
15 |
'STRATEGY': 'social.strategies.pyramid_strategy.PyramidStrategy' |
16 |
} |
17 |
|
18 |
|
19 |
def get_helper(name): |
20 |
settings = get_current_registry().settings |
21 |
return settings.get(setting_name(name), DEFAULTS.get(name, None)) |
22 |
|
23 |
|
24 |
def load_strategy(): |
25 |
return get_strategy(get_helper('STRATEGY'), get_helper('STORAGE')) |
26 |
|
27 |
|
28 |
def load_backend(strategy, name, redirect_uri): |
29 |
backends = get_helper('AUTHENTICATION_BACKENDS')
|
30 |
Backend = get_backend(backends, name) |
31 |
return Backend(strategy=strategy, redirect_uri=redirect_uri)
|
32 |
|
33 |
|
34 |
def psa(redirect_uri=None): |
35 |
def decorator(func): |
36 |
@wraps(func)
|
37 |
def wrapper(request, *args, **kwargs): |
38 |
backend = request.matchdict.get('backend')
|
39 |
if not backend: |
40 |
return HTTPNotFound('Missing backend') |
41 |
|
42 |
uri = redirect_uri |
43 |
if uri and not uri.startswith('/'): |
44 |
uri = request.route_url(uri, backend=backend) |
45 |
|
46 |
request.strategy = load_strategy() |
47 |
request.backend = load_backend(request.strategy, backend, uri) |
48 |
return func(request, *args, **kwargs)
|
49 |
return wrapper
|
50 |
return decorator
|
51 |
|
52 |
|
53 |
def login_required(func): |
54 |
@wraps(func)
|
55 |
def wrapper(request, *args, **kwargs): |
56 |
is_logged_in = module_member( |
57 |
request.backend.setting('LOGGEDIN_FUNCTION')
|
58 |
) |
59 |
if not is_logged_in(request): |
60 |
raise HTTPForbidden('Not authorized user') |
61 |
return func(request, *args, **kwargs)
|
62 |
return wrapper
|
63 |
|
64 |
|
65 |
def backends(request, user): |
66 |
"""Load Social Auth current user data to context under the key 'backends'.
|
67 |
Will return the output of social.backends.utils.user_backends_data."""
|
68 |
storage = module_member(get_helper('STORAGE'))
|
69 |
return {
|
70 |
'backends': user_backends_data(
|
71 |
user, get_helper('AUTHENTICATION_BACKENDS'), storage
|
72 |
) |
73 |
} |
74 |
|
75 |
|
76 |
def strategy(*args, **kwargs): |
77 |
warnings.warn('@strategy decorator is deprecated, use @psa instead')
|
78 |
return psa(*args, **kwargs)
|