Exemplo n.º 1
0
 def cas_init():
     cas = CAS()
     app = getAppMgr().get('flaskApp')
     cas.init_app(app=app)
     app.config['CAS_SERVER'] = 'https://cas.banggood.cn/cas/login'
     app.config['CAS_AFTER_LOGIN'] = '******'
     getAppMgr().insert('cas', cas)
Exemplo n.º 2
0
    def test_cas_init_app_properties(self):

        self.app = flask.Flask(__name__)
        cas = CAS()

        cas.init_app(self.app)

        with self.app.test_request_context():
            self.assertEqual(cas.username, None)

            self.assertEqual(cas.token, None)
Exemplo n.º 3
0
def tflask(config):
    cas = CAS()
    app = TFlask(config.SERVICE_NAME)
    # 只为注入mysql链接,使用config中内容没有使用current_app.config
    app.config.from_object(config)
    t_middleware(app)
    register_logger(app, config)
    register_extensions(app)
    cas.init_app(app)
    app.config['CAS_SERVER'] = 'https://sso.yupaopao.com'
    app.config['CAS_AFTER_LOGIN'] = '******'
    return app
Exemplo n.º 4
0
    def test_cas_init_app_properties(self):
        
        self.app = flask.Flask(__name__)
        cas = CAS()

        cas.init_app(self.app)

        with self.app.test_request_context():
            self.assertEqual(
                cas.username,
                None)

            self.assertEqual(
                cas.token,
                None)
Exemplo n.º 5
0
    def test_cas_init_app_with_prefix_url(self):
        self.app = flask.Flask(__name__)
        cas = CAS()
        cas.init_app(self.app, '/cas')

        self.app.secret_key = "SECRET_KEY"
        self.app.testing = True

        self.app.config['CAS_SERVER'] = 'http://cas.server.com'
        self.app.config['CAS_AFTER_LOGIN'] = '******'

        with self.app.test_client() as client:
            response = client.get('/cas/login/')
            self.assertEqual(response.status_code, 302)
            self.assertEqual(
                response.headers['Location'],
                'http://cas.server.com/cas?service=http%3A%2F%2Flocalhost%2Fcas%2Flogin%2F')
Exemplo n.º 6
0
    def test_cas_init_app_with_prefix_url(self):
        self.app = flask.Flask(__name__)
        cas = CAS()
        cas.init_app(self.app, '/cas')

        self.app.secret_key = "SECRET_KEY"
        self.app.testing = True

        self.app.config['CAS_SERVER'] = 'http://cas.server.com'

        with self.app.test_client() as client:
            response = client.get('/cas/login/')
            self.assertEqual(response.status_code, 302)
            self.assertEqual(
                response.headers['Location'],
                'http://cas.server.com/cas?service=http%3A%2F%2Flocalhost%2Fcas%2Flogin%2F'
            )
Exemplo n.º 7
0
def init_app():
    """ 初始化APP
    :return:
    """
    app = CAS(Flask(__name__)).app
    app.config.from_object(settings)
    # initialize database
    logging.basicConfig(level=logging.DEBUG)
    return app
Exemplo n.º 8
0
def init_app(app):
    if app is not None:
        # Resolve Untrusted Certificate Issues
        ssl._create_default_https_context = ssl._create_unverified_context
        cas = CAS(app)
        app.config['CAS_SERVER'] = settings.CAS_SERVER
        app.config['CAS_AFTER_LOGIN'] = settings.CAS_AFTER_LOGIN
        app.config['SECRET_KEY'] = settings.SECRET_KEY
        app.config['CAS_VALIDATE_ROUTE'] = settings.CAS_VALIDATE_ROUTE
