Beispiel #1
0
def google_login():
    if session.get('google_token'):
        del session['google_token']
    session['next'] = session.get('next') or request.referrer or None
    return google.authorize(
        callback=url_for('oauth.google_oauth_authorized',
            _external=True))
Beispiel #2
0
def get_tex_file():
    try:
        os.mkdir('instance/texfiles')
    except OSError:
        pass

    user = User()

    text = get_header(user.data['config'])
    text += get_general(user.data['general'])
    text += get_education(user.data['educations'])
    text += get_experience(user.data['experiences'])
    text += get_project(user.data['projects'])
    text += get_publication(user.data['publications'])
    text += get_skill(user.data['skills'])
    text += get_footer()

    text = text.replace('&', '\&')

    try:
        os.mkdir('instance/texfiles/{}'.format(get_hash(
            session.get('user_id'))))
    except OSError:
        pass

    with open(
            'instance/texfiles/{}/main.tex'.format(
                get_hash(session.get('user_id'))), 'w') as file:
        file.write(text)

    file.close()
def user_home():
    if session.get("logged_user_id"):
        user_info = factory.get_user_info_dao().get_user_info(session.get("logged_user_id"))
        return render_template(
            "user_home.html", uid=session.get("logged_user_id"), userinfo=user_info, favcolor=user_info.favcolor
        )
    return redirect("/")
def user_mission_control():
    if session.get("logged_user_id"):
        cuser = factory.get_user_dao().get_user(session.get("logged_user_id"))
        user_info = factory.get_user_info_dao().get_user_info(session.get("logged_user_id"))
        missions = factory.get_mission_dao().get_all_missions_for_user(session.get("logged_user_id"))
        return render_template(
            "user_mission_control.html",
            user=cuser,
            uid=session.get("logged_user_id"),
            missions=missions,
            favcolor=user_info.favcolor,
        )
    return redirect("/")
Beispiel #5
0
def hello():
    user_ip = session.get('user_ip')
    # login_form = LoginForm()
    username = session.get('username')

    context = {
        'user_ip': user_ip,
        'todos': todos,
        # 'login_form': login_form,
        'username': username
    }

    return render_template('hello.html', **context)
def user_settings():
    if session.get("logged_user_id"):
        cuser = factory.get_user_dao().get_user(session.get("logged_user_id"))
        user_info = factory.get_user_info_dao().get_user_info(session.get("logged_user_id"))
        return render_template(
            "user_settings.html",
            uid=session.get("logged_user_id"),
            user=cuser,
            userinfo=user_info,
            tenure=(date.today().year - int(cuser.datejoined.split("/")[2])),
            favcolor=user_info.favcolor,
        )
    return redirect("/")
Beispiel #7
0
def profile():
    '''
    Маршрутизация в профиль пользователя
    '''
    if auth_request():
        if request.method == 'POST':
            print(request.form)
            fm = request.form

            pw = fm.get('password')
            if pw == '':
                return redirect(url_for('profile'))
            elif "'" in pw or '"' in pw or '`' in pw or ';' in pw:
                return redirect(
                    url_for('profile', error='Wrong symbols in new password'))
            elif len(pw) < 6:
                return redirect(
                    url_for(
                        'profile',
                        error=
                        'The new password must be longer than 6 characters'))
            else:
                new_pw = bcrypt.generate_password_hash(pw)
                req(f"""
                    update `abiturients` set fname = "{fm.get('firstname')}", sname = "{fm.get('secondname')}", tname = "{fm.get('tridname')}", birthday = "{fm.get('birthday')}" where userID = (select id from `users` where login = "******");
                    update `users` set login = '******'login')}', password = "******" where login = "******";
                """)
                session['userLogin'] = fm.get('login')
                return redirect(url_for('profile'))

        else:
            un = session.get('userLogin')
            st = session.get('userState')
            print(un, st, session.get('userID'))
            data = getUserData(un, 'abiturients.fname', 'abiturients.sname',
                               'abiturients.tname', 'abiturients.birthday',
                               'passports.serial', 'passports.number',
                               'claims.phone', 'users.login', 'users.password')
            return render_template('profile.html',
                                   username=un,
                                   state=st,
                                   userFN=data[1],
                                   userSN=data[0],
                                   userTN=data[2],
                                   userAge=data[3],
                                   userPass=data[4] + data[5],
                                   userPhone=data[6],
                                   userLogin=data[7],
                                   userPassword=data[8])
    else:
        return redirect(url_for('login'))
