コード例 #1
0
ファイル: db.py プロジェクト: NiklasMM/fobiweapp
def setup_db():
    # Setup Flask-User
    db_adapter = SQLAlchemyAdapter(db, User)
    user_manager = UserManager(db_adapter, app, register_form=MyRegisterForm, password_validator=my_password_validator)

    db.create_all()

    # Create 'user007' user with 'secret' and 'agent' roles
    if not User.query.filter(User.email == secret_config.ADMIN_EMAIL).first():
        user1 = User(
            email=secret_config.ADMIN_EMAIL, active=True,
            password=user_manager.hash_password(secret_config.ADMIN_PW),
            qualification="RH", first_name="Admin", last_name="Admin",
            gender="m")
        user1.roles.append(Role(name='admin'))
        db.session.add(user1)
        db.session.commit()
コード例 #2
0
ファイル: __init__.py プロジェクト: kevincrane/kevcrablog
def create_app(config='dev'):
    """ Flask application factory
    :param str config: type of app to build, either "prod" or "dev"
    """
    # Create flask application
    app = Flask(__name__)
    app.config.from_object('settings')
    app.config['ENV'] = config
    app.jinja_env.trim_blocks = True

    # Debug toolbar (when debug=true)
    debug_toolbar = DebugToolbarExtension(app)
    app.config['DEBUG_TB_PROFILER_ENABLED'] = True
    app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False

    # Register Blueprints
    app.register_blueprint(views_base.base)
    app.register_blueprint(views_blog.blog)

    # Flask-Assets; bundles all css/js files in minifed file
    assets = Environment(app)
    css_all = Bundle('css/bootstrap-flatly.min.css', 'css/highlightjs.min.css', 'css/font-awesome.css', 'css/main.css',
                     filters='cssmin', output='gen/style.css')
    js_all = Bundle('js/vendor/jquery.min.js', 'js/vendor/bootstrap.min.js', 'js/vendor/showdown-gfm.min.js',
                    'js/vendor/highlight.min.js', 'js/main.js', filters='jsmin', output='gen/libs.js')
    assets.register('css_all', css_all)
    assets.register('js_all', js_all)
    if app.config['DEBUG']:
        assets.debug = True
        app.config['ASSETS_DEBUG'] = True

    # Set up Flask-User
    babel = Babel(app)
    db_adapter = SQLAlchemyAdapter(db, User)
    user_manager = UserManager(db_adapter, app)  # Init Flask-User and bind to app

    # Init the cache
    cache.init_app(app)

    Moment(app)  # moment.js
    Misaka(app, autolink=True,  # Misaka Markdown
           fenced_code=True, lax_html=True, strikethrough=True,
           superscript=True, tables=True, wrap=True)

    # Init Admin page
    admin = Admin(app, index_view=AdminMain(endpoint='admin'))
    admin.add_view(PostAdminView())
    admin.add_view(NewPostView())
    admin.add_view(ModelView(Comment, db.session))
    static_path = os.path.join(BASE_DIR, 'app', 'static')
    admin.add_view(FileAdminView(static_path, '/static/', name='Static Files'))

    # Initialize DB
    db.init_app(app)

    return app
コード例 #3
0
 def bootstrap_user(self):
     if not self.user_bootstrapped:
         from .models import User
         self.db_adapter = SQLAlchemyAdapter(self.db, User)
         self.user_manager = UserManager(self.db_adapter, self.app)
         self.user_bootstrapped = True
