Example #1
0
def recover():
    """recover"""
    if request.method == 'GET':
        return render_template('recover_password.html')
    username = request.form['username']
    registered_user = User.query.filter_by(username=username,).first()
    if registered_user is None:
        flash(gettext('Invalid username'), 'danger')
        return redirect(url_for('recover', lang=g.current_lang))

    fromaddr = '%s <%s>' % (APP.config['GHC_SITE_TITLE'],
                            APP.config['GHC_ADMIN_EMAIL'])
    toaddr = registered_user.email

    template_vars = {
        'config': APP.config,
        'password': registered_user.password
    }
    msg = render_template2('recover_password_email.txt', template_vars)

    send_email(APP.config['GHC_SMTP'], fromaddr, toaddr, msg)

    flash(gettext('Password sent via email'), 'success')

    if 'next' in request.args:
        return redirect(request.args.get('next'))
    return redirect(url_for('home', lang=g.current_lang))
Example #2
0
def commitblog():
    if 'logged_in' in session:
        title = request.form['title'].strip()
        blogpost = request.form['blogpost'].strip()

        if 'Preview Blog' in request.form.values():
            return redirect(url_for('add_blog',preview=1,title=title,blogpost=blogpost,recover=1))

        error = 0
        if title == "":
            error = 1
            flash("You must make a title","error")
        if blogpost == "":
            error = 1
            flash("You must make the blogpost","error")

        if error:
            return redirect(url_for('add_blog',title=title,blogpost=blogpost,recover=1))
        time_var = unixtime()
        g.db.execute("""
INSERT INTO post (title, text, removed,unixtime,views) VALUES (?,?,0,?,0)
""",(title,blogpost,time_var))
        g.db.commit()
        blogid = query_db("""SELECT id FROM post WHERE unixtime=?""",[time_var],True)['id']
    else:
        return abort(403)
    return redirect(url_for('blogpost',blogid=blogid))
Example #3
0
def oauth2callback():
  flow = client.flow_from_clientsecrets(
      CLIENT_SECRETS,
      scope='https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/userinfo.email',
      redirect_uri=flask.url_for('oauth2callback', _external=True))
  if 'code' not in flask.request.args:
    auth_uri = flow.step1_get_authorize_url()
    # webbrowser.open_new_tab(auth_uri)
    return flask.redirect(auth_uri)
  else:
    auth_code = flask.request.args.get('code')
    credentials = flow.step2_exchange(auth_code)
    flask.session['credentials'] = credentials.to_json()
    
    http_auth = credentials.authorize(httplib2.Http())
    result = main.classes(http_auth, flask.session["initData"])

    campus = flask.session["initData"]["campus"][::]

    flask.session.pop("initData",None)

    if "success" in result:
      return flask.redirect(flask.url_for("index"+campus)+'#'+result["course"].replace(" ","+"))
    else:
      return flask.redirect(flask.url_for('index'+campus)+"#BadInput")
Example #4
0
def m_clinic_update():
    action_type = request.values.get("action_type", None)
    if not action_type:
        flash("No such action type !", MESSAGE_ERROR)
        return redirect(url_for("m_clinic_list"))

    if action_type == "n":
        return render_template("m_clinic_new.html")
    elif action_type in ["m", "d"]:
        id = request.values.get("id", None)
        if not id:
            flash("No clinic id supply", MESSAGE_ERROR)
            return redirect(url_for("m_clinic_list"))
        c = connection.Clinic.one({'id' : int(id)})
        if action_type == "m":
            return render_template("m_clinic_update.html", clinic = c)
        elif action_type == "d":
            c.active = 1
            c.save()
            l = connection.SystemLog()
            l.uid = session['user_profile']['id']
            l.type = u'DELETE CLINIC'
            l.content = u'%s delete the clinic [name : %s, id : %d]' % (session['user_profile']['name'], c.name, c.id)
            flash("The clinic [%s] has been deleted successfully !" % c.name, MESSAGE_INFO)
            return redirect(url_for("m_clinic_list"))
    else:
        flash("No such action type !", MESSAGE_ERROR)
        return redirect(url_for("m_clinic_list"))