Beispiel #8
0
def isLoggedin():
    if not session.get("usid"):
        return None
    mySqlconnect = MysqlConnect()

    cur = mySqlconnect.cnx.cursor()
    stmt_select = "select uid, firstname, pwdhash from users where uid=%s;"
    values = [session.get("usid")]
    cur.execute(stmt_select, values)
    row = cur.fetchone()
    if not row:
        return None

    return row
Beispiel #9
0
def get_info():
    """If host_id provided returns that host info elif host_id in session returns your host info else 400"""
    if not session.get('host_id'):
        session['host_id'] = current_user.workplace_uid
    host_id = get_request_data(request).get('host_id') or session.get(
        'host_id')
    if not host_id:
        return jsonify({'message':
                        "No host id provided"}), HTTP_400_BAD_REQUEST
    host = Host(uid=host_id)
    # 404 if there is a host with no title in db. No unnamed hosts allowed.
    response = host.to_dict()
    if response is None:
        return jsonify({'message': "No such host in db"}), HTTP_404_NOT_FOUND
    return jsonify(response)
Beispiel #10
0
def cambiarPassword(passActual, passNueva):
    if session.get('conectado') == 'S':
        usuarioCod = session.get('usua_cod')
        usuario = db.session.query(Usuarios).filter(
            Usuarios.usua_cod == usuarioCod).first()
        if bcrypt.check_password_hash(usuario.usua_password, passActual):
            usuario.usua_password = bcrypt.generate_password_hash(passNueva)
            usuario.usua_fecha_modificacion = fechaActual
            usuario.usua_cod_modificacion = session.get('usua_cod')
            db.session.commit()
            return True
        else:
            return False
    else:
        return False
Beispiel #11
0
def home():
    """Render website's home page."""
    if not session.get('logged_in'):

        return render_template('login.html')
    else:
        return render_template('home.html')
Beispiel #12
0
    def to_db(self):
        id = session.get('user_id')
        db = get_db()

        db.execute('UPDATE user SET resume_data = ? WHERE id = ?',
                   (dumps(self.data), id))
        db.commit()
Beispiel #13
0
def index():
    if session.get('conectado') == 'S':
        titulo = "COLFEAR | PRINCIPAL"
        return render_template('principal.html', titulo=titulo)
    else:
        titulo = "COLFEAR | INICIO DE SESIÓN"
        return render_template('login.html', titulo=titulo)
Beispiel #14
0
 def wrapper(*args, **kwargs):
     # 提取函数名,从而判断用户类型
     print re.findall('(\w+)_', func.__name__)[0]
     if session.get(re.findall('(\w+?)_', func.__name__)[0]) != None:
         return func(*args, **kwargs)
     else:
         return redirect(url_for('index'))
Beispiel #15
0
 def wrapper(*args, **kwargs):
     # 提取函数名,从而判断用户类型
     print re.findall('(\w+)_', func.__name__)[0]
     if session.get(re.findall('(\w+?)_', func.__name__)[0]) != None:
         return func(*args, **kwargs)
     else:
         return redirect(url_for('index'))