Exemplo n.º 9
0
def get_flask_app(templates_auto_reload=True):
    # TODO this should be initialized explicity in main_module.py only if needed
    global GLOBAL_APP
    global GLOBAL_CORS
    global GLOBAL_CAS
    global HAS_FLASK
    if not HAS_FLASK:
        print('flask is not installed')
        return None
    if GLOBAL_APP is None:
        if hasattr(sys, '_MEIPASS'):
            # hack for pyinstaller directory
            root_dpath = sys._MEIPASS
        else:
            root_dpath = abspath(dirname(dirname(__file__)))
        tempalte_dpath = join(root_dpath, 'web', 'templates')
        static_dpath = join(root_dpath, 'web', 'static')
        if ut.VERBOSE:
            print('[get_flask_app] root_dpath = %r' % (root_dpath, ))
            print('[get_flask_app] tempalte_dpath = %r' % (tempalte_dpath, ))
            print('[get_flask_app] static_dpath = %r' % (static_dpath, ))
            print('[get_flask_app] GLOBAL_APP_NAME = %r' % (GLOBAL_APP_NAME, ))
        GLOBAL_APP = flask.Flask(GLOBAL_APP_NAME,
                                 template_folder=tempalte_dpath,
                                 static_folder=static_dpath)

        # Add more verbose logging
        import logging
        stream_handler = logging.StreamHandler()
        stream_handler.setLevel(logging.INFO)
        GLOBAL_APP.logger.addHandler(stream_handler)

        if ut.VERBOSE:
            print('[get_flask_app] USING FLASK SECRET KEY: %r' %
                  (GLOBAL_APP_SECRET, ))
        GLOBAL_APP.secret_key = GLOBAL_APP_SECRET

        if templates_auto_reload:
            GLOBAL_APP.config['TEMPLATES_AUTO_RELOAD'] = True
        GLOBAL_APP.QUERY_OBJECT = None
        GLOBAL_APP.QUERY_OBJECT_JOBID = None
        GLOBAL_APP.QUERY_OBJECT_FEEDBACK_BUFFER = []
        GLOBAL_APP.GRAPH_CLIENT_DICT = {}

        if HAS_FLASK_CORS:
            GLOBAL_CORS = CORS(GLOBAL_APP,
                               resources={r"/api/*": {
                                   "origins": "*"
                               }})  # NOQA
        if HAS_FLASK_CAS:
            GLOBAL_CAS = CAS(GLOBAL_APP, '/cas')
            GLOBAL_APP.config['SESSION_TYPE'] = 'memcached'
            GLOBAL_APP.config['SECRET_KEY'] = GLOBAL_APP_SECRET
            GLOBAL_APP.config['CAS_SERVER'] = 'https://cas-auth.rpi.edu'
            GLOBAL_APP.config['CAS_AFTER_LOGIN'] = '******'
    return GLOBAL_APP
    def post(self):
        """
        Handles student registration requests, which come in the form of POST requests submitted via the form
        that is generated in GET requests
        Input: self
        Output: a rendering of the student register page: with a success message and link to the student
                dashboard if everything went well, or with an error message if there was a problem
        """
        # Get the database objects we will need
        students = gbmodel.students()
        teams = gbmodel.teams()

        # Continue processing the POST request
        try:
            # Get the student_id and information the student submitted via the form
            student_id = CAS().username
            name = request.form.getlist('name')[0]
            email_address = request.form.getlist('email_address')[0]
            session_id = request.form.getlist('session_id')[0]

            # Verify that the student isn't already registered for the target session
            if students.get_student_in_session(student_id,
                                               session_id) is not None:
                logging.warning((
                    "A student tried to register for a Capstone session, but the student was "
                    "already registered for the session"))
                return self.display_error("You are already in this session")

            # Add the student to the database
            # The student won't be on a team when they first sign up, so we have to assign them to the
            # empty team for the target session. We start by checking if the empty team exists. If the
            # target session doesn't have one yet, we create it
            if teams.get_tid_from_name("", session_id) is None:
                teams.insert_team(session_id, "")

            # Insert the student into the database (as a part of the empty team)
            students.insert_student(name, email_address, student_id,
                                    session_id, "")

            # Log the event and render the page with a message telling the student that they have been
            # registered (along with a link to the student page)
            logging.info("A student registered for a Capstone session")
            return render_template('studentRegister.html',
                                   message="Successfully registered!",
                                   is_error=False)

        # https://stackoverflow.com/questions/47719838/how-to-catch-all-exceptions-in-try-catch-block-python
        except Exception as error:
            logging.error("Student Registration Failure: " + str(error))
            return self.display_error("Something went wrong")
Exemplo n.º 11
0
def validate_student():
    """
    function to grab cas username and passes the value to gbmmodel to vaidate
    INPUT: none
    OUTPUT: return False if the id does not exist
            return student infomation otherwise
    """
    cas = CAS()
    username = cas.username
    students = gbmodel.students()
    found_student = students.validate(username)
    if found_student is False:
        return False
    return found_student
Exemplo n.º 12
0
def validate_professor():
    """
    check to see if professor id is in the professor table
    INPUT: none
    OUTPUT: return False if the id does not exist
            return True otherwise
    """
    cas = CAS()
    username = cas.username
    professors = gbmodel.professors()
    found_professors = professors.get_professor(username)
    if not found_professors:
        return False
    return found_professors
Exemplo n.º 13
0
Arquivo: cas.py Projeto: Valdimus/Maat
 def __init__(self,
              server,
              *args,
              after_login="******",
              login_route="/cas/login",
              logout_route="/cas/logout",
              validate_route="/cas/serviceValidate",
              **kwargs):
     Webservice.__init__(*args, **kwargs)
     self.__cas = CAS(self.app)
     self.app.config["CAS_SERVER"] = server
     self.app.config["CAS_AFTER_LOGIN"] = after_login
     self.app.config["CAS_LOGIN_ROUTE"] = login_route
     self.app.config["CAS_LOGOUT_ROUTE"] = logout_route
     self.app.config["CAS_VALIDATE_ROUTE"] = validate_route
Exemplo n.º 14
0
    def test_cas_constructor(self):
        self.app = flask.Flask(__name__)
        CAS(self.app)

        self.app.secret_key = "SECRET_KEY"
        self.app.testing = True

        self.app.config['CAS_SERVER'] = 'http://cas.server.com'
        self.app.config['CAS_AFTER_LOGIN'] = '******'

        with self.app.test_client() as client:
            response = client.get('/login/')
            self.assertEqual(response.status_code, 302)
            self.assertEqual(
                response.headers['Location'],
                'http://cas.server.com/cas?service=http%3A%2F%2Flocalhost%2Flogin%2F'
            )
Exemplo n.º 15
0
def create_app(config_name):
    """
    创建Flask的应用对象
    :param config_name :str 配置模式的名字 ["develop","product"]
    :rturn:
    """
    app = Flask(__name__)
    cas = CAS(app, '/cas')

    # 根据配置模式的名字获取配置参数的类:
    config_class = config_map.get(config_name)
    app.config.from_object(config_class)

    # 使用app初始化db
    db.init_app(app)

    # 创建数据redis 连接对象
    global redis_store
    redis_store = redis.StrictRedis(host=config_class.REDIS_HOST,
                                    port=config_class.REDIS_PORT)

    # 利用flask_session,将session 数据保存到redis中
    Session(app)

    # 为flask补充csrf防护
    CSRFProtect(app)

    # 为flask 添加自定义转换器
    # app.url_map.converters["re"] = ReConverter

    # 注册蓝本
    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    # 注册蓝图
    # from ihome import api_1_0
    # app.register_blueprint(api_1_0.api, url_prefix="/api/v1.0")
    #
    # # 注册静态文件蓝图
    # from ihome import web_html
    # app.register_blueprint(web_html.html)

    return app