Example #5
0
    def index(self):
        query = self.get_query()

        ordering = request.args.get('ordering') or ''
        query = self.apply_ordering(query, ordering)

        # process the filters from the request
        filter_form, query, cleaned, field_tree = self.process_filters(query)

        # create a paginated query out of our filtered results
        pq = PaginatedQuery(query, self.paginate_by)

        if request.method == 'POST':
            id_list = request.form.getlist('id')
            if request.form['action'] == 'delete':
                return redirect(url_for(self.get_url_name('delete'), id=id_list))
            else:
                return redirect(url_for(self.get_url_name('export'), id=id_list))

        return render_template(self.templates['index'],
            model_admin=self,
            query=pq,
            ordering=ordering,
            filter_form=filter_form,
            field_tree=field_tree,
            active_filters=cleaned,
            **self.get_extra_context()
        )
Example #6
0
def processes():
    fragments = []
    fragments.append("""<h3> Running Processes </h3><hr>""")
    fragments.append("<table>")
    process_data = process_list()
    fragments.append("<tr>")
    for h in ["PID", "RSS", "%MEM", "%CPU", "COMMAND"]:
        fragments.append("<td>%s</td>" % h)
    fragments.append("</tr>")
    for i in xrange(len(process_data["PID"])):
        fragments.append("<tr>")
        for h in ["PID", "RSS", "%MEM", "%CPU", "COMMAND"]:
            if h == 'PID':
                fragments.append("<td><a href='%s'>%s</a></td>" % (url_for('process', pid=process_data['PID'][i]), process_data[h][i]))
            elif h == 'RSS':
                fragments.append("<td><a href='%s'>%s</a></td>" % (url_for('chart', pid=process_data['PID'][i], var='rss'), process_data[h][i]))
            elif h == '%CPU':
                fragments.append("<td><a href='%s'>%s</a></td>" % (url_for('chart', pid=process_data['PID'][i], var='cpu'), process_data[h][i]))
            elif h == '%MEM':
                fragments.append("<td><a href='%s'>%s</a></td>" % (url_for('chart', pid=process_data['PID'][i], var='mem'), process_data[h][i]))
            else:
                fragments.append("<td>%s</td>" % process_data[h][i])
        fragments.append("</tr>")
    fragments.append("</table>")
    return build_page("\n".join(fragments), title='Processes')
Example #7
0
def m_doctor_update():
    action_type = request.values.get("action_type", None)
    if not action_type:
        flash("No such action type !", MESSAGE_ERROR)
        return redirect(url_for("m_doctor_list"))

    if action_type == "n":
        cs = connection.Clinic.find({'active':0}).sort('name')
        cats = connection.Category.find({'active':0}).sort('name')
        return render_template("m_doctor_new.html", clinics = cs, categories = cats)
    elif action_type in ["m", "d"]:
        id = request.values.get("id", None)
        if not id:
            flash("No doctor id supply", MESSAGE_ERROR)
            return redirect(url_for("m_doctor_list"))
        d = connection.DoctorProfile.one({'id' : int(id)})
        if action_type == "m":
            cs = connection.Clinic.find({'active':0}).sort('name')
            cats = connection.Category.find({'active':0}).sort('name')
            return render_template("m_doctor_update.html", doctor = d, clinics = cs, categories = cats)
        elif action_type == "d":
            info = d.populate()
            d.active = 1
            d.save()
            l = connection.SystemLog()
            l.uid = session['user_profile']['id']
            l.type = u'DELETE DOCTOR'
            l.content = u'%s delete the doctor profile [name : %s, id : %d]' % (session['user_profile']['name'], info['name'], d.id)
            flash("The doctor profile [%s] has been deleted successfully !" % info['name'], MESSAGE_INFO)
            return redirect(url_for("m_doctor_list"))
    else:
        flash("No such action type !", MESSAGE_ERROR)
        return redirect(url_for("m_clinic_list"))
Example #8
0
def copr_delete(copr):
    return process_delete(
        copr,
        url_on_error=url_for("coprs_ns.copr_detail",
                             username=copr.user.name, coprname=copr.name),
        url_on_success=url_for("coprs_ns.coprs_by_owner", username=copr.user.username)
    )