コード例 #4
0
def create_app(test_config=None):                   # For automated tests
    # Setup Flask and read config from ConfigClass defined above
    app = Flask(__name__)
    app.config.from_object(__name__ + '.ConfigClass')

    # Load local_settings.py if file exists         # For automated tests
    try:
        app.config.from_object('local_settings')
    except:
        pass

    # Over-write app config                         # For automated tests
    if test_config:
        for key, value in test_config.items():
            app.config[key] = value

    # Setup Flask-Mail, Flask-Babel and Flask-SQLAlchemy
    app.mail = Mail(app)
    app.babel = babel = Babel(app)
    app.db = db = SQLAlchemy(app)

    @babel.localeselector
    def get_locale():
        translations = [str(translation)
                        for translation in babel.list_translations()]
        return request.accept_languages.best_match(translations)

    # Define User model. Make sure to add flask.ext.user UserMixin!!
    class User(db.Model, UserMixin):
        id = db.Column(db.Integer, primary_key=True)
        active = db.Column(db.Boolean(), nullable=False, default=False)
        email = db.Column(db.String(255), nullable=False, unique=True)
        password = db.Column(db.String(255), nullable=False, default='')
        username = db.Column(db.String(50), nullable=False, unique=True)
        confirmed_at = db.Column(db.DateTime())
        reset_password_token = db.Column(
            db.String(100), nullable=False, default='')
        tweets = db.relationship('Tweet', backref='user', lazy='dynamic')

    app.User = User

    class Tweet(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        text = db.Column(db.String(144), nullable=False, default='')
        tweeted_at = db.Column(db.DateTime())
        user_id = db.Column(db.Integer, db.ForeignKey('user.id'))

    # Create all database tables
    db.create_all()

    # Setup Flask-User
    db_adapter = SQLAlchemyAdapter(db,  User)       # Select database adapter
    # Init Flask-User and bind to app
    user_manager = UserManager(db_adapter, app)

    # Setup forms
    class TweetForm(Form):
        text = StringField('Message', validators=[Required()])
        submit = SubmitField('Submit')

    # The '/' page is accessible to anyone
    @app.route('/')
    def home_page():
        if current_user.is_authenticated():
            return profile_page()
        return render_template("index.html")

    # The '/profile' page requires a logged-in user
    @app.route('/profile')
    # Use of @login_required decorator
    @login_required
    def profile_page():
        return render_template("profile.html")

    @app.route('/tweet/new', methods=['GET', 'POST'])
    @login_required
    def new_tweet():
        form = TweetForm()
        if form.validate_on_submit():
            tweet = Tweet()
            form.populate_obj(tweet)
            tweet.tweeted_at = datetime.now()
            tweet.user = current_user
            db.session.add(tweet)
            db.session.commit()
            flash("Your message is tweeted.")
            return redirect(url_for("list_tweet"))
        return render_template("new_tweet.html", form=form)

    @app.route('/tweet/list')
    @login_required
    def list_tweet():
        tweets = Tweet.query.order_by(Tweet.tweeted_at).limit(50)
        print(tweets[0].user.username)
        return render_template("list_tweet.html", tweets=tweets)

    bootstrap = Bootstrap(app)
    return app
コード例 #5
0
def create_app(debug=True, test=False):
    '''creates app instance, db instance, and apimanager instance'''

    app.config['DEBUG'] = debug

    # Generate DB URI
    if settings.SQL_ADAPTER == 'sqlite':
        db_uri = settings.SQLALCHEMY_SQLITE_URI
    elif settings.SQL_ADAPTER == 'mysql':
        if test:
            db_to_use = settings.MYSQL_TEST_DB
        elif settings.DEBUG:
            db_to_use = settings.MYSQL_DEVELOPMENT_DB
        else:
            db_to_use = settings.MYSQL_PRODUCTION_DB
        db_uri = 'mysql://%s:%s@localhost/%s' % (
            settings.MYSQL_USER, settings.MYSQL_PASSWORD, db_to_use)
    else:
        raise ValueError("Value of SQL_ADAPTER in settings must be either"
                         "'sqlite' or 'mysql'")

    app.config['SQLALCHEMY_DATABASE_URI'] = db_uri
    app.secret_key = "very_sekret"  # move this out of here eventually

    # Add slim support
    Flask.jinja_options['extensions'].append(SlimishExtension)

    # Initialize assets
    init_assets(app)

    # Initialize caching
    db.init_app(app)
    cache.init_app(app)

    # i18n support
    Babel(app)

    # Opbeat error logging
    if settings.OPBEAT_ENABLED:
        app.config['OPBEAT'] = {
            'ORGANIZATION_ID': settings.OPBEAT_ORGANIZATION_ID,
            'APP_ID': settings.OPBEAT_APP_ID,
            'SECRET_TOKEN': settings.OPBEAT_SECRET_TOKEN,
            'INCLUDE_PATHS': ['nsweb'],
            'DEBUG': settings.DEBUG or settings.OPBEAT_DEBUG
        }
        Opbeat(app)

    # API
    marshmallow.init_app(app)

    # Set up mail stuff
    if settings.MAIL_ENABLE:
        params = [
            'MAIL_USERNAME', 'MAIL_PASSWORD', 'MAIL_DEFAULT_SENDER',
            'MAIL_SERVER', 'MAIL_PORT', 'MAIL_USE_SSL'
        ]
        app.config.update({(p, getattr(settings, p)) for p in params})
        mail.init_app(app)

    # Set up user management
    app.config['CSRF_ENABLED'] = True
    app.config['USER_ENABLE_FORGOT_PASSWORD'] = True
    from nsweb.models.users import User
    db_adapter = SQLAlchemyAdapter(db, User)
    UserManager(db_adapter, app, password_validator=password_validator)

    # load blueprints
    register_blueprints()
コード例 #6
0
ファイル: app.py プロジェクト: jvlomax/arctic-game-jam
    occupation = db.Column(db.String)

    def __init__(self, name, email, age, info, sex, occupation):
        self.name = name
        self.email = email
        self.age = age
        self.info = info
        self.sex = sex
        self.occupation = occupation

    def __repr__(self):
        return "<Person %s>" % self.name

db.create_all()
db_adapter = SQLAlchemyAdapter(db, User)
user_manager = UserManager(db_adapter, password_validator=password_validator)
user_manager.init_app(app)

@app.route("/ajax/register", methods=["POST"])
def register_user():
    if request.method == "POST":
        name = request.form["nameInput"]
        email = request.form["emailInput"]
        age = request.form["ageInput"]
        info = request.form["textarea"]
        sex = request.form["sex"]
        occupation = request.form["occupationInput"]

        p = Person.query.filter_by(email=email).all()
        if p:
            return "400"
コード例 #7
0
ファイル: app.py プロジェクト: JPT580/ddns
def create_app(test_config=None):  # For automated tests
    # Setup Flask and read config from ConfigClass defined above
    app = Flask(__name__)
    app.config.from_object(__name__ + '.ConfigClass')

    # Load local_settings.py if file exists         # For automated tests
    try: app.config.from_object('local_settings')
    except: pass

    # Load optional test_config                     # For automated tests
    if test_config:
        app.config.update(test_config)

    # Initialize Flask extensions
    babel = Babel(app)  # Initialize Flask-Babel
    mail = Mail(app)  # Initialize Flask-Mail
    db = SQLAlchemy(app)  # Initialize Flask-SQLAlchemy

    @babel.localeselector
    def get_locale():
        translations = [str(translation) for translation in babel.list_translations()]
        return request.accept_languages.best_match(translations)

    # Define the User-Roles pivot table
    user_roles = db.Table('user_roles',
        db.Column('id', db.Integer(), primary_key=True),
        db.Column('user_id', db.Integer(), db.ForeignKey('user.id', ondelete='CASCADE')),
        db.Column('role_id', db.Integer(), db.ForeignKey('role.id', ondelete='CASCADE')))

    # Define Role model
    class Role(db.Model):
        id = db.Column(db.Integer(), primary_key=True)
        name = db.Column(db.String(50), unique=True)

    # Define User model. Make sure to add flask.ext.user UserMixin!!
    class User(db.Model, UserMixin):
        id = db.Column(db.Integer, primary_key=True)
        active = db.Column(db.Boolean(), nullable=False, default=False)
        username = db.Column(db.String(50), nullable=False, unique=True)
        email = db.Column(db.String(255), nullable=False, unique=True)
        confirmed_at = db.Column(db.DateTime())
        password = db.Column(db.String(255), nullable=False, default='')
        reset_password_token = db.Column(db.String(100), nullable=False, default='')
        # Relationships
        roles = db.relationship('Role', secondary=user_roles, backref=db.backref('users', lazy='dynamic'))

    # Reset all the database tables
    db.create_all()

    # Setup Flask-User
    db_adapter = SQLAlchemyAdapter(db, User)
    user_manager = UserManager(db_adapter, username_validator=username_validator)
    user_manager.init_app(app)

    # Create the default admin user if not exists.
    if not User.query.filter(User.username == ConfigClass.DDNS_ADMIN_USERNAME).first():
        adminuser = User(username=ConfigClass.DDNS_ADMIN_USERNAME, email=ConfigClass.DDNS_ADMIN_EMAIL, active=True,
                password=user_manager.hash_password(ConfigClass.DDNS_ADMIN_PASSWORD))
        adminuser.roles.append(Role(name='admin'))
        db.session.add(adminuser)
        db.session.commit()

    @app.route('/')
    def home_page():
        if current_user.is_authenticated():
            return profile_page()
        return render_template('index.html')

    @app.route('/profile')
    @login_required
    def profile_page():
        return render_template('profile.html')

    @app.route('/dns')
    @login_required
    def update_dns():
        return render_template('dns.html')

    @app.route('/special')
    @roles_required('admin')
    def special_page():
        return render_template('admin.html')

    return app
コード例 #8
0
def create_app(test_config=None):  # For automated tests
    # Setup Flask and read config from ConfigClass defined above
    app = Flask(__name__)
    app.config.from_object(__name__ + '.ConfigClass')

    # Load local_settings.py if file exists         # For automated tests
    try:
        app.config.from_object('local_settings')
    except:
        pass

    # Over-write app config                         # For automated tests
    if test_config:
        for key, value in test_config.items():
            app.config[key] = value

    # Setup Flask-Mail, Flask-Babel and Flask-SQLAlchemy
    app.mail = Mail(app)
    app.babel = babel = Babel(app)
    app.db = db = SQLAlchemy(app)

    @babel.localeselector
    def get_locale():
        translations = [
            str(translation) for translation in babel.list_translations()
        ]
        return request.accept_languages.best_match(translations)

    # Define the User-Roles pivot table
    user_roles = db.Table(
        'user_roles', db.Column('id', db.Integer(), primary_key=True),
        db.Column('user_id', db.Integer(),
                  db.ForeignKey('user.id', ondelete='CASCADE')),
        db.Column('role_id', db.Integer(),
                  db.ForeignKey('role.id', ondelete='CASCADE')))

    # Define Role model
    class Role(db.Model):
        id = db.Column(db.Integer(), primary_key=True)
        name = db.Column(db.String(50), unique=True)

    # Define User model. Make sure to add flask.ext.user UserMixin!!
    class User(db.Model, UserMixin):
        id = db.Column(db.Integer, primary_key=True)
        # Flask-User fields
        active = db.Column(db.Boolean(), nullable=False, default=False)
        email = db.Column(db.String(255), nullable=False, default='')
        password = db.Column(db.String(255), nullable=False, default='')
        # Application fields
        first_name = db.Column(db.String(50), nullable=False, default='')
        last_name = db.Column(db.String(50), nullable=False, default='')
        # Relationships
        roles = db.relationship('Role',
                                secondary=user_roles,
                                backref=db.backref('users', lazy='dynamic'))

    # Reset all the database tables
    db.create_all()

    # Setup Flask-User
    db_adapter = SQLAlchemyAdapter(db, User)
    user_manager = UserManager(db_adapter, app, register_form=MyRegisterForm)

    # The '/' page is accessible to anyone
    @app.route('/')
    def home_page():
        if current_user.is_authenticated():
            return profile_page()
        return render_template_string("""
            {% extends "base.html" %}
            {% block content %}
            <h2>{%trans%}Home Page{%endtrans%}</h2>
            <p><a href="{{ url_for('user.login') }}">{%trans%}Sign in{%endtrans%}</a></p>
            {% endblock %}
            """)

    # The '/profile' page requires a logged-in user
    @app.route('/profile')
    @login_required  # Use of @login_required decorator
    def profile_page():
        return render_template_string("""
            {% extends "base.html" %}
            {% block content %}
            <h2>{%trans%}Profile Page{%endtrans%}</h2>
            <p> {%trans%}Hello{%endtrans%}
                {{ current_user.first_name }},</p>
            <p> <a href="{{ url_for('user.change_password') }}">
                {%trans%}Change password{%endtrans%}</a></p>
            <p> <a href="{{ url_for('user.logout') }}?next={{ url_for('user.login') }}">
                {%trans%}Sign out{%endtrans%}</a></p>
            {% endblock %}
            """)

    return app
コード例 #9
0
ファイル: tst_app.py プロジェクト: sundisee/Flask-User
def init_app(app, test_config=None):                   # For automated tests
    # Setup Flask and read config from ConfigClass defined above
    app.config.from_object(__name__+'.ConfigClass')

    # Load local_settings.py if file exists         # For automated tests
    try: app.config.from_object('local_settings')
    except: pass

    # Load optional test_config                     # For automated tests
    if test_config:
        app.config.update(test_config)

    # Initialize Flask extensions
    babel = Babel(app)                              # Initialize Flask-Babel
    mail = Mail(app)                                # Initialize Flask-Mail

    # Reset all the database tables
    db.create_all()

    # Setup Flask-User
    db_adapter = SQLAlchemyAdapter(db,  User, UserInvitationClass=UserInvitation)
    user_manager = UserManager(db_adapter, app)

    # Create regular 'member' user
    if not User.query.filter(User.username=='member').first():
        user = User(username='******', email='*****@*****.**', active=True,
                password=user_manager.hash_password('Password1'), confirmed_at=datetime.datetime.utcnow())
        db.session.add(user)
        db.session.commit()

    # Create 'user007' user with 'secret' and 'agent' roles
    if not User.query.filter(User.username=='user007').first():
        user1 = User(username='******', email='*****@*****.**', active=True,
                password=user_manager.hash_password('Password1'))
        user1.roles.append(Role(name='secret'))
        user1.roles.append(Role(name='agent'))
        db.session.add(user1)
        db.session.commit()

    # The '/' page is accessible to anyone
    @app.route('/')
    def home_page():
        return render_template_string("""
            {% extends "base.html" %}
            {% block content %}
            <h2>{%trans%}Home Page{%endtrans%}</h2>
            <p><a href="{{ url_for('user.login') }}">{%trans%}Sign in{%endtrans%}</a></p>
            {% endblock %}
            """)

    # The '/profile' page requires a logged-in user
    @app.route('/user/profile')
    @login_required                                 # Use of @login_required decorator
    @confirm_email_required
    def user_profile_page():
        return render_template_string("""
            {% extends "base.html" %}
            {% block content %}
            <h2>{%trans%}Profile Page{%endtrans%}</h2>
            <p> {%trans%}Hello{%endtrans%}
                {{ current_user.username or current_user.email }},</p>
            <p> <a href="{{ url_for('user.change_username') }}">
                {%trans%}Change username{%endtrans%}</a></p>
            <p> <a href="{{ url_for('user.change_password') }}">
                {%trans%}Change password{%endtrans%}</a></p>
            <p> <a href="{{ url_for('user.invite') }}">
                {%trans%}Invite User{%endtrans%}</a></p>
            <p> <a href="{{ url_for('user.logout') }}?next={{ url_for('user.login') }}">
                {%trans%}Sign out{%endtrans%}</a></p>
            {% endblock %}
            """)

    # The '/special' page requires a user that has the 'special' AND ('sauce' OR 'agent') role.
    @app.route('/special')
    @roles_required('secret', ['sauce', 'agent'])   # Use of @roles_required decorator
    def special_page():
        return render_template_string("""
            {% extends "base.html" %}
            {% block content %}
            <h2>{%trans%}Special Page{%endtrans%}</h2>
            {% endblock %}
            """)

    # For testing only
    app.db = db
    app.UserEmailClass = UserEmail

    return app
コード例 #10
0
def create_app():
    """ Flask application factory """

    # Setup Flask app and app.config
    app = Flask(__name__)
    app.config.from_object(__name__ + '.ConfigClass')

    # Initialize Flask extensions
    db = SQLAlchemy(app)  # Initialize Flask-SQLAlchemy
    mail = Mail(app)  # Initialize Flask-Mail

    # Define User model. Make sure to add flask.ext.user UserMixin !!!
    class User(db.Model, UserMixin):
        id = db.Column(db.Integer, primary_key=True)
        active = db.Column(db.Boolean(), nullable=False, default=False)
        username = db.Column(db.String(50), nullable=False, unique=True)
        password = db.Column(db.String(255), nullable=False, default='')
        email = db.Column(db.String(255), nullable=False, unique=True)
        confirmed_at = db.Column(db.DateTime())
        reset_password_token = db.Column(db.String(100),
                                         nullable=False,
                                         default='')

    # Create all database tables
    db.create_all()

    # Setup Flask-User
    db_adapter = SQLAlchemyAdapter(db, User)  # Register the User model
    user_manager = UserManager(db_adapter, app)  # Initialize Flask-User

    # The Home page is accessible to anyone
    @app.route('/')
    def home_page():
        return render_template_string("""
            {% extends "base.html" %}
            {% block content %}
                <p><a href="{{ url_for('home_page') }}">Home page</a> |
                   <a href="{{ url_for('profile_page') }}">Profile page</a></p>

                <h2>Home page</h2>

                {% if current_user.is_authenticated() %}
                    <p><a href="{{ url_for('user.logout')  }}">Sign out</a></p>
                {% else %}
                    <p><a href="{{ url_for('user.login') }}">Sign in</a></p>
                {% endif %}
            {% endblock %}
            """)

    # The Profile page requires a logged-in user
    @app.route('/profile')
    @login_required  # Use of @login_required decorator
    def profile_page():
        return render_template_string("""
            {% extends "base.html" %}
            {% block content %}
                <p><a href="{{ url_for('home_page') }}">Home page</a> |
                   <a href="{{ url_for('profile_page') }}">Profile page</a></p>

                <h2>Profile page</h2>

                <p>Username: {{ current_user.username }}</p>
                <p>Email:    {{ current_user.email }}   </p>

                <p><a href="{{ url_for('user.change_username') }}">Change username</a></p>
                <p><a href="{{ url_for('user.change_password') }}">Change password</a></p>
                <p><a href="{{ url_for('user.logout') }}">Sign out</a></p>
            {% endblock %}
            """)

    return app
コード例 #11
0
ファイル: webrob.py プロジェクト: volnik/docker
    reset_password_token = db.Column(db.String(100), nullable=False, default='')
    container_id = db.Column(db.String(255), nullable=False, default='')

    # Relationships
    roles = db.relationship('Role', secondary=user_roles,
            backref=db.backref('users', lazy='dynamic'))

#class MyRegisterForm(RegisterForm):
    #roles = SelectField('Rolle', validators=[Required('Rolle erforderlich')])

# Reset all the database tables
db.create_all()

# Setup Flask-User
db_adapter = SQLAlchemyAdapter(db,  User)
user_manager = UserManager(db_adapter, app)#, register_form=MyRegisterForm)

if not User.query.filter(User.username=='testuser').first():
    user1 = User(username='******', email='*****@*****.**', active=True,
        password=user_manager.hash_password('Password1'))
    user1.roles.append(Role(name='admin'))
    user1.roles.append(Role(name='user'))
    db.session.add(user1)
    db.session.commit()

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Docker stuff

def docker_connect():
    c = docker.Client(base_url='unix://var/run/docker.sock', version='1.12',timeout=10)
    return c
コード例 #12
0
def create_app():

    app = flask.Flask(__name__)
    app.debug = True

    # Configurations set above in the ConfigClass ...
    app.config.from_object(__name__ + '.ConfigClass')

    #app.logger.debug(ssl.PROTOCOL_TLSv1)

    # Initialize Flask extensions
    db = SQLAlchemy(app)  # Initialize Flask-SQLAlchemy
    mail = Mail(app)  # Initialize Flask-Mail ...
    bcrypt = Bcrypt(app)  # Inifialize Bcrypt ...

    # Define the User data model. Make sure to add flask.ext.user UserMixin !!!
    class User(db.Model, UserMixin):

        id = db.Column(db.Integer, primary_key=True)

        password = db.Column(db.String(255), nullable=False, server_default='')
        #reset_password_token = db.Column(db.String(100), nullable=False, server_default='')
        authenticate = db.Column(db.Boolean)

        email = db.Column(db.String(255), nullable=False, unique=True)
        confirmed_at = db.Column(db.DateTime())

        is_enabled = db.Column(db.Boolean(), nullable=False, default=False)
        active = db.Column('is_active',
                           db.Boolean(),
                           nullable=False,
                           server_default='0')
        registered_on = db.Column('registered_on', db.DateTime)

        chrome_hash = db.Column(db.String(500))
        secure_token = db.Column(db.String(500))

        def hash_password(self, password):
            self.password = bcrypt.generate_password_hash(password)

        def verify_password(self, password):
            return bcrypt.check_password_hash(self.password, password)

        def activate(self):
            self.authenticate = True

        def is_authenticated(self):
            return True

        def is_active(self):
            return True

        def is_anonymous(self):
            return False

        def get_id(self):
            return unicode(self.id)

        def set_chrome_hash(self):
            self.chrome_hash = str(hashlib.sha224(self.email).hexdigest())

        def set_secure_token(self):
            secure_token = make_secure_token(self.email)

    class Path(db.Model):

        __tablename__ = 'paths'

        id = db.Column(db.Integer, primary_key=True)
        path = db.Column(db.String(50), nullable=False, unique=True)
        url = db.Column(db.String(250), nullable=False)
        creator_id = db.Column(db.Integer, nullable=True)
        clicks = db.Column(db.Integer, default=0)
        note = db.Column(db.String(300), default="No note.")
        timestamp = db.Column(db.DateTime)

    ### INITIALIZE THE DB, USER MODEL, LOGIN MANAGER, ETC. ... ###

    db.create_all()  # Create all database tables if they don't exist ...
    db_adapter = SQLAlchemyAdapter(db, User)  # Register the User model
    user_manager = UserManager(db_adapter, app)  # Initialize Flask-User
    login_manager = LoginManager()  # Initialize the Login manager? ...
    login_manager.init_app(
        app)  # this needs a secret key, set above in the Config class

    @login_manager.user_loader
    def load_user(id):
        return User.query.get(int(id))

    ######################################################################
    #                                                                    #
    #                       CONFIRMATION EMAILS                          #
    #                                                                    #
    ######################################################################

    def get_serializer(secret_key=None):
        app.logger.debug("in get_serializer")
        if secret_key is None:
            secret_key = app.secret_key
        return URLSafeSerializer(secret_key)

    @app.route('/users/activate/<payload>')
    def activate_user(payload):
        app.logger.debug("in activate_user")
        s = get_serializer()
        try:
            user_id = s.loads(payload)
        except BadSignature:
            abort(404)

        user = User.query.get_or_404(user_id)
        user.authenticate = True
        db.session.commit()

        flash('User activated')
        return flask.redirect(home_url)

    def get_activation_link(user):
        app.logger.debug("in get_activation_link")
        s = get_serializer()
        payload = s.dumps(user.id)

        return url_for('activate_user', payload=payload)

    def send_confirmation_email(user):
        link = get_activation_link(user)
        msg = Message("Hello", sender="*****@*****.**")
        msg.add_recipient(user.email)
        msg.body = "people.ischool.berkeley.edu/~brian.carlo/server" + link
        mail.send(msg)

    ######################################################################
    #                                                                    #
    #                       REGISTRATION AND LOGIN                       #
    #                                                                    #
    ######################################################################

    @app.route('/login.html', methods=["GET", "POST"])
    def login():
        if request.method == 'GET':
            return render_template('login.html')
        email = request.form['email']
        password = request.form['password']

        registered_user = User.query.filter_by(email=email).first()

        if registered_user.verify_password(password):
            login_user(registered_user)
            flash('Logged in successfully')
            return flask.redirect(dashboard_url)
        else:
            flash('Username or Password is invalid', 'error')
            return render_template('login.html')

    @app.route('/register.html', methods=['GET', 'POST'])
    def register():
        if request.method == 'GET':
            return render_template('register.html')
        try:
            user = User(email=request.form['email'])
            user.hash_password(request.form['password'])
            db.session.add(user)
            db.session.commit()
            registered_user = User.query.filter_by(email=user.email).first()
            send_confirmation_email(registered_user)
            registered_user.set_chrome_hash()

            app.logger.debug(registered_user.chrome_hash)
            db.session.commit()

            response = make_response(flask.redirect(home_url))
            response.set_cookie('chrome_id',
                                value=registered_user.chrome_hash,
                                max_age=2592000)
            return response
        except:
            flash(
                "That e-mail address is already Nerping for real. Maybe Nerp a different e-mail?"
            )
            return render_template('register.html')

    ######################################################################
    #                                                                    #
    #                           POSTING PATHS!                           #
    #                                                                    #
    ######################################################################

    @app.before_request
    def validate():  # runs before any app.route()
        """ Helper validates URLs and handles errors for CHROME_PUT(), SHORTS_PUT(). """
        if request.path == '/shorts':  # if the server request is to '/shorts' ...
            shortpath = str(
                request.form.get('shortpath')).strip()  # grab the shortpath
            if shortpath == "":
                pass  # if there's no path, no worries
            else:
                if Path.query.filter_by(path=shortpath).first():
                    app.logger.debug("made it here")
                    flash("already taken!")

            inputURL = str(
                request.form.get('url')).lower().strip()  # grab the URL
            if inputURL == None or inputURL == "":  # if it's not there ...
                abort(412)  # throw the 412

    def insert_path_for_user_or_not(path, inputURL):
        """ HELPER FOR CHROME_PUT(), SHORTS_PUT() """
        try:
            new_path = Path(path=path,
                            url=inputURL,
                            creator_id=current_user.id,
                            timestamp=datetime.utcnow())
            app.logger.debug("UID!")
        except:
            app.logger.debug("NOID!")
            new_path = Path(path=path,
                            url=inputURL,
                            creator_id=None,
                            timestamp=datetime.utcnow())
        db.session.add(new_path)
        db.session.commit()

    def make_random_path():
        """ HELPER FOR CHROME_PUT(), SHORTS_PUT() """
        myPath = ""
        for i in range(7):
            myPath = myPath + chr(random.choice(possible))
        return myPath

    def format_url(inputURL):
        """ HELPER FOR CHROME_PUT(), SHORTS_PUT() """
        parsed = urlparse(inputURL)
        if parsed.scheme == "":
            inputURL = "http://" + inputURL

        h = httplib2.Http()
        try:
            response = h.request(inputURL, 'HEAD')
            inputURL = response[0]['content-location']
            return inputURL
        except:
            return False

    def insert_note(path):
        added_path = Path.query.filter_by(path=path).first()
        added_path.note = str(request.form.get('note', ''))

    @app.route('/chrome', methods=['PUT', 'POST'])
    def chrome_put():

        if 'chrome_id' not in request.cookies:
            user_id = 0
        else:
            chrome_hash = request.cookies.get('chrome_id')
            user = User.query.filter_by(chrome_hash=chrome_hash).first()
            user_id = user.id

        inputURL = str(request.form.get('url', '')).lower()

        inputURL = format_url(inputURL)
        if not inputURL:
            response = make_response("Broken URL. Try another")
            return response

        shortpath = str(request.form.get('shortpath', ''))

        if not shortpath:
            myPath = make_random_path()
            while Path.query.filter_by(path=myPath).first():
                myPath = make_random_path()
            insert_path_for_user_or_not(myPath, inputURL)
            insert_note(myPath)
        else:
            insert_path_for_user_or_not(shortpath, inputURL)
            insert_note(shortpath)
        return flask.redirect(
            'http://people.ischool.berkeley.edu/~brian.carlo/server/chrome.html'
        )

    @app.route('/shorts', methods=['PUT', 'POST'])
    def shorts_put():
        try:
            inputURL = str(request.form.get('url', '')).lower()
            inputURL = format_url(inputURL)
            if not inputURL:
                response = make_response("Broken URL. Try another")
                return response

            shortpath = str(request.form.get('shortpath', ''))

            app.logger.debug(inputURL + "," + shortpath)

            if not shortpath:
                myPath = make_random_path()
                while Path.query.filter_by(path=myPath).first():
                    myPath = make_random_path()
                insert_path_for_user_or_not(myPath, inputURL)
                path = myPath
            else:
                insert_path_for_user_or_not(shortpath, inputURL)
                path = shortpath
            try:
                if current_user.id:
                    return flask.redirect(dashboard_url)
            except:
                flash("nerp.me/" + path)
                return render_template('promo.html')

        except:
            abort(405)

    @app.route('/delete', methods=['POST', 'PUT'])
    @login_required
    def delete_nerp():
        nerp_id = str(request.form.get('nerp_id',
                                       ''))  # REMEMBER TO CHANGE "NERP-ID"
        death_row_nerp = Path.query.filter_by(id=nerp_id).first()
        db.session.delete(death_row_nerp)
        db.session.commit()

    ######################################################################
    #                                                                    #
    #                           GET METHODS!                             #
    #                                                                    #
    ######################################################################

    @app.route('/shorts/<shortpath>', methods=['GET'])
    def shorts_shortpath(shortpath):
        try:
            path = Path.query.filter_by(path=shortpath).first()
            url = path.url
            path.clicks = path.clicks + 1
            db.session.commit()
            return flask.redirect(url)
        except:
            abort(404)

    @app.route('/chrome.html', methods=['GET'])
    def chrome_dash():
        return render_template('chrome.html')

    @app.route('/home.html', methods=['GET'])
    def root():
        return render_template('promo.html')

    @app.route('/dashboard.html', methods=['GET'])
    @login_required
    def dashboard():
        items = Path.query.filter_by(creator_id=current_user.id).order_by(
            Path.timestamp.desc()).all()
        top_nerps = Path.query.order_by(Path.clicks.desc()).limit(10)
        return render_template('dashboard.html',
                               items=items,
                               top_nerps=top_nerps)

    @app.route('/logout', methods=['GET'])
    def logout():
        logout_user()
        return flask.redirect(home_url)

    ######################################################################
    #                                                                    #
    #                           ERROR HANDLERS!                          #
    #                                                                    #
    ######################################################################

    @app.errorhandler(412)
    def precondition_failed(e):
        flash("put in a url, dumbass")
        try:
            if current_user.is_authenticated:
                return flask.redirect(dashboard_url)
        except:
            return render_template('promo.html')

    @app.errorhandler(404)
    def page_not_found(e):
        return render_template('404.html'), 404

    @app.errorhandler(405)
    def method_not_allowed(e):
        return render_template('promo.html'), 405

    @app.errorhandler(409)
    def conflict(e):
        return render_template(
            'final_temp_3.html',
            code=409,
            message="Short path already exists. Please choose a different path."
        ), 409

    return app
コード例 #13
0
        return slug

    def getName(self):
        import HTMLParser
        parser = HTMLParser.HTMLParser()
        s =  parser.unescape(self.name)
        return s.replace('"','\\"')

    def __repr__(self):
        return '<VoteOption %s %s>' % (self.vote.name, self.name)



class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(25), unique=True)
    password = db.Column(db.String(50))
    email = db.Column(db.String(50))
    reset_password_token = db.Column(db.String(100), nullable=True, default="")
    confirmed_at = db.Column(db.DateTime(), nullable=True)
    active = db.Column(db.Boolean(), nullable=False, default=False)
    create = db.Column(db.Boolean(), nullable=False, default=False)
    admin = db.Column(db.Boolean(), nullable=True, default=False)

    def can_create(self):
        return self.create