Exemplo n.º 16
0
    def setUp(self):

        self.app = flask.Flask(__name__)

        @self.app.route('/')
        def root():
            return ''

        self.app.secret_key = "SECRET_KEY"
        self.cas = CAS(self.app)
        self.app.testing = True

        self.app.config['CAS_SERVER'] = 'http://cas.server.com'
        self.app.config['CAS_TOKEN_SESSION_KEY'] = '_CAS_TOKEN'
        self.app.config['CAS_USERNAME_SESSION_KEY'] = 'CAS_USERNAME'
        self.app.config['CAS_ATTRIBUTES_SESSION_KEY'] = 'CAS_ATTRIBUTES'
        self.app.config['CAS_AFTER_LOGIN'] = '******'
        self.app.config['CAS_LOGIN_ROUTE'] = '/cas'
        self.app.config['CAS_LOGOUT_ROUTE'] = '/cas/logout'
        self.app.config['CAS_VALIDATE_ROUTE'] = '/cas/serviceValidate'
        self.app.config['CAS_AFTER_LOGOUT'] = 'http://localhost:5000'
Exemplo n.º 17
0
		session = request.environ['beaker.session']
		return session

	def save_session(self, app, session, response):
		session.save()

app = Flask(__name__, static_folder='./dist/static', template_folder='./dist')

#POTENTIALLY IMPORTANT: 
app.config.from_object(__name__)

# Initialize HTTPS redirection.
sslify = SSLify(app)

# Initialize CAS login
cas = CAS()
cas.init_app(app)
app.config['CAS_SERVER'] = 'https://fed.princeton.edu/cas/'
app.config['CAS_AFTER_LOGIN'] = '******'
app.config['SESSION_TYPE'] = 'filesystem'

# This is a secret key for storing sessions.
secret_key = environ.get('SECRET_KEY', "developmentsecretkey")
app.secret_key = secret_key

# Initialize CORS
CORS(app, supports_credentials=True)

app.wsgi_app = SessionMiddleware(app.wsgi_app, session_opts)
app.session_interface = BeakerSessionInterface()
Exemplo n.º 18
0
from . import config
from .logging_config import logging_init

logging_init()

app = Flask(__name__, instance_relative_config=True)
app.logger.propagate = True
config.load(app)

db = SQLAlchemy(app)
migrate = Migrate(app, db)
FlaskCLI(app)
thumb = Thumbnail(app)

cas_v2 = CAS(app, '/api/cas')
cas = CAS(app, '/v1/cas')
CORS(app)

login_manager = LoginManager()
login_manager.init_app(app)

mail = Mail(app)

from .v1.public import public
from .v1.private import private
from .v1.admin import admin
from .api.admin import admin_api
from .api.public import public_api
from .api.private import private_api
from .api.resources import resources_api
Exemplo n.º 19
0
from . import TIMESTAMP_FORMAT, generate
from .decorators import admin_required
from .api import api, API_BASE, create_meeting, get_user_and_enrollment, meeting_types, meeting_type_urls, get_meeting, update_meeting

# Loads any variables from the .env file
load_dotenv()

# Initialize Flask application
app = Flask(__name__)

# Serve static files on Heroku
# app.wsgi_app = WhiteNoise(app.wsgi_app, root='static/')

# Initialize CAS authentication on the /cas endpoint
# Adds the /cas/login and /cas/logout routes
cas = CAS(app, '/cas')

# This must be a RANDOM string you generate once and keep secret
app.secret_key = os.environ.get('FLASK_SECRET_KEY')

# Used in templates
app.config['APP_TITLE'] = 'RCOS Meeting Management'

# Must be set to this to use RPI CAS
app.config['CAS_SERVER'] = 'https://cas-auth.rpi.edu/cas'

# What route to go to after logging in
app.config['CAS_AFTER_LOGIN'] = '******'


@app.template_filter()
Exemplo n.º 20
0
from flask import Flask, make_response, \
request, jsonify, render_template, redirect, url_for
from flask_mail import Mail, Message
import requests
import json
import os
from flask_cas import CAS, login_required, login, logout

app = Flask(__name__)

cas = CAS(app, '/cas')
cas.init_app(app)

DATABASE_URL = "http://*****:*****@app.route("/loginPage")
@app.route("/")
def portal():
    return render_template("login.tpl")


@app.route("/events")
def events_list():
    query_url = DATABASE_URL + "/event/sort_date"
    fetch_req = requests.get(url=query_url)
Exemplo n.º 21
0
import markdown
import bleach
from bleach import sanitizer
import glob
from flask import Flask, request, escape, abort, Markup, flash, g, url_for, render_template, redirect
from flask_babel import Babel, gettext
from flask_cas import CAS, login_required, login, logout
from models import BabelConfig

application = Flask(__name__)
application.secret_key = open("secret.key", 'r').read()

cas = CAS(application, '/login')
babel = Babel(application)
application.config['CAS_AFTER_LOGIN'] = "******"
application.config['CAS_SERVER'] = "https://cas.binets.fr/"
application.config.from_object(BabelConfig)


@babel.localeselector
def get_locale():
    browser = request.accept_languages.best_match(
        BabelConfig.SUPPORTED_LANGUAGES.keys())
    return 'fr'
    if not (browser is None):
        return browser