Example #9
0
def render_generate_repo_file(copr, name_release):

    # we need to check if we really got name release or it's a full chroot (caused by old dnf plugin)
    if name_release in [c.name for c in copr.mock_chroots]:
        chroot = [c for c in copr.mock_chroots if c.name == name_release][0]
        kwargs = dict(coprname=copr.name, name_release=chroot.name_release)
        if copr.is_a_group_project:
            fixed_url = url_for("coprs_ns.group_generate_repo_file",
                                group_name=copr.group.name, **kwargs)
        else:
            fixed_url = url_for("coprs_ns.generate_repo_file",
                                username=copr.user.username, **kwargs)
        return flask.redirect(fixed_url)

    mock_chroot = coprs_logic.MockChrootsLogic.get_from_name(name_release, noarch=True).first()
    if not mock_chroot:
        raise ObjectNotFound("Chroot {} does not exist".format(name_release))

    url = os.path.join(copr.repo_url, '') # add trailing slash
    repo_url = generate_repo_url(mock_chroot, url)
    pubkey_url = urljoin(url, "pubkey.gpg")
    response = flask.make_response(
        flask.render_template("coprs/copr.repo", copr=copr, url=repo_url, pubkey_url=pubkey_url))
    response.mimetype = "text/plain"
    response.headers["Content-Disposition"] = \
        "filename={0}.repo".format(copr.repo_name)
    return response
Example #10
0
def checkEpisode(id):
    episode = Episode.query.get_or_404(id)

    if request.method == 'GET':
        return redirect(url_for('showEpisode', id=episode.id))

    url = request.referrer

    if not validate_token():
        return redirect(url_for('checkEpisode', id=episode.id))

    add = request.form.get('add', None)
    if add:
        if episode not in current_user.watched_episodes:
            current_user.watched_episodes.append(episode)
            flash('Added to watched!', 'success')
    else:
        if episode in current_user.watched_episodes:
            current_user.watched_episodes.remove(episode)
            flash('Removed from watched!', 'success')

    fav = UserSerie.query.\
        filter_by(user=current_user, \
        serie=episode.serie).first()
    if fav is not None:
        fav.last_watched = datetime.now()
        db.session.add(fav)

    db.session.commit()

    if url is not None:
        return redirect(url)

    return redirect(url_for('showEpisode', id=episode.id))
Example #11
0
    def handle_action(self, return_view=None):
        action = request.form.get('action')
        ids = request.form.getlist('rowid')
        page, sort, sort_desc, search, filters = self._get_action_extra_args()
        select_all = request.form.get('select-all', 0, type=int)
        select_page = request.form.get('select-page', 0, type=int)

        if select_all:
            count, query = self.get_list(None, sort, sort_desc, search, filters, False)
        elif select_page:
            count, query = self.get_list(page, sort, sort_desc, search, filters, False)
        else:
            query = get_query_for_ids(self.get_query(), self.model, ids)

        handler = self._actions_data.get(action)

        if handler and self.is_action_allowed(action):
            response = handler[0](ids, query)

            if response is not None:
                return response

        if not return_view:
            url = url_for('.' + self._default_view)
        else:
            url = url_for('.' + return_view)

        return redirect(url)
Example #12
0
def checkSeries(id):
    series = Serie.query.get_or_404(id)

    if request.method == 'GET':
        return redirect(url_for('showSeries', id=series.id))

    url = request.referrer

    if not validate_token():
        return redirect(url_for('checkSeries', id=series.id))

    add = request.form.get('add', None)
    if add:
        if series not in current_user.favorite_series:
            current_user.favorite_series.append(series)
            flash('Added to watchlist!', 'success')
    else:
        current_user.favorite_series.remove(series)
        flash('Removed from watchlist!', 'success')
    db.session.commit()

    if url is not None:
        return redirect(url)

    return redirect(url_for('showSeries', id=series.id))
Example #13
0
def login():

    if request.method == 'GET':
        return render_template('login.html')
    username = request.form['username']
    password = request.form['password']

    remember_me = False
    if 'remember_me' in request.form:
        remember_me = True


    registered_user = db.session.query(User).filter_by(login=username).first()

 
    if registered_user is None:
        flash('Username or Password is invalid' , 'error')
        return redirect(url_for('login'))
    if not registered_user.check_password(password):
        flash('Password is invalid','error')
        return redirect(url_for('login'))
    login_user(registered_user, remember = remember_me)

    flash('Logged in successfully')
    return redirect(request.args.get('next') or url_for('upload'))
