Python bottle cookies issue on GAE - python

Am new to the bottle framework but we want to use it for a project which we are working on. This is the code causing the error. This is my full code in my file.
I can add the imported modules also if need arises
`
import model
import sessionDAO
import userDAO
import bottle
import re
import cgi
import logging
#bottle.route('/')
def index_page():
cookie = bottle.request.get_cookie('session',path='/')
username = sessions.get_username(cookie)
return bottle.template('blog_template', dict(username=username))
#bottle.get('/signup')
def signup():
return bottle.template('signup',dict(username="", password="",
password_error="",
email="", username_error="", email_error="",
verify_error =""))
#bottle.get('/login')
def login():
return bottle.template('login', dict(username='',password='', login_error=''))
#bottle.get('/welcome')
def welcome():
cookie = bottle.request.get_cookie('session',path='/')
username = sessions.get_username(cookie)
if username is None:
print "welcome cant verify/identify user, sending you to the signup page"
bottle.redirect('/signup')
return bottle.template('welcome',dict(username=username))
#bottle.get('/internal_error')
#bottle.view('error_template')
def internal_error():
return dict(error='System encountered a DB error ')
#bottle.get('/logout')
def logout():
cookie = bottle.request.get_cookie('session',path='/')
sessions.end_session(cookie)
bottle.response.set_cookie('session','', path='/')
bottle.redirect('/signup')
#bottle.post('/login')
def process_login():
username = bottle.request.forms.get('username')
password = bottle.request.forms.get('password')
print "user submitted ", username, "pass ", password
user_record = users.validate_login(username,password)
if user_record:
session_id = sessions.start_session(user_record.id)
if session_id is None:
print "internal error"
bottle.redirect('/internal_error')
cookie = session_id
bottle.response.set_cookie('session',cookie, path='/')
bottle.redirect('/welcome')
else:
return bottle.template('login', dict(username=cgi.escape(username),password="",login_error="Invalid Login"))
#bottle.post('/signup')
def register():
username = bottle.request.forms.get('username')
password = bottle.request.forms.get('password')
email = bottle.request.forms.get('email')
verify = bottle.request.forms.get('verify')
errors = {'username':username,'email':email}
if validate_signup(username,password,verify,email,errors):
if not users.add_user(username,password,email):
errors['username_error'] = "User already Exist"
return bottle.template('signup',errors)
session_id = sessions.start_session(username)
print session_id
bottle.response.set_cookie('session', session_id, path='/')
bottle.redirect('/welcome')
else:
print "User did not validate"
return bottle.template('signup',errors)
def validate_signup(username,password,verify,email,errors):
USER_RE = re.compile(r"^[a-zA-Z0-9_-]{3,20}$")
PASS_RE = re.compile(r"^.{6,20}$")
EMAIL_RE = re.compile(r"^[\S]+#[\S]+\.[\S]+$")
errors['username_error'] = ""
errors['password_error'] = ""
errors['verify_error'] = ""
errors['email_error'] = ""
if not USER_RE.match(str(username)):
errors['username_error'] = "Invalid username, try letters and numbers only"
return False
if not PASS_RE.match(str(password)):
errors['password_error'] = "Invalid password"
return False
if password != str(verify):
errors['verify_error'] = 'Password must match'
return False
if email != "":
if not EMAIL_RE.match(str(email)):
errors['email_error'] = 'Invalid email address'
return False
return True
#bottle.error(500)
def error500(error):
logging.debug(str(error))
print str(error)
bottle.redirect('/signup')
# return bottle.template('error_template',dict(error=str(error)))
user_data = model.User
session_data = model.Session
users = userDAO.UserDAO(user_data)
sessions = sessionDAO.SessionDAO(session_data)
app = bottle.app()
`
the set cookie is not working even if I remove the path args..

Related

How can I keep token from turning to None?