db_adapter = SQLAlchemyAdapter(db, User)
user_manager = UserManager(db_adapter=db_adapter,login_manager=loginManager, app=app)     # Init Flask-User and bind to app

コード例 #14
0
ファイル: test_app.py プロジェクト: yacneyac/Flask-User
def create_app(test_config=None):  # For automated tests
    # Setup Flask and read config from ConfigClass defined above
    app = Flask(__name__)
    app.config.from_object(__name__ + '.ConfigClass')

    # Load local_settings.py if file exists         # For automated tests
    try:
        app.config.from_object('local_settings')
    except:
        pass

    # Load optional test_config                     # For automated tests
    if test_config:
        app.config.update(test_config)

    # Initialize Flask extensions
    db = SQLAlchemy(app)  # Initialize Flask-SQLAlchemy
    mail = Mail(app)  # Initialize Flask-Mail
    babel = Babel(app)  # Initialize Flask-Babel

    @babel.localeselector
    def get_locale():
        translations = [
            str(translation) for translation in babel.list_translations()
        ]
        language = request.accept_languages.best_match(translations)
        print('translations=', repr(translations), 'language=', repr(language))
        return language

    # Define User model. Make sure to add flask.ext.user UserMixin!!
    class User(db.Model, UserMixin):
        id = db.Column(db.Integer, primary_key=True)
        active = db.Column(db.Boolean(), nullable=False, default=False)
        username = db.Column(db.String(50), nullable=False, unique=True)
        password = db.Column(db.String(255), nullable=False, default='')
        email = db.Column(db.String(255), nullable=False, unique=True)
        confirmed_at = db.Column(db.DateTime())
        reset_password_token = db.Column(db.String(100),
                                         nullable=False,
                                         default='')

    # Create all database tables
    db.create_all()

    # Setup Flask-User
    db_adapter = SQLAlchemyAdapter(db, User)  # Select database adapter
    user_manager = UserManager(db_adapter,
                               app)  # Init Flask-User and bind to app

    # The Home page is accessible to anyone
    @app.route('/')
    def home_page():
        return render_template_string("""
            {% extends "base.html" %}
            {% block content %}
                <h2>{%trans%}Home Page{%endtrans%}</h2>
                {% if current_user.is_authenticated() %}
                <p> <a href="{{ url_for('profile_page') }}">
                    {%trans%}Profile Page{%endtrans%}</a></p>
                <p> <a href="{{ url_for('user.logout') }}">
                    {%trans%}Sign out{%endtrans%}</a></p>
                {% else %}
                <p> <a href="{{ url_for('user.login') }}">
                    {%trans%}Sign in or Register{%endtrans%}</a></p>
                {% endif %}
            {% endblock %}
            """)
        if current_user.is_authenticated():
            return redirect(url_for('profile_page'))
        else:
            return redirect(url_for('user.login'))

