I can’t figure out why I can’t get passed the login page. It doesn’t matter if I type in the right or wrong credentials, It reloads the login page, instead of signing me in.
import json
from flask import Flask, render_template, request, url_for, redirect
from flask.ext.bootstrap import Bootstrap
from flask.ext.login import LoginManager, UserMixin, login_required, login_user, current_user
from bson.objectid import ObjectId
from lib.mongo import db
from scripts.twitter_stats import ratio_of_wiki_links
app = Flask(__name__)
app.config["SECRET_KEY"] = ''
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
bootstrap = Bootstrap(app)
class User(UserMixin):
def __init__(self, name, password, id, active=True):
self.name = name
self.password = password
self.id = id
self.active = active
def is_active(self):
account = db.accounts.find_one({ "_id": ObjectId("561c7990e4b060b59d7cbcd1")})
if not account['username'] == self.name and account['password'] == self.password:
self.active = False
return self.active
def is_anonymous(self):
return False
def is_authenticated(self):
return True
def get_id(self):
return str(db.accounts.find_one({'username': self.name})['_id'])
@login_manager.user_loader
def load_user(userid):
user = db.accounts.find_one({'_id': userid})
return user
@app.route('/login', methods=['POST', 'GET'])
def login():
account = db.accounts.find_one({ "_id": ObjectId("561c7990e4b060b59d7cbcd1")})
password = account['password']
user = account['username']
error = None
if request.method == 'POST':
username = request.form['username']
passw = request.form['password']
if username != user or passw != password:
error = 'Invalid Credentials, please try again'
else:
user = User(username, passw, account['_id'])
login_user(user)
return redirect(url_for('home'))
return render_template('login.html', error=error)
@app.route('/')
@login_required
def home():
account = db.accounts.find_one({'account': 'twitter'})
entry = db.tweets.find().sort([['_id', -1]]).limit(1)
entry = list(entry)[0]['post']
# if g.user.is_authenticated():
# g.user = user.name
return render_template('index.html', account=account, entry=entry)
2
Answers
For those of you struggling with the same issue, my problem was with the load_user method. I fixed it by changing it to this:
You should call
add_routes
before run app