Beispiel #16
0
def patient_upload_illness():
    if not session.get("lid") is None:
        data = {}
        did = request.args['did']
        data['did'] = did
        q = "SELECT * FROM `files` INNER JOIN `doctors` USING(doctor_id) where patient_id='%s' and doctor_id='%s'" % (
            session['pid'], did)
        data['ill'] = select(q)
        if 'action' in request.args:
            action = request.args['action']
            id = request.args['id']
        else:
            action = None
        if action == 'delete':
            q = "delete from `files` where file_id='%s'" % (id)
            delete(q)
            flash('Deleted...')
            return redirect(url_for('patient.patient_upload_illness', did=did))

        if 'submit' in request.form:
            ill = request.form['ill']
            sym = request.form['sym']
            file = request.files['file']
            path = "static/" + str(uuid.uuid4()) + file.filename
            file.save(path)
            q = "INSERT INTO `files` (`patient_id`,`doctor_id`,`uploadfile`,`illness`,`symptoms`,`date`) VALUES('%s','%s','%s','%s','%s',curdate())" % (
                session['pid'], did, path, ill, sym)
            insert(q)
            flash('Uploaded Successfully...')
            return redirect(url_for('patient.patient_upload_illness', did=did))
        return render_template("patient_upload_illness.html", data=data)
    else:
        return redirect(url_for("public.login"))
Beispiel #17
0
def projectList():
    postcode = None
    parcelles = None
    if request.method == "GET":
        postcode = request.args.get("code_postal")

    if postcode != None:
        if str(postcode).isdigit():
            # création d'un curseur permettant l'utilisation de dictionnaires
            cursor = connexion.cursor(
                cursor_factory=psycopg2.extras.RealDictCursor)
            cursor.execute(
                "SELECT * FROM parcelle WHERE parcelle.code_postal = %s", (postcode,))
            parcelles = cursor.fetchall()
            # affichage de la liste des parcelles
            return render_template("create_project.html", parcelles=parcelles, code_postal=postcode)

    if request.method == "POST":
        login = session.get('login')
        parcelle_id = request.form.get("parcelle_id")
        ca = request.form.get("ca")
        if login == None:
            return "Veuillez vous connecter", 401
        try:
            cursor = connexion.cursor()
            # ajout de la nouvelle parcelle
            cursor.execute(
                "INSERT INTO projet (date_creation,chiffre_affaire,statut,parcelle_id,username) VALUES ((SELECT NOW()),%s,'en cours', %s,%s);", (ca, parcelle_id, login,))
            connexion.commit()
        except:
            return "Erreur: Impossible de créer le projet", 500
    # en cas de code postal non spécifié, ou apres ajout réussi, retour au formulaire pour demander un code postal
    return render_template("ask_code.html")
Beispiel #18
0
 def wrapped(*args, **kwargs):
     if not session.get("logged_in"):
         return redirect(url_for("login", next=request.url))
     elif permission is not None and not User.get_by_id(session["user"]).has_permission(permission):
         flash("Permission denied", "danger")
         return redirect(url_for("main_page"))
     else:
         return func(*args, **kwargs)
Beispiel #19
0
def cambioPassword():
    if session.get('conectado') == 'S':
        titulo = "COLFEAR | Cambio de Contraseña"
        return render_template('cambioPassword.html', titulo=titulo)
    else:
        flash(u'Debe ingresar sus credenciales para ingresar al sistema',
              'warning')
        return redirect(url_for('index'))
Beispiel #20
0
def principal():
    if session.get('conectado') == 'S':
        titulo = "COLFEAR | PRINCIPAL"
        return render_template('principal.html', titulo=titulo)
    else:
        flash(u'Debe ingresar sus credenciales para ingresar al sistema',
              'warning')
        return redirect(url_for('index'))
Beispiel #21
0
def send_token():
    if not change_language():
        email = request.form.get("email", session.get("email"))
        ticket = session.get("ticket")
        if not email or not ticket:
            abort(400)

        session["email"] = email
        current_app.al.create_account_step1(email, ticket)

    return render_template(
        "token_was_sent.mako",
        form_action="/send_token",
        email=session["email"],
        token_error=False,
        language=session["language"],
    )
Beispiel #22
0
def patient_view_hospital():
    if not session.get("lid") is None:
        data = {}
        q = "SELECT * FROM `hospitals`"
        data['hospital'] = select(q)
        return render_template("patient_view_hospital.html", data=data)
    else:
        return redirect(url_for("public.login"))
Beispiel #23
0
def get_workplace():
    user_id = session.get('user_id')
    user = User(user_id)
    if user.workplace_uid is not None:
        session['host_id'] = user.workplace_uid
    else:
        session.pop('host_id', None)
    return jsonify({'code': 0, 'host_id': user.workplace_uid})