moisLettres = [
    'jan', 'fév', 'mars', 'avr', 'mai', 'juin', 'jui', 'août', 'sep', 'oct',
    'nov', 'déc'
Exemplo n.º 22
0
 def __init__(self, app):
     super(CASAuth, self).__init__(app)
     for setting in CAS_SETTINGS:
         if setting in os.environ:
             self.app.config[setting] = os.environ[setting]
     self.cas = CAS(app, '/cas')
Exemplo n.º 23
0
from flask import Flask
from config import Config
from celery import Celery
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_mail import Mail
from flask_cas import CAS
from flask_redis import FlaskRedis
from elasticsearch import Elasticsearch

app = Flask(__name__)
app.config.from_object(Config)
celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL'])
celery.conf.update(app.config)
cors = CORS(app)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
mail = Mail(app)
cas = CAS(app)
redis = FlaskRedis(app)
elasticsearch = Elasticsearch([app.config['ELASTICSEARCH_URL']]) \
    if app.config['ELASTICSEARCH_URL'] else None

from app import routes, errors, api
app.register_blueprint(api.api_bp, url_prefix='/api')
Exemplo n.º 24
0
import os
from flask import Flask
from flask_cas import CAS
from flask_cors import CORS
import click

from .config import current_mode

app = Flask(__name__)
app_mode = current_mode()
app.config.from_object('app.config.{}'.format(app_mode))
app.logger.info('>>> %s' % app_mode)

# CAS Config
app.config['CAS_SERVER'] = 'https://sso.your-server.com/'
app.config['CAS_LOGIN_ROUTE'] = '/cas/login'
app.config['CAS_AFTER_LOGIN'] = '******'
cas = CAS(
    app,
    '/cas')  # Add your sub-directory path if needed, such as `/my-app/cas`

from .api import api_bp
from .client import client_bp

# Blueprints
if app_mode == 'Development':  # Use this way to know Production or Development
    CORS(api_bp, supports_credentials=True)  # CORS enabled for development
app.register_blueprint(api_bp)
app.register_blueprint(client_bp)
                                    for (key, value) in flask.request.headers
                                    if key != 'Host'
                                },
                                data=flask.request.get_data(),
                                cookies=flask.request.cookies,
                                allow_redirects=False)

    excluded_headers = [
        'content-encoding', 'content-length', 'transfer-encoding', 'connection'
    ]
    headers = [(name, value) for (name, value) in response.raw.headers.items()
               if name.lower() not in excluded_headers]

    return Response(response.content,
                    mimetype=response.headers.get("content-type"),
                    status=response.status_code,
                    headers=headers)


cas = CAS(app, PATH_INFO + "/cas")
app.config["CAS_AFTER_LOGIN"] = "******"
app.config["CAS_LOGIN_ROUTE"] = "/signin"
app.config["SESSION_TYPE"] = "filesystem"

# For mod_wgsi compatibility
application = app

if __name__ == "__main__":
    app.debug = True
    app.run()
Exemplo n.º 26
0
from flask_sqlalchemy import SQLAlchemy
from flask_cas import CAS

db = SQLAlchemy()
cas = CAS()
Exemplo n.º 27
0
app.config['UPLOAD_EXTENSIONS'] = ['.jpg', '.png', '.jpeg']
app.config['MAX_CONTENT_LENGTH'] = 2048 * 2048

app.secret_key = 'uwu'
app.secret_key = ''.join([ random.choice(('ABCDEFGHIJKLMNOPQRSTUVXYZ' +
                                          'abcdefghijklmnopqrstuvxyz' +
                                          '0123456789'))
                           for i in range(20) ])

# This gets us better error messages for certain common request errors
app.config['TRAP_BAD_REQUEST_ERRORS'] = True

# CAS setup
from flask_cas import CAS

CAS(app)

app.config['CAS_SERVER'] = 'https://login.wellesley.edu:443'
app.config['CAS_LOGIN_ROUTE'] = '/module.php/casserver/cas.php/login'
app.config['CAS_LOGOUT_ROUTE'] = '/module.php/casserver/cas.php/logout'
app.config['CAS_VALIDATE_ROUTE'] = '/module.php/casserver/serviceValidate.php'
app.config['CAS_AFTER_LOGIN'] = '******'

@app.route('/logged_in/')
def logged_in():
    return redirect(url_for('index'))

@app.route('/')
def index():
    if 'CAS_USERNAME' in session:
        username = session['CAS_USERNAME']