I am trying to follow along with a couple online tutorials for creating a reset password feature in my app. Both these tutorials use itsdangerous TimedJSONWebSignatureSerializer, which has since been deprecated, so I'm working with an older version of itsdangerous. Probably not best practice, I know.
The issue that I'm running into is that when I'm in the reset_token function and use verify_token(), its supposed to return the variable "email" to me, which I then save in "user". The reset_token function runs through the first time to bring up the html page and on this first run through, user = the email address, as it should. However, then when I hit "submit" on my reset password page, the code runs through a second time and then user = None, which therefore makes my query not work.
How do I make "email" not turn to None on the second run through of my code?
from flask import Flask, request, render_template, session, redirect, url_for
import mysql.connector
from flask_mail import Mail, Message
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
def get_token(user, expires_sec=600):
serial = Serializer(app.config['SECRET_KEY'], expires_in=expires_sec)
return serial.dumps({'user_id': user}).decode('utf-8')
def verify_token(token):
serial = Serializer(app.config['SECRET_KEY'])
try:
email = serial.loads(token)['user_id']
except:
return None
return email
def send_mail(email):
token = get_token(email)
msg = Message('Password Reset Request', recipients=[email], sender='censoring this :)')
msg.body = f'''
To reset your password, please follow the link below.
{url_for('reset_token', token=token, _external=True)}
If you did not request a password reset, please ignore this message.
'''
mail.send(msg)
#app.route('/password_reset', methods=['post', 'get'])
def password_reset():
error = None
success = None
def check(s):
email_format = r'\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
if re.match(email_format, s):
return True
else:
return False
if request.method == 'POST':
email = request.form.get('email')
if not check(email):
error = "*Invalid email"
else:
query = "SELECT * FROM users WHERE email = %s"
cursor.execute(query, (email,))
cursor.fetchall()
count_rows = cursor.rowcount
if count_rows < 1:
error = "*We do not have that email address on file."
else:
send_mail(email)
success = "*Reset request sent. Please check your email."
return render_template('password_reset.html', error=error, msg=success)
#app.route('/password_reset/<token>', methods=['get', 'post'])
def reset_token(token):
error = None
success = None
user = verify_token(token)
print(user)
if user is None:
error = "That token is either invalid or expired. Please try again."
return redirect(url_for('password_reset'))
if request.method == 'POST':
password = request.form.get('password')
password_2 = request.form.get('password_2')
if len(password) < 6:
error = "*Your password must have at least 6 characters."
elif password != password_2:
error = "*Passwords do not match."
else:
query = "UPDATE users SET password=%s WHERE email=%s"
cursor.execute(query, (password, user))
mydb.commit()
success = "Your password has been created!"
return render_template('change_password.html')

Why am I getting "Invalid salt" in django?

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'),

Why do I get a Key error when calling flask session?

