def create_app(): """ Setup the Flask application to handle any remote service routine calls. This includes interaction between the modules when run remotely and the front-end. Returns: Flask object. """ app = flask.Flask(__name__) app.config.update( dict(DEBUG=True, SECRET_KEY=config['REMU']['secret_key'].encode())) key = config['REMU']['secret_key'].encode() fern = fernet.Fernet(key) # We are required to set user_loader to the method responsible for # user account lookup. login_manager = flask_login.LoginManager(app) login_manager.login_view = 'admin.login' login_manager.user_loader(db.get_user) # Ensure the application is able to reach the Manager module. for m in modules: if isinstance(m, Manager): l.debug("Adding local manager to app config") app.config['MANAGER'] = m if "MANAGER" not in app.config: l.debug("Adding remote manager to app config") app.config['MANAGER'] = RemoteComponent(config['MANAGER']['address'], config['MANAGER']['port'], [ Manager, ]) @app.route('/<path:path>') def catch_all(path): """ Routing method to handle any path not specifically defined in the user and admin blueprints. This is useful as it allows us to decrypt the url prior to handling the request. Returns: str. The view (or result) to return to the caller. """ if "favicon.ico" in path: return "" try: url = urlparse.urlparse(flask.request.url) path = url.path[1:].encode() path = fern.decrypt(path).decode() except fernet.InvalidToken: l.error("Unable to decrpyt url: %s", url.path) return flask.render_template("404.html") l.debug("Received path: %s", path) if path.find('?') > 0: method, query = path.split('?') query = urlparse.parse_qsl(query) params = {} for k, v in query: try: e = ast.literal_eval(v) params[k] = e except ValueError: params[k] = v else: method = path params = None l.debug("Parsed args: %s", str(params)) result = "" for m in modules: try: function = getattr(m, method) if function: result = function( **params) if params is not None else function() break except AttributeError: pass # We must return a string for the Flask view --- needs to be encrypted?? l.debug("Result: %s", str(result)) return str(result) @app.before_request def assets(): """ Ugly workaround to deal with the inline resource requests from bundle.js """ if "static" in flask.request.path: file = flask.request.path[flask.request.path.find("static") + 7:] return flask.send_from_directory('static', file) return None return app
from flask import Blueprint, render_template, request, make_response, url_for, abort, jsonify, redirect import flask_login as session_login from authentication.forms import LoginInformationForm, UserInformationForm from models import User, db from werkzeug.exceptions import BadRequest, Unauthorized, Forbidden from sqlalchemy.exc import IntegrityError blueprint = Blueprint('authentication', __name__, url_prefix='/authentication', static_folder='static', template_folder='templates') login_manager = session_login.LoginManager() def user_to_dict(user_obj): """ Returns the `authentication.models.User` dictionary representation """ u = { 'id': user_obj.id, 'username': user_obj.username, 'password_hash': user_obj.password_hash, 'email': user_obj.email, 'firstname': user_obj.firstname, 'middlename': user_obj.middlename, 'lastname': user_obj.lastname, 'gender': user_obj.gender, 'account_type': user_obj.account_type } return u @login_manager.user_loader def load_user(user_id): return User.query.filter_by(id=user_id).first_or_404()
def __init__(self, anonymous_user): self.login_manager = flask_login.LoginManager() self.login_manager.anonymous_user = anonymous_user self.app = None
# and make it possible to spoof the KDC import kerberos from flask import flash, redirect, url_for from flask_login import current_user from wtforms import Form, PasswordField, StringField from wtforms.validators import InputRequired from airflow import models from airflow.configuration import conf from airflow.exceptions import AirflowConfigException from airflow.security import utils from airflow.utils.log.logging_mixin import LoggingMixin from airflow.utils.session import provide_session # pylint: disable=c-extension-no-member LOGIN_MANAGER = flask_login.LoginManager() LOGIN_MANAGER.login_view = 'airflow.login' # Calls login() below LOGIN_MANAGER.login_message = None class AuthenticationError(Exception): """Error raised when authentication error occurs""" class KerberosUser(models.User, LoggingMixin): """User authenticated with Kerberos""" def __init__(self, user): self.user = user @staticmethod def authenticate(username, password):
import flask import flask_login import flask_migrate import flask_babel import ipaddress import redis from datetime import datetime, timedelta from flask.sessions import SessionMixin, SessionInterface from itsdangerous.encoding import want_bytes from werkzeug.datastructures import CallbackDict from werkzeug.middleware.proxy_fix import ProxyFix # Login configuration login = flask_login.LoginManager() login.login_view = "sso.login" @login.unauthorized_handler def handle_needs_login(): """ redirect unauthorized requests to login page """ return flask.redirect(flask.url_for('sso.login')) # DNS stub configured to do DNSSEC enabled queries resolver = dns.resolver.Resolver() resolver.use_edns(0, 0, 1232) resolver.flags = dns.flags.AD | dns.flags.RD
def __init__(self, app=None, login_manager=flask_login.LoginManager()): self.app = app self.login_manager = login_manager if app is not None: self.init_app(app)
import flask import os import flask_sqlalchemy import flask_migrate import flask_login from flask_uploads import configure_uploads, IMAGES, UploadSet basedir = os.path.abspath(os.path.dirname(__file__)) app = flask.Flask(__name__) app.config['SECRET_KEY'] = 'sdjhgsjghlakjf' # if "ON_HEROKU" in os.environ: app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('DATABASE_URL') # else: # app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('DATABASE_URL_LOCAL') app.config['UPLOADED_IMAGES_DEST'] = os.path.join(basedir, 'static/images') images = UploadSet('images', IMAGES) configure_uploads(app, images) db = flask_sqlalchemy.SQLAlchemy(app) migrate = flask_migrate.Migrate(app, db) login_mngr = flask_login.LoginManager(app) from app import routes, models # sqlite:////Users/nikita/Desktop/DevInst/Heroku/My_blog/app/app.db
def setup(index, app): if 'clientID' not in app.config.get( 'peter', {}) or 'clientSecret' not in app.config.get('peter', {}): return #TODO mount error messages at /login and /auth app.config['SECRET_KEY'] = app.config['peter']['clientSecret'] app.config['USE_SESSION_FOR_NEXT'] = True app.register_blueprint(flask_dance.contrib.discord.make_discord_blueprint( client_id=app.config['peter']['clientID'], client_secret=app.config['peter']['clientSecret'], scope='identify', redirect_to='auth_callback'), url_prefix='/login') app.register_blueprint(flask_dance.contrib.twitch.make_twitch_blueprint( client_id=app.config['twitch']['clientID'], client_secret=app.config['twitch']['clientSecret'], redirect_to='twitch_auth_callback'), url_prefix='/login') login_manager = flask_login.LoginManager() login_manager.login_view = 'discord.login' login_manager.login_message = None # Because discord.login does not show flashes, any login message would be shown after a successful login. This would be confusing. login_manager.anonymous_user = AnonymousUser @login_manager.user_loader def load_user(user_id): try: return DiscordPerson( user_id ) # instantiates Mensch, DiscordGuest, or DiscordPerson depending on user data except ValueError: return None login_manager.init_app(app) @app.before_request def global_users(): flask.g.admin = Mensch.admin() flask.g.treasurer = Mensch.treasurer() if flask_login.current_user.is_admin and 'viewAs' in app.config['web']: flask.g.view_as = True flask.g.user = DiscordPerson(app.config['web']['viewAs']) else: flask.g.view_as = False flask.g.user = flask_login.current_user @app.route('/auth') def auth_callback(): if not flask_dance.contrib.discord.discord.authorized: flask.flash('Discord-Login fehlgeschlagen.', 'error') return flask.redirect(flask.url_for('index')) response = flask_dance.contrib.discord.discord.get('/api/v6/users/@me') if not response.ok: return flask.make_response( ('Discord meldet Fehler {} auf {}: {}'.format( response.status_code, jinja2.escape(response.url), jinja2.escape(response.text)), response.status_code, [])) person = DiscordPerson(response.json()['id']) if not person.is_active: try: person.profile_data except FileNotFoundError: flask.flash( 'Sie haben sich erfolgreich mit Discord angemeldet, sind aber nicht im Gefolge Discord server.', 'error') return flask.redirect(flask.url_for('index')) else: flask.flash( 'Dein Account wurde noch nicht freigeschaltet. Stelle dich doch bitte einmal kurz im #general vor und warte, bis ein admin dich bestätigt.', 'error') return flask.redirect(flask.url_for('index')) flask_login.login_user(person, remember=True) flask.flash(jinja2.Markup('Hallo {}.'.format(person.__html__()))) next_url = flask.session.get('next') if next_url is None: return flask.redirect(flask.url_for('index')) elif is_safe_url(next_url): return flask.redirect(next_url) else: return flask.abort(400) @app.route('/auth/twitch') def twitch_auth_callback(): if not flask.g.user.is_active: return flask.make_response(( 'Bitte melden Sie sich zuerst mit Discord an, bevor Sie sich mit Twitch anmelden.', 403, [])) #TODO template if not flask.g.user.is_mensch: return flask.make_response(( 'Die Twitch-Integration ist nur für verifizierte Gefolgemenschen verfügbar.', 403, [])) #TODO template if not flask_dance.contrib.twitch.twitch.authorized: flask.flash('Twitch-Login fehlgeschlagen.', 'error') return flask.redirect(flask.url_for('index')) response = flask_dance.contrib.twitch.twitch.get('users') if not response.ok: return flask.make_response( ('Twitch meldet Fehler {} auf {}: {}'.format( response.status_code, jinja2.escape(response.url), jinja2.escape(response.text)), response.status_code, [])) flask.g.user.twitch = response.json()['data'][0] flask.flash('Twitch-Konto erfolgreich verknüpft.') next_url = flask.session.get('next') if next_url is None: return flask.redirect(flask.url_for('index')) elif is_safe_url(next_url): return flask.redirect(next_url) else: return flask.abort(400) @app.route('/logout') def logout(): flask_login.logout_user() return flask.redirect(flask.url_for('index')) @index.child('mensch', 'Menschen und Gäste', decorators=[mensch_required]) @gefolge_web.util.template('menschen-index') def menschen(): pass @menschen.children(DiscordPerson, methods=['GET', 'POST']) @gefolge_web.util.template() def profile(person): import gefolge_web.event.model if not person.is_active: return gefolge_web.util.render_template('profile-404', mensch=person), 404 if person.is_mensch and (flask.g.user.is_admin or flask.g.user.is_treasurer or flask.g.user == person): transfer_money_form = TransferMoneyForm(person) if transfer_money_form.submit_transfer_money_form.data and transfer_money_form.validate( ): recipient = transfer_money_form.recipient.data person.add_transaction( gefolge_web.util.Transaction.transfer( recipient, -transfer_money_form.amount.data, transfer_money_form.comment.data)) recipient.add_transaction( gefolge_web.util.Transaction.transfer( person, transfer_money_form.amount.data, transfer_money_form.comment.data)) if flask.g.user != person: peter.msg( person, '<@{}> ({}) hat {} von deinem Guthaben an <@{}> ({}) übertragen. {}: <https://gefolge.org/me>' .format( flask.g.user.snowflake, flask.g.user, transfer_money_form.amount.data, recipient.snowflake, recipient, 'Kommentar und weitere Infos' if transfer_money_form.comment.data else 'Weitere Infos')) if flask.g.user != recipient: peter.msg( recipient, '<@{}> ({}) hat {} an dich übertragen. {}: <https://gefolge.org/me>' .format( person.snowflake, person, transfer_money_form.amount.data, 'Kommentar und weitere Infos' if transfer_money_form.comment.data else 'Weitere Infos')) return flask.redirect(flask.g.view_node.url) wurstmineberg_transfer_money_form = WurstminebergTransferMoneyForm( person) if wurstmineberg_transfer_money_form.submit_wurstmineberg_transfer_money_form.data and wurstmineberg_transfer_money_form.validate( ): transaction = gefolge_web.util.Transaction.wurstmineberg( wurstmineberg_transfer_money_form.amount.data) person.add_transaction(transaction) gefolge_web.util.cached_json( lazyjson.File('/opt/wurstmineberg/money.json') )['transactions'].append({ 'amount': wurstmineberg_transfer_money_form.amount.data.value, 'currency': 'EUR', 'time': '{:%Y-%m-%dT%H:%M:%SZ}'.format( transaction.time.astimezone(pytz.utc)), 'type': 'gefolge' }) else: transfer_money_form = None wurstmineberg_transfer_money_form = None return { 'events': [ event for event in gefolge_web.event.model.Event if person in event.signups ], 'person': person, 'transfer_money_form': transfer_money_form, 'wurstmineberg_transfer_money_form': wurstmineberg_transfer_money_form } @profile.catch_init(ValueError) def profile_catch_init(exc, value): return gefolge_web.util.render_template('profile-404', snowflake=value), 404 @profile.child('edit', 'bearbeiten', methods=['GET', 'POST']) @gefolge_web.util.template('profile-edit') def profile_edit(person): if flask.g.user != person and not flask.g.user.is_admin: flask.flash( 'Du bist nicht berechtigt, dieses Profil zu bearbeiten.', 'error') return flask.redirect(flask.g.view_node.parent.url) profile_form = ProfileForm(person) if profile_form.submit_profile_form.data and profile_form.validate(): gefolge_web.util.log( 'profileEdit', { 'mensch': person.snowflake, 'nickname': profile_form.nickname.data, 'timezone': None if profile_form.timezone.data is None else str( profile_form.timezone.data), 'enableDejavu': profile_form.enable_dejavu.data, 'eventTimezoneOverride': profile_form.event_timezone_override.data }) person.nickname = profile_form.nickname.data if profile_form.timezone.data is None: if 'timezone' in person.userdata: del person.userdata['timezone'] else: person.userdata['timezone'] = str(profile_form.timezone.data) person.userdata['enableDejavu'] = profile_form.enable_dejavu.data person.userdata[ 'eventTimezoneOverride'] = profile_form.event_timezone_override.data return flask.redirect(flask.g.view_node.parent.url) else: return {'person': person, 'profile_form': profile_form} @profile.child('reset-key') def reset_api_key(person): if flask.g.user.is_admin or flask.g.user == person: del person.api_key return flask.redirect(flask.url_for('api_index')) else: flask.flash( jinja2.Markup( 'Du bist nicht berechtigt, den API key für {} neu zu generieren.' .format(person.__html__())), 'error') return flask.redirect(flask.url_for('api_index')) @index.redirect('me', decorators=[mensch_required] ) #TODO profile pages for Discord guests? def me(): return menschen, flask.g.user
from flask import * from flask_cors import CORS from config_file import config_var import flask_migrate as fm import flask_sqlalchemy as fs import flask_login application=Flask(__name__) application.config.from_object(config_var) CORS(application) # For setting up the database everytime the system is run database_var=fs.SQLAlchemy(application) database_migration=fm.Migrate(application,database_var) # For letting the user_login login_var=flask_login.LoginManager(application) login_var.login_view='login_page' # print(application) from application_code import routing,data_table_model
if ':memory:' in flaskApp.config['SQLALCHEMY_DATABASE_URI']: logging.error('Invalid SQLALCHEMY_DATABASE_URI: :memory:') sys.exit(1) # set random secret key if not provided in the Flask configuration if 'SECRET_KEY' not in flaskApp.config or not flaskApp.config['SECRET_KEY']: flaskApp.config.update(SECRET_KEY=os.urandom(24)) # check and create private public keypair if not existing if not caesar.check_keys_exsist(appConfig.database['privkey'], appConfig.database['pubkey']): caesar.generate_keys(appConfig.database['privkey'], appConfig.database['pubkey']) # finish database initialization ilsc.appDB.init_app(flaskApp) # init login manager flaskLoginManager = flask_login.LoginManager(flaskApp) @flaskLoginManager.user_loader def user_loader(userguid): user = ilsc.User.query.filter_by(userid=userguid).first() return user @flaskLoginManager.unauthorized_handler def unauthorized(): flask.session['next_url'] = flask.request.path return flask.redirect(flask.url_for('r_signin'),code=302) def check_roles(roles=None): ''' custom login_required decorator '''
def __init__(self): self.login_manager = flask_login.LoginManager()
def __init__(self): self.login_manager = flask_login.LoginManager() self.login_manager.login_view = 'airflow.login' self.login_manager.session_protection self.flask_app = None self.api_url = None
app.secret_key = 'demo' class User(flask_login.UserMixin): def __init__(self, **kwargs): super(User, self).__init__(**kwargs) def is_admin(self): print('[user] {}'.format(self.id)) return True my_username = '******' my_password = '******' user_instance = User() login_manager = flask_login.LoginManager(app=app) def admin_required(func): @wraps(func) def decorated_view(*args, **kwargs): if flask_login.current_user.is_admin(): return func(*args, **kwargs) flask.abort(403) return decorated_view @login_manager.user_loader def user_loader(user_login_id): user_instance.id = user_login_id
from flask import Flask, render_template, request, session, redirect, url_for, flash import re import flask_login import mysql.connector from app import app, mysql # Импортим app, и объект DB from collections import namedtuple import mysql.connector as connector import hashlib ADMIN_ROLE_ID = 1 MANAGE_ROLE_ID = 2 USER_ROLE_ID = 3 login_manager = flask_login.LoginManager() # Инициализируем логин менеджер login_manager.init_app(app) login_manager.login_view = "login" login_manager.login_message = "Для доступа к этой странице необходимо пройти процедуру аунтификации." def is_admin(): return flask_login.current_user.role_id == ADMIN_ROLE_ID # Проверка роли юзера текущей сессии def is_manager(): return flask_login.current_user.role_id == MANAGE_ROLE_ID # Проверка роли юзера текущей сессии class UsersPolicy: def __init__(self, record=None): self.record = record def create(self): return is_admin()
# my modules from app.services.configs.mcf import Config, Database_Config from app.services.courier.svg import SvgMaster from app.services.courier.jsr import JsonMaster from app.alchemy import session as Session from app.alchemy.models.users import User """ Service User""" folder = "templates" blueprint: flask.Blueprint = flask.Blueprint('user_api', __name__, template_folder=folder) login_manager: flogin.LoginManager = flogin.LoginManager() # courier: Courier = Courier() Session.global_init(Database_Config.USER) session = Session.create_session() def init_blueprint(folder: str=Config.TEMPLATES_FOLDER): global blueprint blueprint = flask.Blueprint('user_api', __name__, template_folder=folder) def init_login(app: flask.Flask=None): login_manager.setup_app(app) def setTemplateFolder(self, folder="templates"): global blueprint blueprint = flask.Blueprint('user_api', __name__, template_folder=folder)
import sqlite3 import hashlib # from wtforms import * bp = flask.Blueprint('usermanager', __name__) app = flask.Flask(__name__) app.config.update( dict( DATABASE=os.path.join(app.root_path, 'entries.sqlite'), USER_DATABASE=os.path.join(app.root_path, 'users.sqlite'), DEBUG=True, SECRET_KEY='123456', )) login_manager = fl.LoginManager() login_manager.init_app(app) # Mock database, change to sqlite later # users = {'*****@*****.**': {'password': '******'}} class User(fl.UserMixin): pass @login_manager.user_loader def user_loader(username): user = query_db('select * from users where username = ?', [username], one=True) if user is None:
def __init__(self, cfg=None, name=__name__, image_processor_class=ImageProcessor): ''' Launch App ''' self.cfg = cfg = get_config(cfg) self.app = Flask(name or self.__class__.__name__, template_folder=os.path.join(APP_ROOT, 'templates')) self.app.secret_key = cfg.SECRET_KEY if cfg.TEMPLATE_DIRECTORIES: app.jinja_loader = jinja2.ChoiceLoader([app.jinja_loader] + [ jinja2.FileSystemLoader(path) for path in cfg.TEMPLATE_DIRECTORIES ]) self.app.wsgi_app = PrefixMiddleware(self.app.wsgi_app, prefix=self.cfg.BASE_URL) self.login_manager = flask_login.LoginManager() self.login_manager.init_app(self.app) ''' Data Storage - loading image paths and dates - used to store currently loaded images - loading and storing labels - currently via csv, but that can change - loading image processor used for all image pipelines ''' self.imdb = uo.uoimdb(cfg=cfg) if not len(self.imdb.df): raise SystemExit("No images found at {}... \(TnT)/".format( self.imdb.abs_file_pattern)) # # store number of times an image was viewed # if not 'views' in self.imdb.df.columns: # self.imdb.df['views'] = 0 print('Image Database Shape: {}'.format(self.imdb.df.shape)) print(self.imdb.df.head()) # load all labels utils.ensure_dir(self.cfg.LABELS_LOCATION) self.labels_dfs = {} for f in glob.glob(os.path.join(self.cfg.LABELS_LOCATION, '*.csv')): lbl_name = os.path.splitext(os.path.basename(f))[0] self.labels_dfs[lbl_name] = pd.read_csv(f).set_index('id').fillna( '') if not len(self.labels_dfs): self.new_label_set_df(self.cfg.DEFAULT_LABELS_FILE) # performs the image processing self.image_processor = image_processor_class(self.imdb) utils.ensure_dir(self.cfg.IMAGE_CACHE_LOCATION) # used for finding consecutive days self.dates_list = list( np.sort(np.unique(self.imdb.df.date.dt.strftime(cfg.DATE_FORMAT)))) # expose the configuration options to javascript so it can properly construct links self.app.context_processor(self.inject_globals) self.define_routes() # load all generated random samples self.random_samples = RandomSamples(self.imdb, self.image_processor) self.random_samples.load_samples()
def __init__(self): self.outputFrame = None self.name = "No one" # lock = threading.Lock() # Initialize our Flaskapp self.app = Flask(__name__) self.app.config.from_object(Config) # Initialize login manager for individual users self.login_manager = flask_login.LoginManager() self.login_manager.init_app(self.app) @self.login_manager.user_loader def user_loader(email): if email not in self.users: return user = User() user.id = email return user @self.login_manager.request_loader def request_loader(request): email = request.form.get("email") if email not in self.users: return user = User() user.id = email user.is_authenticated = ( request.form["password"] == self.users[email]["password"]) return user @self.login_manager.unauthorized_handler def unauthorized_handler(): flash("You cannot access Videos until logged in") return redirect(url_for("home")) def generate(): while True: # check if the output frame is available, otherwise skip # the iteration of the loop if self.outputFrame is None: continue # encode the frame in JPEG format (flag, encodedImage) = cv2.imencode(".jpg", self.outputFrame) # ensure the frame was successfully encoded if not flag: continue # print("shitttt") # yield the output frame in the byte format yield (b"--frame\r\n" b"Content-Type: image/jpeg\r\n\r\n" + bytearray(encodedImage) + b"\r\n") @self.app.route("/video_feed") @flask_login.login_required def video_feed(): # return the response generated along with the specific media # type (mime type) return Response( generate(), mimetype="multipart/x-mixed-replace; boundary=frame") @self.app.route("/") def home(): return render_template("index.html", content="what are you doing here?") # Route for handling the login page logic @self.app.route("/login", methods=["GET", "POST"]) def login(): form = LoginForm() if form.validate_on_submit(): flash("Login requested for user {}, remember_me={}".format( form.username.data, form.remember_me.data)) if form.username.data not in self.users: flash("Invalid username or password") return redirect(url_for("login")) elif form.password.data == self.users[ form.username.data]["password"]: user = User() user.id = form.username.data flask_login.login_user(user) return redirect("/") else: flash("Invalid username or password") return redirect(url_for("login")) return render_template("login.html", title="Sign In", form=form) @self.app.route("/pepperoni") def pepperoni(): return "Hello! Here are some nice pepperonis!" @self.app.route("/video") @flask_login.login_required def video(): return render_template("video.html")
# coding: utf-8 """Set up flask.ext.login for our own purposes.""" from __future__ import unicode_literals import functools import flask_login as login # from flask.ext import login import flask from flaskshop.database import models LOGIN_MANAGER = login.LoginManager() LOGIN_MANAGER.login_message_category = 'message info' @LOGIN_MANAGER.user_loader def load_user(user_id): """Function used by flask.ext.login to load a user object given an ID. Checks if the app is in maintenance mode (and returns an anonymous user if so), and otherwise simply loads the user object from the database. """ if flask.current_app.config['MAINTENANCE_MODE']: return LOGIN_MANAGER.anonymous_user else: return models.User.query.get_or_404(user_id) LOGIN_MANAGER.login_view = 'shop.home'
from flask import Flask from flask_sqlalchemy import SQLAlchemy import flask_login as fl app = Flask(__name__) app.config.from_object('config') # Database db = SQLAlchemy(app) manager = fl.LoginManager() manager.init_app(app) sales = fl.LoginManager() sales.init_app(app) cook = fl.LoginManager() cook.init_app(app) deliverer = fl.LoginManager() deliverer.init_app(app) customer = fl.LoginManager() customer.init_app(app) from app import views, models
def register_extensions(app): """ register extensions to the app """ app.jinja_env.add_extension('jinja2.ext.do') # Global values in jinja # Uncomment to enable profiler # See scripts/profile_analyzer.py to analyze output # app = setup_profiler(app) # Compress app responses with gzip compress = Compress() compress.init_app(app) # Influx db time-series database db.init_app(app) influx_db.init_app(app) # Limit authentication blueprint requests to 200 per minute limiter = Limiter(app, key_func=get_ip_address) limiter.limit("200/minute")(routes_authentication.blueprint) # Language translations babel = Babel(app) @babel.localeselector def get_locale(): try: user = User.query.filter( User.id == flask_login.current_user.id).first() if user and user.language != '': for key in LANGUAGES: if key == user.language: return key # Bypass endpoint test error "'AnonymousUserMixin' object has no attribute 'id'" except AttributeError: pass return request.accept_languages.best_match(LANGUAGES.keys()) # User login management login_manager = flask_login.LoginManager() login_manager.init_app(app) @login_manager.user_loader def user_loader(user_id): user = User.query.filter(User.id == user_id).first() if not user: return return user @login_manager.unauthorized_handler def unauthorized(): flash(gettext('Please log in to access this page'), "error") return redirect(url_for('routes_authentication.do_login')) # Create and populate database if it doesn't exist with app.app_context(): db.create_all() populate_db() # This is disabled because there's a bug that messes up user databases # The upgrade script will execute alembic to upgrade the database # alembic_upgrade_db() # Check user option to force all web connections to use SSL # Fail if the URI is empty (pytest is running) if app.config['SQLALCHEMY_DATABASE_URI'] != 'sqlite://': with session_scope( app.config['SQLALCHEMY_DATABASE_URI']) as new_session: misc = new_session.query(Misc).first() if misc and misc.force_https: SSLify(app)
import flask_sqlalchemy import flask_migrate import flask_bootstrap import flask_login import flask_mail import flask_moment import werkzeug from app import config # ~ from app import forms bazadanych = flask_sqlalchemy.SQLAlchemy() migracje = flask_migrate.Migrate() stylista = flask_bootstrap.Bootstrap() zalogowany = flask_login.LoginManager() wysylacz = flask_mail.Mail() momencik = flask_moment.Moment() # ~ from app import models # ~ aplikacja = flask.Flask( __name__ ) # ~ aplikacja.config.from_object( config.Config ) # ~ bazadanych.init_app( aplikacja ) # ~ migracje.init_app( aplikacja, bazadanych ) # ~ stylista.init_app( aplikacja ) # ~ zalogowany.init_app( aplikacja ) # ~ from app.auth import auth as bp_auth # ~ aplikacja.register_blueprint( bp_auth )
def init_login(app): login_manager = login.LoginManager() login_manager.user_loader(load_user) login_manager.init_app(app)
def init_login(): login_manager = login.LoginManager()
def changedetection_app(conig=None, datastore_o=None): global datastore datastore = datastore_o app.config.update(dict(DEBUG=True)) #app.config.update(config or {}) login_manager = flask_login.LoginManager(app) login_manager.login_view = 'login' # Setup cors headers to allow all domains # https://flask-cors.readthedocs.io/en/latest/ # CORS(app) @login_manager.user_loader def user_loader(email): user = User() user.get_user(email) return user @login_manager.unauthorized_handler def unauthorized_handler(): # @todo validate its a URL of this host and use that return redirect(url_for('login', next=url_for('index'))) @app.route('/logout') def logout(): flask_login.logout_user() return redirect(url_for('index')) # https://github.com/pallets/flask/blob/93dd1709d05a1cf0e886df6223377bdab3b077fb/examples/tutorial/flaskr/__init__.py#L39 # You can divide up the stuff like this @app.route('/login', methods=['GET', 'POST']) def login(): global messages if request.method == 'GET': output = render_template("login.html", messages=messages) # Show messages but once. messages = [] return output user = User() user.id = "*****@*****.**" password = request.form.get('password') if (user.check_password(password)): flask_login.login_user(user, remember=True) next = request.args.get('next') # if not is_safe_url(next): # return flask.abort(400) return redirect(next or url_for('index')) else: messages.append({'class': 'error', 'message': 'Incorrect password'}) return redirect(url_for('login')) @app.before_request def do_something_whenever_a_request_comes_in(): # Disable password loginif there is not one set app.config['LOGIN_DISABLED'] = datastore.data['settings']['application']['password'] == False @app.route("/", methods=['GET']) @login_required def index(): global messages limit_tag = request.args.get('tag') pause_uuid = request.args.get('pause') if pause_uuid: try: datastore.data['watching'][pause_uuid]['paused'] ^= True datastore.needs_write = True return redirect(url_for('index', tag = limit_tag)) except KeyError: pass # Sort by last_changed and add the uuid which is usually the key.. sorted_watches = [] for uuid, watch in datastore.data['watching'].items(): if limit_tag != None: # Support for comma separated list of tags. for tag_in_watch in watch['tag'].split(','): tag_in_watch = tag_in_watch.strip() if tag_in_watch == limit_tag: watch['uuid'] = uuid sorted_watches.append(watch) else: watch['uuid'] = uuid sorted_watches.append(watch) sorted_watches.sort(key=lambda x: x['last_changed'], reverse=True) existing_tags = datastore.get_all_tags() rss = request.args.get('rss') if rss: fg = FeedGenerator() fg.title('changedetection.io') fg.description('Feed description') fg.link(href='https://changedetection.io') for watch in sorted_watches: if not watch['viewed']: fe = fg.add_entry() fe.title(watch['url']) fe.link(href=watch['url']) fe.description(watch['url']) fe.guid(watch['uuid'], permalink=False) dt = datetime.datetime.fromtimestamp(int(watch['newest_history_key'])) dt = dt.replace(tzinfo=pytz.UTC) fe.pubDate(dt) response = make_response(fg.rss_str()) response.headers.set('Content-Type', 'application/rss+xml') return response else: output = render_template("watch-overview.html", watches=sorted_watches, messages=messages, tags=existing_tags, active_tag=limit_tag, has_unviewed=datastore.data['has_unviewed']) # Show messages but once. messages = [] return output @app.route("/scrub", methods=['GET', 'POST']) @login_required def scrub_page(): from pathlib import Path global messages if request.method == 'POST': confirmtext = request.form.get('confirmtext') limit_timestamp = int(request.form.get('limit_date')) if confirmtext == 'scrub': for uuid, watch in datastore.data['watching'].items(): if len(str(limit_timestamp)) == 10: datastore.scrub_watch(uuid, limit_timestamp = limit_timestamp) else: datastore.scrub_watch(uuid) messages.append({'class': 'ok', 'message': 'Cleaned all version history.'}) else: messages.append({'class': 'error', 'message': 'Wrong confirm text.'}) return redirect(url_for('index')) return render_template("scrub.html") # If they edited an existing watch, we need to know to reset the current/previous md5 to include # the excluded text. def get_current_checksum_include_ignore_text(uuid): import hashlib from backend import fetch_site_status # Get the most recent one newest_history_key = datastore.get_val(uuid, 'newest_history_key') # 0 means that theres only one, so that there should be no 'unviewed' history availabe if newest_history_key == 0: newest_history_key = list(datastore.data['watching'][uuid]['history'].keys())[0] if newest_history_key: with open(datastore.data['watching'][uuid]['history'][newest_history_key], encoding='utf-8') as file: raw_content = file.read() handler = fetch_site_status.perform_site_check(datastore=datastore) stripped_content = handler.strip_ignore_text(raw_content, datastore.data['watching'][uuid]['ignore_text']) checksum = hashlib.md5(stripped_content).hexdigest() return checksum return datastore.data['watching'][uuid]['previous_md5'] @app.route("/edit/<string:uuid>", methods=['GET', 'POST']) @login_required def edit_page(uuid): global messages import validators # More for testing, possible to return the first/only if uuid == 'first': uuid = list(datastore.data['watching'].keys()).pop() if request.method == 'POST': url = request.form.get('url').strip() tag = request.form.get('tag').strip() # Extra headers form_headers = request.form.get('headers').strip().split("\n") extra_headers = {} if form_headers: for header in form_headers: if len(header): parts = header.split(':', 1) if len(parts) == 2: extra_headers.update({parts[0].strip(): parts[1].strip()}) update_obj = {'url': url, 'tag': tag, 'headers': extra_headers } # Notification URLs form_notification_text = request.form.get('notification_urls') notification_urls = [] if form_notification_text: for text in form_notification_text.strip().split("\n"): text = text.strip() if len(text): notification_urls.append(text) datastore.data['watching'][uuid]['notification_urls'] = notification_urls # Ignore text form_ignore_text = request.form.get('ignore-text') ignore_text = [] if form_ignore_text: for text in form_ignore_text.strip().split("\n"): text = text.strip() if len(text): ignore_text.append(text) datastore.data['watching'][uuid]['ignore_text'] = ignore_text # Reset the previous_md5 so we process a new snapshot including stripping ignore text. if len(datastore.data['watching'][uuid]['history']): update_obj['previous_md5'] = get_current_checksum_include_ignore_text(uuid=uuid) validators.url(url) # @todo switch to prop/attr/observer datastore.data['watching'][uuid].update(update_obj) datastore.needs_write = True messages.append({'class': 'ok', 'message': 'Updated watch.'}) trigger_n = request.form.get('trigger-test-notification') if trigger_n: n_object = {'watch_url': url, 'notification_urls': datastore.data['settings']['application']['notification_urls']} notification_q.put(n_object) messages.append({'class': 'ok', 'message': 'Notifications queued.'}) return redirect(url_for('index')) else: output = render_template("edit.html", uuid=uuid, watch=datastore.data['watching'][uuid], messages=messages) return output @app.route("/settings", methods=['GET', "POST"]) @login_required def settings_page(): global messages if request.method == 'GET': if request.values.get('notification-test'): url_count = len(datastore.data['settings']['application']['notification_urls']) if url_count: import apprise apobj = apprise.Apprise() apobj.debug = True # Add each notification for n in datastore.data['settings']['application']['notification_urls']: apobj.add(n) outcome = apobj.notify( body='Hello from the worlds best and simplest web page change detection and monitoring service!', title='Changedetection.io Notification Test', ) if outcome: messages.append( {'class': 'notice', 'message': "{} Notification URLs reached.".format(url_count)}) else: messages.append( {'class': 'error', 'message': "One or more Notification URLs failed"}) return redirect(url_for('settings_page')) if request.values.get('removepassword'): from pathlib import Path datastore.data['settings']['application']['password'] = False messages.append({'class': 'notice', 'message': "Password protection removed."}) flask_login.logout_user() return redirect(url_for('settings_page')) if request.method == 'POST': password = request.values.get('password') if password: import hashlib import base64 import secrets # Make a new salt on every new password and store it with the password salt = secrets.token_bytes(32) key = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt, 100000) store = base64.b64encode(salt + key).decode('ascii') datastore.data['settings']['application']['password'] = store messages.append({'class': 'notice', 'message': "Password protection enabled."}) flask_login.logout_user() return redirect(url_for('index')) try: minutes = int(request.values.get('minutes').strip()) except ValueError: messages.append({'class': 'error', 'message': "Invalid value given, use an integer."}) else: if minutes >= 5: datastore.data['settings']['requests']['minutes_between_check'] = minutes datastore.needs_write = True else: messages.append( {'class': 'error', 'message': "Must be atleast 5 minutes."}) # 'validators' package doesnt work because its often a non-stanadard protocol. :( datastore.data['settings']['application']['notification_urls'] = [] trigger_n = request.form.get('trigger-test-notification') for n in request.values.get('notification_urls').strip().split("\n"): url = n.strip() datastore.data['settings']['application']['notification_urls'].append(url) datastore.needs_write = True if trigger_n: n_object = {'watch_url': "Test from changedetection.io!", 'notification_urls': datastore.data['settings']['application']['notification_urls']} notification_q.put(n_object) messages.append({'class': 'ok', 'message': 'Notifications queued.'}) output = render_template("settings.html", messages=messages, minutes=datastore.data['settings']['requests']['minutes_between_check'], notification_urls="\r\n".join( datastore.data['settings']['application']['notification_urls'])) messages = [] return output @app.route("/import", methods=['GET', "POST"]) @login_required def import_page(): import validators global messages remaining_urls = [] good = 0 if request.method == 'POST': urls = request.values.get('urls').split("\n") for url in urls: url = url.strip() if len(url) and validators.url(url): new_uuid = datastore.add_watch(url=url.strip(), tag="") # Straight into the queue. update_q.put(new_uuid) good += 1 else: if len(url): remaining_urls.append(url) messages.append({'class': 'ok', 'message': "{} Imported, {} Skipped.".format(good, len(remaining_urls))}) if len(remaining_urls) == 0: # Looking good, redirect to index. return redirect(url_for('index')) # Could be some remaining, or we could be on GET output = render_template("import.html", messages=messages, remaining="\n".join(remaining_urls) ) messages = [] return output # Clear all statuses, so we do not see the 'unviewed' class @app.route("/api/mark-all-viewed", methods=['GET']) @login_required def mark_all_viewed(): # Save the current newest history as the most recently viewed for watch_uuid, watch in datastore.data['watching'].items(): datastore.set_last_viewed(watch_uuid, watch['newest_history_key']) messages.append({'class': 'ok', 'message': "Cleared all statuses."}) return redirect(url_for('index')) @app.route("/diff/<string:uuid>", methods=['GET']) @login_required def diff_history_page(uuid): global messages # More for testing, possible to return the first/only if uuid == 'first': uuid = list(datastore.data['watching'].keys()).pop() extra_stylesheets = ['/static/css/diff.css'] try: watch = datastore.data['watching'][uuid] except KeyError: messages.append({'class': 'error', 'message': "No history found for the specified link, bad link?"}) return redirect(url_for('index')) dates = list(watch['history'].keys()) # Convert to int, sort and back to str again dates = [int(i) for i in dates] dates.sort(reverse=True) dates = [str(i) for i in dates] if len(dates) < 2: messages.append( {'class': 'error', 'message': "Not enough saved change detection snapshots to produce a report."}) return redirect(url_for('index')) # Save the current newest history as the most recently viewed datastore.set_last_viewed(uuid, dates[0]) newest_file = watch['history'][dates[0]] with open(newest_file, 'r') as f: newest_version_file_contents = f.read() previous_version = request.args.get('previous_version') try: previous_file = watch['history'][previous_version] except KeyError: # Not present, use a default value, the second one in the sorted list. previous_file = watch['history'][dates[1]] with open(previous_file, 'r') as f: previous_version_file_contents = f.read() output = render_template("diff.html", watch_a=watch, messages=messages, newest=newest_version_file_contents, previous=previous_version_file_contents, extra_stylesheets=extra_stylesheets, versions=dates[1:], newest_version_timestamp=dates[0], current_previous_version=str(previous_version), current_diff_url=watch['url']) return output @app.route("/preview/<string:uuid>", methods=['GET']) @login_required def preview_page(uuid): global messages # More for testing, possible to return the first/only if uuid == 'first': uuid = list(datastore.data['watching'].keys()).pop() extra_stylesheets = ['/static/css/diff.css'] try: watch = datastore.data['watching'][uuid] except KeyError: messages.append({'class': 'error', 'message': "No history found for the specified link, bad link?"}) return redirect(url_for('index')) print(watch) with open(list(watch['history'].values())[-1], 'r') as f: content = f.readlines() output = render_template("preview.html", content=content, extra_stylesheets=extra_stylesheets) return output @app.route("/favicon.ico", methods=['GET']) def favicon(): return send_from_directory("/app/static/images", filename="favicon.ico") # We're good but backups are even better! @app.route("/backup", methods=['GET']) @login_required def get_backup(): import zipfile from pathlib import Path # create a ZipFile object backupname = "changedetection-backup-{}.zip".format(int(time.time())) # We only care about UUIDS from the current index file uuids = list(datastore.data['watching'].keys()) backup_filepath = os.path.join(app.config['datastore_path'], backupname) with zipfile.ZipFile(backup_filepath, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=8) as zipObj: # Be sure we're written fresh datastore.sync_to_json() # Add the index zipObj.write(os.path.join(app.config['datastore_path'], "url-watches.json"), arcname="url-watches.json") # Add the flask app secret zipObj.write(os.path.join(app.config['datastore_path'], "secret.txt"), arcname="secret.txt") # Add any snapshot data we find, use the full path to access the file, but make the file 'relative' in the Zip. for txt_file_path in Path(app.config['datastore_path']).rglob('*.txt'): parent_p = txt_file_path.parent if parent_p.name in uuids: zipObj.write(txt_file_path, arcname=str(txt_file_path).replace(app.config['datastore_path'], ''), compress_type=zipfile.ZIP_DEFLATED, compresslevel=8) return send_from_directory(app.config['datastore_path'], backupname) @app.route("/static/<string:group>/<string:filename>", methods=['GET']) def static_content(group, filename): # These files should be in our subdirectory full_path = os.path.realpath(__file__) p = os.path.dirname(full_path) try: return send_from_directory("{}/static/{}".format(p, group), filename=filename) except FileNotFoundError: abort(404) @app.route("/api/add", methods=['POST']) @login_required def api_watch_add(): global messages url = request.form.get('url').strip() if datastore.url_exists(url): messages.append({'class': 'error', 'message': 'The URL {} already exists'.format(url)}) return redirect(url_for('index')) # @todo add_watch should throw a custom Exception for validation etc new_uuid = datastore.add_watch(url=url, tag=request.form.get('tag').strip()) # Straight into the queue. update_q.put(new_uuid) messages.append({'class': 'ok', 'message': 'Watch added.'}) return redirect(url_for('index')) @app.route("/api/delete", methods=['GET']) @login_required def api_delete(): global messages uuid = request.args.get('uuid') datastore.delete(uuid) messages.append({'class': 'ok', 'message': 'Deleted.'}) return redirect(url_for('index')) @app.route("/api/checknow", methods=['GET']) @login_required def api_watch_checknow(): global messages tag = request.args.get('tag') uuid = request.args.get('uuid') i = 0 running_uuids = [] for t in running_update_threads: running_uuids.append(t.current_uuid) # @todo check thread is running and skip if uuid: if uuid not in running_uuids: update_q.put(uuid) i = 1 elif tag != None: # Items that have this current tag for watch_uuid, watch in datastore.data['watching'].items(): if (tag != None and tag in watch['tag']): if watch_uuid not in running_uuids and not datastore.data['watching'][watch_uuid]['paused']: update_q.put(watch_uuid) i += 1 else: # No tag, no uuid, add everything. for watch_uuid, watch in datastore.data['watching'].items(): if watch_uuid not in running_uuids and not datastore.data['watching'][watch_uuid]['paused']: update_q.put(watch_uuid) i += 1 messages.append({'class': 'ok', 'message': "{} watches are rechecking.".format(i)}) return redirect(url_for('index', tag=tag)) # @todo handle ctrl break ticker_thread = threading.Thread(target=ticker_thread_check_time_launch_checks).start() threading.Thread(target=notification_runner).start() # Check for new release version threading.Thread(target=check_for_new_version).start() return app
if not super(ExtendedLoginForm, self).validate(): return False if self.username.data.strip() == '': return False self.user = db.session.query(User).filter( User.username == self.username.data).first() if self.user is None: return False if self.password.data == self.user.password: return True return False user_datastore = SQLAlchemyUserDatastore(SQLAlchemy(app), User, Role) security = Security(app, user_datastore, login_form=ExtendedLoginForm) lm = login.LoginManager(app) lm.login_view = 'index' @login_required @roles_required('privileged_user') @app.route('/testroles') def TestLogin(): if current_user.is_authenticated: if current_user.has_role('privileged_user'): context = {'user_name': get_current_user_first_name()} return render_template('testroles.html', **context) else: return make_response("Unauthorized User") else: return redirect('/login')
from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate import flask_login as login app = Flask(__name__) app.config['SECRET_KEY'] = "Impossible to guess" #---CONFIG----- app.config['DEBUG'] = False app.config['TESTING'] = False app.config['CSRF_ENABLED'] = True app.config['DATABASE_FILE'] = 'du_lieu/ql_mae.db?check_same_thread=False' app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get( 'DATABASE_URL') or 'sqlite:///du_lieu/ql_mae.db?check_same_thread=False' app.config['SQLALCHEMY_ECHO'] = True app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) db.init_app(app) db.create_all() migrate = Migrate(app, db) login_manager = login.LoginManager() login_manager.init_app(app) import Mae.xu_ly.xu_ly_model # import Mae.app_Web_ban_hang import Mae.app_quan_ly import Mae.app_admin
from dotenv import load_dotenv from passlib.hash import pbkdf2_sha256 import flask_login load_dotenv() MONGO_URI = os.environ.get('MONGO_URI') DB_NAME = "animal_shelter" # Creates a mongo client client = pymongo.MongoClient(MONGO_URI) app = Flask(__name__) app.secret_key = os.environ.get("SECRET_KEY") # set the secret key # Creates a login manager login_manager = flask_login.LoginManager() # this relatd to OOP login_manager.init_app( app) # this login manager is created to manage logins for our flask app # use back the user class from flask_login class User(flask_login.UserMixin): pass def encrypt_password(plaintext): return pbkdf2_sha256.hash(plaintext) def verify_password(plaintext, encrypted): return pbkdf2_sha256.verify(plaintext, encrypted)
from flask import Flask from flask import Flask, Response, request, render_template, redirect, url_for import flask import mongoQ import flask_login import send app = Flask(__name__) app.config['MONGO_DBNAME'] = 'savetheworld' app.config['MONGO_URI'] = 'mongodb://127.0.0.1:27017/savetheworld' app.secret_key="deadsea" mongo = mongoQ.stwishDB(app) login_manager = flask_login.LoginManager() login_manager.init_app(app) class User(flask_login.UserMixin): pass @login_manager.user_loader def user_loader(username): uid = mongo.getUID({"username":username}) if uid == None: return user = User() user.id = username return user @app.route("/login",methods=['GET','POST'])
import flask as fl import database as db import models as ml import flask_login as flog import datetime from passlib.hash import sha512_crypt import forms as fm from proj_types import State import flask_wtf as wtf lm = flog.LoginManager() # initialise the login lib def index(): unconfirmed_list = ml.User.query.filter(ml.User.confirmed == False).all() return fl.render_template('/index.html', unconfirmed_list=unconfirmed_list) def login(): if fl.request.method == 'GET': current = datetime.datetime.now() if 'logged_in' in fl.session: return fl.redirect(fl.url_for('index')) return fl.render_template('/login.html', current=current) else: username = fl.request.form['username'] pw = fl.request.form['pw'] # now check this against the database user_list = ml.User.query.filter(ml.User.email == username).all() if len(user_list) == 1: user = user_list[0]