views.py
def create_reply(request, topic_id):
if request.method == 'POST':
t = topic.objects.get(id=topic_id)
past_time = int(time.time() - t.locktime)
r = post()
r.topic = t
if request.POST['content']:
r.content = request.POST['content']
else:
return error(request, '不能空着')
# messages.add_message(request, messages.WARNING, _('content cannot be empty'))
# return HttpResponseRedirect(reverse('topic_view', kwargs={'topic_id': topic_id}))
if past_time > 300:
messages.add_message(request, messages.WARNING, _('overtime'))
return HttpResponseRedirect(reverse('topic_view', kwargs={'topic_id': topic_id}))
r.user = request.user
# when success to reply ,unlock the topic.
t.locker = '0'
t.locked = False
t.last_replier = request.user.username
r.floor = t.reply_count + 1
r.keyword = t.keyword
if t.keyword == "keywordwrite":
t.keyword = rand_key()
elif t.keyword == "freewrite":
t.keyword = None
user_has_subscribed = t.subscriber.filter(
username=request.user.username
)
if not user_has_subscribed:
t.subscriber.add(request.user)
t.save()
r.save()
sendemail.after_response(t.subscriber.all(),t)
sendemail(t.subscriber.all(), t)
return HttpResponseRedirect(reverse('topic_view', kwargs={'topic_id': t.id}))
elif request.method == 'GET':
return error(request, 'don\'t get')
sendemail is
from django.core.mail import EmailMessage
import after_response
#after_response.enable
def sendemail(users_list,topic):
def get_mail_list(users_list):
def getmail(user):
return user.email
mail_list = map(getmail,users_list)
return mail_list
link ='http://www.gushijielong.cn/topic/'+str(topic.id)
mail_list=get_mail_list(users_list)
mailtitle =u'你关注的主题:'+ topic.title + u'有新的接续了'
mailcontent = u'点击查看'+ topic.title + u'的新接续' + "<a href='" + link + u"'>点击</a>"
email = EmailMessage(mailtitle, mailcontent, to=mail_list)
email.content_subtype = "html"
print mailcontent
email.send()
This code is for sending email to the subscribers when a topic has a new reply.
It works( I can receive the emails ) in runserver, but not in apache.
sendemail() works well when I excute it in the server's console.
Related
I am creating university management system using django. I have created faculty(teacher) registration form. For that, in my views.py
def faculty_registration(request):
data = {}
form = FacultyRegisterForm()
activetab = 'list'
if request.method == 'POST':
activetab = 'add'
form = FacultyRegisterForm(request.POST)
if form.is_valid():
userdata = User()
if User.objects.filter(username=request.POST.get('email')).exists():
messages.error(request, f"This email already exists.")
return redirect('/faculty/faculty_registration')
else:
userdatafirst_name = request.POST.get("first_name")
userdata.username = request.POST.get('email')
userdata.email = request.POST.get('email')
try:
fac_ID = Faculty.objects.last().id
except:
fac_ID = 0
LastInsertId = fac_ID+1
print('after_id',LastInsertId)
password = User.objects.make_random_password()
faculty_pw = password+str(LastInsertId)
print("pass",faculty_pw)
userdata.password = make_password(faculty_pw)
print( "teacher_pasword",userdata.password)
userdata.save()
fac = Faculty()
fac.faculty_college_id = request.POST.get("faculty_college")
fac.faculty_programme_id = request.POST.get('faculty_programme')
fac.salutation = request.POST.get("salutation")
fac.first_name = request.POST.get("first_name")
fac.middle_name = request.POST.get("middle_name")
fac.last_name = request.POST.get("last_name")
fac.phone = request.POST.get("phone")
fac.email = request.POST.get("email")
fac.address = request.POST.get('address')
fac.department = request.POST.get('department')
fac.highest_qualification = request.POST.get("highest_qualification")
fac.years_of_experience = request.POST.get('years_of_experience')
fac.previous_institute = request.POST.get('previous_institute')
# fac.documents = request.POST.get("documents")
if 'documents' in request.FILES:
filename = request.FILES['documents']
if str(filename).lower().split('.')[-1] == 'pdf':
if int(len(request.FILES['documents'].read())) < (3 * 1024 * 1024):
fac.documents = request.FILES['documents']
else:
messages.warning(request, "please upload a pdf within 3 mb")
navshow = 'add'
return redirect('faculty_registration')
else:
messages.warning(request, "please upload a pdf")
navshow = 'add'
return redirect('faculty_registration')
fac.photo = request.FILES.get('photo', 'faculty_picture/def.png')
fac.created_by_id = request.user.id
fac.user_id = userdata.id
fac.save()
assign_role(userdata, 'teacher')
html_content = render_to_string("email_template.html",{'title':'Kindly Note your Mailid and Password For Login.','to_mail':fac.email,'to_password':faculty_pw})
text_content = strip_tags(html_content)
msg = EmailMessage(
'Welcome to University', #subject
text_content, #content
settings.EMAIL_HOST_USER, #from email
[fac.email], #reclist
)
msg.content_subtype = "html" # Main content is now text/html
msg.send()
# print("send_email",send_email)
messages.success(request, f"Lecturer has been added successfully")
return redirect('/faculty/faculty_registration')
else:
print("\ninvalid form\n")
else:
form = FacultyRegisterForm()
# fac_data = Faculty.objects.order_by('-id')
fac_data = Faculty.objects.order_by(Lower('first_name'))
data['form'] = form
data['faculties'] = fac_data
data['activetab'] = activetab
return render(request, 'faculty_register.html', data)
Also I have added searchbar button to search faculty name.
So I created following function:
def searchbar (request):
data = {}
find = request.GET['find']
res = Faculty.objects.filter(Q(first_name__icontains=find) | Q(middle_name__icontains=find)| Q(last_name__icontains=find))
activetab = 'list'
form = FacultyRegisterForm()
data['form'] = form
data['activetab'] = activetab
data['faculties'] = res
return render(request,"faculty_register.html",data)
I have also added 'add' functionality to add faculty.
Now my problem is when I click search button, I am not able to add faculty because I think i am rendering the same page 'faculty_register.html' in both return function. So how can I get same page data even after clicking 'search button'.
URLs:
urlpatterns = [
path('faculty_registration', views.faculty_registration, name='faculty_registration'),
path('faculty/searchbar', views.searchbar, name= 'searchbarf')]
I've tried to add searchbar function in faculty_registration but not able to solve this.
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')
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..
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