# The Profile page requires a logged-in user

    @app.route('/profile')
    @login_required  # Use of @login_required decorator
    def profile_page():
        return render_template_string("""
            {% extends "base.html" %}
            {% block content %}
                <h2>{%trans%}Profile Page{%endtrans%}</h2>
                <p> {%trans%}Hello{%endtrans%}
                    {{ current_user.username or current_user.email }},</p>
                <p> <a href="{{ url_for('home_page') }}">
                    {%trans%}Home Page{%endtrans%}</a></p>
                <p> <a href="{{ url_for('user.change_username') }}">
                    {%trans%}Change username{%endtrans%}</a></p>
                <p> <a href="{{ url_for('user.change_password') }}">
                    {%trans%}Change password{%endtrans%}</a></p>
                <p> <a href="{{ url_for('user.logout') }}">
                    {%trans%}Sign out{%endtrans%}</a></p>
            {% endblock %}
            """)

    return app
コード例 #15
0
ファイル: login_views.py プロジェクト: dhocker/ahps_web
# Define User model. Make sure to add flask.ext.user UserMixin!!
class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    active = db.Column(db.Boolean(), nullable=False, default=False)
    username = db.Column(db.String(50), nullable=False, unique=True)
    password = db.Column(db.String(255), nullable=False, default='')


