Example #1
0
def init_and_sync_repo(course, force_sync=False):
    """
    Initializes a git repository in the pages folder if no repository already exists, then
    synchronizes it with the remote specified in the configuration file if the
    origin didn't exist before or if force_sync is True.
    Warning: the local changes will be overwritten.
    :return:
    """
    path = os.path.join(syllabus.get_root_path(),
                        syllabus.get_pages_path(course))
    git_config = syllabus.get_config()['courses'][course]['pages']['git']
    try:
        if not os.path.exists(path):
            os.makedirs(path)
        repo = Repo(path)
    except InvalidGitRepositoryError:
        # this is currently not a git repo
        repo = Repo.init(path)
    try:
        origin = repo.remote("origin").set_url(git_config['remote'])
    except:
        origin = repo.create_remote("origin", git_config['remote'])
        # sync the repo if the origin wasn't already there
        force_sync = True
    if force_sync:
        git_force_sync(course, origin, repo)
        syllabus.get_toc(course, True)
Example #2
0
def git_force_sync(course, origin, repo):
    git_config = syllabus.get_config()['courses'][course]['pages']['git']
    private_key_path = git_config['repository_private_key']
    branch = git_config['branch']
    if private_key_path is not None:
        # We need to be compatible with git < 2.3 as CentOS7 uses an older version, so here is an ugly code
        # to use a deployment key that will work with old git versions

        # set the ssh executable
        ssh_executable_path = os.path.join(syllabus.get_root_path(),
                                           "ssh_executable.sh")
        with open(ssh_executable_path, "w") as f:
            f.write(
                '#!/bin/sh\nID_RSA=%s\nssh -o StrictHostKeyChecking=no -i $ID_RSA "$@"'
                % private_key_path)
        os.system("chmod +x %s" % ssh_executable_path)
        with repo.git.custom_environment(GIT_SSH=ssh_executable_path):
            origin.fetch()
            # complete synchronization (local changes will be overwritten)
            repo.git.reset('--hard', 'origin/%s' % branch)
        # Hereunder is a more pretty version, uncomment it when the git version is >= 2.3
        # with repo.git.custom_environment(GIT_SSH_COMMAND='ssh -i %s -o StrictHostKeyChecking=no' % private_key_path):
        #     origin.fetch()
        #     # complete synchronization (local changes will be overwritten)
        #     repo.git.reset('--hard', 'origin/%s' % branch)
    else:
        origin.fetch()
        # complete synchronization (local changes will be overwritten)
        repo.git.reset('--hard', 'origin/%s' % branch)
Example #3
0
def get_cheat_sheet():
    with open(
            os.path.join(syllabus.get_root_path(),
                         'cheat_sheet/rst-cheatsheet.rst'), "r") as f:
        code_html = render_template_string(
            publish_string(f.read(),
                           writer_name='html',
                           settings_overrides=default_rst_opts))
        return "<div id=\"cheat_sheet\" style=\"overflow-y: scroll\">" + code_html + "</div>"
Example #4
0
from onelogin.saml2.utils import OneLogin_Saml2_Utils

import syllabus
import syllabus.utils.directives
import syllabus.utils.pages
from syllabus.admin import admin_blueprint
from syllabus.database import init_db, db_session, update_database
from syllabus.models.params import Params
from syllabus.models.user import hash_password, User
from syllabus.saml import prepare_request, init_saml_auth
from syllabus.utils.inginious_lti import get_lti_data, get_lti_submission
from syllabus.utils.pages import seeother, get_content_data, permission_admin
from syllabus.utils.toc import Content, Chapter, TableOfContent, ContentNotFoundError, Page

app = Flask(__name__,
            template_folder=os.path.join(syllabus.get_root_path(),
                                         'templates'),
            static_folder=os.path.join(syllabus.get_root_path(), 'static'))
