i had a problem when i was try to make the auto logout in odoo 10. I was created change password page, after change password, i want end session and back to login page again. But the result never land me to teh login page. Here my code :
#api.model
def create(self, vals):
res = super(MyPass, self).create(vals)
get_new_passwd = vals['new_password']
get_conf_passwd = vals['confirm_pwd']
if get_conf_passwd != get_new_passwd:
raise ValidationError ("Pass")
hashing_pass = CryptContext(['pbkdf2_sha512']).encrypt(get_new_passwd)
data_users = self.env['res.users'].browse(self.env.uid)
data_users.write({'password_crypt': hashing_pass})
request.session.logout(keep_db=True
I found the solution.
def check(self, **kw):
get_re_users = request.env.user
error = {}
if get_re_users.passwd_changed:
return werkzeug.utils.redirect('/web')
else:
if request.httprequest.method == 'POST':
get_new_passwd = http.request.params['new_password']
get_conf_passwd = http.request.params['confirm_pwd']
session = http.request.session
hashing_pass = CryptContext(['pbkdf2_sha512']).encrypt(get_new_passwd)
data_users = http.request.env['res.users'].sudo().browse(http.request.env.uid)
data_users.write({'password_crypt': hashing_pass, "passwd_changed":True, "name":get_username_odoo, "login":get_name_login})
if session.db and session.uid:
session.logout(keep_db=True)
# return {
# 'type' : 'ir.actions.act_url',
# 'url': '/web',
# 'target': 'self',
# }
return werkzeug.utils.redirect('/web/login')
return http.request.render('name_model.id_view')
Related
I have written a code for registration and login in django. While doing login, I am getting the error "Invalid salt"
Following is the code:
#api_view(['POST'])
def login(request):
email = request.data.get('email')
mobile_number = request.data.get('mobile_number')
pin = request.data.get('pin')
res = dict()
print(dict, "dictonaryyyyyy")
if email != None:
email_result = Users.objects.filter(email= email).first()
print(email_result.pin, "emaillll")
if email_result != None:
if bcrypt.checkpw(pin.encode("utf-8"), email_result.pin.encode('utf-8')):
# if bcrypt.checkpw(pin, )
print("........")
payload_data = dict()
payload_data['email'] = email_result.email
token = generate_token(payload_data)
print(token, "token.........")
res['messages'] = "Authentication Successful"
res['status'] = 200,
res['token'] = token
return Response(res, status = status.HTTP_200_OK)
...
...
How to get rid of this error?
It got solved, the hashed password was being saved as a binary instead of string at the time of registrattion.
To convert it into a string, the pin is required to be decoded at the time of creating the object.
pin = pin.decode('utf-8'),
i am making a django website with multiple forms also used foregin key(user_id) to link one form with other in the database but at the last i get value error the error is:Exception Type: ValueError
Exception Value:
The view Capp.views.InsertProduct didn't return an HttpResponse object. It returned None insteated ,
the following is view.py file code(not complete code but only where error can lie)models.py part
def InsertProduct(request):
if request.method == 'POST':
if request.POST.get('user_id') and request.POST.get('pname') and request.POST.get('pcategory') and request.POST.get('pdetails') and request.POST.get('foundedin') and request.POST.get('orderoftest') and request.POST.get('t1') and request.POST.get('t2') and request.POST.get('t3') and request.POST.get('f1') and request.POST.get('f2') and request.POST.get('f3') and request.POST.get('f4') and request.POST.get('f5'):
saveproduct = ProInsert()
saveproduct.user_id = request.POST.get('user_id')
saveproduct.pname = request.POST.get('pname')
saveproduct.pcategory = request.POST.get('pcategory')
saveproduct.pdetails = request.POST.get('pdetails')
saveproduct.foundedin = request.POST.get('foundedin')
saveproduct.orderoftest = request.POST.get('orderoftest')
saveproduct.t1 = request.POST.get('t1')
saveproduct.t2 = request.POST.get('t2')
saveproduct.t3 = request.POST.get('t3')
saveproduct.f1 = request.POST.get('f1')
saveproduct.f2 = request.POST.get('f2')
saveproduct.f3 = request.POST.get('f3')
saveproduct.f4 = request.POST.get('f4')
saveproduct.f5 = request.POST.get('f5')
checkpname = ProInsert.objects.filter(
pname=saveproduct.pname).first()
return render(request, 'product_details.html')#here I had add what u said sir
if checkpname:
msgpname = messages.success(request, 'The user with Product Name ' +
request.POST['pname']+' already exist...!')
return render(request, 'product_details.html', {'msgpname': msgpname})
saveproduct.save()
messages.success(request, 'Product Added..!')
return render(request, 'product_details.html')
else:
return render(request, 'product_details.html')
I think you got it wrong I have update your code and commented the part i was telling you.
def InsertProduct(request):
if request.method == 'POST':
if request.POST.get('user_id') and request.POST.get('pname') and request.POST.get('pcategory') and request.POST.get('pdetails') and request.POST.get('foundedin') and request.POST.get('orderoftest') and request.POST.get('t1') and request.POST.get('t2') and request.POST.get('t3') and request.POST.get('f1') and request.POST.get('f2') and request.POST.get('f3') and request.POST.get('f4') and request.POST.get('f5'):
saveproduct = ProInsert()
saveproduct.user_id = request.POST.get('user_id')
saveproduct.pname = request.POST.get('pname')
saveproduct.pcategory = request.POST.get('pcategory')
saveproduct.pdetails = request.POST.get('pdetails')
saveproduct.foundedin = request.POST.get('foundedin')
saveproduct.orderoftest = request.POST.get('orderoftest')
saveproduct.t1 = request.POST.get('t1')
saveproduct.t2 = request.POST.get('t2')
saveproduct.t3 = request.POST.get('t3')
saveproduct.f1 = request.POST.get('f1')
saveproduct.f2 = request.POST.get('f2')
saveproduct.f3 = request.POST.get('f3')
saveproduct.f4 = request.POST.get('f4')
saveproduct.f5 = request.POST.get('f5')
checkpname = ProInsert.objects.filter(
pname=saveproduct.pname).first()
# return render(request, 'product_details.html')# NO need to add here as code below will be dead in this case.
if checkpname:
msgpname = messages.success(request, 'The user with Product Name ' +
request.POST['pname']+' already exist...!')
return render(request, 'product_details.html', {'msgpname': msgpname})
saveproduct.save()
messages.success(request, 'Product Added..!')
return render(request, 'product_details.html')
else:
return render(request, 'product_details.html')# What i meant was to add it here
else:
return render(request, 'product_details.html')
I'm new in django developpemnt , in my view i have some elif conditions that mastring some functions, in execution on the last condition i have this issue :
The view Expéditions.views.changelisteexpédition didn't return an HttpResponse object. It returned None instead.
def changelisteexpédition(request,id=id):
if "Editer" in request.POST:
.......
elif "Bloquer" in request.POST :
.......
elif "Supprimer" in request.POST:
.......
elif "Annuler" in request.POST:
.......
elif "Débloquer" in request.POST :
.......
elif "Top Départ" in request.POST :
trsp = transporteur.objects.all().order_by('id')
obj = get_object_or_404(Expédition,id=request.POST.get("choix"))
form = TopdépartForm(request.POST)
if form.is_valid():
Topdépart.objects.create(
Expédition = obj,
transporteur = request.POST.get("transporteur"),
chauffeur = request.POST.get("chauffeur"),
bl = request.POST.get("bl"),
plomb = request.POST.get("plomb"),
commentaire = request.POST.get("commentaire"),
date = request.POST.get("date"),
immatriculation = request.POST.get("immatriculation")
)
obj.statut = "Expédié"
obj.transporteur = request.POST.get("transporteur")
obj.chauffeur = request.POST.get("chauffeur")
obj.immatriculation = request.POST.get("immatriculation")
obj.save()
a = Commande.objects.get(numcommande=obj.numcommande)
a.quantitélivrée = obj.quantitélivrée
a.statut = "Expédié"
a.save()
j = Ligneexpédition.objects.filter(numcommande=obj.numcommande)
for i in j :
c = Articles.objects.get(sku=i.sku)
c.stockexpedié = c.stockexpedié + i.quantitélivrée
c.save()
return HttpResponseRedirect("asnintransit")
else :
form = TopdépartForm()
context = {
'form':form,`enter code here`
'obj':obj,
'trsp':trsp
}
return render(request,'topdépart.html',context)
I need some help.
Thanks.
In this part:
else:
form = TopdépartForm()
You are not returning a render() method, so basically I'm telling you to indent the last portion of your code like this:
else :
form = TopdépartForm()
context = {
'form':form,`enter code here`
'obj':obj,
'trsp':trsp
}
return render(request,'topdépart.html',context)
I'm 90% confident it will make your code work, if not, reach again I'll try to replicate
I have a funny and strange bug in my facebook for websites. When I log a user in with facebook, as a user I must press reload to get the user data from the cookie. Otherwise the cookie doesn't find a user. If I press reload once after login and reload once after logout I can login and logout but that indicates I've been doing something wrong. Could you help my find the bug?
I used the code from https://gist.github.com/1190267 and tried logging the cookie lookup and it doesn't find a user first time:
def get_user_from_cookie(cookies, app_id, app_secret):
"""Parses the cookie set by the official Facebook JavaScript SDK.
cookies should be a dictionary-like object mapping cookie names to
cookie values.
If the user is logged in via Facebook, we return a dictionary with the
keys "uid" and "access_token". The former is the user's Facebook ID,
and the latter can be used to make authenticated requests to the Graph API.
If the user is not logged in, we return None.
Download the official Facebook JavaScript SDK at
http://github.com/facebook/connect-js/. Read more about Facebook
authentication at http://developers.facebook.com/docs/authentication/.
"""
logging.debug('getting user from cookie')
cookie = cookies.get("fbsr_" + app_id, "")
if not cookie:
logging.debug('no cookie found')
return None
The login URL I use is
https://www.facebook.com/dialog/oauth?client_id=164355773607006&redirect_uri=http://www.koolbusiness.com
and logging a login scenario doesn't get the cookie until a reload:
"GET /?code=AQB9sh9RWdZsUC_TBWFHLOnOKehjk2ls6kN1ZzCBQRFa6s2ra58e5slaBSI8lYwC5q9Q_f524nsrF-Ts-mgxAHc9xIvt3U7rufKlfJuNfkRbGwgPWZZLCYCwnWHPdb00ANd8QOHB_bYMaI-R_mdI3nQW6bRvpD0DR-SOW-jSvhS8bel4_KlzaBFY3DnYNvxhJgY HTTP/1.1" 200 6248 - "Mozilla/5.0 (X11; Linux x86_64; rv:2.0) Gecko/20100101 Firefox/4.0" "www.koolbusiness.com" ms=80 cpu_ms=0 api_cpu_ms=0 cpm_usd=0.000777 instance=00c61b117c460a7d3f730b42451a4153b74e
D 2011-11-22 07:36:28.182
getting user from cookie
D 2011-11-22 07:36:28.183
no cookie found
Why? Similarly when I try to log out I must do it twice and I can't see where the bug is. I've been trying to use as much serverside I can and I suspect that my problem is handling the cookie. Can you tell me what to do? My function to set the cookie is:
def set_cookie(self, name, value, expires=None):
if value is None:
value = 'deleted'
expires = datetime.timedelta(minutes=-50000)
jar = Cookie.SimpleCookie()
jar[name] = value
jar[name]['path'] = '/'
if expires:
if isinstance(expires, datetime.timedelta):
expires = datetime.datetime.now() + expires
if isinstance(expires, datetime.datetime):
expires = expires.strftime('%a, %d %b %Y %H:%M:%S')
jar[name]['expires'] = expires
self.response.headers.add_header(*jar.output().split(': ', 1))
And here are 2 classes that should do it for me. As I said, everything works if I reload which is very strange tht the cookie is not set after a facebook login and that the cookie is set just by reloading my index pge after an FB login.
Thank you
class BaseHandler(webapp2.RequestHandler):
facebook = None
user = None
csrf_protect = True
#property
def current_user(self):
if not hasattr(self, "_current_user"):
self._current_user = None
cookie = facebook.get_user_from_cookie(
self.request.cookies, facebookconf.FACEBOOK_APP_ID, facebookconf.FACEBOOK_APP_SECRET)
logging.debug("logging cookie"+str(cookie))
if cookie:
# Store a local instance of the user data so we don't need
# a round-trip to Facebook on every request
user = FBUser.get_by_key_name(cookie["uid"])
logging.debug("user "+str(user))
if not user:
graph = facebook.GraphAPI(cookie["access_token"])
profile = graph.get_object("me")
user = FBUser(key_name=str(profile["id"]),
id=str(profile["id"]),
name=profile["name"],
profile_url=profile["link"],
access_token=cookie["access_token"])
user.put()
elif user.access_token != cookie["access_token"]:
user.access_token = cookie["access_token"]
user.put()
self._current_user = user
return self._current_user
#property
def current_sender(self):
if not hasattr(self, "_current_sender"):
self._current_sender = None
host=os.environ.get('HTTP_HOST', os.environ['SERVER_NAME'])
if host.find('.br') > 0:
sender = 'info#montao.com.br'
else:
sender = 'admin#koolbusiness.com'
self._current_sender = sender
return self._current_sender
#property
def current_logo(self):
if not hasattr(self, "_current_logo"):
self._current_logo = None
self._current_logo = os.environ.get('HTTP_HOST', os.environ['SERVER_NAME'])
return self._current_logo
def initialize(self, request, response):
"""General initialization for every request"""
super(BaseHandler, self).initialize(request, response)
try:
self.init_facebook()
self.init_csrf()
self.response.headers['P3P'] = 'CP=HONK' # iframe cookies in IE
except Exception, ex:
self.log_exception(ex)
raise
def handle_exception(self, ex, debug_mode):
"""Invoked for unhandled exceptions by webapp"""
self.log_exception(ex)
self.render('error',
trace=traceback.format_exc(), debug_mode=debug_mode)
def log_exception(self, ex):
"""Internal logging handler to reduce some App Engine noise in errors"""
msg = ((str(ex) or ex.__class__.__name__) +
': \n' + traceback.format_exc())
if isinstance(ex, urlfetch.DownloadError) or \
isinstance(ex, DeadlineExceededError) or \
isinstance(ex, CsrfException) or \
isinstance(ex, taskqueue.TransientError):
logging.warn(msg)
else:
logging.error(msg)
def set_cookie(self, name, value, expires=None):
if value is None:
value = 'deleted'
expires = datetime.timedelta(minutes=-50000)
jar = Cookie.SimpleCookie()
jar[name] = value
jar[name]['path'] = '/'
if expires:
if isinstance(expires, datetime.timedelta):
expires = datetime.datetime.now() + expires
if isinstance(expires, datetime.datetime):
expires = expires.strftime('%a, %d %b %Y %H:%M:%S')
jar[name]['expires'] = expires
self.response.headers.add_header(*jar.output().split(': ', 1))
def render_jinja(self, name, **data):
logo = 'Koolbusiness.com'
logo_url = '/_/img/kool_business.png'
analytics = 'UA-3492973-18'
domain = 'koolbusiness'
if get_host().find('.br') > 0:
cookie_django_language = 'pt-br'
logo = 'Montao.com.br'
logo_url = '/_/img/montao_small.gif'
analytics = 'UA-637933-12'
domain = None
elif get_host().find('allt') > 0 and not self.request.get('hl'):
logo = ''
cookie_django_language = 'sv'
elif get_host().find('gralumo') > 0 \
and not self.request.get('hl'):
cookie_django_language = 'es_AR'
else:
cookie_django_language = self.request.get('hl', '')
if cookie_django_language:
if cookie_django_language == 'unset':
del self.request.COOKIES['django_language']
else:
self.set_cookie('django_language', cookie_django_language)
translation.activate(cookie_django_language)
"""Render a Jinja2 template"""
if not data:
data = {}
data['js_conf'] = json.dumps({
'appId': facebookconf.FACEBOOK_APP_ID,
'canvasName': facebookconf.FACEBOOK_CANVAS_NAME,
'userIdOnServer': self.user.id if self.user else None,
})
data['logged_in_user'] = self.user
data['message'] = self.get_message()
data['csrf_token'] = self.csrf_token
data['canvas_name'] = facebookconf.FACEBOOK_CANVAS_NAME
data['current_user']=self.current_user
gkeys = ''
if os.environ.get('HTTP_HOST'):
url = os.environ['HTTP_HOST']
else:
url = os.environ['SERVER_NAME']
data['user']=users.get_current_user()
data['facebook_app_id']=facebookconf.FACEBOOK_APP_ID
user = users.get_current_user()
data['logout_url']=users.create_logout_url(self.request.uri) if users.get_current_user() else 'https://www.facebook.com/dialog/oauth?client_id='+facebookconf.FACEBOOK_APP_ID+'&redirect_uri='+self.request.uri
host=os.environ.get('HTTP_HOST', os.environ['SERVER_NAME'])
data['host']=host
if host.find('.br') > 0:
logo = 'Montao.com.br'
logo_url = '/_/img/montao_small.gif'
analytics = 'UA-637933-12'
domain = None
else:
logo = 'Koolbusiness.com'
logo_url = '/_/img/kool_business.png'
analytics = 'UA-3492973-18'
domain = 'koolbusiness'
data['domain']=domain
data['analytics']=analytics
data['logo']=logo
data['logo_url']=logo_url
data['admin']=users.is_current_user_admin()
if user:
data['greeting'] = ("Welcome, %s! (sign out)" %
(user.nickname(), users.create_logout_url("/")))
template = jinja_environment.get_template('templates/'+name+'.html')
self.response.out.write(template.render(data))
"""
self.response.out.write(template.render(
os.path.join(
os.path.dirname(__file__), 'templates', name + '.html'),
data))
"""
def render(self, name, **data):
logo = 'Koolbusiness.com'
logo_url = '/_/img/kool_business.png'
analytics = 'UA-3492973-18'
domain = 'koolbusiness'
if get_host().find('.br') > 0:
cookie_django_language = 'pt-br'
logo = 'Montao.com.br'
logo_url = '/_/img/montao_small.gif'
analytics = 'UA-637933-12'
domain = None
elif get_host().find('allt') > 0 and not self.request.get('hl'):
logo = ''
cookie_django_language = 'sv'
elif get_host().find('gralumo') > 0 \
and not self.request.get('hl'):
cookie_django_language = 'es_AR'
else:
cookie_django_language = self.request.get('hl', '')
if cookie_django_language:
if cookie_django_language == 'unset':
del self.request.COOKIES['django_language']
else:
self.set_cookie('django_language', cookie_django_language)
translation.activate(cookie_django_language)
"""Render a template"""
if not data:
data = {}
data['js_conf'] = json.dumps({
'appId': facebookconf.FACEBOOK_APP_ID,
'canvasName': facebookconf.FACEBOOK_CANVAS_NAME,
'userIdOnServer': self.user.id if self.user else None,
})
data['logged_in_user'] = self.user
data['message'] = self.get_message()
data['csrf_token'] = self.csrf_token
data['canvas_name'] = facebookconf.FACEBOOK_CANVAS_NAME
data['current_user']=self.current_user
data['user']=users.get_current_user()
data['facebook_app_id']=facebookconf.FACEBOOK_APP_ID
user = users.get_current_user()
data['logout_url']=users.create_logout_url(self.request.uri) if users.get_current_user() else 'https://www.facebook.com/dialog/oauth?client_id='+facebookconf.FACEBOOK_APP_ID+'&redirect_uri='+self.request.uri
host=os.environ.get('HTTP_HOST', os.environ['SERVER_NAME'])
data['host']=host
if not host.find('.br') > 0:
logo = 'Koolbusiness.com'
logo_url = '/_/img/kool_business.png'
analytics = 'UA-3492973-18'
domain = 'koolbusiness'
data['domain']=domain
data['analytics']=analytics
data['logo']=logo
data['logo_url']=logo_url
data['admin']=users.is_current_user_admin()
if user:
data['greeting'] = ("Welcome, %s! (sign out)" %
(user.nickname(), users.create_logout_url("/")))
gkeys = ''
if os.environ.get('HTTP_HOST'):
url = os.environ['HTTP_HOST']
else:
url = os.environ['SERVER_NAME']
self.response.out.write(template.render(
os.path.join(
os.path.dirname(__file__), 'templates', name + '.html'),
data))
def init_facebook(self):
facebook = Facebook()
user = None
# initial facebook request comes in as a POST with a signed_request
if 'signed_request' in self.request.POST:
facebook.load_signed_request(self.request.get('signed_request'))
# we reset the method to GET because a request from facebook with a
# signed_request uses POST for security reasons, despite it
# actually being a GET. in webapp causes loss of request.POST data.
self.request.method = 'GET'
#self.set_cookie(
#'', facebook.user_cookie, datetime.timedelta(minutes=1440))
elif 'u' in self.request.cookies:
facebook.load_signed_request(self.request.cookies.get('u'))
# try to load or create a user object
if facebook.user_id:
user = FBUser.get_by_key_name(facebook.user_id)
if user:
# update stored access_token
if facebook.access_token and \
facebook.access_token != user.access_token:
user.access_token = facebook.access_token
user.put()
# refresh data if we failed in doing so after a realtime ping
if user.dirty:
user.refresh_data()
# restore stored access_token if necessary
if not facebook.access_token:
facebook.access_token = user.access_token
if not user and facebook.access_token:
me = facebook.api('/me', {'fields': _USER_FIELDS})
try:
friends = [user['id'] for user in me['friends']['data']]
user = FBUser(key_name=facebook.user_id,
id=facebook.user_id, friends=friends,
access_token=facebook.access_token, name=me['name'],
email=me.get('email'), picture=me['picture'])
user.put()
except KeyError, ex:
pass # ignore if can't get the minimum fields
self.facebook = facebook
self.user = user
def init_csrf(self):
"""Issue and handle CSRF token as necessary"""
self.csrf_token = self.request.cookies.get('c')
if not self.csrf_token:
self.csrf_token = str(uuid4())[:8]
self.set_cookie('c', self.csrf_token)
if self.request.method == 'POST' and self.csrf_protect and \
self.csrf_token != self.request.get('_csrf_token'):
raise CsrfException('Missing or invalid CSRF token.')
def set_message(self, **obj):
"""Simple message support"""
self.set_cookie('m', base64.b64encode(json.dumps(obj)) if obj else None)
def get_message(self):
"""Get and clear the current message"""
message = self.request.cookies.get('m')
if message:
self.set_message() # clear the current cookie
return json.loads(base64.b64decode(message))
class Facebook(object):
"""Wraps the Facebook specific logic"""
def __init__(self, app_id=facebookconf.FACEBOOK_APP_ID,
app_secret=facebookconf.FACEBOOK_APP_SECRET):
self.app_id = app_id
self.app_secret = app_secret
self.user_id = None
self.access_token = None
self.signed_request = {}
def api(self, path, params=None, method='GET', domain='graph'):
"""Make API calls"""
if not params:
params = {}
params['method'] = method
if 'access_token' not in params and self.access_token:
params['access_token'] = self.access_token
result = json.loads(urlfetch.fetch(
url='https://' + domain + '.facebook.com' + path,
payload=urllib.urlencode(params),
method=urlfetch.POST,
headers={
'Content-Type': 'application/x-www-form-urlencoded'})
.content)
if isinstance(result, dict) and 'error' in result:
raise FacebookApiError(result)
return result
def load_signed_request(self, signed_request):
"""Load the user state from a signed_request value"""
try:
sig, payload = signed_request.split('.', 1)
sig = self.base64_url_decode(sig)
data = json.loads(self.base64_url_decode(payload))
expected_sig = hmac.new(
self.app_secret, msg=payload, digestmod=hashlib.sha256).digest()
# allow the signed_request to function for upto 1 day
if sig == expected_sig and \
data['issued_at'] > (time.time() - 86400):
self.signed_request = data
self.user_id = data.get('user_id')
self.access_token = data.get('oauth_token')
except ValueError, ex:
pass # ignore if can't split on dot
#property
def user_cookie(self):
"""Generate a signed_request value based on current state"""
if not self.user_id:
return
payload = self.base64_url_encode(json.dumps({
'user_id': self.user_id,
'issued_at': str(int(time.time())),
}))
sig = self.base64_url_encode(hmac.new(
self.app_secret, msg=payload, digestmod=hashlib.sha256).digest())
return sig + '.' + payload
#staticmethod
def base64_url_decode(data):
data = data.encode('ascii')
data += '=' * (4 - (len(data) % 4))
return base64.urlsafe_b64decode(data)
#staticmethod
def base64_url_encode(data):
return base64.urlsafe_b64encode(data).rstrip('=')
Solution: Avoid javascript, avoid cookies and use serverside OAuth 2.0 and it is much easier to follow what is going on and this works:
class FBUser(db.Model):
id = db.StringProperty(required=True)
created = db.DateTimeProperty(auto_now_add=True)
updated = db.DateTimeProperty(auto_now=True)
name = db.StringProperty(required=True)
profile_url = db.StringProperty()
access_token = db.StringProperty(required=True)
name = db.StringProperty(required=True)
picture = db.StringProperty()
email = db.StringProperty()
friends = db.StringListProperty()
dirty = db.BooleanProperty()
class I18NPage(I18NHandler):
def get(self):
if self.request.get('code'):
args = dict(
code = self.request.get('code'),
client_id = facebookconf.FACEBOOK_APP_ID,
client_secret = facebookconf.FACEBOOK_APP_SECRET,
redirect_uri = 'http://www.koolbusiness.com/',
)
logging.debug("client_id"+str(args))
file = urllib.urlopen("https://graph.facebook.com/oauth/access_token?" + urllib.urlencode(args))
try:
logging.debug("reading file")
token_response = file.read()
logging.debug("read file"+str(token_response))
finally:
file.close()
access_token = cgi.parse_qs(token_response)["access_token"][-1]
graph = main.GraphAPI(access_token)
user = graph.get_object("me") #write the access_token to the datastore
fbuser = main.FBUser.get_by_key_name(user["id"])
logging.debug("fbuser "+str(fbuser))
if not fbuser:
fbuser = main.FBUser(key_name=str(user["id"]),
id=str(user["id"]),
name=user["name"],
profile_url=user["link"],
access_token=access_token)
fbuser.put()
elif fbuser.access_token != access_token:
fbuser.access_token = access_token
fbuser.put()
I created a django application with a user login/registration page. I am trying to implement a facebook login also possible along with my django login. For doing so i was following this link : enter link description here. As the documentaion says, i have created a file called FaebookConnectMiddleware.py and put in settings.py folder; and changed the db name to my db name. Now the facebook log in works fine, but after it logs in, its redirected to that same page (django registration page,dats where i put FB login button).How can i redirect it to another page in my application. Can somebody help me to solve this. I will paste FacebookConnectMiddleware.py code here.
# FacebookConnectMiddleware.py
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.conf import settings
import md5
import urllib
import time
import simplejson
from datetime import datetime
# These values could be placed in Django's project settings
# More info here: http://nyquistrate.com/django/facebook-connect/
FACEBOOK_API_KEY = 'xxxxx'
FACEBOOK_SECRET_KEY = 'xxxx'
REST_SERVER = 'http://api.facebook.com/restserver.php'
# You can get your User ID here: http://developers.facebook.com/tools.php?api
MY_FACEBOOK_UID = 'xxx#gmail.com'
NOT_FRIEND_ERROR = 'You must be my Facebook friend to log in.'
PROBLEM_ERROR = 'There was a problem. Try again later.'
ACCOUNT_DISABLED_ERROR = 'Your account is not active.'
ACCOUNT_PROBLEM_ERROR = 'There is a problem with your account.'
class FacebookConnectMiddleware(object):
def process_request(self, request):
try:
# Set the facebook message to empty. This message can be used to dispaly info from the middleware on a Web page.
request.facebook_message = None
# Don't bother trying FB Connect login if the user is already logged in
if not request.user.is_authenticated():
# FB Connect will set a cookie with a key == FB App API Key if the user has been authenticated
if FACEBOOK_API_KEY in request.COOKIES:
signature_hash = self.get_facebook_signature(request.COOKIES, True)
# The hash of the values in the cookie to make sure they're not forged
if(signature_hash == request.COOKIES[FACEBOOK_API_KEY]):
# If session hasn't expired
if(datetime.fromtimestamp(float(request.COOKIES[FACEBOOK_API_KEY+'_expires'])) > datetime.now()):
# Make a request to FB REST(like) API to see if current user is my friend
are_friends_params = {
'method':'Friends.areFriends',
'api_key': FACEBOOK_API_KEY,
'session_key': request.COOKIES[FACEBOOK_API_KEY + '_session_key'],
'call_id': time.time(),
'v': '1.0',
'uids1': MY_FACEBOOK_UID,
'uids2': request.COOKIES[FACEBOOK_API_KEY + '_user'],
'format': 'json',
}
are_friends_hash = self.get_facebook_signature(are_friends_params)
are_friends_params['sig'] = are_friends_hash
are_friends_params = urllib.urlencode(are_friends_params)
are_friends_response = simplejson.load(urllib.urlopen(REST_SERVER, are_friends_params))
# If we are friends
if(are_friends_response[0]['are_friends'] is True):
try:
# Try to get Django account corresponding to friend
# Authenticate then login (or display disabled error message)
django_user = UniversityDetails.objects.get(username=request.COOKIES[FACEBOOK_API_KEY + '_user'])
user = authenticate(username=request.COOKIES[FACEBOOK_API_KEY + '_user'],
password=md5.new(request.COOKIES[FACEBOOK_API_KEY + '_user'] + settings.FACEBOOK_SECRET_KEY).hexdigest())
if user is not None:
if user.is_active:
login(request, user)
self.facebook_user_is_authenticated = True
else:
request.facebook_message = ACCOUNT_DISABLED_ERROR
self.delete_fb_cookies = True
else:
request.facebook_message = ACCOUNT_PROBLEM_ERROR
self.delete_fb_cookies = True
except User.DoesNotExist:
# There is no Django account for this Facebook user.
# Create one, then log the user in.
# Make request to FB API to get user's first and last name
user_info_params = {
'method': 'Users.getInfo',
'api_key': FACEBOOK_API_KEY,
'call_id': time.time(),
'v': '1.0',
'uids': request.COOKIES[FACEBOOK_API_KEY + '_user'],
'fields': 'first_name,last_name',
'format': 'json',
}
user_info_hash = self.get_facebook_signature(user_info_params)
user_info_params['sig'] = user_info_hash
user_info_params = urllib.urlencode(user_info_params)
user_info_response = simplejson.load(urllib.urlopen(REST_SERVER, user_info_params))
# Create user
user = UniversityDetails.objects.create_user(request.COOKIES[FACEBOOK_API_KEY + '_user'], '',
md5.new(request.COOKIES[FACEBOOK_API_KEY + '_user'] +
settings.SECRET_KEY).hexdigest())
user.first_name = user_info_response[0]['first_name']
user.last_name = user_info_response[0]['last_name']
user.save()
# Authenticate and log in (or display disabled error message)
user = authenticate(username=request.COOKIES[FACEBOOK_API_KEY + '_user'],
password=md5.new(request.COOKIES[FACEBOOK_API_KEY + '_user'] + settings.FACEBOOK_SECRET_KEY).hexdigest())
if user is not None:
if user.is_active:
login(request, user)
self.facebook_user_is_authenticated = True
else:
request.facebook_message = ACCOUNT_DISABLED_ERROR
self.delete_fb_cookies = True
else:
request.facebook_message = ACCOUNT_PROBLEM_ERROR
self.delete_fb_cookies = True
# Not my FB friend
else:
request.facebook_message = NOT_FRIEND_ERROR
self.delete_fb_cookies = True
# Cookie session expired
else:
logout(request)
self.delete_fb_cookies = True
# Cookie values don't match hash
else:
logout(request)
self.delete_fb_cookies = True
# Logged in
else:
# If FB Connect user
if FACEBOOK_API_KEY in request.COOKIES:
# IP hash cookie set
if 'fb_ip' in request.COOKIES:
try:
real_ip = request.META['HTTP_X_FORWARDED_FOR']
except KeyError:
real_ip = request.META['REMOTE_ADDR']
# If IP hash cookie is NOT correct
if request.COOKIES['fb_ip'] != md5.new(real_ip + FACEBOOK_SECRET_KEY + settings.FACEBOOK_SECRET_KEY).hexdigest():
logout(request)
self.delete_fb_cookies = True
# FB Connect user without hash cookie set
else:
logout(request)
self.delete_fb_cookies = True
# Something else happened. Make sure user doesn't have site access until problem is fixed.
except:
request.facebook_message = PROBLEM_ERROR
logout(request)
self.delete_fb_cookies = True
def process_response(self, request, response):
# Delete FB Connect cookies
# FB Connect JavaScript may add them back, but this will ensure they're deleted if they should be
if self.delete_fb_cookies is True:
response.delete_cookie(FACEBOOK_API_KEY + '_user')
response.delete_cookie(FACEBOOK_API_KEY + '_session_key')
response.delete_cookie(FACEBOOK_API_KEY + '_expires')
response.delete_cookie(FACEBOOK_API_KEY + '_ss')
response.delete_cookie(FACEBOOK_API_KEY)
response.delete_cookie('fbsetting_' + FACEBOOK_API_KEY)
self.delete_fb_cookies = False
if self.facebook_user_is_authenticated is True:
try:
real_ip = request.META['HTTP_X_FORWARDED_FOR']
except KeyError:
real_ip = request.META['REMOTE_ADDR']
response.set_cookie('fb_ip', md5.new(real_ip + FACEBOOK_SECRET_KEY + settings.FACEBOOK_SECRET_KEY).hexdigest())
# process_response() must always return a HttpResponse
return response
# Generates signatures for FB requests/cookies
def get_facebook_signature(self, values_dict, is_cookie_check=False):
signature_keys = []
for key in sorted(values_dict.keys()):
if (is_cookie_check and key.startswith(FACEBOOK_API_KEY + '_')):
signature_keys.append(key)
elif (is_cookie_check is False):
signature_keys.append(key)
if (is_cookie_check):
signature_string = ''.join(['%s=%s' % (x.replace(FACEBOOK_API_KEY + '_',''), values_dict[x]) for x in signature_keys])
else:
signature_string = ''.join(['%s=%s' % (x, values_dict[x]) for x in signature_keys])
signature_string = signature_string + FACEBOOK_SECRET_KEY
return md5.new(signature_string).hexdigest()
views These functions does the login/registration for the django application.
def registrationForm(request):
if request.method == "POST":
firstName = request.POST.get("firstName")
lastName = request.POST.get("lastName")
email = request.POST.get("email")
password = request.POST.get("password")
sex = request.POST.get("sex")
birthday = request.POST.get("birthday")
UniversityDetails(firstName=firstName,lastName=lastName,email=email,password=password,sex=sex,birthday=birthday).save()
send_mail('Email Verification', 'You have registered successfully', 'xx#gmail.com',
['xx#gmail.com'], fail_silently=False)
return render_to_response('login.html')
return render_to_response("registrationForm.html")
def login(request):
if request.POST:
#sessionObj = request.session['active_token']
# print sessionObj
email=request.POST.get("username")
password = request.POST.get("password")
user = UniversityDetails.objects.filter(email=email,password=password)
if(not user):
return render_to_response("registrationForm.html",{'invalid': True })
else:
return render_to_response("login.html")
return render_to_response("registrationForm.html")
registrationForm.html
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({
appId:'114322105313139', cookie:true,
status:true, xfbml:true
});
</script>
<fb:login-button perms="email,user_checkins" onlogin=”location.reload(false);">Login with Facebook</fb:login-button>
I think you just need to declare the variable at the top of your class as false
class FacebookConnectMiddleware(object):
facebook_user_is_authenticated = False