# Create all database tables
db.create_all()


# Setup Flask-User
db_adapter = SQLAlchemyAdapter(db,  User)       # Select database adapter
user_manager = UserManager(db_adapter, app,
    register_view_function = register_disabled # disable user self-registration
    )     # Init Flask-User and bind to app


# Seed the admin account
admin = User.query.filter_by(username='******').first()
if not admin:
    print "admin account does not exist. Creating..."
    user1 = User(username='******', active=True,
            password=user_manager.hash_password('Password1'))
    db.session.add(user1)
    db.session.commit()
    print "admin account created. Be sure to change the password."


# The Profile page requires a logged-in user
コード例 #16
0
ファイル: __init__.py プロジェクト: mcilroy/qfpc
# Initialize Flask extensions
babel = Babel(app)                              # Initialize Flask-Babel

@babel.localeselector
def get_locale():
    translations = [str(translation) for translation in babel.list_translations()]
    return request.accept_languages.best_match(translations)

from .models import User,Role,db, MemberInfo
# Reset all the database tables
#db.drop_all()
db.create_all()

# Setup Flask-User
db_adapter = SQLAlchemyAdapter(db,  User)
user_manager = UserManager(db_adapter, app)

# Create 'user007' user with 'secret' and 'agent' roles
if not User.query.filter(User.username=='admin').first():
    user1 = User(username='******', active=True,
            password=user_manager.hash_password('1'))
    user1.roles.append(Role(name='admin'))
    db.session.add(user1)
    db.session.commit()
if not User.query.filter(User.username=='user').first():
    user2 = User(username='******', active=True,
            password=user_manager.hash_password('1'))
    user2.roles.append(Role(name='user'))
    db.session.add(user2)
    db.session.commit()
if not User.query.filter(User.username=='superAdmin').first():
コード例 #17
0
ファイル: models.py プロジェクト: pcraster/fwo
        srid = point['epsg']

        projection = pyproj.Proj("+init=EPSG:%d" % (point['epsg']))
        if point['epsg'] != 4326:
            (x, y) = projection(x, y, inverse=True)
            srid = 4326

        self.geom = WKTElement('POINT(%.7f %.7f)' % (x, y), srid=srid)
        self.properties = json.dumps(point['properties'])

    def as_dict(self):
        """
        Returns the point as a GeoJSON-point-like dictionary. This dict can
        be plugged into some sort of JSON converter (like Flask's jsonify())
        and a nice GeoJSON feature should come rolling out.
        """
        pt = to_shape(self.geom)
        return {
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [pt.x, pt.y]
            },
            "properties": json.loads(self.properties)
        }