Exemplo n.º 28
0
def create_app(config, debug=False, testing=False, config_overrides=None):
    cas = CAS()
    app = Flask(__name__)
    cas.init_app(app)
    app.config.from_object(config)

    app.debug = debug
    app.testing = testing

    if config_overrides:
        app.config.update(config_overrides)

    if not app.testing:
        logging.basicConfig(level=logging.INFO)

    with app.app_context():
        model = sql
        model.init_app(app)


    @app.route('/')
    def index():
        if cas.username is not None:
            return redirect(url_for('browse'))
        return render_template('index.html')

    @app.route('/validate')
    def validate():
        netid = cas.username
        if netid is None:
            return redirect('/')
        response = redirect(url_for('browse'), code=status.HTTP_302_FOUND)
        user = sql.User.query.filter_by(netid=netid).first()
        if user is None:
            newUser = sql.User(netid=netid, upvoted_reviews = "", upvoted_rants = "", downvoted_rants = "", upvoted_descriptions = "", downvoted_descriptions = "", upvoted_replies = "", downvoted_replies = "")
            sql.db.session.add(newUser)
            sql.db.session.commit()
        return response

    @app.route('/browse')
    def browse():
        netid = cas.username
        if netid is None:
            return redirect(url_for('index'))
        page = request.args.get('page')
        search = request.args.get('search')
        order = request.args.get('order')
        if order == None:
            order = "dept"
        courses = request.cookies.get('courses')
        if (courses == None) or (courses == ""):
            num = '0'
        else:
            num = str(len(courses.split(' ')))
        if page is None or search is None:
            return render_template('home.html', netid=netid, incart=num)

        #find list of classes that match search
        #returns a tuple of type results, pageInt, length, num_pages
        results, pageInt, length, num_pages = sc.matched_courses(search, order, page)

        descriptions = []

        for course in results:
            urban = course.descriptions.order_by(sql.Description.upvotes.desc()).first()
            if urban == None:
                desc = course.description
            elif urban.upvotes < 10:
                desc = course.description
            else:
                desc = urban.text

            desc = desc.split()
            count = 40
            if len(desc) > count:
                desc = desc[0:count]
                desc.append("...")
            desc = " ".join(desc)
            descriptions.append(desc)

        #return searched classes (for specific page)
        return render_template('browse.html', netid=netid, courses=results,
        current=pageInt, num_results=length, pages=num_pages, search=search, order=order, incart=num, desc=descriptions)

    @app.route('/course')
    def course():
        netid = cas.username
        if netid is None:
            return redirect(url_for('index'))
        course_id = request.args.get('id')
        search = request.args.get('search')
        page = request.args.get('page')
        order = request.args.get('order')
        if course_id is None:
            return redirect(url_for('browse'))
        if not course_id.isdigit():
            return redirect(url_for('browse'))
        c_id = int(course_id)
        course = sql.Course.query.filter_by(c_id=c_id).first()
        if course == None:
            return redirect(url_for('browse'))
        courses_cookie = request.cookies.get('courses')
        if (courses_cookie == None) or (courses_cookie == ""):
            num = '0'
        else:
            num = str(len(courses_cookie.split(' ')))
        return render_template('course.html', netid=netid, course=course, search=search, page=page, order=order, incart=num)

    @app.route('/addtocart')
    def add_to_cart():
        netid = cas.username
        if netid is None:
            return redirect(url_for('index'))
        course_id = request.args.get('id')
        search = request.args.get('search')
        page = request.args.get('page')
        order = request.args.get('order')
        if course_id is None:
            return redirect(url_for('browse'))
        if not course_id.isdigit():
            return redirect(url_for('browse'))
        c_id = int(course_id)
        course = sql.Course.query.filter_by(c_id=c_id).first()
        if course == None:
            return redirect(url_for('browse'))
        courses_cookie = request.cookies.get('courses')
        if (courses_cookie == None) or (courses_cookie == ""):
            response = make_response(render_template('course.html', netid=netid, search=search, page=page, order=order, course=course, incart='1'))
            response.set_cookie('courses', course_id)
            return response
        else:
            if course_id not in courses_cookie:
                num = str(len(courses_cookie.split(' ')) + 1)
                response = make_response(render_template('course.html', netid=netid, search=search, page=page, order=order, course=course, incart=num))
                response.set_cookie('courses', (courses_cookie + ' ' + course_id))
                return response
            else:
                num = str(len(courses_cookie.split(' ')))
                return make_response(render_template('course.html', netid=netid, search=search, page=page, order=order, course=course, incart=num))

    @app.route('/about')
    def about():
        netid = cas.username
        loggedIn = netid is not None
        courses = request.cookies.get('courses')
        if (courses == None) or (courses == ""):
            num = '0'
        else:
            num = str(len(courses.split(' ')))
        return render_template('about.html', netid=netid, loggedIn=loggedIn, incart=num)

    def delete(course, string):
        if len(string) < 4: return ""
        courses = string.split(' ')
        result = ""
        for i in range(0, len(courses)):
            if (courses[i] != ' ') and (courses[i] != course):
                result += courses[i] + " "
        return result.strip()

    @app.route('/cart')
    def cart():
        netid = cas.username
        if netid is None:
            return redirect(url_for('index'))
        course_cookie = request.cookies.get('courses')
        courses = []
        if course_cookie == None:
            return render_template('cart.html', netid=netid, courses=courses, incart='0')
        course_id = request.args.get('id')
        removeAll = request.args.get('remall')
        if removeAll != None:
            response = make_response(render_template('cart.html', netid=netid, incart='0'))
            response.set_cookie('courses', '')
            return response
        if course_id != None:
            if not course_id.isdigit():
                '''going to want to redirect back to course page not browse'''
                return redirect(url_for('cart'))
            if course_id in course_cookie:
                course_cookie = delete(course_id, course_cookie)
                course_ids = course_cookie.split(' ')
                if (course_cookie == None) or (course_cookie == ""):
                    num = '0'
                else:
                    num = str(len(course_ids))
                for course_id in course_ids:
                    if course_id != '':
                        c_id = int(course_id)
                        course = sql.Course.query.filter_by(c_id=c_id).first()
                        if course != None: courses.append(course)
                response = make_response(render_template('cart.html', netid=netid, courses=courses, incart=num))
                response.set_cookie('courses', course_cookie)
                return response
        course_ids = course_cookie.split(' ')
        for course_id in course_ids:
            if course_id != '':
                c_id = int(course_id)
                course = sql.Course.query.filter_by(c_id=c_id).first()
                if course != None: courses.append(course)
        if (course_cookie == None) or (course_cookie == ""):
            num = '0'
        else:
            num = str(len(course_ids))
        return render_template('cart.html', netid=netid, courses=courses, incart=num)

    @app.route('/api/descriptions/<int:c_id>', methods=['POST'])
    def post_description(c_id):
        if cas.username is None:
            abort(401)
        course = sql.Course.query.filter_by(c_id=c_id).first()
        if course == None:
            abort(404)
        text = request.form['text']
        description = sql.Description(text=text, upvotes=0, course=course)
        sql.db.session.add(description)
        sql.db.session.commit()
        return json.dumps({'text': description.text, 'upvotes': description.upvotes}), 201

    @app.route('/api/descriptions/<int:description_id>', methods=['PUT'])
    def update_description(description_id):
        netid = cas.username
        if netid is None:
            abort(401)
        vote = 0
        paramVote = request.form['vote']
        try:
            vote = int(paramVote)
        except ValueError:
            abort(401)
        description = sql.Description.query.get(description_id)
        user = sql.User.query.filter_by(netid=netid).first()
        if vote == 1:
            if str(description_id) not in user.upvoted_descriptions:
                user.upvoted_descriptions += " " + str(description_id) + " "
            else:
                vote = -1
                user.upvoted_descriptions = user.upvoted_descriptions.replace(" " + str(description_id) + " ", "")
            if str(description_id) in user.downvoted_descriptions:
                user.downvoted_descriptions = user.downvoted_descriptions.replace(" " + str(description_id) + " ", "")
                vote = 2
        elif vote == -1:
            if str(description_id) not in user.downvoted_descriptions:
                user.downvoted_descriptions += " " + str(description_id) + " "
            else:
                vote = 1
                user.downvoted_descriptions = user.downvoted_descriptions.replace(" " + str(description_id) + " ", "")
            if str(description_id) in user.upvoted_descriptions:
                user.upvoted_descriptions = user.upvoted_descriptions.replace(" " + str(description_id) + " ", "")
                vote = -2
        if description == None:
            abort(404)
        description.upvotes += vote
        sql.db.session.commit()
        return json.dumps({'upvotes': description.upvotes}), 201

    @app.route('/api/descriptions/<int:c_id>', methods=['GET'])
    def get_descriptions(c_id):
        netid = cas.username
        if netid is None:
            abort(401)
        course = sql.Course.query.filter_by(c_id=c_id).first()
        if course == None:
            abort(404)
        user = sql.User.query.filter_by(netid=netid).first()
        descriptions = course.descriptions.order_by(sql.Description.upvotes.desc()).all()
        descriptionsJson = []
        for description in descriptions:
            if description.upvotes <= -10:
                sql.db.session.delete(description)
                continue
            dDict = {}
            dDict['id'] = description.id
            dDict['text'] = description.text
            dDict['upvotes'] = description.upvotes
            dDict['action'] = 0
            if str(description.id) in user.upvoted_descriptions:
                dDict['action'] = 1
            elif str(description.id) in user.downvoted_descriptions:
                dDict['action'] = -1
            descriptionsJson.append(dDict)
        sql.db.session.commit()
        return json.dumps(descriptionsJson)

    @app.route('/api/rants/<int:c_id>', methods=['POST'])
    def post_rant(c_id):
        if cas.username is None:
            abort(401)
        course = sql.Course.query.filter_by(c_id=c_id).first()
        if course == None:
            abort(404)
        text = request.form['text']
        rant = sql.Rant(text=text, upvotes=0, course=course)
        sql.db.session.add(rant)
        sql.db.session.commit()
        return json.dumps({'id': rant.id, 'text': rant.text, 'upvotes': rant.upvotes}), 201

    @app.route('/api/rants/<int:rant_id>', methods=['PUT'])
    def update_rant(rant_id):
        netid = cas.username
        if netid is None:
            abort(401)
        vote = 0
        paramVote = request.form['vote']
        try:
            vote = int(paramVote)
        except ValueError:
            abort(401)
        rant = sql.Rant.query.get(rant_id)
        user = sql.User.query.filter_by(netid=netid).first()
        if vote == 1:
            if str(rant_id) not in user.upvoted_rants:
                user.upvoted_rants += " " + str(rant_id) + " "
            else:
                vote = -1
                user.upvoted_rants = user.upvoted_rants.replace(" " + str(rant_id) + " ", "")
            if str(rant_id) in user.downvoted_rants:
                user.downvoted_rants = user.downvoted_rants.replace(" " + str(rant_id) + " ", "")
                vote = 2
        elif vote == -1:
            if str(rant_id) not in user.downvoted_rants:
                user.downvoted_rants += " " + str(rant_id) + " "
            else:
                vote = 1
                user.downvoted_rants = user.downvoted_rants.replace(" " + str(rant_id) + " ", "")
            if str(rant_id) in user.upvoted_rants:
                user.upvoted_rants = user.upvoted_rants.replace(" " + str(rant_id) + " ", "")
                vote = -2
        if rant == None:
            abort(404)
        rant.upvotes += vote
        sql.db.session.commit()
        return json.dumps({'upvotes': rant.upvotes}), 201

    @app.route('/api/rants/<int:c_id>', methods=['GET'])
    def get_rants(c_id):
        netid = cas.username
        if netid is None:
            abort(401)
        course = sql.Course.query.filter_by(c_id=c_id).first()
        if course == None:
            abort(404)
        try:
            isHot = request.args.get('sort-by') == 'true'
        except ValueError:
            isHot = False
        rants = course.rants.order_by(sql.Rant.timestamp.desc()).all()
        if isHot:
            rants.sort(key=lambda k: k.upvotes, reverse=True)
        user = sql.User.query.filter_by(netid=netid).first()
        rantsJson = []
        currentTime = datetime.datetime.utcnow()
        for rant in rants:
            rantDict = {}
            rantDict['id'] = rant.id
            rantDict['text'] = rant.text
            rantDict['upvotes'] = rant.upvotes
            rantDict['replies'] = []
            rantDict['action'] = 0
            if str(rant.id) in user.upvoted_rants:
                rantDict['action'] = 1
            elif str(rant.id) in user.downvoted_rants:
                rantDict['action'] = -1
            rantDict['timestamp'] = util.elapsedTime(rant.timestamp, currentTime)
            for reply in rant.replies.all():
                replyDict = {}
                replyDict['id'] = reply.id
                replyDict['text'] = reply.text
                replyDict['upvotes'] = reply.upvotes
                replyDict['action'] = 0
                if str(reply.id) in user.upvoted_replies:
                    replyDict['action'] = 1
                elif str(reply.id) in user.downvoted_replies:
                    replyDict['action'] = -1
                replyDict['timestamp'] = util.elapsedTime(reply.timestamp, currentTime)
                rantDict['replies'].append(replyDict)
            rantsJson.append(rantDict)
        return json.dumps(rantsJson)

    @app.route('/api/replies/<int:rant_id>', methods=['POST'])
    def post_reply(rant_id):
        if cas.username is None:
            abort(401)
        rant = sql.Rant.query.get(rant_id)
        if rant == None:
            abort(404)
        text = request.form['text']
        reply = sql.Reply(text=text, upvotes=0, parent=rant)
        sql.db.session.add(reply)
        sql.db.session.commit()
        time = util.elapsedTime(reply.timestamp, datetime.datetime.utcnow())
        return json.dumps({'id': reply.id, 'text': reply.text, 'upvotes': reply.upvotes, 'timestamp': time}), 201

    @app.route('/api/replies/<int:reply_id>', methods=['PUT'])
    def update_reply(reply_id):
        netid = cas.username
        if netid is None:
            abort(401)
        vote = 0
        paramVote = request.form['vote']
        try:
            vote = int(paramVote)
        except ValueError:
            abort(401)
        reply = sql.Reply.query.get(reply_id)
        user = sql.User.query.filter_by(netid=netid).first()
        if vote == 1:
            if str(reply_id) not in user.upvoted_replies:
                user.upvoted_replies += " " + str(reply_id) + " "
            else:
                vote = -1
                user.upvoted_replies = user.upvoted_replies.replace(" " + str(reply_id) + " ", "")
            if str(reply_id) in user.downvoted_replies:
                user.downvoted_replies = user.downvoted_replies.replace(" " + str(reply_id) +  " ", "")
                vote = 2
        elif vote == -1:
            if str(reply_id) not in user.downvoted_replies:
                user.downvoted_replies += " " + str(reply_id) + " "
            else:
                vote = 1
                user.downvoted_replies = user.downvoted_replies.replace(" " + str(reply_id) +  " ", "")
            if str(reply_id) in user.upvoted_replies:
                user.upvoted_replies = user.upvoted_replies.replace(" " + str(reply_id) + " ", "")
                vote = -2
        if reply == None:
            abort(404)
        reply.upvotes += vote
        sql.db.session.commit()
        return json.dumps({'upvotes': reply.upvotes}), 201

    @app.route('/api/reviews/<int:c_id>', methods=['POST'])
    def post_review(c_id):
        if cas.username is None:
            abort(401)
        course = sql.Course.query.filter_by(c_id=c_id).first()
        if course == None:
            abort(404)
        sem_code = 0
        rating = 0.0
        try:
            sem_code =int(request.form['sem_code'])
        except ValueError:
            abort(400)
        try:
            rating = float(request.form['rating'])
        except ValueError:
            abort(400)
        text = request.form['text']
        term = sql.Term.query.filter_by(c_id=c_id, code=sem_code).first()
        num = len(term.reviews.all())
        review = sql.Review(rating=rating,
                            text=text,
                            num=num,
                            upvotes=0,
                            scraped=False,
                            term=term)
        sql.db.session.add(review)
        term.overall_rating = (term.overall_rating * num + review.rating) / (num + 1)
        course.avg_rating = sum(t.overall_rating for t in course.terms.all()) / len(course.terms.all())
        sql.db.session.commit()
        return json.dumps({'sem_code': review.sem_code, 'text': review.text, 'upvotes': review.upvotes}), 201

    @app.route('/api/reviews/<int:review_id>', methods=['PUT'])
    def update_review(review_id):
        netid = cas.username
        if netid is None:
            abort(401)
        upvotes = 0
        paramVotes = request.form['upvotes']
        try:
            upvotes = int(paramVotes)
        except ValueError:
            abort(401)
        review = sql.Review.query.get(review_id)
        if review == None:
            abort(404)
        user = sql.User.query.filter_by(netid=netid).first()
        if upvotes == 1:
            if " " + str(review_id) + " " not in user.upvoted_reviews:
                user.upvoted_reviews += " " + str(review_id) + " "
            else:
                upvotes = -1
                user.upvoted_reviews = user.upvoted_reviews.replace(" " + str(review_id) + " ", "")
        review.upvotes += upvotes
        sql.db.session.commit()
        return json.dumps({'upvotes': review.upvotes}), 201

    @app.route('/api/reviews/<int:c_id>', methods=['GET'])
    def get_reviews(c_id):
        netid = cas.username
        if netid is None:
            abort(401)
        course = sql.Course.query.filter_by(c_id=c_id).first()
        if course == None:
            abort(404)
        try:
            byUpvotes = request.args.get('sort-by') == 'true'
        except ValueError:
            byUpvotes = False
        user = sql.User.query.filter_by(netid=netid).first()
        terms = course.terms.all()
        reviewsJson = {}
        for term in terms:
            code = term.code
            reviewsJson[code] = {}
            percentages = [0, 0, 0, 0, 0]
            termCode = str(term.code)[1:]
            if termCode[2:3] == "2":
                termString = "Fall " + str(int(termCode[:2]) - 1)
            else:
                termString = "Spring " + termCode[:2]
            reviewsJson[code]['term_string'] = termString
            reviewsJson[code]['average_rating'] = term.overall_rating
            reviewsJson[code]['instructors'] = []
            for instructor in term.instructors:
                instrucDict = {}
                instrucDict['emplid'] = instructor.emplid
                instrucDict['first_name'] = instructor.first_name
                instrucDict['last_name'] = instructor.last_name
                reviewsJson[code]['instructors'].append(instrucDict)
            reviewsJson[code]['reviews'] = []
            reviewsForTerm = term.reviews.order_by(sql.Review.timestamp.desc()).all()
            if byUpvotes:
                reviewsForTerm.sort(key=lambda k: k.upvotes, reverse=True)
            for review in reviewsForTerm:
                reviewDict = {}
                reviewDict['id'] = review.id
                reviewDict['sem_code'] = review.sem_code
                reviewDict['rating'] = review.rating
                reviewDict['text'] = review.text
                reviewDict['action'] = 0
                if str(review.id) in user.upvoted_reviews:
                    reviewDict['action'] = 1
                reviewDict['upvotes'] = review.upvotes
                reviewsJson[code]['reviews'].append(reviewDict)
                ratingMap = {}
                if not review.scraped:
                    percentages[5-int(review.rating)] += 1
            total = sum([freq for freq in percentages])
            if total > 0:
                percentages = [(percent / total * 100) for percent in percentages]
                max_percent = max(percentages)
                percentages = [percent / max_percent * 100 for percent in percentages]
            reviewsJson[code]['percentages'] = [percent for percent in percentages]
        return json.dumps(reviewsJson)

    # Add an error handler. This is useful for debugging the live application,
    # however, you should disable the output of the exception for production
    # applications.
    @app.errorhandler(500)
    def server_error(e):
        return """
        An internal error occurred: <pre>{}</pre>
        See logs for full stacktrace.
        """.format(e), 500

    return app