Beispiel #24
0
def retrieve_mail():
    """查询邮件"""

    # 获取参数
    mail_title = request.args.get('mail_title')
    user_id = request.args.get('user_id')
    channel_id = int(session['select_channel'])
    begin_time = request.args.get('beginDate')
    end_time = request.args.get('endDate')

    # 处理时间
    begin_time = time_util.start(begin_time)
    end_time = time_util.end(end_time)

    # 校验参数
    if begin_time >= end_time:
        return jsonify(result='fail', msg=u'结束时间不能小于开始时间!')

    # 从数据库获取并处理数据
    mail_title_str = ''
    user_id_str = ''
    if mail_title:
        mail_title_str = ' AND mail_title LIKE "%%%s%%"' % mail_title
    if user_id:
        user_id_str = " AND user_id='%s'" % user_id
    retrieve_mail_sql = """SELECT id,user_id,push_player_id,mail_title,mail_content,
                                    mail_accessories,status,push_time,expire 
                            FROM admin_mail 
                            WHERE (push_time>=%s AND push_time<=%s) 
                            OR push_time=0 
                            %s%s
                            ORDER BY status;""" \
                        % (begin_time, end_time, mail_title_str, user_id_str)
    mail_datas = LogQry(channel_id).qry(retrieve_mail_sql)
    datas = []
    status_num = {0: u'待发送', 1: u'已发送'}
    for mail_id, user_id, push_player_id, mail_title, mail_content, \
        mail_accessories, status, push_time, expire in mail_datas:
        mails_dict = dict()
        mails_dict['mail_id'] = mail_id
        mails_dict['user_id'] = user_id
        mails_dict['push_player_id'] = push_player_id
        mails_dict['mail_title'] = mail_title
        mails_dict['mail_content'] = mail_content.replace('\n', '<br>')
        mails_dict['push_time'] = time_util.formatDateTime(
            push_time) if push_time > 0 else ''
        mails_dict['mail_accessories'] = id_map_property(mail_accessories)
        mails_dict['expire'] = expire if expire else ''
        mails_dict['status'] = status_num[status]
        datas.append(mails_dict)

    # 高级用户可以操作邮件的发送按钮
    is_high_level_user = False
    if session.get('access_level') == 1:
        is_high_level_user = True

    # 返回数据
    return jsonify(result='ok', data=datas, is_high=is_high_level_user)
Beispiel #25
0
def load_logged_in_user():
    # Load logged in user from session, if present
    user_id: Optional[int] = session.get("user_id")

    if user_id is None:
        g.user = None
    else:
        g.user = (get_db().execute("SELECT * FROM user WHERE id = ?",
                                   (user_id, )).fetchone())
Beispiel #26
0
def home():
    params_tpl = {}
    # Checks if user is logged
    if not session.get("uid", None) is None:
        # Gets the user from db
        user = user_db_service.get_user_by_uid(session["uid"])
        if not user is None: params_tpl["user_address"] = user.address
    # Renders the home page
    return render_template('index.html', params_tpl=params_tpl)
def assign_loggedin_customer():
    g.user = None
    customerid = session.get('customerid')
    if customerid is not None:
        customer = Customers.query.get(customerid)
        if customer is not None and customer.is_active:
                g.user = customer
        else:
            session.clear()
Beispiel #28
0
def home():
    params_tpl = {}
    # Checks if user is logged
    if not session.get("uid", None) is None:
        # Gets the user from db
        user = user_db_service.get_user_by_uid(session["uid"])
        if not user is None: params_tpl["user_address"] = user.address
    # Renders the home page
    return render_template('index.html', params_tpl=params_tpl)
Beispiel #29
0
def patient_view_doctor():
    if not session.get("lid") is None:
        data = {}
        hid = request.args['hid']
        q = "SELECT * FROM `doctors` where hospital_id='%s'" % (hid)
        data['doctor'] = select(q)
        return render_template("patient_view_doctor.html", data=data)
    else:
        return redirect(url_for("public.login"))