I have a problem with users trying to register on my application (which is a Flask app deployed on Pythonanywhere with MongoDB Atlas).
Basically when they register they receive an email with a token that they need to click on to confirm. When they click on that link they should enter the application, but instead they receive an error.
When I check the error log, this is what I see (under "/auth/register") when it calls:
existing_user = User.get_by_email(session["email"])
return super(SecureCookieSession, self).__getitem__(key)
Exception KeyError: 'email' was thrown out.
It seems that somehow the session["email"] does not work?
This is my code:
#app.route('/confirm/<token>')
def confirm_email(token):
try:
email = ts.loads(token, salt="email-confirm-key", max_age=7200)
except:
return render_template("token_expired.html")
user = Database.find_one(collection="users", query={"email": email})
return redirect(url_for("register_user"))
#app.route("/auth/register", methods=["GET", "POST"])
def register_user():
existing_user = User.get_by_email(session["email"])
if existing_user is None:
email = session["email"].lower() # our website is making a request to our app
username = session["username"]
companyname = session["companyname"].lower()
password = session["password"].encode("utf-8")
hashed_password = bcrypt.hashpw(password, bcrypt.gensalt())
User.register(email, username, companyname, hashed_password)
session["companyname"] = companyname
excisting_company = Database.find_one(collection="companies", query={"email": session["email"]})
if excisting_company is None:
new_company = NewCompany(session["companyname"], session["email"])
new_company.company_save_to_mongo()
else:
return "A company has already been registered under your email address"
else:
return render_template("email_already_exists.html")
return redirect(url_for("user_results"))
#classmethod
def get_by_email(cls, email):
find_email = Database.find_one(collection="users", query={"email": email})
if find_email is not None:
return cls(email=find_email["email"], username=find_email["username"],
companyname=find_email["companyname"], hashed_password=find_email["password"],
date=find_email["date"], _id=find_email["_id"])
I cant seem to figure out why, as when I register myself it works just fine.
Your help would be greatly appreciated here, many thanks in advance.
UPDATE:
Here is where I set the session["email"]:
#app.route("/email_confirmation", methods=["GET", "POST"])
def confirmation():
email = request.form["email"].lower()
companyname = request.form["companyname"].lower()
password = request.form["password"]
username = request.form["username"]
session["password"] = password
session["email"] = email
session["companyname"] = companyname
session["username"] = username
existing_user = User.get_by_email(email)
if existing_user is None:
msg = Message("Confirm your email", sender=("hello#weliketalent.com"),
recipients=[email])
token = ts.dumps(email, salt="email-confirm-key")
confirm_url = url_for("confirm_email", token=token, _external=True)
msg.html = render_template("email/activate.html", confirm_url=confirm_url)
mail.send(msg)
The error is telling you that there is no "email" value in session object.
I don't see you setting this value anywhere in your code. How is it supposed to get there? Somebody needs to set it somewhere before this code runs.
In addition to that, you should design your code not to crash in such cases, as this could be a security vulnerability. You can use if "email" not in session for test.

Login and logout with web.py