Example #14
0
def _do_login_user(user, next, remember_me=False):
    # User must have been authenticated
    if not user: return unauthenticated()

    # Check if user account has been disabled
    if not _call_or_get(user.is_active):
        flash(_('Your account has not been enabled.'), 'error')
        return redirect(url_for('user.login'))

    # Check if user has a confirmed email address
    user_manager = current_app.user_manager
    if user_manager.enable_email and user_manager.enable_confirm_email \
            and not current_app.user_manager.enable_login_without_confirm_email \
            and not user.has_confirmed_email():
        url = url_for('user.resend_confirm_email')
        flash(_('Your email address has not yet been confirmed. Check your email Inbox and Spam folders for the confirmation email or <a href="%(url)s">Re-send confirmation email</a>.', url=url), 'error')
        return redirect(url_for('user.login'))

    # Use Flask-Login to sign in user
    #print('login_user: remember_me=', remember_me)
    login_user(user, remember=remember_me)

    # Send user_logged_in signal
    signals.user_logged_in.send(current_app._get_current_object(), user=user)

    # Prepare one-time system message
    flash(_('You have signed in successfully.'), 'success')

    # Redirect to 'next' URL
    return redirect(next)
Example #15
0
def delete():
    user = models.find_user(session['login'])
    if user is None:
        flash('Cannot delete unless logged in', category='error')
        return render_template('index.html'), 404

    path = request.form['path']
    branch = request.form['branch']

    article = models.read_article(path, rendered_text=False, branch=branch)

    if article is None:
        flash('Cannot find article to delete', category='error')
        return redirect(url_for('index'))

    if not models.delete_article(article, 'Removing article', user.login,
                                 user.email):
        flash('Failed removing article', category='error')
    else:
        flash('Article successfully deleted', category='info')

    # This article should have only been on one of these lists but trying to
    # remove it doesn't hurt so just forcefully remove it from both just in
    # case.
    published = False
    tasks.remove_from_listing(article.title, published, user.login, user.email,
                              branch=article.branch)

    published = not published
    tasks.remove_from_listing(article.title, published, user.login, user.email,
                              branch=article.branch)

    return redirect(url_for('index'))
 def _get_modelview_urls(self, modelview_urls=None):
     view_name = self.__class__.__name__
     modelview_urls = modelview_urls or {}
     modelview_urls['show'] = url_for(view_name + ".show", pk="")
     modelview_urls['add'] = url_for(view_name + ".add")
     modelview_urls['edit'] = url_for(view_name + ".edit", pk="")
     return modelview_urls
Example #17
0
def register():
    """
    Displays Registration page to visitors
    """
    form = RegistrationForm(request.form)
    if form.validate_on_submit():
        # Check if passwords match
        if form.password.data != form.password_check.data:
            flash(u'Passwords do not match. Please try again', 'error')
            return redirect(url_for('index.register'))

        # Check if user exists
        if user_exists(form.user_id.data):
            flash(u'Sorry, a user with that account already exists', 'error')
            return redirect(url_for('index.register'))

        # Add user to database
        result = add_new_user(form.user_id.data, form.password.data,
                              form.first_name.data, form.middle_name.data,
                              form.last_name.data, form.e_mail.data,
                              form.street1.data, form.street2.data,
                              form.state.data, form.country.data,
                              form.zipcode.data)

        user_id = result.first()['user_id']
        bulk_add_preferences(user_id, form.preferences.data)
        
        flash(u"Congratulations, you've registered with MovieNet")
        return redirect(url_for('index.show_home'))

    return render_template('register.html', form=form)
Example #18
0
def totp_user_view():
	if not totp_user_enabled(session['username']):
		if request.method == 'GET':
			return render_template('totp_enable.html',active="user")
		elif request.method == 'POST':
			## verify the token entered
			token = request.form['totp_token']

			if totp_verify_token(session['username'],token):
				flash("Two step logon has been enabled for your account","alert-success")
				g.redis.set('totp.%s.enabled' % session['username'],"True")
			else:
				flash("Invalid code! Two step logons could not be enabled","alert-danger")
	
			return redirect(url_for('totp_user_view'))
				
	else:
		if request.method == 'GET':
			return render_template('totp_disable.html',active="user")
		elif request.method == 'POST':

			## verify the token entered
			token = request.form['totp_token']

			if totp_verify_token(session['username'],token):
				g.redis.delete('totp.%s.enabled' % session['username'])
				g.redis.delete('totp.%s.key' % session['username'])
				flash("Two step logons have been disabled for your account","alert-warning")
			else:
				flash("Invalid code! Two step logons were not disabled","alert-danger")
	
			return redirect(url_for('totp_user_view'))