Beispiel #30
0
def get_sso_token() -> str:
    csrf_name = '_sso_token'
    csrf_token = session.get(csrf_name, None)
    if not csrf_token:
        csrf_token = generate_token()
        setattr(_app_ctx_stack.top, csrf_name, csrf_token)
    else:
        setattr(_app_ctx_stack.top, csrf_name, csrf_token)
    return csrf_token
def add_user_mission():
    if session.get("logged_user_id"):
        title = request.args.get("title")
        description = request.args.get("description")
        start = request.args.get("start")
        goal = request.args.get("goal")
        units = request.args.get("units")
        current_track = 0
        end = "01/01/1970"
        complete = 0
        new_user_mission = mission_bean(
            session.get("logged_user_id"), title, description, current_track, goal, units, start, end, complete
        )
        if factory.get_mission_dao().add_new_user_mission(new_user_mission) is True:
            return "true"
        else:
            return "false"
    return redirect("/")
Beispiel #32
0
 def wrapper(resp):
     next_url = session.get('next') or url_for('main.frontpage')
     session['next'] = None
     if resp is None:
         flash('You denied the request to sign in.')
         return redirect(next_url)
     func(resp)
     flash('You were logged in successfully')
     return redirect(next_url)
Beispiel #33
0
def patient_view_precaution():
    if not session.get("lid") is None:
        data = {}
        fid = request.args['fid']
        q = "SELECT * FROM `files` INNER JOIN `doctors` USING(`doctor_id`) INNER JOIN `precaution` USING(`file_id`) WHERE `file_id`='%s'" % (
            fid)
        data['precaution'] = select(q)
        return render_template("patient_view_precaution.html", data=data)
    else:
        return redirect(url_for("public.login"))
Beispiel #34
0
def listadoPersonas():
    if session.get('conectado') == 'S':
        titulo = "COLFEAR | Listado Personas"
        personas = db.session.query(Personas).all()
        return render_template('listadoPersonas.html',
                               titulo=titulo,
                               personas=personas)
    else:
        flash(u'Debe ingresar sus credenciales para ingresar al sistema',
              'warning')
        return redirect(url_for('index'))
Beispiel #35
0
def registrarPersona():
    if session.get('conectado') == 'S':
        titulo = "COLFEAR | Registrar Personas"
        carreras = db.session.query(Carreras).all()
        return render_template('registrarPersona.html',
                               titulo=titulo,
                               carreras=carreras)
    else:
        flash(u'Debe ingresar sus credenciales para ingresar al sistema',
              'warning')
        return redirect(url_for('index'))
Beispiel #36
0
def hello():
    user_ip = session.get('user_ip')
    login_form = LoginForm()
    username = session.get('username')
    context = {
        'user_ip': user_ip,
        'todos': todos,
        'login_form': login_form,
        'username': username
    }

    if login_form.validate_on_submit():
        username = login_form.username.data
        session['username'] = username

        flash('Nombre de usuario registrado con éxito!')

        return redirect(url_for('index'))

    return render_template('hello.html', **context)
Beispiel #37
0
def patient_add_rating():
    if not session.get("lid") is None:
        if 'submit' in request.form:
            rate = request.form['rate']
            q = "INSERT INTO `rate`(`user_id`,`rated`,`date`) VALUES('%s','%s',curdate())" % (
                session['pid'], rate)
            insert(q)
            flash('success...')

        return render_template("patient_add_rating.html")
    else:
        return redirect(url_for("public.login"))
Beispiel #38
0
def main_page():
    """
    Webserver index page.

    :return: The main page.
    :rtype: flask.Response
    """
    if session.get('logged_in', False):
        user = User.get_by_id(session['user'])
    else:
        user = None
    return render_template('main_page.html', user=user)