I have a little problem with web.py. Exacly I have problem with sessions.
Link to my app:
http://len.iem.pw.edu.pl/~witkowr1/apps/demo/
Login/password: wtq/wtq
Code:
# -*- coding: utf-8 -*-
import web
import json
from web.contrib.template import render_jinja
import datetime
prefix = '/~witkowr1/apps/demo'
urls = (
prefix + '/login','Login',
prefix + '/logout','Logout',
prefix + '/', 'Index',
)
app = web.application(urls, globals())
wsgi = app.wsgifunc()
session = web.session.Session(app, web.session.DiskStore('sessions'),initializer={'time':datetime.datetime.now()})
render = render_jinja('static', encoding = 'utf-8')
render._lookup.globals.update(assets=prefix+'/static')
class Login:
def GET(self):
web.seeother(prefix+'/')
def POST(self):
login = web.input().login
password = web.input().passwd
if login == 'wtq' and password == 'wtq':
session.logged_in = True
session.time = datetime.datetime.now()
last_login = web.cookies().get('time')
if last_login == None:
last_login_data = u'Zalogowałeś się pierwszy raz.'
else:
last_login_data = last_login
return render.logged(name=login, date_last_login=last_login_data)
else:
session.logged_in = False
error=u'Niepoprawne dane. SprĂłbuj jeszcze raz.'
return render.login(error_msg=error)
class Logout:
def GET(self):
web.seeother(prefix+'/')
def POST(self):
session.logged_in = False
web.setcookie('time',session.time)
message = u'Zostałeś poprawnie wylogowany.'
session.kill()
return render.login(error_msg=message)
class Index:
def GET(self):
return render.login()
if __name__ == "__main__":
app.run()
I would like to verify session and if I login early, I see site with latest login date.
Now, when I refresh the site, I must login again.
I think, that I check session, when I rendering HTML site, but I don't know, what I do it.
Please help!
The problem here is that you are not checking whether they are logged in if they access the page with GET method.
You would need to make a change like:
def GET(self):
if session.logged_in:
last_login = web.cookies().get('time')
if last_login == None:
last_login_data = u'Zalogowałeś się pierwszy raz.'
else:
last_login_data = last_login
return render.logged(name=login, date_last_login=last_login_data)
else:
web.seeother(prefix+'/')
But you should rewrite this, a lot, so that you are taken to another page once you are logged in, and that page is responsible for rendering this information. There is a lot of room for improvement in the structure of your application.
That said, the simple answer is - even though you store the session, the "GET" method of login is entirely unaware of sessions, and will always return the login prompt.
Not sure if you solved your problem already but since it looks like there are often some problems with sessions in web.py I pushed a small and crude demo of it to bitbucket. Works fine for me so hope this works for you.
You can get it via:
git clone https://victorkohler#bitbucket.org/victorkohler/webpy-login.git
I solved my problem.
Very stupid mistakes :)
Code:
# -*- coding: utf-8 -*-
import web
from web.contrib.template import render_jinja
import datetime
prefix = ''
urls = (
prefix + '/', 'Index',
prefix + '/login','Login',
prefix + '/logout','Logout',
)
app = web.application(urls, globals())
wsgi = app.wsgifunc()
web.config.debug = False
session = web.session.Session(app, web.session.DiskStore('sessions'),initializer={'time':datetime.datetime.now()})
render = render_jinja('static', encoding = 'utf-8')
render._lookup.globals.update(assets=prefix+'/static')
allowed = (
('user','user'),
)
class Login:
def GET(self):
web.seeother(prefix+'/')
def POST(self):
login = web.input().login
passwd = web.input().passwd
if(login,passwd) in allowed:
session.logged_in = True
session.login = login
session.time = datetime.datetime.now()
last_login = web.cookies().get('time')
if last_login == None:
last_login_data = u'Zalogowałeś się pierwszy raz.'
else:
last_login_data = last_login
return render.logged(name=login, date_last_login = last_login_data)
else:
session.logged_in = False
error=u'Niepoprawne dane. Spróbuj jeszcze raz.'
return render.login(error_msg=error)
class Logout:
def GET(self):
web.seeother(prefix+'/')
def POST(self):
session.logged_in = False
web.setcookie('time',session.time)
message = u'Zostałeś poprawnie wylogowany.'
session.kill()
return render.login(error_msg=message)
class Index:
def GET(self):
if session.get ('logged_in') == True:
last_login = web.cookies().get('time')
if last_login == None:
last_login_data = u'Zalogowałeś się pierwszy raz.'
else:
last_login_data = last_login
return render.logged(name=session.get ('login'), date_last_login = last_login_data)
else:
return render.login()
if __name__ == "__main__":
app.run()
This is not an answer to your question but an extension of the question. I have a similar solution to the login from the webpy cookbook (http://webpy.org/cookbook/userauthbasic) but would like to load the variable allowed from a database.
allowed = (
('user','user'),
)
When I tried a read to assign the value to the variable it comes out as "None" when executed in the login class.
def readUsersDb():
def POST(self):
# load user data into allowed variable
usersDbFilePath = 'userdata/irf/default/'
usersDbFile = 'usersDb.db'
usersDbFilePath = usersDbFilePath + usersDbFile
conn = sqlite3.connect(usersDbFilePath)
c = conn.cursor()
c.execute('SELECT * FROM users')
output = c.fetchall()
conn.close()
global allowed
allowed = output
readUsersDb()
The login functions when the variable allowed is hard coded. I used the format from the database read and it still functions as expected so it is not a format issue.
#response: [(u'user1', 'user1'), (u'user2', 'user2'), (u'user3', 'user3')]
Hopefully someone has tried to do this previously. If it is a faux pas to add a question as an answer I apologize ahead of time.

redirecting url after facebook logs in successfully with django app

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

Categories