db_adapter = SQLAlchemyAdapter(db, User)
user_manager = UserManager(db_adapter, app)
mail = Mail(app)
コード例 #18
0
ファイル: tst_app.py プロジェクト: ox0spy/Flask-User
def create_app(test_config=None):                   # For automated tests
    # Setup Flask and read config from ConfigClass defined above
    app = Flask(__name__)
    app.config.from_object(__name__+'.ConfigClass')

    # Load local_settings.py if file exists         # For automated tests
    try: app.config.from_object('local_settings')
    except: pass

    # Over-write app config                         # For automated tests
    if test_config:
        for key, value in test_config.items():
            app.config[key] = value

    # Setup Flask-Mail, Flask-Babel and Flask-SQLAlchemy
    app.mail = Mail(app)
    app.babel = babel = Babel(app)
    app.db = db = SQLAlchemy(app)

    @babel.localeselector
    def get_locale():
        return request.accept_languages.best_match(['en', 'nl'])

    # Define the User-Roles pivot table
    user_roles = db.Table('user_roles',
        db.Column('id', db.Integer(), primary_key=True),
        db.Column('user_id', db.Integer(), db.ForeignKey('user.id', ondelete='CASCADE')),
        db.Column('role_id', db.Integer(), db.ForeignKey('role.id', ondelete='CASCADE')))

    # Define Role model
    class Role(db.Model):
        id = db.Column(db.Integer(), primary_key=True)
        name = db.Column(db.String(50), unique=True)

    # Define User model. Make sure to add flask.ext.user UserMixin!!
    class User(db.Model, UserMixin):
        id = db.Column(db.Integer, primary_key=True)
        active = db.Column(db.Boolean(), nullable=False, default=False)
        username = db.Column(db.String(50), nullable=True, unique=True)
        email = db.Column(db.String(255), nullable=True, unique=True)
        confirmed_at = db.Column(db.DateTime())
        password = db.Column(db.String(255), nullable=False, default='')
        reset_password_token = db.Column(db.String(100), nullable=False, default='')
        # Relationships
        roles = db.relationship('Role', secondary=user_roles,
                backref=db.backref('users', lazy='dynamic'))
    app.User = User

    # Reset all the database tables
    db.create_all()

    # Setup Flask-User
    db_adapter = SQLAlchemyAdapter(db,  User)
    user_manager = UserManager(db_adapter, app)

    # Create 'user007' user with 'secret' and 'agent' roles
    if not User.query.filter(User.username=='user007').first():
        user1 = User(username='******', email='*****@*****.**', active=True,
                password=user_manager.hash_password('Password1'))
        user1.roles.append(Role(name='secret'))
        user1.roles.append(Role(name='agent'))
        db.session.add(user1)
        db.session.commit()

    # The '/' page is accessible to anyone
    @app.route('/')
    def home_page():
        # if current_user.is_authenticated():
        #     return profile_page()
        return render_template_string("""
            {% extends "base.html" %}
            {% block content %}
            <h2>{%trans%}Home Page{%endtrans%}</h2>
            <p><a href="{{ url_for('user.login') }}">{%trans%}Sign in{%endtrans%}</a></p>
            {% endblock %}
            """)

    # The '/profile' page requires a logged-in user
    @app.route('/profile')
    @login_required                                 # Use of @login_required decorator
    def profile_page():
        return render_template_string("""
            {% extends "base.html" %}
            {% block content %}
            <h2>{%trans%}Profile Page{%endtrans%}</h2>
            <p> {%trans%}Hello{%endtrans%}
                {{ current_user.username or current_user.email }},</p>
            <p> <a href="{{ url_for('user.change_username') }}">
                {%trans%}Change username{%endtrans%}</a></p>
            <p> <a href="{{ url_for('user.change_password') }}">
                {%trans%}Change password{%endtrans%}</a></p>
            <p> <a href="{{ url_for('user.logout') }}?next={{ url_for('user.login') }}">
                {%trans%}Sign out{%endtrans%}</a></p>
            {% endblock %}
            """)

    # The '/special' page requires a user that has the 'special' AND ('sauce' OR 'agent') role.
    @app.route('/special')
    @roles_required('secret', ['sauce', 'agent'])   # Use of @roles_required decorator
    def special_page():
        return render_template_string("""
            {% extends "base.html" %}
            {% block content %}
            <h2>{%trans%}Special Page{%endtrans%}</h2>
            {% endblock %}
            """)

    return app
コード例 #19
0
ファイル: signals_app.py プロジェクト: neurosnap/Flask-User
def create_app():
    """ Flask application factory """

    # Setup Flask app and app.config
    app = Flask(__name__)
    app.config.from_object(__name__+'.ConfigClass')

    # Initialize Flask extensions
    db = SQLAlchemy(app)                            # Initialize Flask-SQLAlchemy
    mail = Mail(app)                                # Initialize Flask-Mail

    # Define the User data model. Make sure to add flask.ext.user UserMixin !!!
    class User(db.Model, UserMixin):
        id = db.Column(db.Integer, primary_key=True)

        # User authentication information
        username = db.Column(db.String(50), nullable=False, unique=True)
        password = db.Column(db.String(255), nullable=False, server_default='')
        reset_password_token = db.Column(db.String(100), nullable=False, server_default='')

        # User email information
        email = db.Column(db.String(255), nullable=False, unique=True)
        confirmed_at = db.Column(db.DateTime())

        # User information
        active = db.Column('is_active', db.Boolean(), nullable=False, server_default='0')
        first_name = db.Column(db.String(100), nullable=False, server_default='')
        last_name = db.Column(db.String(100), nullable=False, server_default='')

    # Create all database tables
    db.create_all()

    # Setup Flask-User
    db_adapter = SQLAlchemyAdapter(db, User)        # Register the User model
    user_manager = UserManager(db_adapter, app)     # Initialize Flask-User

    @user_logged_in.connect_via(app)
    def logged_in(sender, user, **extra):
        sender.logger.info("USER LOGGED IN")

    @user_logged_out.connect_via(app)
    def logged_out(sender, user, **extra):
        sender.logger.info("USER LOGGED OUT")

    # The Home page is accessible to anyone
    @app.route('/')
    def home_page():
        return render_template_string("""
            {% extends "base.html" %}
            {% block content %}
                <h2>Home page</h2>
                <p>This page can be accessed by anyone.</p><br/>
                <p><a href={{ url_for('home_page') }}>Home page</a> (anyone)</p>
                <p><a href={{ url_for('members_page') }}>Members page</a> (login required)</p>
            {% endblock %}
            """)

    # The Members page is only accessible to authenticated users
    @app.route('/members')
    @login_required                                 # Use of @login_required decorator
    def members_page():
        return render_template_string("""
            {% extends "base.html" %}
            {% block content %}
                <h2>Members page</h2>
                <p>This page can only be accessed by authenticated users.</p><br/>
                <p><a href={{ url_for('home_page') }}>Home page</a> (anyone)</p>
                <p><a href={{ url_for('members_page') }}>Members page</a> (login required)</p>
            {% endblock %}
            """)

    return app
コード例 #20
0
ファイル: model.py プロジェクト: Auzzy/bfig-sponsor-tracker
    target.name = target.filename.rsplit('/',
                                         maxsplit=1)[-1].rsplit('.',
                                                                maxsplit=1)[0]
    target.type = data.AssetType[target.type_name]


@event.listens_for(User, 'load')
def load_user(target, context):
    target.type = data.UserType[
        target.
        type_name] if target.type_name in data.UserType.__members__ else None


def password_validator(form, field):
    password = field.data
    if len(password) < 6:
        raise ValidationError("Password must have at least 6 characters.")


if not hasattr(app, "user_manager"):
    db_adapter = SQLAlchemyAdapter(db,
                                   User,
                                   UserAuthClass=UserAuth,
                                   UserEmailClass=UserEmail)
    user_manager = UserManager(db_adapter,
                               app,
                               password_validator=password_validator)

if __name__ == '__main__':
    manager.run()
コード例 #21
0
from flask.ext.bootstrap import Bootstrap
from flask.ext.login import LoginManager
from flask.ext.mail import Mail
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.user import SQLAlchemyAdapter, UserManager

basedir = os.path.expanduser('~') + '/.kex/'

app = Flask(__name__)

app.config.from_object('config.default')
# app.config.from_object('config.production')

db = SQLAlchemy(app)
mail = Mail(app)
Bootstrap(app)
login_manager = LoginManager()
login_manager.init_app(app)

from models import User

db_adapter = SQLAlchemyAdapter(db, User)
user_manager = UserManager(db_adapter=db_adapter,
                           app=app,
                           login_manager=login_manager)

from keys import keys

app.register_blueprint(keys)

