from flask import Flask, request, redirect, url_for
from flask.ext.sqlalchemy import SQLAlchemy
from flaskext.auth import Auth, login_required, logout
from flaskext.auth.models.sa import get_user_class

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)
auth = Auth(app, login_url_name='index')

User = get_user_class(db.Model)

@login_required()
def admin():
    return 'Admin! Excellent!'

def index():
    if request.method == 'POST':
        username = request.form['username']
        user = User.query.filter(User.username==username).one()
        if user is not None:
            # Authenticate and log in!
            if user.authenticate(request.form['password']):
                return redirect(url_for('admin'))
        return 'Failure :('
    return '''
            <form method="POST">
                Username: <input type="text" name="username"/><br/>
                Password: <input type="password" name="password"/><br/>
                <input type="submit" value="Log in"/>
            </form>
Exemple #2
0
# -*- coding: utf-8 -*-
import datetime
from flask_sqlalchemy import SQLAlchemy
from flaskext.auth.models.sa import get_user_class

db = SQLAlchemy()

# authentication User class from flask-auth
User = get_user_class(db.Model)

class Profile(db.Model):
    __tablename__ = "profile"
    __searchable__ = ["username", "email", "first_name", "last_name"]

    id = db.Column(db.Integer, primary_key = True)
    # yes, this is redundant. Live with it.
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(254))
    first_name = db.Column(db.String(255))
    middle = db.Column(db.String(1))
    last_name = db.Column(db.String(255))
    street = db.Column(db.String(255))
    street2 = db.Column(db.String(255))
    country = db.Column(db.String(3))
    subdivision = db.Column(db.String(6))
    city = db.Column(db.String(32))
    postal_code = db.Column(db.String(12))
    created = db.Column(db.DateTime, default=datetime.datetime.utcnow)
    updated = db.Column(db.DateTime, onupdate=datetime.datetime.utcnow)
    user_id = db.Column(db.Integer, db.ForeignKey("user.id"))
    user = db.relationship("User", backref="profile")
Exemple #3
0
def routes(app, db): 
    User = get_user_class(db.Model)

    def user_create():
        if request.method == 'POST':
            username = request.form['username']
            if User.query.filter(User.username==username).first():
                return 'User already exists.'
            password = request.form['password']
            user = User(username=username, password=password, role="admin")
            db.session.add(user)
            db.session.commit()
            return redirect(url_for('index'))
        return '''
                <form method="POST">
                    Username: <input type="text" name="username"/><br/>
                    Password: <input type="password" name="password"/><br/>
                    <input type="submit" value="Create"/>
                </form>
            '''
    app.add_url_rule('/users/create/', 'user_create', user_create, methods=['GET', 'POST'])

    @permission_required(resource="read", action="posts")
    def index():
        return render_template("view.html", subject="everything")
    app.add_url_rule("/", "index", index)

    @permission_required(resource="read", action="posts")
    def browse():
        return render_template("browse.html")
    app.add_url_rule("/browse", "browse", browse)

    @permission_required(resource="read", action="posts")
    def view(subject):
        return render_template("view.html", subject=subject)
    app.add_url_rule("/s/<string:subject>", "view", view)
 
    @permission_required(resource="administer", action="things")
    def admin_block():
        return render_template("administration.html")
    app.add_url_rule("/admin", "admin_block", admin_block)

    # only register, login and logout don't require permissions
    @app.route("/register", methods = ["GET", "POST"])
    def register():
        if request.method == "POST":
            return redirect(url_for("index"))
        return render_template("register.html")

    @app.route("/login", methods = ["GET", "POST"])
    def login():

        if request.method == "POST":
            email = request.form["email"]

            """
            if "register" in request.form and request.form["register"]:
                return render_template(
                        "login.html",
                        error = "Registration token sent to %s."%email)

            if not email in g.users:
                return render_template(
                        "login.html", error = "%s not found."%email)

            if "forgot" in request.form and request.form["forgot"]:
                return render_template(
                        "login.html",
                        error = "Password reset sent to %s."%email)

            """

            user = User.query.filter(User.username==email).one()
            if user is not None:
                if not user.authenticate(request.form["password"]):
                    return render_template(
                        "login.html",
                        error = "Incorrect password for %s."%email,
                        email = email)
                return redirect(url_for("index"))
        return render_template("login.html")

    @app.route("/logout")
    def logmeout():
        logout()
        return redirect(url_for("login"))