Example #19
0
def admin_message_send():
    to = request.values.get('to')
    subject = request.values.get('subject')
    summary = request.values.get('summary')
    content = request.values.get('content')

    if subject == '':
        session['error_message'] = '标题为必填。'
        return redirect(url_for('admin_message'))

    if to == '':
        session['error_message'] = '收件方必填。'
        return redirect(url_for('admin_message'))

    if summary == '':
        session['error_message'] = '简介必填'
        return redirect(url_for('admin_message'))

    send_content = '{:<30}'.format(summary) + content
    if to == 'all':
        for b_username in r_session.smembers('users'):
            send_msg(b_username.decode('utf-8'), subject,
                     send_content, 3600 * 24 * 7)

    else:
        send_msg(to, subject, send_content, 3600 * 24)

    return redirect(url_for(endpoint='admin_message'))
Example #20
0
def generatedistance():

    request.form['query']   
    query = request.form['query'] 
    
    path = ''
    cached_plid= ['pl170577122547466496','pl147773287731036416','pl151894969496371456', 'pl151764388523540736','pl152858163299746048','pl196764123525021952','pl196411940837261312', 'pl197125380790813184', 'pl197529051726872832']
    for plids in cached_plid:
        if query == plids:
            path = "cached"
    if path=="cached":
        songs_and_artists, min_edgepath, shuffle, avg_shuffle, orig_artists_and_songs, improvement = get_cached(query)
        filename = 'request_' + query + '.png'
        url = url_for('static', filename =  'request_' + query + '.png')
        url2 = url_for('static', filename="comparison_"+filename)
    else:
        beatstracks = beatspl2tracks(query)
        entracks = beats2echonest(beatstracks)
        filename = 'request_' + query + '.png'
        songdatalist, dist_matrix, playlist, summarydf, orig_artists_and_songs = EN_id2summary(filename, entracks)
        min_edgepath, shuffle, avg_shuffle, improvement, songs_and_artists = DiGraph(songdatalist, dist_matrix, playlist, summarydf, filename)
        url = url_for('static', filename=filename)
        url2 = url_for('static', filename="comparison_"+filename)

    artists = []
    for song in songs_and_artists:
        artists.append(song[1])
    beats_img = "https://api.beatsmusic.com/api/playlists/"+query+"/images/default?size=large"

    
    mean_shuff, var_shuff, std_shuff = scipy.stats.bayes_mvs(shuffle, alpha=0.95)
    
    
    return render_template('generatedistance.html', query=query, beats_img=beats_img, url = url, url2=url2, minval=min_edgepath, shuffle=shuffle, avg_shuffle=avg_shuffle, improvement=improvement, songs_and_artists=songs_and_artists, orig_artists_and_songs=orig_artists_and_songs, mean_shuff=mean_shuff)
Example #21
0
def m_nurse_update():
    action_type = request.values.get("action_type", None)
    if not action_type:
        flash("No such action type !", MESSAGE_ERROR)
        return redirect(url_for("m_nurse_list"))

    if action_type == "n":
        cs = connection.Clinic.find({'active':0}).sort('name')
        return render_template("m_nurse_new.html", clinics = cs)
    elif action_type in ["m", "d"]:
        id = request.values.get("id", None)
        if not id:
            flash("No nurse id supply", MESSAGE_ERROR)
            return redirect(url_for("m_nurse_list"))
        n = connection.NurseProfile.one({'id' : int(id)})
        if action_type == "m":
            cs = connection.Clinic.find({'active':0}).sort('name')
            return render_template("m_nurse_update.html", nurse = n, clinics = cs)
        elif action_type == "d":
            n.active = 1
            n.save()
            l = connection.SystemLog()
            l.uid = session['user_profile']['id']
            l.type = u'DELETE NURSE'
            l.content = u'%s delete the nurse [name : %s, id : %d]' % (session['user_profile']['name'], n.name, n.id)
            flash("The nurse [%s] has been deleted successfully !" % n.name, MESSAGE_INFO)
            return redirect(url_for("m_nurse_list"))
    else:
        flash("No such action type !", MESSAGE_ERROR)
        return redirect(url_for("m_nurse_list"))