def prepare_bitid_challenge(callback_uri):
    # Creates a new nonce associated to this session
    nonce = Nonce(session["sid"])
    nonce.uid = session.get("uid", None)
    # Stores the nonce in database
    nonce_db_service.create_nonce(nonce)
    # Builds the challenge (bitid uri) 
    bitid_uri = bitid.build_uri(callback_uri, nonce.nid)
    # Gets the qrcode uri
    qrcode = bitid.qrcode(bitid_uri)
    # Returns a dictionary storing data related to the challenge
    return {"callback_uri": callback_uri, "bitid_uri": bitid_uri, "qrcode": qrcode}
Beispiel #40
0
def get_client_score():
    data = get_request_data(request)
    client_id = data.get('client_id')
    if client_id is None:
        return jsonify({'message': "client_id required"}), HTTP_400_BAD_REQUEST
    host_id = session.get('host_id')
    if host_id is None:
        return jsonify({'message':
                        "Please login as a staff"}), HTTP_403_FORBIDDEN
    score = Score(host_id, client_id).score
    if score is None:
        return jsonify({'message': "No host with this id"}), HTTP_404_NOT_FOUND
    return jsonify({'code': 0, 'points': score})
Beispiel #41
0
    def __init__(self, signup=False):
        config = Config()
        self.data['config'] = config.data

        if signup is True:
            return

        id = session.get('user_id')
        db = get_db()

        self.data = loads(
            db.execute('SELECT resume_data FROM user WHERE id = ?',
                       (id, )).fetchone()['resume_data'])
def tfa_challenge():
    '''
    Prepares a bitid challenge for 2FA
    '''
    # Checks that user has passed basic authentication
    if not session.get("uid", ""): return redirect(url_for("home")), 401
    # Sets the callback uri
    callback_uri = get_callback_uri("/tfa_callback")
    # Prepares the challenge
    params_tpl = prepare_bitid_challenge(callback_uri)
    # Completes template parameters
    params_tpl["action"] = "tfa_challenge"
    # Renders the bitid challenge page
    return render_template('tfa.html', params_tpl=params_tpl)
def tfa_activation():
    '''
    Prepares a bitid challenge for activation of 2FA
    '''
    # Checks that user is already authenticated
    if not session.get("auth", False): return redirect(url_for("home")), 401  
    # Sets the callback uri
    callback_uri = get_callback_uri("/tfa_activation_callback")
    # Prepares the challenge
    params_tpl = prepare_bitid_challenge(callback_uri)
    # Completes template parameters
    params_tpl["action"] = "tfa_activation"
    # Renders the bitid challenge page
    return render_template('tfa.html', params_tpl=params_tpl)
def tfa_challenge():
    '''
    Prepares a bitid challenge for 2FA
    '''
    # Checks that user has passed basic authentication
    if not session.get("uid", ""): return redirect(url_for("home")), 401
    # Sets the callback uri
    callback_uri = get_callback_uri("/tfa_callback")
    # Prepares the challenge
    params_tpl = prepare_bitid_challenge(callback_uri)
    # Completes template parameters
    params_tpl["action"] = "tfa_challenge"
    # Renders the bitid challenge page
    return render_template('tfa.html', params_tpl=params_tpl)
def user():
    '''
    Prepares rendering of /user page
    '''
    # Checks if user is logged
    if not session.get("auth", False): return redirect(url_for("home")), 401    
    # Gets the user from db
    user = user_db_service.get_user_by_uid(session["uid"])
    if user is None: return redirect(url_for("home")), 401    
    # Gets user's data and add them to dictionary of template parameters
    params_tpl = {"user_login": user.login,
                  "user_signin_count": user.signin_count,
                  "user_tfa": user.tfa_activited(),
                  "user_tfa_address": user.get_tfa_address()}
    # Renders the template
    return render_template("user.html", params_tpl=params_tpl)
def login():
    print(request.method)
    if request.method == 'POST':
        password = request.form['password']
        username = request.form['username']
        if authenticate(str(username), str(password)):
            session['username'] = request.form['username']
            return redirect('/')
        else:
            flash('Invalid username or password. This is NOT a test (or is it)')
            return render_template('login.html')
    elif request.method == 'GET':
        if session.get('username'):
            return redirect('/')
        return render_template('login.html')
    else:
        return redirect('/')