app.register_blueprint(admin_blueprint, url_prefix='/admin')
app.config['TEMPLATES_AUTO_RELOAD'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
session_sk = syllabus.get_config().get("sessions_secret_key", None)
if session_sk is None or session_sk == "":
    raise Exception(
        "You must give a session secret key to use the application")
app.secret_key = session_sk
directives.register_directive('inginious',
                              syllabus.utils.directives.InginiousDirective)
directives.register_directive(
    'inginious-sandbox', syllabus.utils.directives.InginiousSandboxDirective)
directives.register_directive('table-of-contents',
from sqlalchemy.orm.exc import NoResultFound

import syllabus
import syllabus.utils.directives
import syllabus.utils.pages
from syllabus.admin import admin_blueprint, pop_feeback, set_feedback, ErrorFeedback, SuccessFeedback
from syllabus.database import init_db, db_session, update_database, locally_register_new_user, reload_database
from syllabus.models.params import Params
from syllabus.models.user import hash_password_func, User, UserAlreadyExists, verify_activation_mac, get_activation_mac
from syllabus.saml import prepare_request, init_saml_auth
from syllabus.utils.inginious_lti import get_lti_data, get_lti_submission
from syllabus.utils.mail import send_confirmation_mail, send_authenticated_confirmation_mail
from syllabus.utils.pages import seeother, get_content_data, permission_admin, update_last_visited, store_last_visited, render_content, default_rst_opts, get_cheat_sheet
from syllabus.utils.toc import Content, Chapter, TableOfContent, ContentNotFoundError, Page

app = Flask(__name__, template_folder=os.path.join(syllabus.get_root_path(), 'templates'),
            static_folder=os.path.join(syllabus.get_root_path(), 'static'))
app.register_blueprint(admin_blueprint, url_prefix='/admin')
app.config['TEMPLATES_AUTO_RELOAD'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
session_sk = syllabus.get_config().get("sessions_secret_key", None)
if session_sk is None or session_sk == "":
    raise Exception("You must give a session secret key to use the application")
app.secret_key = session_sk
directives.register_directive('inginious', syllabus.utils.directives.InginiousDirective)
directives.register_directive('inginious-sandbox', syllabus.utils.directives.InginiousSandboxDirective)
directives.register_directive('table-of-contents', syllabus.utils.directives.ToCDirective)
directives.register_directive('author', syllabus.utils.directives.AuthorDirective)
directives.register_directive('teacher', syllabus.utils.directives.TeacherDirective)
directives.register_directive('framed', syllabus.utils.directives.FramedDirective)
directives.register_directive('print', syllabus.utils.directives.PrintOnlyDirective)
Example #6
0
def update_database():
    if os.path.isfile(database_path):
        connection = engine.connect()
        version = connection.execute("PRAGMA main.user_version;").first()[0]
        if version < current_version:
            print(
                "database version (%d) is outdated, updating database to version %d"
                % (version, current_version))
        if version < 1:
            print("updating to version 1")
            connection.execute(
                "ALTER TABLE users ADD COLUMN right STRING(30);")
        if version < 2:
            print("updating to version 2")
            connection.execute("""
            CREATE TABLE params(
               git_hook_url STRING(80),
               id           INTEGER PRIMARY KEY
            );
            """)
            connection.execute("""
            INSERT INTO params (git_hook_url, id)
            VALUES (NULL, 1);
            """)
        if version < 3:
            print("updating to version 3")
            from sqlalchemy.schema import CreateTable
            from syllabus.models.user import User
            from syllabus.models.params import Params
            print()

            tmp_path = os.path.join(get_root_path(), 'temp.sqlite')
            engine_tmp = create_engine('sqlite:///%s' % tmp_path,
                                       convert_unicode=True)

            if os.path.isfile(tmp_path):
                os.remove(tmp_path)
            import syllabus.models.user
            import syllabus.models.params
            connection_tmp = engine_tmp.connect()
            connection_tmp.execute(CreateTable(User.__table__))
            connection_tmp.execute(CreateTable(Params.__table__))
            for row in connection.execute(
                    "SELECT username, email, full_name, hash_password, change_password_url, "
                    "right FROM users"):
                connection_tmp.execute("INSERT INTO users (username, email, full_name, hash_password, change_password_url, right, activated) "\
                                       "VALUES ('{}', '{}', {}, '{}', {}, {}, {})".format(row[0], row[1], "NULL" if row[2] is None else "'%s'" % row[2],
                                                                                                row[3], "NULL" if row[4] is None else "'%s'" % row[4],
                                                                                                "NULL" if row[5] is None else "'%s'" % row[5], 1))
            for row in connection.execute(
                    "SELECT git_hook_url, id FROM params"):
                connection_tmp.execute("INSERT INTO params (git_hook_url, id) "\
                                       "VALUES ('{}', '{}')".format(row[0], row[1]))
            os.remove(database_path)
            os.rename(tmp_path, database_path)
            os.chmod(database_path, stat.S_IRWXU | stat.S_IRWXG)
            reload_database()
            connection = engine.connect()

        connection.execute("PRAGMA main.user_version=%d;" % current_version)
    else:
        print("The database does not exist yet.")
Example #7
0
import os

import binascii
import re
import stat
from operator import or_

from sqlalchemy import create_engine
from sqlalchemy.engine import ResultProxy
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from syllabus import get_root_path

database_path = os.path.join(get_root_path(), 'database.sqlite')
engine = create_engine('sqlite:///%s' % database_path, convert_unicode=True)
db_session = scoped_session(
    sessionmaker(autocommit=False, autoflush=False, bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()

current_version = 3


def create_db_user():
    from syllabus.models.user import User
    change_pwd_bytes = os.urandom(20)
    change_pwd_hex = binascii.hexlify(change_pwd_bytes).decode()
    u = User('admin',
             'admin@localhost',
             hash_password=None,
             change_password_url=change_pwd_hex,
Example #8
0
import binascii
import re
import stat
from operator import or_

from sqlalchemy import create_engine
from sqlalchemy.engine import ResultProxy
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from syllabus import get_root_path
from syllabus import get_config

database_uri = os.environ.get(
    "SYLLABUS_DATABASE_URI",
    'sqlite:///%s' % os.path.join(get_root_path(), 'database.sqlite'))
engine = create_engine(database_uri, convert_unicode=True)
db_session = scoped_session(
    sessionmaker(autocommit=False, autoflush=False, bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()

current_version = 3


def create_db_user():
    from syllabus.models.user import User
    change_pwd_bytes = os.urandom(20)
    change_pwd_hex = binascii.hexlify(change_pwd_bytes).decode()
    u = User('admin',
             'admin@localhost',
Example #9
0
def init_saml_auth(req, saml_config):
    auth = OneLogin_Saml2_Auth(req,
                               saml_config,
                               custom_base_path=os.path.join(
                                   syllabus.get_root_path(), "saml"))
    return auth