Example #22
0
def tuchuang_index():
    github_user = _get_user()

    if not github_user:
        flash(u'请正确完成牛逼参数设置后上传图片!', category='warning')
        return redirect(url_for('.info'))

    if request.method == 'POST':
        access_key = str(github_user.get('access_key'))
        secret_key = str(github_user.get('secret_key'))
        bucket_name = str(github_user.get('bucket_name'))
        domain_name = str(github_user.get('domain_name'))
        q = Auth(access_key, secret_key)
        token = q.upload_token(bucket_name)

        upload_files = request.files.getlist('file')
        for upload_file in upload_files:
            key = '%s_%s' % (datetime.now().isoformat(), upload_file.filename)
            ret, info = put_data(up_token=token, key=key, data=upload_file)
            url = '%s/%s' % (domain_name, key)
            f = File()
            f.set('url', url)
            f.set('user', github_user)
            f.save()
        flash(u'成功上传%s张照片!' % len(upload_files), category='success')
        return redirect(url_for('.tuchuang_index'))

    image_id = request.args.get('image_id')
    image = Query(File).get(image_id) if image_id else None

    return render_template('tuchuang.html', image=image)
Example #23
0
def m_events_update():
    id = _g("id")
    if not id :
        flash("No id supplied !", MESSAGE_ERROR)
        return redirect(url_for("m_events_list"))
    action_type = _g("action_type")
    if not action_type in ["m", "c", "p"]:
        flash("No such action !", MESSAGE_ERROR)
        return redirect(url_for("m_events_list"))

    e = DBSession.query(Events).get(id)
#    e = connection.Events.one({"id" : int(id)})

    if action_type == "m":
        return render_template("m_events_update.html", event = e)
    elif action_type == "c": #cancel       
        e.status = 2
        DBSession.add(Message(subject = u"Cancel Booking Event", user_id = e.user_id,
                              content = u"%s cancel the booking request." % session['user_profile']['name']))
        DBSession.commit()
        return jsonify({"success" : True, "message" : "Update successfully !"})
    elif action_type == "p": #confirmed
        e.status = 1
        DBSession.add(Message(subject = u"Confirm Booking Event", user_id = e.user_id,
                              content = u"%s confirm the booking request." % session['user_profile']['name']))
        DBSession.commit()
        return jsonify({"success" : True, "message" : "Update successfully !"})
Example #24
0
def login():
    # 已登录用户则返回首页
    if g.user.is_authenticated:
        return redirect(url_for('frontend.index'))

    login_form = LoginForm()
    if login_form.validate_on_submit():
        people = People.query.authenticate(
            login_form.login.data,
            login_form.password.data,
        )

        if people:
            login_user(people, remember=login_form.remember.data)
            # Flask-Principal 发送信号
            identity_changed.send(current_app._get_current_object(), identity=Identity(people.id))
            print 'sent by login'
            ip = get_client_ip()
            login_log = LoginLog(people.id, ip)
            db.session.add(login_log)
            db.session.commit()

            flash('登录成功', 'success')
            return redirect(url_for('frontend.index'))
        else:
            flash('登录失败', 'warning')

    return render_template('login.html', form=login_form)
Example #25
0
def index():
    url_for('static', filename='logo.ico')
    if request.method == 'POST':
        #Check files that start with 'o-ide*'
        files = glob.glob("oide*")
        print(files)
        #Check if C was compiled
        if len(files) < 1:
            print("Compiling O...")
            compileO()
        #Run code
        code = request.form['code']
        input = request.form['input'].replace('\r\n', '\n')
        if input is None: input = ""
        print('Got code:', code, 'input:', input)
        print('Running O code...')
        p = Popen(['./oide', '-e', code], stdout=PIPE, stderr=PIPE, stdin=PIPE, universal_newlines=True)
        output, error = p.communicate(input)
        #Output to IDE
        if p.returncode:
            print('Output:', output, 'error:', error)
            return render_template('error.html', code=code, input=input, error=error)
        else:
            print('Output:', output, 'stack:', error)
            return render_template('code.html', code=code, input=input, output=output, stack=error or '[]')
    else:
        return render_template('primary.html')
