示例#1
0
def load_user(user_id):
    user = None
    if '=>' in user_id:
        username = user_id.split('=>')[0]
        project = user_id.split('=>')[1]
        sql = database.SQL(project)
        user = User()
        user.initByUsername(sql, username)
        user.set_project(project)
        if not user.found:
            return None
    return user
示例#2
0
def project(project):
    if current_user.is_authenticated and current_user.project == project:
        print 'yes'
        sql = database.SQL(project)
        projectconfig = config.configProject(project)
        myassignments = printmyassignments(project,sql,projectconfig,current_user.id)
        alltext = printalltexts(project,sql, current_user.adminLevel,projectconfig)
        userassignments = printuserassignments(project,projectconfig,sql,current_user.adminLevel)
        menus = printmenues(project,sql, projectconfig)
        mate = printmate(project,projectconfig, sql, current_user.adminLevel)
        return render_template('project.html', project=project, \
            myassignments=myassignments,userassignments=userassignments, alltext=alltext,mate=mate, menus=menus, asset="/static")
    else:
        return flask.redirect(flask.url_for('ulogin', project=project))
示例#3
0
def slogin(project, provider):
    """
    Login handler, must accept both GET and POST to be able to use OpenID.
    """
    
    # We need response object for the WerkzeugAdapter.
    response = make_response()
    
    # Log the user in, pass it the adapter and the provider name.
    result = authomatic.login(WerkzeugAdapter(request, response), provider)
    
    # If there is no LoginResult object, the login procedure is still pending.
    next = request.args.get('next')
    if result:
        if result.user:
            # We need to update the user to get more info.
            result.user.update()
            sql = database.SQL(project)
            user = User()
            if provider == "tw":
                user.initByUsername(sql, "%s@twitter"%(result.user.username))
                if user.found:
                    #login
                    print 'login'
                    user.set_project(project)
                    flask_login.login_user(user)
                else: #create user
                    user.username = "******"%(result.user.username)
                    user.first_name = result.user.name
                    user.createInDB(sql)
                    print 'created'
                    user.set_project(project)
                    flask_login.login_user(user)
            return flask.redirect(next or flask.url_for('index'))

        # The rest happens inside the template.
        return render_template('login.html', result=result)
    
    # Don't forget to return the response.
    return response
示例#4
0
def ulogin(project):
    error = ""
    success = False
    if request.method == 'POST':
        sql = database.SQL(project)
        user = User()
        user.initByUsername(sql, request.form['username'])

        login_user = User()
        login_user.init_password(request.form['username'], request.form['pass'])

        if user.found and login_user.pw_hash == user.pw_hash:
            success = True
            user.set_project(project)
            flask_login.login_user(user)
            next = request.args.get('next')
            return redirect(next or flask.url_for('index'))
        else:
            error = 'Invalid Credentials. Please try again.'


    return render_template('login_page.html', project=project, asset="/static", error=error, success=success)