import views, oauth
コード例 #22
0
def create_app(test_config=None):                   # For automated tests
    # Setup Flask and read config from ConfigClass defined above
    app = Flask(__name__)
    app.config.from_object(__name__+'.ConfigClass')

    # Load local_settings.py if file exists         # For automated tests
    try: app.config.from_object('local_settings')
    except: pass

    # Load optional test_config                     # For automated tests
    if test_config:
        app.config.update(test_config)

    # Initialize Flask extensions
    db = SQLAlchemy(app)                            # Initialize Flask-SQLAlchemy
    mail = Mail(app)                                # Initialize Flask-Mail

    # Define the User data model. Make sure to add flask.ext.user UserMixin!!
    class User(db.Model, UserMixin):
        id = db.Column(db.Integer, primary_key=True)

        # User authentication information
        username = db.Column(db.String(50), nullable=True, unique=True)
        password = db.Column(db.String(255), nullable=False, server_default='')
        reset_password_token = db.Column(db.String(100), nullable=False, server_default='')

        # User email information
        email = db.Column(db.String(255), nullable=True, unique=True)
        confirmed_at = db.Column(db.DateTime())

        # User information
        is_enabled = db.Column(db.Boolean(), nullable=False, server_default='0')
        first_name = db.Column(db.String(100), nullable=False, server_default='')
        last_name = db.Column(db.String(100), nullable=False, server_default='')

        # Relationships
        roles = db.relationship('Role', secondary='user_roles',
                backref=db.backref('users', lazy='dynamic'))

        def is_active(self):
            return self.is_enabled

    # Define the Role data model
    class Role(db.Model):
        id = db.Column(db.Integer(), primary_key=True)
        name = db.Column(db.String(50), unique=True)

    # Define the UserRoles data model
    class UserRoles(db.Model):
        id = db.Column(db.Integer(), primary_key=True)
        user_id = db.Column(db.Integer(), db.ForeignKey('user.id', ondelete='CASCADE'))
        role_id = db.Column(db.Integer(), db.ForeignKey('role.id', ondelete='CASCADE'))

    # Reset all the database tables
    db.create_all()

    # Setup Flask-User
    db_adapter = SQLAlchemyAdapter(db,  User)
    user_manager = UserManager(db_adapter, app)

    # Create regular 'member' user
    if not User.query.filter(User.username=='member').first():
        user = User(username='******', email='*****@*****.**', is_enabled=True,
                password=user_manager.hash_password('Password1'))
        db.session.add(user)
        db.session.commit()

    # Create 'user007' user with 'secret' and 'agent' roles
    if not User.query.filter(User.username=='user007').first():
        user1 = User(username='******', email='*****@*****.**', is_enabled=True,
                password=user_manager.hash_password('Password1'))
        user1.roles.append(Role(name='secret'))
        user1.roles.append(Role(name='agent'))
        db.session.add(user1)
        db.session.commit()

    # The '/' page is accessible to anyone
    @app.route('/')
    def home_page():
        # if current_user.is_authenticated():
        #     return user_profile_page()
        return render_template_string("""
            {% extends "base.html" %}
            {% block content %}
            <h2>{%trans%}Home Page{%endtrans%}</h2>
            <p><a href="{{ url_for('user.login') }}">{%trans%}Sign in{%endtrans%}</a></p>
            {% endblock %}
            """)

    # The '/profile' page requires a logged-in user
    @app.route('/user/profile')
    @login_required                                 # Use of @login_required decorator
    def user_profile_page():
        return render_template_string("""
            {% extends "base.html" %}
            {% block content %}
            <h2>{%trans%}Profile Page{%endtrans%}</h2>
            <p> {%trans%}Hello{%endtrans%}
                {{ current_user.username or current_user.email }},</p>
            <p> <a href="{{ url_for('user.change_username') }}">
                {%trans%}Change username{%endtrans%}</a></p>
            <p> <a href="{{ url_for('user.change_password') }}">
                {%trans%}Change password{%endtrans%}</a></p>
            <p> <a href="{{ url_for('user.logout') }}?next={{ url_for('user.login') }}">
                {%trans%}Sign out{%endtrans%}</a></p>
            {% endblock %}
            """)

    # The '/special' page requires a user that has the 'special' AND ('sauce' OR 'agent') role.
    @app.route('/special')
    @roles_required('secret', ['sauce', 'agent'])   # Use of @roles_required decorator
    def special_page():
        return render_template_string("""
            {% extends "base.html" %}
            {% block content %}
            <h2>{%trans%}Special Page{%endtrans%}</h2>
            {% endblock %}
            """)

    return app
コード例 #23
0
def create_app():
    # Setup Flask and read config from ConfigClass defined above
    app = Flask(__name__)
    app.config.from_object(__name__ + '.ConfigClass')

    # Initialize Flask extensions
    if USERS:
        babel = Babel(app)
        db = SQLAlchemy(app)
        mail = Mail(app)

        @babel.localeselector
        def get_locale():
            translations = [
                str(translation) for translation in babel.list_translations()
            ]
            return request.accept_languages.best_match(translations)

        # Define User model. Make sure to add flask.ext.user UserMixin!!
        class User(db.Model, UserMixin):
            id = db.Column(db.Integer, primary_key=True)
            active = db.Column(db.Boolean(), nullable=False, default=False)
            username = db.Column(db.String(50), nullable=False, unique=True)
            password = db.Column(db.String(255), nullable=False, default='')
            email = db.Column(db.String(255), nullable=False, unique=True)
            confirmed_at = db.Column(db.DateTime())
            reset_password_token = db.Column(db.String(100),
                                             nullable=False,
                                             default='')

        # Create all database tables
        db.create_all()

        # Setup Flask-User
        db_adapter = SQLAlchemyAdapter(db, User)
        user_manager = UserManager(db_adapter, app)

        # The '/profile' page requires a logged-in user
        @app.route('/profile')
        @login_required
        def profile():
            return render_template_string("""
                {% extends "base.html" %}
                {% block content %}
                    <h2>{%trans%}Profile Page{%endtrans%}</h2>
                    <p> {%trans%}Hello{%endtrans%}
                        {{ current_user.username or current_user.email }},</p>
                    <p> <a href="{{ url_for('user.change_username') }}">
                        {%trans%}Change username{%endtrans%}</a></p>
                    <p> <a href="{{ url_for('user.change_password') }}">
                        {%trans%}Change password{%endtrans%}</a></p>
                    <p> <a href="{{ url_for('user.logout') }}?next={{ url_for('user.login') }}">
                        {%trans%}Sign out{%endtrans%}</a></p>
                {% endblock %}
                """)

    def store_metadata(exposed_ports, container_id, container, image_name):
        global BAD
        urlport = ""
        for exposed_port in exposed_ports:
            container_port = c.port(container_id, exposed_port)
            url = "%s:%s" % (DOMAIN, container_port[0]['HostPort'])
            urlport += url + ","

        hmap = {}
        hmap['container_id'] = container_id
        hmap['container'] = container
        hmap['url'] = urlport[:-1]
        hmap['timestamp'] = int(time.time())
        hmap['expired'] = 0
        hmap['image'] = image_name
        data = json.dumps(hmap)
        check_cookie()
        # check cookie formatting, ensure that it exists in sessions
        # also check that it doesn't already exist
        if not BAD:
            cookie = request.cookies.get(COOKIE)
            if re.match(UUID4, cookie):
                if r.sismember('sessions', cookie):
                    r.lpush(cookie, data)
                else:
                    app.logger.info('invalid session')
                    BAD = True
            else:
                app.logger.info('invalid uuid')
                BAD = True

    def get_url(request):
        global BAD
        # this is validated with check_cookie before_request
        if not BAD:
            uid = request.cookies.get(COOKIE)
            container = r.lindex(uid, 0)
            container = json.loads(container)
            url = container['url']
            if "," in url:
                url_list = url.split(',')
                url = url_list[-1]
            return url
        else:
            return ""

    def after_this_request(f):
        if not hasattr(g, 'after_request_callbacks'):
            g.after_request_callbacks = []
        g.after_request_callbacks.append(f)
        return f

    @app.after_request
    def call_after_request_callbacks(response):
        for callback in getattr(g, 'after_request_callbacks', ()):
            callback(response)
        return response

    @app.before_request
    def check_cookie():
        global BAD
        uid = request.cookies.get(COOKIE)
        if uid is None:
            uid = str(uuid.uuid4())

            @after_this_request
            def save_cookie(response):
                # validate uid formatting, and that it doesn't conflict
                if re.match(UUID4, uid):
                    if r.sismember('sessions', uid):
                        app.logger.info('uuid already exists')
                        BAD = True
                    else:
                        r.sadd('sessions', uid)
                        g.uid = uid
                        BAD = False
                        response.set_cookie(COOKIE, uid, httponly=True)
                else:
                    app.logger.info('invalid uuid')
                    BAD = True
                BAD = False

    @app.route('/')
    def index():
        return render_template("index.html")

    @app.route('/github-buttons')
    def github_buttons():
        return render_template("github-btn.html")

    @app.route('/details/wait')
    def wait():
        if SSL:
            return redirect("/gestalt", code=302)
        else:
            return render_template("wait.html")

    @app.route('/new', methods=["POST"])
    def new():
        if not USERS or current_user.is_authenticated():
            exposed_ports = [EXPOSED_PORT1]
            cookie = request.cookies.get(COOKIE)
            if re.match(UUID4, cookie):
                spinup = 1
                # check if this image has already been spun up for this session
                if r.exists(cookie):
                    # !! TODO error check
                    data = r.lrange(cookie, 0, -1)
                    for record in data:
                        jrec = json.loads(record)
                        if jrec['image'] == "lab41/gestalt":
                            if jrec['expired'] == 0:
                                app.logger.info(
                                    'a gestalt container is already running for this session'
                                )
                                spinup = 0
                                return jsonify(url="wait")
                if spinup == 1:
                    host_config = c.create_host_config(publish_all_ports=True)
                    if SSL:
                        container = c.create_container(image=IMAGE_NAME1,
                                                       host_config=host_config,
                                                       environment={
                                                           'REMOTE_HOST':
                                                           RSYSLOG_HOST,
                                                           'PARENT_HOST':
                                                           PARENT_HOST,
                                                           'SSL': "True"
                                                       })
                    else:
                        container = c.create_container(image=IMAGE_NAME1,
                                                       host_config=host_config,
                                                       environment={
                                                           'REMOTE_HOST':
                                                           RSYSLOG_HOST,
                                                           'PARENT_HOST':
                                                           PARENT_HOST
                                                       })
                    c.start(container=container.get('Id'))
                    b = c.inspect_container(container)
                    bad = store_metadata(exposed_ports, container.get('Id'),
                                         container, IMAGE_NAME1)
                    if bad:
                        return render_template("index.html")
                    else:
                        return jsonify(url="launch")
                else:
                    return jsonify(url="wait")
        else:
            return jsonify(url="login")

    @app.route('/details/login')
    def details_login():
        return redirect(url_for('user.login'))

    @app.route('/details/launch')
    def details():
        if not USERS or current_user.is_authenticated():
            url = get_url(request)
            return render_template("details.html",
                                   url=url,
                                   USERS=USERS,
                                   SSL=SSL,
                                   DOMAIN=DOMAIN)
        else:
            return jsonify(url="login")

    @app.route('/robot.txt')
    def robot():
        return render_template("robot.html")

    @app.route('/favicon.ico')
    def favicon():
        return send_from_directory(os.path.join(app.root_path, 'static'),
                                   'favicon.ico',
                                   mimetype='image/vnd.microsoft.icon')

    return app
