Skip to content

Instantly share code, notes, and snippets.

@flavioribeiro
Created July 23, 2011 16:03
Show Gist options
  • Save flavioribeiro/1101582 to your computer and use it in GitHub Desktop.
Save flavioribeiro/1101582 to your computer and use it in GitHub Desktop.
#encoding: utf-8
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect, HttpResponse
from clickemgrupo import settings
import cgi
import simplejson as json
import oauth2 as oauth
from clickemgrupo.apps.user import models as user_models
from clickemgrupo.apps.shopping_cart import models as shoppingcart_models
from clickemgrupo.apps.deal import models as deal_models
from datetime import datetime
request_token_url = "http://stage.saveblock.com/login/oauth/request_token/?oauth_callback=http://localhost:8000/sauthorize"
access_token_url = 'http://stage.saveblock.com/login/oauth/access_token/'
authorize_url = "http://stage.saveblock.com/login/oauth/authorize/"
consumer = oauth.Consumer(settings.SAVEBLOCK_KEY, settings.SAVEBLOCK_SECRET)
client = oauth.Client(consumer)
'''
User Info Example:
{'profile': [{'city': u'Jo\xe3o Pessoa', 'neighborhood': 'Bessa', 'facebook_profile': '', 'orkut_profile': '', 'zipcode': '58035-040', 'sex': 'M', 'twitter_profile': '', 'phone': '', 'state': 'PB', 'about_me': 'husahufsahufsa uhsahusafhua', 'created_on': '2011-04-02T17:25:57.730374', 'address': 'Rua aasaas a', 'updated_on': '2011-04-26T11:40:55.935414', 'id': 3}], 'username': 'flavioribeiro', 'first_name': '', 'last_name': u'Fl\xe1vio', 'id': 5, 'avatar': [{'image_medium': '/static/user_avatar/medium/2011/04/13/3-medium.jpg', 'image_small': '/static/user_avatar/small/2011/04/13/3-small.jpg', 'image_big': '/static/user_avatar/big/2011/04/13/3-big.jpg', 'created_on': '2011-04-13T17:43:35.183652', 'updated_on': '2011-04-13T17:43:35.680972', 'id': 3}], 'email': '[email protected]', 'date_joined': '2011-04-02T17:25:41.324497'}
'''
def login(request, *args):
resp, content = client.request(request_token_url, "GET")
if resp['status'] != '200':
raise Exception("Invalid response from Saveblock")
request.session['request_token'] = dict(cgi.parse_qsl(content))
url = "%s?oauth_token=%s" % (authorize_url,
request.session['request_token']['oauth_token'])
return HttpResponseRedirect(url)
def authorize(request, *args):
token = oauth.Token(request.session['request_token']['oauth_token'],\
request.session['request_token']['oauth_token_secret'])
token.set_verifier(request.GET.get("oauth_verifier"))
client = oauth.Client(consumer, token)
resp, content = client.request(access_token_url, "GET")
if resp['status'] != '200':
raise Exception("Invalid response from Saveblock: " + resp['status'])
access_token = dict(cgi.parse_qsl(content))
token = oauth.Token(access_token['oauth_token'], access_token['oauth_token_secret'])
client = oauth.Client(consumer, token)
resp, content = client.request("http://stage.saveblock.com/api/users/myuser/", "GET")
if resp['status'] != '200':
raise Exception("Invalid response from Saveblock: " + resp['status'])
content = json.loads(content)
user_infos = content[0]
request.session['logged'] = True
request.session['user_infos'] = user_infos
create_new_user(user_infos)
return HttpResponseRedirect("/")
def create_new_user(infos):
user = user_models.InternalUser.objects.filter(name=infos['username'])
if not user:
new_user = user_models.InternalUser()
new_user.name = str(infos['username'])
new_user.saveblock_id = int(infos['id'])
new_user.avatar_icon_url = str(infos['avatar'][0]['image_small'])
new_user.save()
def confirm_buy(request, *args):
deal_id = request.GET['item_id']
user_saveblock_id = request.session['user_infos']['id']
new_buy = shoppingcart_models.Buy()
new_buy.deal = deal_models.Deal.objects.get(id=deal_id)
new_buy.owner = user_models.InternalUser.objects.get(saveblock_id=user_saveblock_id)
new_buy.date = datetime.now()
new_buy.save()
return HttpResponseRedirect("/")
def logout(request, *args):
try:
del request.session['logged']
del request.session['user_infos']
except:
pass
return HttpResponseRedirect("/")
def index(request, *args):
'''
View responsável por mapear o usuário e o Clickemgrupo da sua cidade.
Se o clickemgrupo ainda não estiver funcionando na cidade, ele apontará
pra uma cidade default
'''
DEFAULT_CITY = "João Pessoa"
#Se a cidade estiver na URL
if 'city' in request.path:
try:
city_obj = get_city_object_from_url(request.path.split('/')[-1])
return render_to_response('index.html', {'city': city_obj}, context_instance=RequestContext(request))
except:
city_obj = get_city_object_from_name(DEFAULT_CITY)
return HttpResponseRedirect("/city" + city_obj.url)
#Se não tiver nenhuma cidade na URL, e o usuario estiver logado no Saveblock
city = get_user_city(request)
if city:
try:
city_obj = get_city_object_from_name(city)
except:
city_obj = get_city_object_from_name(DEFAULT_CITY)
#Se não tiver nenhuma cidade na URL e nem o usuario estiver logado no Saveblock
else:
city_obj = get_city_object_from_name(DEFAULT_CITY)
return HttpResponseRedirect("/city" + city_obj.url)
def get_city_object_from_name(city_name):
return deal_models.City.objects.get(name=city_name)
def get_city_object_from_url(city_url):
return deal_models.City.objects.get(url="/" + city_url)
def get_user_city(request):
if request.session.has_key('user_infos'):
user_infos = request.session['user_infos']
if user_infos['profile'][0]['city']:
return user_infos['profile'][0]['city']
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment