예제 #1
1
파일: server.py 프로젝트: dbrgn/pcs-matrix
def step2():
    """Step 2: Get categories."""

    # Get arguments via GET
    start_date = escape(request.args['start_date'])
    end_date = escape(request.args['end_date'])
    service_type = escape(request.args['service_type'])

    # Parse dates
    start_date_obj = datetime.strptime(start_date, '%Y-%m-%d').date()
    end_date_obj = datetime.strptime(end_date, '%Y-%m-%d').date()

    # Get all the categories and positions
    plans = get_plans(service_type, from_date=start_date_obj, until_date=end_date_obj)
    categories = defaultdict(set)
    for plan in plans:
        for job in plan['plan_people']:
            categories[job['category_name']].add(job['position'])

    context = {
        'start_date': start_date,
        'end_date': end_date,
        'service_type': service_type,
        'categories': categories,
    }
    return render_template('step2.html', **context)
예제 #2
1
def editinfo():
    if 'username' in session:
        User = user.query.filter_by(Email=session['email']).first_or_404()
        if request.method == 'POST':
            if request.form['username'] != "":
                print request.form['username']
                User.Username = escape(request.form['username'])
            if request.form['school'] != "":
                print request.form['school']
                User.School = escape(request.form['school'])
            if request.form['blog'] != "":
                print request.form['blog']
                User.Blog = escape(request.form['blog'])
            if request.form['intro'] != "":
                print request.form['intro']
                User.Introduction = escape(request.form['intro'])
            if request.form['age'] != "":
                print  request.form['age']
                User.Age = int(request.form['age'])
            db.session.commit()
            return redirect(url_for('info'))
        else:
            return render_template('edit.html', user=User)
    else:
        flash("Please login system first !!")
        return redirect(url_for('login'))
예제 #3
1
파일: control.py 프로젝트: mapia/server
def post():
    if request.method == 'POST':
        print request.json
        
        session_token = escape(session.get('token'))
        username = redis_connections.get(session_token)
        content = request.json['content']
        lat = request.json['lat']
        lng = request.json['lng']
         
        user = User.query.filter_by(username=username).first() 
        db.session.add(user)
        facebook_post = Post(user=user,content=content, lat=lat, lng=lng)
        db.session.add(facebook_post)

        db.session.commit()
        db.session.flush()
        return jsonify({'message':u'upload posting Successfully!'}),200
    else:
        session_token = escape(session.get('token'))
        username = redis_connections.get(session_token)
        posts = Post.query.filter_by(username=username).all()
        post_list = []
        for each_post in posts:
            post_list.append({'id':each_post.id,'username':each_post.username,'content':each_post.content,'lat':each_post.lat,'lng':each_post.lng,'timestamp':each_post.timestamp})
        print post_list
        return jsonify({'posts': post_list})
예제 #4
1
def editItem(cat_name, item_name):
    if 'username' not in login_session:
        return redirect('/catalog/login')
    itemToEdit = getItem(item_name)
    if request.method == 'POST':
        if request.form['item-name']:
            itemToEdit.name = escape(request.form['item-name'])
        if request.form['item-price']:
            itemToEdit.price = escape(request.form['item-price'])
        if request.form['item-thumb']:
            itemToEdit.thumbnail = escape(request.form['item-thumb'])
        else:
            itemToEdit.thumbnail = 'http://placehold.it/320x150'
        if request.form['item-pic']:
            itemToEdit.picture = escape(request.form['item-pic'])
        else:
            itemToEdit.picture = 'http://placehold.it/173x195'
        if request.form['item-cat']:
            itemToEdit.category_id = request.form['item-cat']
        if request.form['item-desc']:
            itemToEdit.description = escape(request.form['item-desc'])
        session.add(itemToEdit)
        session.commit()
        flash('{0} was successfully updated.'.format(itemToEdit.name))
        return redirect(url_for('showCategory',
                        cat_name=itemToEdit.category.name))
    else:
        categories = getCategories()
        return render_template('edititem.html',
                               item=itemToEdit,
                               categories=categories)
예제 #5
1
def register():
    if not current_user.is_anonymous():
        return redirect(url_for('index'))

    form = form_class.RegistrationForm()
    if form.validate_on_submit():
        ki = gpg.import_keys(form.pgp.data)
        if ki.fingerprints == []:
            fingerp = "--- NO VALID PGP ---"
        else:
            fingerp = ki.fingerprints[0]
        user = models.User(email=escape(form.email.data),
                           name=escape(form.name.data),
                           affiliation=escape(form.affiliation.data),
                           pgp=escape(form.pgp.data),
                           password=form.password.data,
                           fingerprint=fingerp)
        models.db.session.add(user)
        models.db.session.commit()
        syslog.syslog(syslog.LOG_NOTICE, "New user registered: " + form.email.data)
        token = user.generate_confirmation_token()
        send_email(user.email,
                   'CVE-PORTAL -- Account Confirmation',
                   '/emails/confirm',
                   user=user,
                   token=token)
        flash('A confirmation email has been sent to you by email.', 'info')
        return redirect('/login')
    else:
        if form.email.data is not None:
            pass
            #syslog.syslog(syslog.LOG_ERR, "Registering Failed: Email: " + form.email.data + " Name: " + form.name.data + " Affiliation: " + form.affiliation.data)

    return render_template("auth/register.html", form=form)
예제 #6
0
def escape_post(post):
    post['username'] = escape(post['username'])
    post['title'] = escape(post['title'])
    post['tag'] = escape(post['tag'])
    post['content'] = escape(post['content'])

    return post