Beispiel #47
0
    def prepare(self,*k,**kk):
        self.context['display_login_box']=True
        self.context['title']=self.title
        self.context['keywords']=self.keywords
        self.context['description']=self.description
        self.context['tracker']=self.tracker
        if session.get('error'):
            self.context['errors']=[session['error']]
            del session['error']
        self.context['page_header']=self.page_header

        self.navigation=[]

        #create navigation panel
        if self.with_navigation:
            self.navigation.append(html.a(app.config.get('BASE_TITLE'),href="/"))

        self.context['navigation']=self.render_navigation
        self.context['with_navigation']=self.with_navigation
def home():
    '''
    Prepares rendering of home page
    '''
    params_tpl = {}
    # Checks if user is already logged
    if session.get("auth", False):
        # Gets the user from db
        user = user_db_service.get_user_by_uid(session["uid"])
        if not user is None: params_tpl["user_login"] = user.login
    else:
        # Initializes a new session id and stores it in the session cookie
        session["sid"]  = str(uuid.uuid4())
        session["uid"] = None
        session["auth"] = False        
    # Renders the home page
    params_tpl["basic_auth_uri"] = url_for("basic_auth")
    params_tpl["signup_uri"] = url_for("signup")
    return render_template('index.html', params_tpl=params_tpl)
Beispiel #49
0
def list_():
    """ 콘텐츠 리스트 페이지
    태그 시스템을 지원한다.
    ex) eduticket.kr/list/?tag=유아&tag=초등&tag=코믹
    """
    #: 태그
    tags = request.args.getlist("tag")
    #: 공연 분류
    content_type = request.args.get("type", None, type=int)
    #: 지역 분류
    location = request.args.get("location", None, type=int)
    #: block 형식으로 볼 것인지
    blockview = request.args.get("blockview", None)
    if blockview == "True":
        session["listpage_blockview"] = True
    elif blockview == "False":
        session["listpage_blockview"] = False

    #: save GET params to use it in blockview toggle button
    params = request.args.to_dict()
    # Delete 'blockview' to prevent url_for taking duplicate parameter
    params.pop("blockview", None)

    query = Content.query
    # Only show contents with status '판매중'
    query = query.filter(Content.status == 2)
    if tags:
        # Filter for contents with given tags
        # Note this is not the most efficient way of doing this.
        # However, for the sake of readability I would like to avoid using SQL wizardaries.
        query = query.join(Content.tags)
        for tag in tags:
            query = query.filter(Content.tags.any(Tag.name == tag))
    if content_type is not None:
        query = query.filter(Content.genre == content_type)
    if location is not None:
        query = query.filter(Content.location == location)
    contents = query.all()

    if session.get("listpage_blockview", False):
        return render_template("main/listblock.html", **locals())
    else:
        return render_template("main/list.html", **locals())
Beispiel #50
0
def verify_token():
    if not change_language():
        token = request.form.get("token", session.get("token"))
        if not token:
            abort(400)

        session["token"] = token
        try:
            current_app.al.create_account_step2(token)
        except (ALserviceTokenError, ALserviceTicketError):
            return render_template(
                "token_was_sent.mako",
                form_action="/verify_token",
                email=session["email"],
                token_error=True,
                language=session["language"],
            )

    return render_template(
        "save_account.mako", form_action="/verify_token", pin_error=False, language=session["language"]
    )
def refresh_missions():
    user_missions = factory.get_mission_dao().get_all_missions_for_user(session.get("logged_user_id"))
    mission_ouput = """
                    <div class="table-responsive">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>Title</th>
                                <th>Date Started</th>
                                <th>Goal</th>
                                <th>Units</th>
                            </tr>
                        </thead>
                    <tbody id="missions">
                    """
    for x in user_missions:
        mission_ouput += (
            """
        <tr> 
            <td>"""
            + x.title
            + """</td>
            <td>"""
            + x.start
            + """</td>
            <td>"""
            + str(x.track_goal)
            + """</td>
            <td>"""
            + str(x.units)
            + """</td>
        </tr>
        """
        )
    mission_ouput += """
                    </tbody>
                </table>
            </div>
                    """
    return mission_ouput