示例#5
0
def editor(project,text_id,opensentence):
    textid=int(text_id)
    from editor import printhtmlheader,printheadline,printmenues
    if current_user.is_authenticated and current_user.project == project:
        sql = database.SQL(project)
        projectconfig = config.configProject(project)
        txt = ""
        if not projectconfig:
        #print "Content-Type: text/html\n" # blank line: end of headers
            txt = "something went seriously wrong: can't read the configuration of the project",project.encode("utf-8")
        try:
            _,textname,_ = sql.getall(None, "texts",["rowid"],[text_id])[0]
        except:
            pass
            txt+= "something went seriously wrong: The text you are looking for does not seem to exist! project"
            textname="text not found!"
        todo = sql.gettodostatus(current_user.id,textid)
        validator=0
        if todo>0: validator=int(todo) # -1 and 0 => 0, 1 => 1
        projectEsc=project.replace("'","\\'").replace('"','\\"')
        validvalid=sql.validvalid(textid)
        
        exotype, exotoknum =sql.getExo(textid)
        addEmptyUser=None
        #print "uu",sql.exotypes[exotype],sql.exotypes[exotype]=="graphical feedback"
        if sql.exotypes[exotype] in ["teacher visible","graphical feedback", "percentage"] :
            addEmptyUser=current_user.username
        if sql.exotypes[exotype] in ["teacher visible"] :
            validvalid+=[sql.userid(sql.teacher)]
        if sql.exotypes[exotype]=="graphical feedback":
            graphical=1
        if exotoknum and not current_user.adminLevel:    quantityInfo = ">"+str(exotoknum)+" tokens"
        else:                   quantityInfo = str(sql.getnumber(None, "sentences",["textid"],[textid]))+" sentences"
        
        jsdef = config.jsDefPrinter(projectconfig)
        htmlheader = printhtmlheader(projectEsc,textname,current_user,textid,current_user.id,sql,todo,validator,addEmptyUser,validvalid,opensentence, projectconfig)
        headline  = printheadline(project,textname,quantityInfo,current_user)
        userid = current_user.id
        main = ""
        for snr,sid,s,tid in sql.getAllSentences(textid, current_user.username, current_user.id, current_user.adminLevel):
            #print adminLevel, validvalid, validator
            treelinks, firsttreeid, sentenceinfo=sql.links2AllTrees(sid,snr,current_user.username,current_user.adminLevel, todo, validvalid, validator,addEmptyUser=addEmptyUser)
            status=""
            if todo>=0:status=sql.gettreestatus(sid,userid)
            status="<span id='status{nr}' class='status' onClick='nexttreestatus({sid},{nr})'>{status}</span>".format(status=status,sid=sid, nr=snr)
            connectRight=""
            if current_user.adminLevel or (sql.validatorsCanConnect and validator):
                connectRight='''<img class="connectRight" src="/static/images/chain.png" border="0" align="bottom" id='connectRight{nr}' nr='{nr}' title="connect with next tree (+ctrl: split at selcted word)"> '''.format(nr=snr)
            exo=""
            if exotype>1: # 0: no exercise, 1: no feedback
                exo='''<img class="check" src="/static/images/check.png" border="0" align="bottom" id='check{nr}' nr='{nr}' title="check annotation" graphical={graphical}> '''.format(nr=snr, graphical=graphical)
            main += '''<div id='sentencediv{nr}' class='sentencediv' style="margin:10px;" sid={sid}  nr={nr}>
                    <a id='toggler{nr}' class="toggler" treeid="{firsttreeid}" nr="{nr}" >
                        {nr}: {sentence} &nbsp;
                    </a> 
                    <span id="othertrees{nr}" > {treelinks} </span>
                    <img class="saveimg" src="/static/images/save.png" border="0" align="bottom" id='save{nr}' title="save">
                    <img class="undoimg" src="/static/images/undo.png" border="0" align="bottom" id='undo{nr}'>
                    <img class="redoimg" src="/static/images/redo.png" border="0" align="bottom" id='redo{nr}'> 
                    {status}
                    <img class="exportimg" src="/static/images/export.png" border="0" align="bottom" id='export{nr}' nr='{nr}' title="export"> 
                    {connectRight}
                    {exo}
                </div><p><small>{sentenceinfo}</small></p>'''.format(sentence=s.encode("utf-8"),nr=snr, sid=sid, firsttreeid=firsttreeid, project=project.encode("utf-8"), userid=userid, treelinks=treelinks.encode("utf-8"), status=status,connectRight=connectRight,exo=exo,sentenceinfo=sentenceinfo.encode("utf-8"))
        menus = printmenues(projectconfig)
        return render_template('editor.html', project=project, \
            textname=textname,htmlheader=htmlheader,menus=menus, headline=headline,main=main.decode("utf-8"), jsdef=jsdef, asset="/static")
    else:
        return flask.redirect(flask.url_for('ulogin', project=project))
示例#6
0
# -*- coding: utf-8 -*-
import telebot
from lib import weather, keyboard, config, information, database

bot = telebot.TeleBot(config.token)
info_dict = {}
db_worked = database.SQL(config.database_name)

@bot.message_handler(commands=['start'])
def start_message(message):
    bot.send_message(message.chat.id, 'Привет, {}'.format(message.chat.first_name.encode('UTF-8')),
                     reply_markup = keyboard.keyboard_main)


@bot.callback_query_handler(func=lambda call: True)
def callback_worker(call):
    if call.data == 'weather':
        msg = bot.send_message(call.message.chat.id, 'Отправьте свою геолокацию',
                               reply_markup = keyboard.keyboard_geo)
        bot.register_next_step_handler(msg, wethear)
    elif call.data == 'manager_password':
        if db_worked.check_create_user(call.message.chat.id) == 0:
            db_worked.insert_user(call.message.chat.id, call.message.chat.username, call.message.chat.first_name,
                                  call.message.chat.last_name)
        bot.send_message(call.message.chat.id, 'Что Вы хотите сделать?',
                         reply_markup = keyboard.keyboard_manager_password)
    elif call.data == 'show':
        if db_worked.count_rows(call.message.chat.id) != 0:
            bot.send_message(call.message.chat.id, 'Показать все записи или конкретную?',
                             reply_markup = keyboard.keyboard_manager_password_show)
        else:
示例#7
0
	try:	
		projectconfig = config.configProject(project) # read in the settings of the current project
	except:
		print "Error! Can't read the configuration files. Please check that the files project.cfg, functions.cfg, and categories.cfg are present in the project folder	"
		sys.exit("something's wrong")
	if not projectconfig:
		##print "Content-Type: text/html\n" # blank line: end of headers
		print "something went seriously wrong: can't read the configuration of the project"
		if project: print project.encode("utf-8")
		##print "Content-Type: text/html\n" # blank line: end of headers
		print '<script type="text/javascript">window.location.href=".";</script>'
		sys.exit("something's wrong")
	#sql=database.SQL(project)
	#userid = sql.userid(username, realname)
	try:
		sql=database.SQL(project)
		userid = sql.userid(username, realname)
	except Exception , e:
		from sqlite3 import OperationalError
		if isinstance(e, OperationalError) and str(e)in["attempt to write a readonly database","unable to open database file"]:
			print "Error! Make your database and the path leading there from the arborator base modifiable by the apache user!"
		if isinstance(e, KeyError):
			print "Error! the configuration file does not contain all the necessary keys:",str(e)
		else:
			print "strange error accessing the database.<br>",str(e)
			import traceback
			
			traceback.print_exc()
		sys.exit("something's wrong")
	
	if (not projectconfig) and (not action):