예제 #7
0
def show_human_help(prefix):
    '''
    Dump table showing commands matching prefix
    '''
    # XXX There ought to be a better discovery mechanism than an HTML table
    s = '<html><body><table border=1><th>Possible commands:</th><th>Method</th><th>Description</th>'

    permmap = {'r': 'GET', 'rw': 'PUT', 'rx': 'GET', 'rwx': 'PUT'}
    line = ''
    for cmdsig in sorted(app.ceph_sigdict.itervalues(), cmp=descsort):
        concise = concise_sig(cmdsig['sig'])
        flavor = cmdsig.get('flavor', 'mon')
        if flavor == 'tell':
            concise = 'tell/<target>/' + concise
        if concise.startswith(prefix):
            line = ['<tr><td>']
            wrapped_sig = textwrap.wrap(
                concise_sig_for_uri(cmdsig['sig'], flavor), 40
            )
            for sigline in wrapped_sig:
                line.append(flask.escape(sigline) + '\n')
            line.append('</td><td>')
            line.append(permmap[cmdsig['perm']])
            line.append('</td><td>')
            line.append(flask.escape(cmdsig['help']))
            line.append('</td></tr>\n')
            s += ''.join(line)

    s += '</table></body></html>'
    if line:
        return s
    else:
        return ''
예제 #8
0
def login():
    expected_key_list = ['username',
                         'password']

    credentials = request.get_json(force=True)

    if sorted(expected_key_list) != sorted(credentials.keys()):
        abort(400, 'Invalid request.')

    if ('username' in session) and (session['username'] == credentials['username']):
        abort(409, 'Already logged in.')

    user = validate(credentials['username'], credentials['password'])

    if user is None:
        abort(401, 'Login failed')

    user.roles()  # Load roles
    session['username'] = escape(credentials['username'])
    session['password'] = escape(credentials['password'])
    session['user_id'] = user.id
    session['roles'] = user.roles.to_dict()  # session['roles'][0]['name']

    session.permanent = False  # the session will be deleted when the user closes the browser.

    # data = {"username": str(escape(session['username'])), "user_id": user.id,
    # "password": str(escape(session['password']))}



    return jsonify(Profile=user.to_dict())
예제 #9
0
    def test_configure(self, mock_getCircles, mock_HipchatApiHandler, mock_getInstallationFromJWT):
        mock_installation = self.defaultInstallation(set_glassfrogToken=False)
        assert mock_installation.glassfrogToken is None
        mock_getInstallationFromJWT.return_value = mock_installation

        # Loading of page
        rv = self.app.get('/configure.html', follow_redirects=True,
                          query_string=test_values.mock_jwt_data('bogus'))
        assert b'Glassfrog Token' in rv.data

        # Wrong token
        mock_getCircles.return_value = [401, test_values.mock_401_responsebody['message']]
        rv = self.app.post('/configure.html', follow_redirects=True,
                           data=dict(glassfrogtoken=test_values.mock_glassfrogToken),
                           query_string=test_values.mock_jwt_data('bogus'))
        assert mock_getCircles.called
        assert escape(test_values.mock_401_flash_message) in rv.data.decode('utf-8')

        # Right token
        mock_getCircles.return_value = (200, test_values.mock_circles_message)
        rv = self.app.post('/configure.html', follow_redirects=True,
                           data=dict(glassfrogtoken=test_values.mock_glassfrogToken),
                           query_string=test_values.mock_jwt_data('bogus'))
        assert mock_getCircles.called
        assert escape(strings.configured_successfully_flash) in rv.data.decode('utf-8')
        mock_HipchatApiHandler.return_value.sendMessage.assert_called_with(
            color=strings.succes_color,
            message=strings.configured_successfully,
            installation=mock_installation)
예제 #10
0
파일: __init__.py 프로젝트: yhu04/CSV2IATI
def login():
    if request.method == 'POST':
        username = escape(request.form['username'])
        password = escape(request.form['password'])
        
        if ((username == APP_ADMIN_USERNAME) and (username != "YOUR_ADMIN_USERNAME_HERE (MAKE THIS REALLY SECRET)") and (password == APP_ADMIN_PASSWORD)):
            session['username'] = escape(request.form['username'])
            session['user_id'] = '0'
            session['user_name'] = 'Master admin user'
            session['admin'] = '1'
            flash('Hello, admin user.', 'good')
            return redirect(url_for('index'))     
        
        u = User(username,password)
        getuser = User.query.filter_by(username=username).first()
        #u = User.query.filter_by(username=username, password=User.check_password(password)).first()
        
        ## found a user
        if ((getuser) and (getuser.check_password(password))):
            session['username'] = escape(request.form['username'])
            session['user_id'] = getuser.id
            session['user_name'] = getuser.user_name
            if (getuser.admin == 1):
                session['admin'] = getuser.admin
            flash('Welcome back.', 'good')
        elif (getuser):
            flash("That password is incorrect for that user. Please try again.", 'bad')
        else:
            flash("Could not find that user. Please try again.", 'bad')
        return redirect(url_for('index'))
    flash("Please log in.", 'bad')
    return redirect(url_for('index'))
예제 #11
0
파일: __init__.py 프로젝트: yhu04/CSV2IATI
def register():
    # Create database if it doesn't already exist
    db.create_all()
    username = escape(request.form['username'])
    password = escape(request.form['password'])
    user_name = escape(request.form['user_name'])
    email_address = escape(request.form['email'])
    admin = '0'
    user_check = User.query.filter_by(username=username).first()
    if user_check:
        flash("Sorry, that username has already been taken. Please choose another one.", 'bad')
        return redirect(url_for('index'))
    elif (username and password):
        u = User(username,password,user_name=user_name,email_address=email_address,admin=admin)
        db.session.add(u)
        db.session.commit()
        
        session['username'] = u.username
        session['user_id'] = u.id
        session['user_name'] = u.user_name
        flash("Your account has been created.", 'good')
        return redirect(url_for('index'))
    else:
        flash("Please supply a username and password to create your account.", 'bad')
        return redirect(url_for('index'))
예제 #12
0
def index():

    random = False
    unsafe = False
    animated = False
    base = "http://%s/"%request.environ['HTTP_HOST']
    curr = base
    animchecked = ""
    unsfchecked = ""
    randchecked = ""
    if request.args.get('a') is not None:
        animated = True
        animchecked = "checked"
    if request.args.get('u') is not None:
        unsafe = True
        unsfchecked = "checked"
    if request.args.get('r') is not None:
        random = True
        randchecked = "checked"

    redirect_to_url = False
    if request.args.get('adj') and request.args.get('noun'):
        adj = escape(request.args.get('adj'))
        noun = escape(request.args.get('noun'))
        if request.args.get('imgurl'):
            imgurl = escape(request.args.get('imgurl'))
            imgenc = b64encode(imgurl)
        elif request.args.get('imgenc'):
            imgenc = request.args.get('imgenc')
            imgurl = escape(b64decode(imgenc))
        redirect_to_url = True
    else:
        adj,alt_adj,noun,alt_noun = generate.random_phrase_2()
        imgroot = '%s %s'%(adj,noun)
        if random:
            imgroot = '%s %s'%(alt_adj,alt_noun)
        imgurl = find_image(imgroot, animated, unsafe)
        imgenc = b64encode(imgurl)

    current_context = {'adj': adj, 'noun': noun, 'img': imgurl}
    hashed_context = protect_context(current_context)
    url_context = {'hash': hashed_context}
    url_context.update(current_context)

    root = '%s %s'%(adj,noun)
    info_data = b64encode(json.dumps(url_context))
    thisview = "{0}://{1}/{2}".format(
        request.environ['wsgi.url_scheme'],
        request.environ['HTTP_HOST'],
        info_data
    )

    if redirect_to_url:
        return redirect('/{0}'.format(info_data))

    quote=urllib2.quote(colon_to_pct(thisview))

    return render_template('index.html.tpl', text=root, img=imgurl,
        permalink=thisview, current_url=curr, baseurl=base, quotelink=quote,
        animchecked=animchecked, unsfchecked=unsfchecked, randchecked=randchecked)
예제 #13
0
파일: b.py 프로젝트: flipchan/blogger
def user():
    if not flask.session:
	return flask.redirect(flask.url_for('login'))

    if flask.request.method == 'POST':
	blogpost = flask.request.form['blogpost']
	he = blogpost.replace('<', '_') #protect from <scripts>
	blogpost = he
	title = flask.request.form['Title'] 
	nick = flask.escape(flask.session['nick'])
	cur = db.cursor()
	emnick = flask.escape(flask.session['nick'])
	today = datetime.date.today()
	cur.execute('insert into blogs (texten, title, vem, at_time) values (%s, %s, %s, %s)', (blogpost, title, nick, today))
	db.commit()
	cuu = db.cursor()

	t = 'blog post added! check it at /blogg/'
	cuu.execute('select blogg_id from blogs where title=%s', (title,))
	ll = cuu.fetchone()
	AA = str(t) + str(ll[0])
	link = AA
	return flask.render_template('user.html', error=link)  

    
    ff = db.cursor()
    emnick = flask.escape(flask.session['nick'])
    ff.execute('select texten, title from blogs where vem=%s', (emnick,))
    entries = [dict(text=row[0], title=row[1]) for row in ff.fetchall()]
    return flask.render_template('user.html', emnick=emnick, entries=entries)
예제 #14
0
def show_human_help(prefix):
    """
    Dump table showing commands matching prefix
    """
    # XXX There ought to be a better discovery mechanism than an HTML table
    s = "<html><body><table border=1><th>Possible commands:</th><th>Method</th><th>Description</th>"

    permmap = {"r": "GET", "rw": "PUT"}
    line = ""
    for cmdsig in sorted(app.ceph_sigdict.itervalues(), cmp=descsort):
        concise = concise_sig(cmdsig["sig"])
        flavor = cmdsig.get("flavor", "mon")
        if flavor == "tell":
            concise = "tell/<target>/" + concise
        if concise.startswith(prefix):
            line = ["<tr><td>"]
            wrapped_sig = textwrap.wrap(concise_sig_for_uri(cmdsig["sig"], flavor), 40)
            for sigline in wrapped_sig:
                line.append(flask.escape(sigline) + "\n")
            line.append("</td><td>")
            line.append(permmap[cmdsig["perm"]])
            line.append("</td><td>")
            line.append(flask.escape(cmdsig["help"]))
            line.append("</td></tr>\n")
            s += "".join(line)

    s += "</table></body></html>"
    if line:
        return s
    else:
        return ""
예제 #15
0
def register_user():
    if current_user.is_authenticated():
        flash(
            'You are already logged in as %s' % (escape(current_user.username))
        )
        return redirect(url_for('ui.index'))

    form = RegistrationForm()

    if form.validate_on_submit():
        try:
            username = form.username.data
            password = form.password.data
            email = form.email.data.strip()

            if len(email) == 0:
                email = None

            create_user(username, password, email)
            login(username, password)

            flash('Registration successful, welcome %s!' % (username),
                  category='info')
            return redirect(url_for('ui.index'))
        except ValidationError, ve:
            invalids = ','.join([f.title() for f in ve.errors.keys()])
            msg = 'Invalid: %s' % (invalids)
            flash(escape(msg), category='error')
        except ValueError, ve:
            flash(escape(ve.message), category='error')
def show():
    name = request.args.get('name').replace(' ','_')
    age = None
    favoritestyle = None
    gender = None
    try:
        if escape(session['logged_in']): 
            last_name = request.args.get('last_name').replace(' ','_')
            age = str(escape(session['age']))
            favoritestyle = str(escape(session['favoritestyle']))
            gender = str(escape(session['gender']))
            one_click = Clicks(last_name,name,age,favoritestyle,gender)
            db.session.add(one_click)
            db.session.commit()
        else:
            pass
    except:
        pass
    data = com.getJSONData(name)
    related_data = []
    commentlist = []
    comments = Comments.query.filter_by(furniture_name = name).all()
    for comment in comments:
        commentlist.append(comment.comment)
    related_list = mth.match_furniture(name,age,favoritestyle,gender)
    for related in related_list:
        related_data.append(com.readJSON(related))
    return render_template('show.html', commentlist = commentlist, name = name.replace('_',' '), img_url = data['img_url'][0], description = data['description'], price = data['price'], related_data = related_data)
예제 #17
0
파일: main.py 프로젝트: dann815/boxflaskjwt
def load_auth_object_into_current_pageload_context():
    if "/static/" in request.path:
        return

    if "token_id" in session:
        print str(session)
        print "ACCESS TOKEN FOUND: {0}".format(escape(session['token_id']))
        auth = JWTAuth(client_id=app.config['CLIENT_ID'],
            client_secret=app.config['CLIENT_SECRET'],
            enterprise_id=app.config['EID'],
            jwt_key_id=app.config['KEY_ID'],
            rsa_private_key_file_sys_path=os.path.join(os.path.dirname(__file__),'rsakey.pem'),
            store_tokens=store_tokens,
            access_token=escape(session['token_id'])) # <-- This is the difference.  Uses the old token.
    else:
        print "CLIENT_ID: {0}".format(app.config['CLIENT_ID'])
        print "CLIENT_SECRET: {0}".format(app.config['CLIENT_SECRET'])
        print "EID: {0}".format(app.config['EID'])
        print "KEY_ID: {0}".format(app.config['KEY_ID'])
        print str(store_tokens)

        auth = JWTAuth(client_id=app.config['CLIENT_ID'],
            client_secret=app.config['CLIENT_SECRET'],
            enterprise_id=app.config['EID'],
            jwt_key_id=app.config['KEY_ID'],
            rsa_private_key_file_sys_path=os.path.join(os.path.dirname(__file__),'rsakey.pem'),
            store_tokens=store_tokens)
    g.auth = auth
예제 #18
0
def reg():
  session['hour'] = request.form['hour']
  session['minute'] = request.form['minute']
  session['radial'] = request.form['radial']
  session['camp'] = escape(request.form['camp'])
  session['emac'] = request.form['mac']
  session['radio'] = request.form['radio']
  session['contact'] = escape(request.form['contact'])
  session['email'] = escape(request.form['email'])
  session['quad'] = get_quad(session['hour'], session['minute'])
  p_insert = "insert into participants\
              (hour, minute, radial, quad, mac, camp, contact, email, created_at) \
              values ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', now())" % \
              (session['hour'], session['minute'], session['radial'], session['quad'], session['emac'], session['camp'], session['contact'], session['email'])
  p_id_val = "select id from participants where mac = '%s'" % session['emac']
  app.logger.debug(p_insert)
  db = get_db()
  cursor = db.cursor()
  try:
    try: 
      cursor.execute(p_insert)
      db.commit()
      cursor.execute(p_id_val)
      session['p_id'] = int(cursor.fetchone()[0])
    except:
      cursor.execute(p_id_val)
      session['p_id'] = int(cursor.fetchone()[0])
  except MySQLdb.Error as myerr:
    app.logger.debug('mysql error: %s' % myerr)
    flash('There was an error: %s' % myerr, 'error')
  except Exception, e:
    flash('Error processing request: %s' % e, 'error')
예제 #19
0
def profile():
    username = escape(session['username'])
    #POST METHOD MEANS UPDATING PASSWORD
    if request.method == 'POST':
        if 'searched' in request.form:
            if request.form['searched']!= "":
                return redirect(url_for("recipeList", tag = request.form['searched']))
        else:
            real_pwd = MongoWork.find_pword(username)
            currpwd = request.form.get("curpas")
            if currpwd != real_pwd:
                flash("Sorry! Please enter the correct current password!")
                return redirect(url_for("profile"))
            newpwdinput = request.form.get("newpas")
            newrepwdinput = request.form.get("newrepas")
            if newpwdinput == newrepwdinput and check_pword(newpwdinput): #matched successfully, update passwords
                username = escape(session['username'])
                MongoWork.update_password(username,newpwdinput)
                flash("Password was successfully updated.")
                return redirect(url_for("profile"))
            elif not check_pword(newpwdinput):
                flash("Your password must be at least SIX characters long and have an uppercase letter, lowercase letter, and a number!")
                return redirect(url_for("profile"))
            else:
                flash("Passwords did not match. Password was not updated.")
                return redirect(url_for("profile"))
    else: #GET METHOD
        user_info = MongoWork.find_usrinfo(username)
        fname = user_info['firstname']
        lname = user_info['lastname']
        u = user_info['uname']
        return render_template("profile.html",fname=fname, lname=lname,u=u); 
예제 #20
0
파일: hello.py 프로젝트: bramses/URStudying
def edit_me():
	if 'username' in session:
		u = User.query.filter_by(fullname = escape(session['username']) ).first()	
		if u:
			posts = u.posts.filter(Post.end > datetime.now())
			return render_template("edit.html", posts = posts, user_name = escape(session['username']))
	return render_template("no_session.html")
예제 #21
0
파일: ceph_rest_api.py 프로젝트: eliq/ceph
def show_human_help(prefix):
    """
    Dump table showing commands matching prefix
    """
    # XXX this really needs to be a template
    #s = '<html><body><style>.colhalf { width: 50%;} body{word-wrap:break-word;}</style>'
    #s += '<table border=1><col class=colhalf /><col class=colhalf />'
    #s += '<th>Possible commands:</th>'
    # XXX the above mucking with css doesn't cause sensible columns.
    s = '<html><body><table border=1><th>Possible commands:</th><th>Method</th><th>Description</th>'

    possible = []
    permmap = {'r':'GET', 'rw':'PUT'}
    line = ''
    for cmdsig in sorted(glob.sigdict.itervalues(), cmp=descsort):
        concise = concise_sig(cmdsig['sig'])
        if concise.startswith(prefix):
            line = ['<tr><td>']
            wrapped_sig = textwrap.wrap(concise_sig_for_uri(cmdsig['sig']), 40)
            for sigline in wrapped_sig:
                line.append(flask.escape(sigline) + '\n')
            line.append('</td><td>')
            line.append(permmap[cmdsig['perm']])
            line.append('</td><td>')
            line.append(flask.escape(cmdsig['help']))
            line.append('</td></tr>\n')
            s += ''.join(line)

    s += '</table></body></html>'
    if line:
        return s
    else:
        return ''
예제 #22
0
def employerChangeDescription(iid):
    if escape(session['type']) == 'employer':
        cid = adb.get_cid(escape(session['uname']))

        if adb.check_ci_ids(cid, iid):
            if request.method == 'GET':
                if os.path.isfile(os.path.join(app.config['UPLOAD_FOLDER'],
                                                  "desc{}.txt".format(iid))):
                    txtfile = open(os.path.join(app.config['UPLOAD_FOLDER'],
                                              "desc{}.txt".format(iid)))

                    return render_template('employereditdescription.html',
                                           txt=txtfile.read())
                else:
                    return render_template('employeradddescription.html')


            if request.method == 'POST':
                #use the logged in uname(email) and position name
                #to create position in db module
                txtfile = request.files['txt_file']
                if txtfile and allowed_text(txtfile.filename):
                    fname = "desc{}.{}".format(iid, 'txt')
                    txtfile.save(os.path.join(app.config['UPLOAD_FOLDER'],
                                              fname))
                    flash("Successfully added your description!")
                    return redirect('/Employer/ViewInternships')

                else:
                    flash("Could not add your description.")
                    return redirect('/Employer/ViewInternships')

    return redirect('/Employer')
예제 #23
0
def studentResume():
    if escape(session['type']) == 'student':
        if request.method == 'GET':
            sid = adb.get_sid(escape(session['uname']))
            if get_txtfile(sid):
                #txtfile = open(get_txtfile(sid))
                return render_template('studenteditresume.html', sid=sid, ext=get_txtext(get_txtfile(sid)))
            else:
                return render_template('studentaddresume.html')


        if request.method == 'POST':
            #use the logged in uname(email) and position name
            #to create position in db module
            sid = adb.get_sid(escape(session['uname']))
            txtfile = request.files['txt_file']
            if txtfile and allowed_text(txtfile.filename):
                fname = "resume{}.{}".format(sid, get_txtext(txtfile.filename))
                txtfile.save(os.path.join(app.config['UPLOAD_FOLDER'],
                                          fname))
                flash("Successfully added your resume!")
                return redirect('/Student/Home')

            else:
                flash("Could not add your resume")
                return redirect('/Student/Home')

    return redirect('/Student')
예제 #24
0
def delete(m_id):
    if request.method == "POST":
        if 'delete' in request.form:
            try:
                data.execute("DELETE FROM Mentorteams WHERE m_id = ?", m_id)
            except:
                flash("Could not delete team, there are people/items associated with it")
                return redirect(url_for('mentorteams.mentorteam', m_id=m_id))
            return redirect(url_for('mentorteams.overview'))
        else:
            flash(escape("Nothing deleted"))
            return redirect(url_for('mentorteams.mentorteam', m_id=m_id))

    else:
        teams = data.execute("SELECT * FROM Mentorteams WHERE m_id = ?", m_id)
        if len(teams) != 1:
            flash(escape("Det hold findes ikke"))
            return redirect(url_for("mentorteams.overview"))
        team = teams[0]

        w = html.WebBuilder()
        w.form()
        w.formtable()
        w.html("Vil du slette holdet?")
        w.html('<button type="submit" name="delete" value="delete">Slet</button>', "Slet mentorhold?")
        form = w.create()
        return render_template("form.html", form=form)
예제 #25
0
파일: session.py 프로젝트: mrmonday/panel2
def create():
    if request.method == 'POST':
        redir_target = request.form.get('outmodule', 'index')

        try:
            username = request.form['username'].strip().rstrip()
            password = request.form['password'].strip().rstrip()
            email = request.form['email'].strip().rstrip()
            if len(username) == 0:
                return render_template_or_json('create.html', error='No username provided')
            if escape(username) != username or ' ' in username:
                return render_template_or_json('create.html', error='Username contains invalid characters')
            if len(password) == 0:
                return render_template_or_json('create.html', error='No password provided') 
            if len(email) == 0:
                return render_template_or_json('create.html', error='No email provided') 
            if escape(email) != email or '@' not in email:
                return render_template_or_json('create.html', error='E-mail address is malformed')
            user = User(username, password, email)
        except:
            return render_template_or_json('create.html', error='Username is already taken')
            
        if user is not None:
            sess = Session(user)
            session['session_id'] = sess.id
            session['session_challenge'] = sess.challenge
            return redirect(url_for(redir_target))

    return render_template_or_json('create.html')
예제 #26
0
파일: views.py 프로젝트: zackdever/location
def login():
    """Show the login page, and log in the user."""

    # try to log the user in
    if request.method == "POST":
        if "username" not in request.form or "password" not in request.form:
            flash("Please provide both your username and password", "error")
        else:
            username = escape(request.form["username"])
            password = escape(request.form["password"])
            user = current_app.db.users.find_one({"username": username})

            if user and bcrypt.hashpw(password, user["password"]) == user["password"]:
                login_user(User(username, user["_id"]))
                return redirect(request.args.get("next") or url_for("ui.index"))
            else:
                flash("That username and/or password is incorrect.", "error")

    # if the user is already authenticated, go to the index page
    if current_user.is_authenticated():
        return redirect(url_for("ui.index"))

    # if they were redirected here, bring them back once they're logged in
    next = request.args.get("next")
    action_args = "?next=%s" % next if next is not None else ""

    return render_template("login.html", action_args=action_args)
예제 #27
0
파일: login.py 프로젝트: lifeeth/lastuser
def confirm_email(md5sum, secret):
    emailclaim = UserEmailClaim.query.filter_by(md5sum=md5sum).first()
    if emailclaim is not None:
        # Claim exists
        if emailclaim.verification_code == secret:
            # Verification code matches
            if g.user is None or g.user == emailclaim.user:
                # Not logged in as someone else
                # Claim verified!
                useremail = emailclaim.user.add_email(emailclaim.email, primary=emailclaim.user.email is None)
                db.session.delete(emailclaim)
                db.session.commit()
                return render_message(
                    title="Email address verified",
                    message=Markup(
                        "Hello %s! Your email address <code>%s</code> has now been verified."
                        % (escape(emailclaim.user.fullname), escape(useremail.email))
                    ),
                )
            else:
                # Logged in as someone else. Abort
                abort(403)
        else:
            # Verification code doesn't match
            abort(403)
    else:
        # No such email claim
        abort(404)
예제 #28
0
def employerEditLogo():
    if escape(session['type']) == 'employer':
        if request.method == 'GET':
            cid = adb.get_cid(escape(session['uname']))
            if os.path.isfile(os.path.join(app.config['UPLOAD_FOLDER'],
                                              "logo{}.jpg".format(cid))):
                return render_template('employereditlogo.html',
                                       imgpath=app.config['UPLOAD_FOLDER'] +
                                            "logo{}.jpg".format(cid), cid=cid)
            else:
                return render_template('employeraddlogo.html', cid=cid)


        if request.method == 'POST':
            #use the logged in uname(email) and position name
            #to create position in db module
            cid = adb.get_cid(escape(session['uname']))
            imgfile = request.files['img_file']
            if imgfile and allowed_image(imgfile.filename):
                fname = "logo{}.{}".format(cid, 'jpg')
                imgfile.save(os.path.join(app.config['UPLOAD_FOLDER'],
                                          fname))
                flash("Successfully added your logo!")
                return redirect('/Employer/Home')

            else:
                flash("Could not add image file")
                return redirect('/Employer/Home')

    return 'employer'
예제 #29
0
def delete(t_id):
    if request.method == "POST":
        if 'delete' in request.form:
            try:
                data.execute("DELETE FROM Tours WHERE t_id = ?", t_id)
            except:
                flash("Could not delete tour, there are people/items associated with it")
                return redirect(url_for('rustours.rustour', t_id=t_id))
            return redirect(url_for('rustours.overview'))
        else:
            flash(escape("Nothing deleted"))
            return redirect(url_for('rustours.rustour', t_id=t_id))

    else:
        tours = data.execute("SELECT * FROM Tours WHERE t_id = ?", t_id)
        if len(tours) != 1:
            flash(escape("Den tur findes ikke"))
            return redirect(url_for("rustours.overview"))
        tour = tours[0]

        w = html.WebBuilder()
        w.form()
        w.formtable()
        w.html("Vil du slette rusturen?")
        w.html('<button type="submit" name="delete" value="delete">Slet rustur</button>', "Slet rustur?")
        form = w.create()
        return render_template("form.html", form=form)
예제 #30
0
def reset_email(user, kwargs):
    resetreq = PasswordResetRequest.query.filter_by(user=user, reset_code=kwargs['secret']).first()
    if not resetreq:
        return render_message(title=_("Invalid reset link"),
            message=_(u"The reset link you clicked on is invalid"))
    if resetreq.created_at < datetime.utcnow() - timedelta(days=1):
        # Reset code has expired (> 24 hours). Delete it
        db.session.delete(resetreq)
        db.session.commit()
        return render_message(title=_("Expired reset link"),
            message=_(u"The reset link you clicked on has expired"))

    # Logout *after* validating the reset request to prevent DoS attacks on the user
    logout_internal()
    db.session.commit()
    # Reset code is valid. Now ask user to choose a new password
    form = PasswordResetForm()
    form.edit_user = user
    if form.validate_on_submit():
        user.password = form.password.data
        db.session.delete(resetreq)
        db.session.commit()
        return render_message(title=_("Password reset complete"), message=Markup(
            _(u"Your password has been reset. You may now <a href=\"{loginurl}\">login</a> with your new password.").format(
                loginurl=escape(url_for('.login')))))
    return render_form(form=form, title=_("Reset password"), formid='reset', submit=_("Reset password"),
        message=Markup(_(u"Hello, <strong>{fullname}</strong>. You may now choose a new password.").format(
            fullname=escape(user.fullname))),
        ajax=False)
예제 #31
0
def sma(symbol):
    ti = TechIndicators(key=config.alpha_vantage_key)
    data = ti.get_sma(symbol=symbol, time_period=50)

    return 'SMA50 2019-12-24: {}'.format(escape(data[0]['2019-12-24']['SMA']))
예제 #32
0
                def inner(start_index=1, max_result=50, total=0):
                    """Retireves youtube playlist videos recursively

                    :param start_index: Index to start for fetching videos in playlist
                    :param max_result: Maximum results to return
                    :param total: variable to keep track of total videos fetched
                    """
                    r = requests.get(
                        'http://gdata.youtube.com/feeds/api/playlists/%s?v=2&alt=json&max-result=50&start-index=%d'
                        % (playlist_id, start_index))
                    if r.json is None:
                        raise DataProcessingError(
                            "Unable to fetch data, please check the youtube url"
                        )
                    else:
                        # fetch playlist info
                        playlist.title = r.json['feed']['title']['$t']
                        if 'media$description' in r.json['feed'][
                                'media$group']:
                            playlist.description = escape(
                                r.json['feed']['media$group']
                                ['media$description']['$t'])
                        for item in r.json['feed'].get('entry', []):
                            # If the video is private still youtube provides the title but doesn't
                            # provide thumbnail & urls, check for private video
                            is_private = item.get('app$control')
                            if is_private is not None and is_private[
                                    'yt$state']['reasonCode']:
                                continue
                            video = Video(playlist=playlist)
                            video.title = item['title']['$t']
                            video.video_url = item['media$group'][
                                'media$player']['url']
                            if 'media$description' in item['media$group']:
                                video.description = escape(
                                    item['media$group']['media$description']
                                    ['$t'])
                            for video_content in item['media$group'][
                                    'media$thumbnail']:
                                if video_content['yt$name'] == 'mqdefault':
                                    thumbnail_url_request = requests.get(
                                        video_content['url'])
                                    filestorage = return_werkzeug_filestorage(
                                        thumbnail_url_request,
                                        filename=secure_filename(
                                            item['title']['$t']))
                                    video.thumbnail_path = thumbnails.save(
                                        filestorage)
                            video.video_sourceid = item['media$group'][
                                'yt$videoid']['$t']
                            video.video_source = u"youtube"
                            video.make_name()
                            playlist.videos.append(video)
                        #When no more data is present to retrieve in playlist 'feed' is absent in json
                        if 'entry' in r.json['feed']:
                            total += len(r.json['feed']['entry'])
                            if total <= r.json['feed'][
                                    'openSearch$totalResults']:
                                # check for empty playlist
                                if not r.json['feed'].get('entry', []):
                                    raise DataProcessingError("Empty Playlist")
                                inner(start_index=total + 1, total=total)
예제 #33
0
def nl2br_filters(s):
    return escape(s).replace('\n', Markup('</br>'))
예제 #34
0
def show_user_profile(username):
    return '{}\'s profile'.format(escape(username))
예제 #35
0
 def datasource_link(self):
     url = "/superset/explore/{obj.type}/{obj.id}/".format(obj=self)
     name = escape(self.datasource_name)
     return Markup('<a href="{url}">{name}</a>'.format(**locals()))
예제 #36
0
 def link(self):
     name = escape(self.datasource_name)
     return Markup('<a href="{self.url}">{name}</a>').format(**locals())
예제 #37
0
 def link(self) -> Markup:
     name = escape(self.name)
     anchor = f'<a target="_blank" href="{self.explore_url}">{name}</a>'
     return Markup(anchor)
예제 #38
0
파일: util.py 프로젝트: cz0930/funtyping
def get_user_id():
    if 'user_id' in session:
        return escape(session['user_id'])
    return 0
예제 #39
0
def cookie_setter():
    response = flask.make_response(flask.redirect('/'))
    response.set_cookie('name', escape(flask.request.args.get('name')))
    return response
예제 #40
0
def process_playlist(playlist, playlist_url):
    """
    Get metadata for the playlist from the corresponding site
    """
    # Parse the playlist url
    if playlist_url:
        parsed = urlparse(escape(playlist_url))
        # Check video source and get corresponding data
        if parsed.netloc in ['youtube.com', 'www.youtube.com']:
            try:
                # first two character of playlist id says what type of playlist, ignore them
                playlist_id = parse_qs(parsed.query)['list'][0][2:]

                def inner(start_index=1, max_result=50, total=0):
                    """Retireves youtube playlist videos recursively

                    :param start_index: Index to start for fetching videos in playlist
                    :param max_result: Maximum results to return
                    :param total: variable to keep track of total videos fetched
                    """
                    r = requests.get(
                        'http://gdata.youtube.com/feeds/api/playlists/%s?v=2&alt=json&max-result=50&start-index=%d'
                        % (playlist_id, start_index))
                    if r.json is None:
                        raise DataProcessingError(
                            "Unable to fetch data, please check the youtube url"
                        )
                    else:
                        # fetch playlist info
                        playlist.title = r.json['feed']['title']['$t']
                        if 'media$description' in r.json['feed'][
                                'media$group']:
                            playlist.description = escape(
                                r.json['feed']['media$group']
                                ['media$description']['$t'])
                        for item in r.json['feed'].get('entry', []):
                            # If the video is private still youtube provides the title but doesn't
                            # provide thumbnail & urls, check for private video
                            is_private = item.get('app$control')
                            if is_private is not None and is_private[
                                    'yt$state']['reasonCode']:
                                continue
                            video = Video(playlist=playlist)
                            video.title = item['title']['$t']
                            video.video_url = item['media$group'][
                                'media$player']['url']
                            if 'media$description' in item['media$group']:
                                video.description = escape(
                                    item['media$group']['media$description']
                                    ['$t'])
                            for video_content in item['media$group'][
                                    'media$thumbnail']:
                                if video_content['yt$name'] == 'mqdefault':
                                    thumbnail_url_request = requests.get(
                                        video_content['url'])
                                    filestorage = return_werkzeug_filestorage(
                                        thumbnail_url_request,
                                        filename=secure_filename(
                                            item['title']['$t']))
                                    video.thumbnail_path = thumbnails.save(
                                        filestorage)
                            video.video_sourceid = item['media$group'][
                                'yt$videoid']['$t']
                            video.video_source = u"youtube"
                            video.make_name()
                            playlist.videos.append(video)
                        #When no more data is present to retrieve in playlist 'feed' is absent in json
                        if 'entry' in r.json['feed']:
                            total += len(r.json['feed']['entry'])
                            if total <= r.json['feed'][
                                    'openSearch$totalResults']:
                                # check for empty playlist
                                if not r.json['feed'].get('entry', []):
                                    raise DataProcessingError("Empty Playlist")
                                inner(start_index=total + 1, total=total)

                inner()
            except requests.ConnectionError:
                raise DataProcessingError("Unable to establish connection")
            except gaierror:
                raise DataProcessingError("Unable to resolve the hostname")
            except KeyError:
                raise
                raise DataProcessingError(
                    "Supplied youtube URL doesn't contain video information")
        else:
            raise ValueError("Unsupported video site")
    else:
        raise ValueError("Video URL is missing")
예제 #41
0
 def hello():
     message = request.args.get("msg", "Hello World")
     bot.send_message(message)
     return 'Sent: {0}!'.format(escape(message))
예제 #42
0
 def link(self):
     name = escape(self.name)
     return Markup(
         '<a href="{self.explore_url}">{name}</a>'.format(**locals()))