Exemplo n.º 29
0
def create_app():
    '''Application factory'''

    # Figure out environment to set log config
    environment = os.getenv('FLASK_ENV')
    if environment != 'production':
        environment = 'development'

    # Load log config, and create log before flask app
    log_config = json.load(open(f'log/log_config_{environment}.json'))
    dictConfig(log_config)

    # Create flask app
    app = Flask(__name__)
    app.config.from_object(get_config())

    # Add separate handler for werkzeug request/traffic info,
    # but set log level to same as for flask log
    werkzeug_log = logging.getLogger('werkzeug')
    werkzeug_log.setLevel(logging.root.level)

    # Note that if environment is set to 'development', then the config module
    # will set FLASK_DEBUG=1, which will also set log-level to DEBUG.
    # To override this, change log level explicitly here:
    # app.logger.setLevel(logging.root.level)

    # Enable cross-site resource forgery protections
    CSRFProtect(app)

    # Enable authentication against Bioatlas CAS server
    cas = CAS(app)

    # Enable flask email
    app.mail = Mail(app)

    # Make some variables available in all templates,
    # for dynamic display of menu items and email links
    @app.context_processor
    def inject_into_templates():
        CONFIG = get_config()
        if cas.attributes:
            user = cas.username
            # To show in menu when user is logged in
            firstname = cas.attributes['cas:firstname']
        else:
            user = None
            firstname = None

        return dict(sbdi_contact_page=CONFIG.SBDI_CONTACT_PAGE,
                    sbdi_start_page=CONFIG.SBDI_START_PAGE,
                    sbdi_seq_search_page=CONFIG.SBDI_SEQ_SEARCH_PAGE,
                    sbdi_molecular_page=CONFIG.SBDI_MOLECULAR_PAGE,
                    bioatlas_page=CONFIG.BIOATLAS_PAGE,
                    taxonomy_page=CONFIG.TAXONOMY_PAGE,
                    user=user,
                    firstname=firstname,
                    max_file_size=CONFIG.MAX_CONTENT_LENGTH,
                    valid_extensions=', '.join(CONFIG.VALID_EXTENSIONS))

    with app.app_context():
        from molmod.routes import blast_routes, filter_routes, main_routes
        app.register_blueprint(main_routes.main_bp)
        app.register_blueprint(blast_routes.blast_bp)
        app.register_blueprint(filter_routes.filter_bp)
        errors.init_app(app)

    return app
Exemplo n.º 30
0
    Response,
    make_response,
)

# Initial directory system setup
setup_directories()

logging.basicConfig(level=logging.DEBUG)
UPLOAD_FOLDER = "uploaded"

app = Flask(__name__)
app.secret_key = os.urandom(24)
app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
app.config["SEND_FILE_MAX_AGE_DEFAULT"] = 0

cas = CAS(app, "/cas")
app.config["CAS_SERVER"] = "https://sso-prod.sun.ac.za"
app.config["CAS_AFTER_LOGIN"] = "******"


@app.before_request
def before_request_callback():
    session["user"] = cas.username
    session["title"] = User(session["user"]).title


@app.route("/favicon.ico")
def favicon():
    return send_from_directory("static", "favicon.ico")