Example #26
0
def user_change_password():
    user = session.get('user_info')
    o_password = request.values.get('old_password')
    n_password = request.values.get('new_password')
    n2_password = request.values.get('new2_password')
    session['action'] = 'password'

    if n_password != n2_password:
        session['error_message'] = '新密码输入不一致.'
        return redirect(url_for('user_profile'))

    if len(n_password) < 8:
        session['error_message'] = '密码必须8位及以上.'
        return redirect(url_for('user_profile'))

    user_key = '%s:%s' % ('user', user.get('username'))
    user_info = json.loads(r_session.get(user_key).decode('utf-8'))

    hashed_password = hash_password(o_password)

    if user_info.get('password') != hashed_password:
        session['error_message'] = '原密码错误'
        return redirect(url_for('user_profile'))

    user_info['password'] = hash_password(n_password)
    r_session.set(user_key, json.dumps(user_info))

    return redirect(url_for('user_profile'))
Example #27
0
def delete_post(username, post_id, reply_id=None):
    """Deletes posts.

    """
    # The default redirect is different for a post/reply deletion
    # Reply deletion keeps you on the page and post deletion takes you to feed
    if reply_id is not None:
        redirect_url = handle_next(request, url_for('posts.view_post',
                                   username=username, post_id=post_id))
    else:
        redirect_url = handle_next(request, url_for('users.feed'))

    user_id = get_uid(username)
    if not check_post(user_id, post_id, reply_id):
        return abort(404)

    if reply_id is not None:
        _post = get_post(reply_id)

        if _post['user_id'] != current_user['_id'] and \
                user_id != current_user['_id']:
            return abort(403)
    else:
        if user_id != current_user['_id']:
            return abort(403)

    if reply_id is not None:
        be_delete_post(reply_id)
        flash('Post has been deleted', 'success')
    else:
        be_delete_post(post_id)
        flash('Post has been deleted along with all replies', 'success')

    return redirect(redirect_url)
Example #28
0
def add_user():

    user = request.form.get('username')
    comment = request.form.get('comment')
    active = bool(request.form.get('active', False))

    if not user:
        flash('Required fields for new user: username')
        return redirect(url_for('usermanager'))

    if User.query.filter(User.name == user).first():
        flash('Cannot add: user %s already exists' % user, category='tmperror')
        return redirect(url_for('usermanager'))

    uobj = User(name=user, comment=comment, active=active)
    uobj.roles = list()

    db_session.add(uobj)
    db_session.commit()

    msg = 'Added new user %s' % user
    app.logger.info(msg)
    flash(msg)

    return redirect(url_for('usermanager'))
Example #29
0
def outage_create():
    checked = False
    if request.form.get('checked') is not None:
        checked = True

    flagged = False 
    if request.form.get('flagged') is not None:
        flagged = True

    start_datetime = None
    if request.form.get('start_datetime') is not None:
        try:
            start_datetime = datetime.datetime.strptime(request.form.get('start_datetime'),
                '%Y-%m-%d %H:%M:%S')
        except Exception as e:
            flash('Start Date/Time formatted incorrectly')
            return redirect(url_for('outage_new'))

    end_datetime = None
    if (request.form.get('end_datetime') is not None) and ('None' not in request.form.get('end_datetime')):
        try:
            end_datetime = datetime.datetime.strptime(request.form.get('end_datetime'),
                '%Y-%m-%d %H:%M:%S')
        except Exception as e:
            flash('End Date/Time formatted incorrectly')
            return redirect(url_for('outage_new'))

    return redirect(url_for('outage_detail', outage_id=outage_id))
Example #30
0
def delete(resource_identifier):
    """delete a resource"""
    resource = Resource.query.filter_by(identifier=resource_identifier).first()
    if g.user.role != 'admin' and g.user.username != resource.owner.username:
        msg = gettext('You do not have access to delete this resource')
        flash(msg, 'danger')
        return redirect(url_for('get_resource_by_id', lang=g.current_lang,
                                identifier=resource_identifier))

    if resource is None:
        flash(gettext('Resource not found'), 'danger')
        return redirect(url_for('home', lang=g.current_lang))

    runs = Run.query.filter_by(resource_identifier=resource_identifier).all()

    for run in runs:
        DB.session.delete(run)

    DB.session.delete(resource)

    try:
        DB.session.commit()
        flash(gettext('Resource deleted'), 'success')
        return redirect(url_for('home', lang=g.current_lang))
    except Exception as err:
        DB.session.rollback()
        flash(str(err), 'danger')
        return redirect(url_for(request.referrer))