Skip to content

Instantly share code, notes, and snippets.

@simplyluke
Created April 2, 2017 23:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simplyluke/c06818b6ffb93898956abdf255de7e1e to your computer and use it in GitHub Desktop.
Save simplyluke/c06818b6ffb93898956abdf255de7e1e to your computer and use it in GitHub Desktop.
flask auth
import os
from flask import Flask, request, session, url_for, redirect, \
render_template, abort, g, flash
from flask_bcrypt import Bcrypt
app = Flask(__name__)
bcrypt = Bcrypt(app)
app.config.from_object(os.environ['APP_SETTINGS'])
# Controllers
@app.before_request
def before_request():
g.admin = None
if 'admin_id' in session:
g.admin = Admin.query.filter_by(id=session['admin_id']).first()
@app.route("/")
def hello():
return "Hello World!"
# Admin
@app.route('/admin')
def admin():
if g.admin is not None:
return render_template('admin.html', error="Admin is not logged in")
else:
return redirect(url_for('login'))
# Users
@app.route('/login', methods=['GET', 'POST'])
def login():
if g.admin:
return redirect(url_for('admin'))
error = None
if request.method == 'POST':
admin = Admin.query.filter_by(username=request.form['username']).first()
if admin is None:
error = 'Invalid username'
elif not bcrypt.check_password_hash(admin.pw_hash, request.form['password']):
error = 'Invalid password'
else:
flash('You were logged in')
session['admin_id'] = admin.id
return redirect(url_for('admin'))
return render_template('login.html', error=error)
@app.route('/register', methods=['GET', 'POST'])
def register():
if g.admin:
return redirect(url_for('admin'))
error = None
if request.method == 'POST':
if not request.form['username']:
error = 'You have to enter a username'
elif not request.form['email'] or '@' not in request.form['email']:
error = 'You have to enter a valid email address'
elif not request.form['password']:
error = 'You have to enter a password'
elif request.form['password'] != request.form['password2']:
error = 'The two passwords do not match'
elif Admin.query.filter_by(username=request.form['username']).first() is not None:
error = 'The username is already taken'
else:
admin = Admin(request.form['username'], request.form['email'], bcrypt.generate_password_hash(request.form['password']).decode('utf-8'))
db.session.add(admin)
db.session.commit()
flash('You were successfully registered, an existing admin will need to approve you before you can login.')
return redirect(url_for('login'))
return render_template('register.html', error=error)
@app.route('/logout')
def logout():
flash('You were logged out')
session.pop('admin_id', None)
return redirect('/')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment