Created
September 8, 2016 20:20
-
-
Save adds68/bf3cb6cb9260f32a865e9a78160bb9e0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask, render_template, url_for, request, session, redirect | |
from flask_pymongo import PyMongo | |
import bcrypt | |
app = Flask(__name__) | |
app.config['MONGO_DBNAME'] = 'flaskapp' | |
app.config['MONGO_URI'] = 'yourdburlhere' | |
mongo = PyMongo(app) | |
@app.route('/') | |
def index(): | |
return render_template('index.html') | |
@app.route('/register', methods=['POST', 'GET']) | |
def register(): | |
if request.method == 'POST': | |
users = mongo.db.users | |
existing_user = users.find_one({'name' : request.form['username']}) | |
if not existing_user: | |
hashpass = bcrypt.hashpw(request.form['pass'].encode('utf-8'), bcrypt.gensalt()) | |
users.insert({'name' : request.form['username'], 'password' : hashpass}) | |
session['username'] = request.form['username'] | |
session['logged_in'] = True | |
return redirect(url_for('index')) | |
return 'That user is already taken' | |
return render_template('register.html') | |
@app.route('/login', methods=['POST']) | |
def login(): | |
users = mongo.db.users | |
login_user = users.find_one({'name': request.form['username']}) | |
if login_user: | |
if bcrypt.hashpw(request.form['pass'].encode('utf-8'), login_user['password'].encode('utf-8')) == login_user['password'].encode('utf-8'): | |
session['username'] = request.form['username'] | |
session['logged_in'] = True | |
return redirect(url_for('index')) | |
return 'Invalid username/password' | |
return 'Invalid username' | |
@app.route('/logout') | |
def logout(): | |
session.clear() | |
session['logged_in'] = False | |
return render_template('index.html') | |
if __name__ == '__main__': | |
app.secret_key = 'helloworld' | |
app.run(debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment