def _create_user(): username = "******" + random_string(6) email = username + "@openease.org" password = random_string(10) session['user_container_name'] = username session['username'] = username flask_user = add_user(user_manager=app.user_manager, name=username, mail=email, pw=password) return flask_user
def start_user_container(user_name, neemHubSettings, knowrob_image='knowrob', knowrob_version='latest'): """ Starts a user container based on the given image. If the container already exists, it will stop and remove the container first. Also, a data container is created and mounted inside the given container, and a rosauth secret is generated. Note that containers are stopped and removed after 10 minutes if the refresh function is not called periodically beforehand. :param application_image: Image the container should be based on :param user_name: Name of the user. """ try: client.notify("create_user_data_container", user_name) client.notify("files_writesecret", user_name, random_string(16)) clear_secretcache() client.notify("start_user_container", user_name, neemHubSettings, knowrob_image, knowrob_version) except JsonRpcError, e: flash("Error: Connection to your openEASE instance failed.") app.logger.error("ConnectionError during connect: " + str(e.message) + str(e.data) + "\n")
def __enter__(self): if not os.access('/tmp/openEASE/dockerbridge/', os.W_OK): client.notify("files_lft_set_writeable") self.lftdir = os.path.join('/tmp/openEASE/dockerbridge', random_string(16)) os.mkdir(self.lftdir) return self
def _generate_rosauth(user_container_name, dest, cache=False): """ Generate the mac for use with rosauth and compile a json object with all necessary information to authenticate with the server. :param user_container_name: Name of the user container :param dest: IP of the destination :return: a json object for ros """ client = request.remote_addr rand = random_string(30) t = int(time.time()) level = "user" end = int(t + 3600) return jsonify({ 'mac': generate_mac(user_container_name, client, dest, rand, t, level, end, cache), 'client': client, 'dest': dest, 'rand': rand, 't': t, 'level': level, 'end': end })
def generate_state_token(): ''' generate a random state token, to be used for every post request ''' if 'state' not in session: session['state'] = random_string() return session['state']
def init_app(extra_config_settings={}): # Initialize app config settings app.config.from_object( 'config.settings') # Read config from 'app/settings.py' file app.config.update(extra_config_settings ) # Overwrite with 'extra_config_settings' parameter if app.testing: app.config[ 'WTF_CSRF_ENABLED'] = False # Disable CSRF checks while testing if os.environ['EASE_DEBUG'] == 'true': app.config['DEBUG'] = True app.config['SECRET_KEY'] = app.config['DEV_SECRET_KEY'] else: try: app.config['SECRET_KEY'] = open('/etc/ease_secret/secret', 'rb').read() except IOError: app.config['SECRET_KEY'] = random_string(64) # Setup Flask-Mail mail = Mail(app) babel = Babel(app) # Setup Flask-User to handle user account related forms from postgres.users import User db_adapter = SQLAlchemyAdapter(db, User) # Init Flask-User and bind to app app.user_manager = UserManager(db_adapter, app, password_validator=oe_password_validator) # Load all models.py files to register db.Models with SQLAlchemy from postgres import users from postgres import settings # Automatically create all registered DB tables db.create_all() db.session.commit() for role in USER_ROLES: create_role(role) # Load all views.py files to register @app.routes() with Flask from pages import main from pages import api from pages import neem_discovery from pages import editor from pages import tutorials from pages import oauth add_user(user_manager=app.user_manager, name='admin', mail=os.environ.get('OPENEASE_MAIL_USERNAME', '*****@*****.**'), pw=ADMIN_USER_DEFAULT_PW, roles=['admin']) app.logger.info("Webapp started.") return app
def setup_stack_monitor(self, config): # Topic and queue names are randomly generated so there's no chance of picking up messages from a previous runs name = self.env_name + '_' + time.strftime( "%Y%m%d-%H%M%S") + '_' + utility.random_string(5) # Creating a topic is idempotent, so if it already exists then we will just get the topic returned. sns = utility.get_boto_resource(config, 'sns') topic_arn = sns.create_topic(Name=name).arn # Creating a queue is idempotent, so if it already exists then we will just get the queue returned. sqs = utility.get_boto_resource(config, 'sqs') queue = sqs.create_queue(QueueName=name) queue_arn = queue.attributes['QueueArn'] # Ensure that we are subscribed to the SNS topic subscribed = False topic = sns.Topic(topic_arn) for subscription in topic.subscriptions.all(): if subscription.attributes['Endpoint'] == queue_arn: subscribed = True break if not subscribed: topic.subscribe(Protocol='sqs', Endpoint=queue_arn) # Set up a policy to allow SNS access to the queue if 'Policy' in queue.attributes: policy = json.loads(queue.attributes['Policy']) else: policy = {'Version': '2008-10-17'} if 'Statement' not in policy: statement = { "Sid": "sqs-access", "Effect": "Allow", "Principal": { "AWS": "*" }, "Action": "SQS:SendMessage", "Resource": "<SQS QUEUE ARN>", "Condition": { "StringLike": { "aws:SourceArn": "<SNS TOPIC ARN>" } } } statement['Resource'] = queue_arn statement['Condition']['StringLike']['aws:SourceArn'] = topic_arn policy['Statement'] = [statement] queue.set_attributes(Attributes={'Policy': json.dumps(policy)}) return topic, queue
def setup_stack_monitor(self, config): # Topic and queue names are randomly generated so there's no chance of picking up messages from a previous runs name = self.env_name + '_' + time.strftime("%Y%m%d-%H%M%S") + '_' + utility.random_string(5) # Creating a topic is idempotent, so if it already exists then we will just get the topic returned. sns = utility.get_boto_resource(config, 'sns') topic_arn = sns.create_topic(Name=name).arn # Creating a queue is idempotent, so if it already exists then we will just get the queue returned. sqs = utility.get_boto_resource(config, 'sqs') queue = sqs.create_queue(QueueName=name) queue_arn = queue.attributes['QueueArn'] # Ensure that we are subscribed to the SNS topic subscribed = False topic = sns.Topic(topic_arn) for subscription in topic.subscriptions.all(): if subscription.attributes['Endpoint'] == queue_arn: subscribed = True break if not subscribed: topic.subscribe(Protocol='sqs', Endpoint=queue_arn) # Set up a policy to allow SNS access to the queue if 'Policy' in queue.attributes: policy = json.loads(queue.attributes['Policy']) else: policy = {'Version': '2008-10-17'} if 'Statement' not in policy: statement = { "Sid": "sqs-access", "Effect": "Allow", "Principal": {"AWS": "*"}, "Action": "SQS:SendMessage", "Resource": "<SQS QUEUE ARN>", "Condition": {"StringLike": {"aws:SourceArn": "<SNS TOPIC ARN>"}} } statement['Resource'] = queue_arn statement['Condition']['StringLike']['aws:SourceArn'] = topic_arn policy['Statement'] = [statement] queue.set_attributes(Attributes={ 'Policy': json.dumps(policy) }) return topic, queue
def _create_token(): current_user.api_token = random_string(64) db.session.commit() session['api_token'] = current_user.api_token
app = Flask(__name__) config = json.load(open('config.json', 'r')) @app.route('/') def home(): google_key = config['google_maps_key'] return render_template('index.min.html', google_key=google_key) @app.route('/<yelp_id>/yelp_reviews.json') def get_reviews(yelp_id): '''this view returns all items in json view''' access_token = config['yelp']['access_token'] headers = dict(Authorization="Bearer %s" % access_token) yelp_api_url = '{base}/businesses/{yelp_id}/reviews'.format( base=config['yelp']['base_url'], yelp_id=yelp_id) response = requests.get(yelp_api_url, headers=headers) if response.status_code != 200: response = {'reviews': []} else: response = response.json() return jsonify(response) if __name__ == '__main__': secret = random_string(30) app.secret_key = secret params = dict(host='localhost', port=8000) app.run(**params)
dbsession.commit() return jsonify(favorite='successful', like='unliked', state=state) else: like = Like(user=user, item=item) dbsession.add(like) dbsession.commit() return jsonify(favorite='successful', like='liked', state=state) @app.route('/search') def search(): ''' this view returns the results of a search query from front end ''' term = request.args.get('search') items = dbsession.query(Item).filter( or_(Item.category.like('%{0}%'.format(term)), Item.title.like('%{0}%'.format(term)))) return render_template('search.html', term=term, items=items) @app.errorhandler(404) def page_not_found(e): ''' default 404 page ''' return render_template('no_such.html', _object='Page'), 404 if __name__ == '__main__': app.secret_key = random_string(30) logging.basicConfig(filename=log, level=logging.DEBUG) params = config['app'] app.run(**params)
import logging import site import sys from os.path import join, dirname, expanduser # Add virtualenv site packages site.addsitedir(join(dirname(__file__), 'env/lib/python3.5/site-packages')) # Path of execution sys.path.insert(0, '/var/www/catalog_app') # Fired up virtualenv before include application activate_env = expanduser(join(dirname(__file__), 'env/bin/activate_this.py')) exec(open(activate_env).read(), {'__file__': activate_env}) from run import app as application, log from utility import random_string application.secret_key = random_string(30) logging.basicConfig(filename=log, level=logging.DEBUG)