예제 #43
0
def index():
    if 'username' in session:
        return 'Logged in as %s' % escape(session['username'])
    return 'You are not logged in'
예제 #44
0
def index():
    if 'user' in session:
        return 'Hey, {}!'.format(escape(session['user']))
    return 'You are not signed in!'
예제 #45
0
def admin(user=None):
    if session['usertype'] != 'ADM':
        flash('Unauthorized access')
        return redirect(url_for('logout'))
    return render_template('admin.html', user=escape(session['user']))
예제 #46
0
파일: app.py 프로젝트: floodta/kempExercise
def index():
    if 'username' in session:
        username_session = escape(session['username']).capitalize()
        return redirect(url_for('menu'))
    return redirect(url_for('login'))
예제 #47
0
def viewPayables(user=None):
    if session['usertype'] == 'PyO' or session['usertype'] == 'ADM':
        return render_template('payables.html', user=escape(session['user']))
    else:
        flash('Unauthorized access')
        return redirect(url_for('logout'))
예제 #48
0
def viewLoansSSS(user=None):
    if session['usertype'] == 'BeO' or session['usertype'] == 'ADM':
        return render_template('loan_SSS.html', user=escape(session['user']))
    else:
        flash('Unauthorized access')
        return redirect(url_for('logout'))
예제 #49
0
def hello():
    name = request.args.get("name", "World")
    return "Hello, " + escape(name) + "!"
예제 #50
0
def regenMarkdown():
    user_pastes = pastes.find({})

    for paste in user_pastes:
        if paste.get("markdown"):
            pastes.update_one(paste, { "$set": { "html": markdown.markdown(escape(paste["markdown"]), extensions=['mdx_truly_sane_lists', 'pymdownx.superfences', 'extra']) } })
예제 #51
0
 def slice_link(self):
     url = self.slice_url
     name = escape(self.slice_name)
     return Markup('<a href="{url}">{name}</a>'.format(**locals()))
예제 #52
0
 def dashboard_link(self):
     title = escape(self.dashboard_title)
     return Markup(
         '<a href="{self.url}">{title}</a>'.format(**locals()))
예제 #53
0
def python_is_cool(text="is cool"):
    """Show Python is cool[default]"""
    return 'Python %s' % escape(text).replace("_", " ")
예제 #54
0
def session_user_data():
    if 'username' in session:
        username = format(escape(session['username']))
        return response(10200, 'hello, {}'.format(username))
    return response(10200, 'hello, stranger')
예제 #55
0
def c_is_fun(text):
    """Show c and text"""
    return 'C %s' % escape(text).replace("_", " ")
예제 #56
0
 def link(self):
     if self.id:
         return Markup("<a href='{}' class='album-link'>{}</a>".format(
             self.url(), escape(self.name)))
     else:
         return self.name
예제 #57
0
def index():
    if 'username' in session:
        return 'logged in as {}'.format(escape(session['username']))
    return redirect(url_for('login'))
예제 #58
0
def nl2br_filter(s):
    """改行文字をbrタグに置き換えるテンプレートフィルター"""
    return escape(s).replace('\n', Markup('<br>'))
예제 #59
0
파일: app.py 프로젝트: Boy-314/appsec
def history():
    if "username" in session:
        username = session["username"]
        flash(f"logged in as {username}")
        select_queryID = select(
            [spellchecks.c.id]).where(spellchecks.c.users_usrnm == username)
        select_querytext = select([
            spellchecks.c.sc_text
        ]).where(spellchecks.c.users_usrnm == username)
        select_numqueries = select(
            [func.count()]).where(spellchecks.c.users_usrnm == username)
        connhistory = engine.connect()
        query_IDs = []
        query_texts = []
        if request.method == "POST":
            adminrequest_user = escape(request.form["userquery"])
            select_queryID = select([
                spellchecks.c.id
            ]).where(spellchecks.c.users_usrnm == adminrequest_user)
            select_querytext = select([
                spellchecks.c.sc_text
            ]).where(spellchecks.c.users_usrnm == adminrequest_user)
            select_numqueries = select([
                func.count()
            ]).where(spellchecks.c.users_usrnm == adminrequest_user)
            select_queryID_result = connhistory.execute(select_queryID)
            select_querytext_result = connhistory.execute(select_querytext)
            select_numqueries_result = connhistory.execute(select_numqueries)
            get_queryIDs = select_queryID_result.fetchall()
            get_querytexts = select_querytext_result.fetchall()
            get_numqueries = select_numqueries_result.fetchone()
            for row in get_queryIDs:
                query_IDs.append("query" + str(row['id']))
                # print("appending query_id")
            for row in get_querytexts:
                query_texts.append(row['sc_text'])
                # print("appending query_text")
            connhistory.close()
            return render_template("history.html",
                                   loggedin=adminrequest_user,
                                   querycount=get_numqueries[0],
                                   querynums=query_IDs,
                                   querytexts=query_texts)
        else:
            select_queryID_result = connhistory.execute(select_queryID)
            select_querytext_result = connhistory.execute(select_querytext)
            select_numqueries_result = connhistory.execute(select_numqueries)
            get_queryIDs = select_queryID_result.fetchall()
            get_querytexts = select_querytext_result.fetchall()
            get_numqueries = select_numqueries_result.fetchone()
            for row in get_queryIDs:
                query_IDs.append("query" + str(row['id']))
                # print("appending query_id")
            for row in get_querytexts:
                query_texts.append(row['sc_text'])
                # print("appending query_text")
            connhistory.close()
            return render_template("history.html",
                                   loggedin=username,
                                   querycount=get_numqueries[0],
                                   querynums=query_IDs,
                                   querytexts=query_texts)
    else:
        flash("login to see this page")
        return redirect(url_for("login"))
    flash("something broke")
    return redirect(url_for("login"))
예제 #60
0
 def link(self):
     return Markup("<a href='{}' class='user-link'>{}</a>".format(
         self.url(), escape(self.name)))