Skip to content

Commit

Permalink
add google auth to example
Browse files Browse the repository at this point in the history
  • Loading branch information
st4lk committed May 27, 2015
1 parent 59d770b commit ec64d00
Show file tree
Hide file tree
Showing 4 changed files with 73 additions and 30 deletions.
10 changes: 9 additions & 1 deletion example_project/config/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,16 +113,24 @@
}

# social auth settings
SOCIAL_AUTH_FACEBOOK_KEY = '295137440610143' # valid redirect domain for this app: restsocialexample.com
# valid redirect domain for all apps: http://restsocialexample.com:8000/
SOCIAL_AUTH_FACEBOOK_KEY = '295137440610143'
SOCIAL_AUTH_FACEBOOK_SECRET = '4b4aef291799a7b9aaf016689339e97f'
SOCIAL_AUTH_FACEBOOK_SCOPE = ['email', ]

SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '976099811367-ihbmg1pfnniln9qgfacleiu41bhl3fqn.apps.googleusercontent.com'
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'JaiLLvY1BK97TSy5_xcGWDhp'
SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = ['email', ]


AUTHENTICATION_BACKENDS = (
'social.backends.facebook.FacebookOAuth2',
'social.backends.google.GoogleOAuth2',
'django.contrib.auth.backends.ModelBackend',
)

SOCIAL_AUTH_PIPELINE = (
'users.social_pipeline.auto_logout', # custom action
'social.pipeline.social_auth.social_details',
'social.pipeline.social_auth.social_uid',
'social.pipeline.social_auth.auth_allowed',
Expand Down
72 changes: 49 additions & 23 deletions example_project/templates/home.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,14 @@
<h1>Django-rest-framework and OAuth 2.0 (facebook) example</h1>
<div>
<h4>rest_framework.authentication.SessionAuthentication</h4>
<div><button id="login_session">Login facebook</button></div>
<div><button id="login_session_facebook">Login facebook</button></div>
<div><button id="login_session_google">Login google</button></div>
<div><button id="logout_session">Logout</button></div>
</div>
<div>
<h4>rest_framework.authentication.TokenAuthentication</h4>
<div><button id="login_token">Login facebook</button></div>
<div><button id="login_token_facebook">Login facebook</button></div>
<div><button id="login_token_google">Login google</button></div>
<div><button id="logout_token">Logout</button></div>
</div>
<div>
Expand All @@ -42,7 +44,6 @@ <h3 id="user_data_header">User data</h3>
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');

function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
Expand All @@ -51,7 +52,7 @@ <h3 id="user_data_header">User data</h3>
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
}
});
Expand Down Expand Up @@ -79,17 +80,40 @@ <h3 id="user_data_header">User data</h3>
$("#user_data_header").html("User data");
}

$('#login_session').click(function(){
function loginUserSession(network, oauth_code){
$.ajax({
method: "POST",
url: "{% url 'login_social_session' %}",
data: {provider: network, code: oauth_code},
}).done(function( data ) {
showUser(data, 'session');
}).fail(function(error){
blankUser(''.concat('(', error.status, ', ', error.statusText, ')'));
});
}

function loginUserToken(network, oauth_code){
$.ajax({
method: "POST",
url: "{% url 'login_social_token_user' %}",
data: {provider: network, code: oauth_code},
}).done(function( data ) {
showUser(data, 'token');
localStorage.setItem('token', data.token);
});
}

$('#login_session_facebook').click(function(){
hello('facebook').login().then(function(auth) {
$.ajax({
method: "POST",
url: "{% url 'login_social_session' %}",
data: {provider: auth.network, code: auth.authResponse.code},
}).done(function( data ) {
showUser(data, 'session');
}).fail(function(error){
blankUser(''.concat('(', error.status, ', ', error.statusText, ')'));
});
loginUserSession('facebook', auth.authResponse.code);
}, function(e) {
alert('Signin error: ' + e.error.message);
});
});

$('#login_session_google').click(function(){
hello('google').login().then(function(auth) {
loginUserSession('google-oauth2', auth.authResponse.code);
}, function(e) {
alert('Signin error: ' + e.error.message);
});
Expand All @@ -103,16 +127,17 @@ <h3 id="user_data_header">User data</h3>
});
});

$('#login_token').click(function(){
$('#login_token_facebook').click(function(){
hello('facebook').login().then(function(auth) {
$.ajax({
method: "POST",
url: "{% url 'login_social_token_user' %}",
data: {provider: auth.network, code: auth.authResponse.code},
}).done(function( data ) {
showUser(data, 'token');
localStorage.setItem('token', data.token);
});
loginUserToken('facebook', auth.authResponse.code);
}, function(e) {
alert('Signin error: ' + e.error.message);
});
});

$('#login_token_google').click(function(){
hello('google').login().then(function(auth) {
loginUserToken('google-oauth2', auth.authResponse.code);
}, function(e) {
alert('Signin error: ' + e.error.message);
});
Expand Down Expand Up @@ -151,6 +176,7 @@ <h3 id="user_data_header">User data</h3>
hello.init(
{
facebook: 295137440610143,
google: '976099811367-ihbmg1pfnniln9qgfacleiu41bhl3fqn.apps.googleusercontent.com',
},
{
redirect_uri: 'http://restsocialexample.com:8000/',
Expand Down
20 changes: 15 additions & 5 deletions example_project/users/social_pipeline.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,25 @@
import hashlib


def auto_logout(*args, **kwargs):
"""Do not compare current user with new one"""
return {'user': None}


def save_avatar(strategy, details, user=None, *args, **kwargs):
"""Get user avatar from social provider."""
if user:
changed = False
backend_name = kwargs['backend'].__class__.__name__.lower()
response = kwargs.get('response', {})
social_thumb = None
if 'facebook' in backend_name:
if 'id' in response:
social_thumb = ("http://graph.facebook.com/{0}/picture?"
"type=normal").format(response['id'])
if user.social_thumb != social_thumb:
user.social_thumb = social_thumb
changed = True
if changed:
else:
social_thumb = "http://www.gravatar.com/avatar/"
social_thumb += hashlib.md5(user.email.lower()).hexdigest()
social_thumb += "?size=100"
if social_thumb and user.social_thumb != social_thumb:
user.social_thumb = social_thumb
strategy.storage.user.changed(user)
1 change: 0 additions & 1 deletion example_project/users/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ def get(self, request, *args, **kwargs):

class LogoutSessionView(APIView):

@method_decorator(ensure_csrf_cookie)
def get(self, request, *args, **kwargs):
logout(request)
return Response(status=status.HTTP_204_NO_CONTENT)
Expand Down

0 comments on commit ec64d00

Please sign in to comment.