コード例 #24
0
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import os

from flask import Flask
from flask.ext.babel import Babel
from flask.ext.mail import Mail
from flask.ext.user import UserManager, SQLAlchemyAdapter

app = Flask(__name__)
app.config.from_object(os.environ['APP_SETTINGS'])
babel = Babel(app)
mail = Mail(app)
from models import db, User
from forms import ExtendedRegisterForm

db.init_app(app)
db_adapter = SQLAlchemyAdapter(db, User)
user_manager = UserManager(db_adapter, app, register_form=ExtendedRegisterForm)
from views import *

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)
コード例 #25
0
ファイル: minimal_app.py プロジェクト: yacneyac/Flask-User
    translations = [str(translation) for translation in babel.list_translations()]
    return request.accept_languages.best_match(translations)

# Define User model. Make sure to add flask.ext.user UserMixin!!
class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    active = db.Column(db.Boolean(), nullable=False, default=False)
    username = db.Column(db.String(50), nullable=False, unique=True)
    password = db.Column(db.String(255), nullable=False, default='')

# Create all database tables
db.create_all()

# Setup Flask-User
db_adapter = SQLAlchemyAdapter(db,  User)       # Select database adapter
user_manager = UserManager(db_adapter, app)     # Init Flask-User and bind to app

# The Home page is accessible to anyone
@app.route('/')
def home_page():
    if current_user.is_authenticated():
        return profile_page()
    return render_template_string("""
        {% extends "base.html" %}
        {% block content %}
        <h2>{%trans%}Home Page{%endtrans%}</h2>
        <p> <a href="{{ url_for('user.login') }}">{%trans%}Sign in{%endtrans%}</a> or
            <a href="{{ url_for('user.register') }}">{%trans%}Register{%endtrans%}</a></p>
        {% endblock %}
        """)
コード例 #26
0
def init_app(app, test_config=None):  # For automated tests
    # Setup Flask and read config from ConfigClass defined above
    app.config.from_object(__name__ + '.ConfigClass')

    # Load local_settings.py if file exists         # For automated tests
    try:
        app.config.from_object('local_settings')
    except:
        pass

    # Load optional test_config                     # For automated tests
    if test_config:
        app.config.update(test_config)

    # Initialize Flask extensions
    babel = Babel(app)  # Initialize Flask-Babel
    mail = Mail(app)  # Initialize Flask-Mail

    # Reset all the database tables
    db.create_all()

    # Setup Flask-User
    db_adapter = SQLAlchemyAdapter(db,
                                   User,
                                   UserInvitationClass=UserInvitation)
    user_manager = UserManager(db_adapter, app)

    # Create regular 'member' user
    if not User.query.filter(User.username == 'member').first():
        user = User(username='******',
                    email='*****@*****.**',
                    active=True,
                    password=user_manager.hash_password('Password1'),
                    confirmed_at=datetime.datetime.utcnow())
        db.session.add(user)
        db.session.commit()

    # Create 'user007' user with 'secret' and 'agent' roles
    if not User.query.filter(User.username == 'user007').first():
        user1 = User(username='******',
                     email='*****@*****.**',
                     active=True,
                     password=user_manager.hash_password('Password1'))
        user1.roles.append(Role(name='secret'))
        user1.roles.append(Role(name='agent'))
        db.session.add(user1)
        db.session.commit()

    # The '/' page is accessible to anyone
    @app.route('/')
    def home_page():
        return render_template_string("""
            {% extends "base.html" %}
            {% block content %}
            <h2>{%trans%}Home Page{%endtrans%}</h2>
            <p><a href="{{ url_for('user.login') }}">{%trans%}Sign in{%endtrans%}</a></p>
            {% endblock %}
            """)

    # The '/profile' page requires a logged-in user
    @app.route('/user/profile')
    @login_required  # Use of @login_required decorator
    @confirm_email_required
    def user_profile_page():
        return render_template_string("""
            {% extends "base.html" %}
            {% block content %}
            <h2>{%trans%}Profile Page{%endtrans%}</h2>
            <p> {%trans%}Hello{%endtrans%}
                {{ current_user.username or current_user.email }},</p>
            <p> <a href="{{ url_for('user.change_username') }}">
                {%trans%}Change username{%endtrans%}</a></p>
            <p> <a href="{{ url_for('user.change_password') }}">
                {%trans%}Change password{%endtrans%}</a></p>
            <p> <a href="{{ url_for('user.invite') }}">
                {%trans%}Invite User{%endtrans%}</a></p>
            <p> <a href="{{ url_for('user.logout') }}?next={{ url_for('user.login') }}">
                {%trans%}Sign out{%endtrans%}</a></p>
            {% endblock %}
            """)

    # The '/special' page requires a user that has the 'special' AND ('sauce' OR 'agent') role.
    @app.route('/special')
    @roles_required('secret',
                    ['sauce', 'agent'])  # Use of @roles_required decorator
    def special_page():
        return render_template_string("""
            {% extends "base.html" %}
            {% block content %}
            <h2>{%trans%}Special Page{%endtrans%}</h2>
            {% endblock %}
            """)

    # For testing only
    app.db = db
    app.UserEmailClass = UserEmail

    return app
コード例 #27
0
ファイル: __init__.py プロジェクト: mcilroy/qfpc
@babel.localeselector
def get_locale():
    translations = [
        str(translation) for translation in babel.list_translations()
    ]
    return request.accept_languages.best_match(translations)


from .models import User, Role, db, MemberInfo
# Reset all the database tables
#db.drop_all()
db.create_all()

# Setup Flask-User
db_adapter = SQLAlchemyAdapter(db, User)
user_manager = UserManager(db_adapter, app)

# Create 'user007' user with 'secret' and 'agent' roles
if not User.query.filter(User.username == 'admin').first():
    user1 = User(username='******',
                 active=True,
                 password=user_manager.hash_password('1'))
    user1.roles.append(Role(name='admin'))
    db.session.add(user1)
    db.session.commit()
if not User.query.filter(User.username == 'user').first():
    user2 = User(username='******',
                 active=True,
                 password=user_manager.hash_password('1'))
    user2.roles.append(Role(name='user'))
    db.session.add(user2)