Beispiel #52
0
def csrf_protect():
    if request.method == "POST":
        token = session.get('_csrf_token', None)
        if not token or token != request.form.get('_csrf_token'):
            abort(400)
Beispiel #53
0
 def check_csrf(self,*args,**kwargs):
     if session.get('csrf')==request.form.get('csrf') and request.form.get('csrf'):
         return post_method(self,*args,**kwargs)
     else:
         raise PermissionDeniedException(error="Permission denied")
def negotiation():
    errors = []  
   
    if session.get('nid', None) is None:
        # Generates a new negotiation if needed
        is_new_nego = True
        session['nid'] = str(uuid.uuid4())
        nego = Negotiation(session['nid'], ROLE_BUYER, TESTNET)
        nego_db_service.create_nego(session['nid'], nego)
    else:
        # Gets the negotiation
        is_new_nego = False
        nego = nego_db_service.get_nego_by_id(session['nid'])
            
    '''
    Prepares the BargainingMessage to be sent (if there's one)
    '''
    if is_new_nego:
        # CASE 1: We start a new negotiation
        # Builds a REQUEST message
        new_msg, errors = negotiator.process(nego)
    elif request.method == 'POST':
        # Case 2: We continue an existing negotiation
        # Gets data sent by the user
        container = request.get_json(False, True, False) if request.mimetype == "application/json" else request.form 
        amount    = int(Decimal(container['amount']) * SATOSHIS_TO_BITCOIN)
        memo      = container['memo']
        # Builds a new message (PROPOSAL or CANCEL) 
        # For this demo, we never send fees (test network)
        new_msg, errors = negotiator.process(nego, memo, amount)
    else:
        new_msg = None
        errors.append('Invalid HTTP method')              
    
    '''
    Sends the BargainingMessage
    '''
    if len(errors) == 0:
        # Appends the new message to the chain
        nego.append(new_msg)
        nego_db_service.update_nego(session['nid'], nego)
        # Sends the message
        next_msg_types = nego.get_next_msg_types()
        uri = SELLER_URI if (new_msg.msg_type == TYPE_BARGAIN_REQUEST) else nego.get_bargain_uri_for_role(ROLE_BUYER)
        response = send_msg(new_msg, uri, next_msg_types)
                
        '''
        Processes the response
        '''
        try:
            if response.code == 200:
                if check_req_format(response): 
                    pbuff = response.read()
                    msg = BargainingMessage.deserialize(pbuff)
                    if not nego.already_received(msg):     
                        if msg.check_msg_fmt(NETWORK): 
                            nego.check_consistency(msg)    
                        nego.append(msg)
                        nego_db_service.update_nego(session['nid'], nego)
            else:
                errors.append('Remote node returned an error')
        except:
            errors.append('A problem occurred while processing the message sent by the remote node')
        
    '''
    Prepares rendering 
    '''
    params_tpl = {}
    params_tpl['errors']     = '' if len(errors) == 0 else '\n'.join(errors)
    params_tpl['wallet_blc'] = get_balance([negotiator.addr1])
    params_tpl['chain']      = nego._msgchain
    params_tpl['completed']  = True if nego.status in {NEGO_STATUS_CANCELLED, NEGO_STATUS_COMPLETED} else False
    return render_template('negotiation.html', params_tpl=params_tpl)
Beispiel #55
0
 def is_accessible(self):
     return session.get('admin_authenticated', False) or current_app.config.get('TESTING', False)
def update_user_favcolor():
    current = factory.get_user_info_dao().get_user_info(session.get("logged_user_id"))
    current.favcolor = request.args.get("color")
    factory.get_user_info_dao().update_user_info(current)
    return "Updated"
def update_user_gender():
    current = factory.get_user_info_dao().get_user_info(session.get("logged_user_id"))
    current.gender = request.form["value"]
    factory.get_user_info_dao().update_user_info(current)
    return "Updated"
def logout():
    if session.get("logged_user_id"):
        session.pop("logged_user_id", None)
    return redirect("/")