Esempio n. 1
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))
Esempio n. 2
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))
Esempio n. 3
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)
Esempio n. 4
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))
Esempio n. 5
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")
Esempio n. 6
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')
Esempio n. 7
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))
Esempio n. 8
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 !"})
Esempio n. 9
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()
        )
Esempio n. 10
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"))
Esempio n. 11
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"))
Esempio n. 12
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'))
Esempio n. 13
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"))
Esempio n. 14
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)
Esempio n. 15
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')
Esempio n. 16
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'))
Esempio n. 17
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'))
Esempio n. 18
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)
Esempio n. 19
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'))
Esempio n. 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)
Esempio n. 21
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)
 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
Esempio n. 23
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)
    )
Esempio n. 24
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))
Esempio n. 25
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)
Esempio n. 26
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'))
Esempio n. 27
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))
Esempio n. 28
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
Esempio n. 29
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)
Esempio n. 30
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'))
Esempio n. 31
0
 def decorated_function(*args, **kwargs):
     if current_user.confirmed is False:
         flash('Please confirm your account!', 'warning')
         return redirect(url_for('user.unconfirmed'))
     return func(*args, **kwargs)
Esempio n. 32
0
def endpoint_info(*args):
    ret = {
        "active_matches": url_for("matches.active", _external=True),
        "matches": url_for("matches.list", _external=True),
    }
    return ret
Esempio n. 33
0
    def post(self, match_id):
        """
        Add a player to a match
        """

        player_id = request.json["player_id"]
        team_id = request.json.get("team_id", None)

        match = g.db.query(Match).get(match_id)
        if not match:
            abort(httplib.NOT_FOUND, description="Match not found")

        if match.status == "completed":
            abort(httplib.BAD_REQUEST, description="You cannot add a player to a completed battle")

        num_players = g.db.query(MatchPlayer) \
            .filter(MatchPlayer.match_id == match.match_id,
                    MatchPlayer.status.in_(["active"])) \
            .count()
        if num_players >= match.max_players:
            abort(httplib.BAD_REQUEST, description="Match is full")

        if team_id:
            team = g.db.query(MatchTeam).get(team_id)
            if not team:
                abort(httplib.NOT_FOUND, description="Team not found")
            if team.match_id != match_id:
                abort(httplib.BAD_REQUEST,
                      description="Team %s is not in match %s" % (team_id, match_id))

        match_player = g.db.query(MatchPlayer) \
                           .filter(MatchPlayer.match_id == match_id,
                                   MatchPlayer.player_id == player_id) \
                           .first()
        if not match_player:
            match_player = MatchPlayer(match_id=match_id,
                                       player_id=player_id,
                                       team_id=team_id,
                                       num_joins=0,
                                       seconds=0,
                                       status="active")
            g.db.add(match_player)
        match_player.num_joins += 1
        match_player.join_date = utcnow()
        match_player.status = "active"

        # remove the player from the match queue
        g.db.query(MatchQueuePlayer).filter(MatchQueuePlayer.player_id == player_id).delete()

        if match.start_date is None:
            match.start_date = utcnow()

        g.db.commit()

        # prepare the response
        resource_uri = url_for("matches.player",
                               match_id=match_id,
                               player_id=player_id,
                               _external=True)
        response_header = {"Location": resource_uri}
        log.info("Player %s has joined match %s in team %s.", player_id, match_id, team_id)

        log_match_event(match_id, player_id, "gameserver.match.player_joined",
                        details={"team_id": team_id})

        return {"match_id": match_id,
                "player_id": player_id,
                "team_id": team_id,
                "url": resource_uri,
                }, httplib.CREATED, response_header
Esempio n. 34
0
    def get(self):
        """This endpoint used by clients to fetch a list of matches available
        for joining
        """
        args = self.get_args.parse_args()
        num_rows = args.get("rows") or 100

        query = g.db.query(Match, Server, Machine)
        query = query.filter(Server.machine_id == Machine.machine_id,
                             Match.server_id == Server.server_id,
                             Match.status.notin_(["ended", "completed"]),
                             Server.status.in_(["started", "running", "active", "ready"]),
                             Server.heartbeat_date >= utcnow() - datetime.timedelta(seconds=60)
                             )
        if args.get("ref"):
            query = query.filter(Server.ref == args.get("ref"))
        if args.get("version"):
            query = query.filter(Server.version == args.get("version"))
        if args.get("placement"):
            query = query.filter(Machine.placement == args.get("placement"))
        if args.get("realm"):
            query = query.filter(Machine.realm == args.get("realm"))
        player_ids = []
        if args.get("player_id"):
            player_ids = args.get("player_id")

        query = query.order_by(-Match.num_players, -Match.server_id)
        query = query.limit(num_rows)
        rows = query.all()

        ret = []
        for row in rows:
            include = True
            if player_ids:
                include = False

            match = row[0]
            server = row[1]
            machine = row[2]
            record = {}
            record["create_date"] = match.create_date
            record["game_mode"] = match.game_mode
            record["map_name"] = match.map_name
            record["max_players"] = match.max_players
            record["match_status"] = match.status
            record["server_status"] = server.status
            record["public_ip"] = server.public_ip
            record["port"] = server.port
            record["version"] = server.version
            record["match_id"] = match.match_id
            record["server_id"] = match.server_id
            record["machine_id"] = server.machine_id
            record["heartbeat_date"] = server.heartbeat_date
            record["realm"] = machine.realm
            record["placement"] = machine.placement
            record["ref"] = server.ref
            record["match_url"] = url_for("matches.entry",
                                          match_id=match.match_id,
                                          _external=True)
            record["server_url"] = url_for("servers.entry",
                                           server_id=server.server_id,
                                           _external=True)
            record["machine_url"] = url_for("machines.entry",
                                            machine_id=server.machine_id,
                                            _external=True)
            conn_url = "%s:%s?player_id=%s?token=%s"
            record["ue4_connection_url"] = conn_url % (server.public_ip,
                                                       server.port,
                                                       current_user["player_id"],
                                                       server.token)
            player_array = []
            players = g.db.query(MatchPlayer) \
                          .filter(MatchPlayer.match_id == match.match_id,
                                  MatchPlayer.status.in_(["active"])) \
                          .all()
            for player in players:
                player_array.append({
                    "player_id": player.player_id,
                    "player_url": url_player(player.player_id),
                })
                if player.player_id in player_ids:
                    include = True
            record["players"] = player_array
            record["num_players"] = len(player_array)

            if include:
                ret.append(record)

        return ret
Esempio n. 35
0
def verificationLogin():
    if 'username' in session:
        pass
    else:
        if request.url_rule.rule != '/login' and request.url_rule.rule != '/register':
            return redirect(url_for('script.login'))
Esempio n. 36
0
def logout():
    """
    Logout
    """
    session.pop('username', None)
    return redirect(url_for('script.login'))
Esempio n. 37
0
def legacy_index():
    """Legacy deposit."""
    c_id = request.args.get('c', type=str)
    if c_id:
        return redirect(url_for('invenio_deposit_ui.new', c=c_id))
    return render_template(current_app.config['DEPOSIT_UI_INDEX_TEMPLATE'])
Esempio n. 38
0
def logout():
    logout_user()
    return redirect(url_for('index'))
Esempio n. 39
0
 def test_signup_fail_required_fields(self):
     self.client.post(url_for("signup"), data={})
     self.assertEquals(
         set(self._get_user_data().keys()),
         set(self.get_context_variable('form').errors.keys())
     )
Esempio n. 40
0
 def decorated_function(*args, **kwargs):
     if current_user.admin is False:
         flash('You are not allowed on this page, please contact administrator', 'warning')
         return redirect(url_for('main.home'))
     return func(*args, **kwargs)
Esempio n. 41
0
 def test_create_fail_required_name(self):
     user = self.create_user(email='*****@*****.**', password='******')
     with signed_in_user(user) as c:
         c.post(url_for('create_pad'), data={})
         self.assertEquals(
             ['name'], self.get_context_variable('form').errors.keys())
Esempio n. 42
0
def logout():
    """Clear the current session, including the stored user id."""
    session.clear()
    return redirect(url_for('index'))
Esempio n. 43
0
 def test_signin_fail(self):
     response = self.client.post(
         url_for('signin'), data=self._get_user_data())
     self.assertIn('Wrong email or password', response.data)
Esempio n. 44
0
 def test_signup_success(self):
     response = self.client.post(
         url_for("signup"), data=self._get_user_data())
     self.assertRedirects(response, url_for('signin'))
     self.assertEquals(1, User.query.count())
Esempio n. 45
0
def upload():
    file = request.files['file']
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        return redirect(url_for('uploaded_file', filename=filename))
Esempio n. 46
0
 def test_create_success(self):
     user = self.create_user(email='*****@*****.**', password='******')
     with signed_in_user(user) as c:
         response = c.post(url_for('create_pad'), data={'name': 'pad'})
         self.assertRedirects(response, '/flask')
         self.assertEquals(1, Pad.query.count())
Esempio n. 47
0
def new_person():
    result = render_template("new_person.html",add_url=url_for("add_person"))
    return result
Esempio n. 48
0
    def test_signin_success(self):
        data = self._get_user_data()
        self.create_user(**data)

        response = self.client.post(url_for('signin'), data=data)
        self.assertRedirects(response, url_for('home'))
Esempio n. 49
0
def moderate_disable():
    comment = Comment.query.get_or_404(id)
    comment.disabled = True
    db.session.add(comment)
    return redirect(url_for('.moderate', page=request.args.get('page', 1, type=int)))
Esempio n. 50
0
def homePage():
    result = render_template("homepage.html",new_person_link = url_for("new_person"), lookup_people_link= url_for("people"))
    return result
Esempio n. 51
0
def delete_post(post_id):
    post_to_delete = BlogPost.query.get(post_id)
    db.session.delete(post_to_delete)
    db.session.commit()
    return redirect(url_for('get_all_posts'))
Esempio n. 52
0
def people():
    peopleList = [{"name":person.name + " " + person.surname, "link":url_for("see_person", index=person.index)} for person in People.Person.select()]
    print(peopleList)
    result = render_template("list_people.html", people_list=peopleList)
    return result
Esempio n. 53
0
def calculate_blend(mtype, name, idstr):
    result=collect_blend(mtype, idstr)
    return redirect(url_for('calculate_sld', _anchor='results_header',
                            formula=str(result.formula), density=result.fu_volume,
                            name=name or mtype, description=result.extra_data.get('description', None),
                            **CALC_DEFAULT_FIELDS))
Esempio n. 54
0
def show_followed():
    resp = make_response(redirect(url_for('.index')))
    resp.set_cookie('show_followed', '1', max_age=30 * 24 * 60 * 60)
    return resp
Esempio n. 55
0
def refresh_folders():
    get_folders_and_store_to_session()
    return redirect(url_for('upload'))
Esempio n. 56
0
def logout():
    logout_user()
    return redirect(url_for('get_all_posts'))
Esempio n. 57
0
 def get(self):
     context = {"carts": Cart.objects(belongs_to=get_current_user())}
     return self.needs_login(
         next=url_for('quokka.modules.cart.history')) or self.render(
             'cart/history.html', **context)
Esempio n. 58
0
def setup():
    errors = get_errors()
    if not config.is_setup():
        if not session.get("nonce"):
            session["nonce"] = generate_nonce()
        if request.method == "POST":
            # General
            ctf_name = request.form.get("ctf_name")
            ctf_description = request.form.get("ctf_description")
            user_mode = request.form.get("user_mode", USERS_MODE)
            set_config("ctf_name", ctf_name)
            set_config("ctf_description", ctf_description)
            set_config("user_mode", user_mode)

            # Style
            theme = request.form.get("ctf_theme", "core")
            set_config("ctf_theme", theme)
            theme_color = request.form.get("theme_color")
            theme_header = get_config("theme_header")
            if theme_color and bool(theme_header) is False:
                # Uses {{ and }} to insert curly braces while using the format method
                css = (
                    '<style id="theme-color">\n'
                    ":root {{--theme-color: {theme_color};}}\n"
                    ".navbar{{background-color: var(--theme-color) !important;}}\n"
                    ".jumbotron{{background-color: var(--theme-color) !important;}}\n"
                    "</style>\n"
                ).format(theme_color=theme_color)
                set_config("theme_header", css)

            # DateTime
            start = request.form.get("start")
            end = request.form.get("end")
            set_config("start", start)
            set_config("end", end)
            set_config("freeze", None)

            # Administration
            name = request.form["name"]
            email = request.form["email"]
            password = request.form["password"]

            name_len = len(name) == 0
            names = Users.query.add_columns("name", "id").filter_by(name=name).first()
            emails = (
                Users.query.add_columns("email", "id").filter_by(email=email).first()
            )
            pass_short = len(password) == 0
            pass_long = len(password) > 128
            valid_email = validators.validate_email(request.form["email"])
            team_name_email_check = validators.validate_email(name)

            if not valid_email:
                errors.append("Please enter a valid email address")
            if names:
                errors.append("That user name is already taken")
            if team_name_email_check is True:
                errors.append("Your user name cannot be an email address")
            if emails:
                errors.append("That email has already been used")
            if pass_short:
                errors.append("Pick a longer password")
            if pass_long:
                errors.append("Pick a shorter password")
            if name_len:
                errors.append("Pick a longer user name")

            if len(errors) > 0:
                return render_template(
                    "setup.html",
                    errors=errors,
                    name=name,
                    email=email,
                    password=password,
                    state=serialize(generate_nonce()),
                )

            admin = Admins(
                name=name, email=email, password=password, type="admin", hidden=True
            )

            # Index page

            index = """<div class="row">
    <div class="col-md-9 offset-md-2">
        <img class="w-100 mx-auto d-block" style="max-width: 500px;padding: 50px;padding-top: 14vh;" src="themes/core/static/img/xsutd-istd-logo-web-2021.png.pagespeed.ic.w1dqDYZAE-.webp">
        <h3 class="text-center">
            <p>A CTF platform for System Security course</p>
        </h3>
        <br>
        <h4 class="text-center">
            <a href="admin">Click here</a> to login and setup your CTF
        </h4>
    </div>
</div>"""

# """<div class="row">
#     <div class="col-md-6 offset-md-3">
#         <img class="w-100 mx-auto d-block" style="max-width: 500px;padding: 50px;padding-top: 14vh;" src="themes/core/static/img/logo.png" />
#         <h3 class="text-center">
#             <p>A cool CTF platform from <a href="https://ctfd.io">ctfd.io</a></p>
#             <p>Follow us on social media:</p>
#             <a href="https://twitter.com/ctfdio"><i class="fab fa-twitter fa-2x" aria-hidden="true"></i></a>&nbsp;
#             <a href="https://facebook.com/ctfdio"><i class="fab fa-facebook fa-2x" aria-hidden="true"></i></a>&nbsp;
#             <a href="https://github.com/ctfd"><i class="fab fa-github fa-2x" aria-hidden="true"></i></a>
#         </h3>
#         <br>
#         <h4 class="text-center">
#             <a href="admin">Click here</a> to login and setup your CTF
#         </h4>
#     </div>
# </div>"""

            page = Pages(title=None, route="index", content=index, draft=False)

            # Visibility
            set_config(
                ConfigTypes.CHALLENGE_VISIBILITY, ChallengeVisibilityTypes.PRIVATE
            )
            set_config(
                ConfigTypes.REGISTRATION_VISIBILITY, RegistrationVisibilityTypes.PUBLIC
            )
            set_config(ConfigTypes.SCORE_VISIBILITY, ScoreVisibilityTypes.PUBLIC)
            set_config(ConfigTypes.ACCOUNT_VISIBILITY, AccountVisibilityTypes.PUBLIC)

            # Verify emails
            set_config("verify_emails", None)

            set_config("mail_server", None)
            set_config("mail_port", None)
            set_config("mail_tls", None)
            set_config("mail_ssl", None)
            set_config("mail_username", None)
            set_config("mail_password", None)
            set_config("mail_useauth", None)

            # Set up default emails
            set_config("verification_email_subject", DEFAULT_VERIFICATION_EMAIL_SUBJECT)
            set_config("verification_email_body", DEFAULT_VERIFICATION_EMAIL_BODY)

            set_config(
                "successful_registration_email_subject",
                DEFAULT_SUCCESSFUL_REGISTRATION_EMAIL_SUBJECT,
            )
            set_config(
                "successful_registration_email_body",
                DEFAULT_SUCCESSFUL_REGISTRATION_EMAIL_BODY,
            )

            set_config(
                "user_creation_email_subject", DEFAULT_USER_CREATION_EMAIL_SUBJECT
            )
            set_config("user_creation_email_body", DEFAULT_USER_CREATION_EMAIL_BODY)

            set_config("password_reset_subject", DEFAULT_PASSWORD_RESET_SUBJECT)
            set_config("password_reset_body", DEFAULT_PASSWORD_RESET_BODY)

            set_config(
                "password_change_alert_subject",
                "Password Change Confirmation for {ctf_name}",
            )
            set_config(
                "password_change_alert_body",
                (
                    "Your password for {ctf_name} has been changed.\n\n"
                    "If you didn't request a password change you can reset your password here: {url}"
                ),
            )

            set_config("setup", True)

            try:
                db.session.add(admin)
                db.session.commit()
            except IntegrityError:
                db.session.rollback()

            try:
                db.session.add(page)
                db.session.commit()
            except IntegrityError:
                db.session.rollback()

            login_user(admin)

            db.session.close()
            with app.app_context():
                cache.clear()

            return redirect(url_for("views.static_html"))
        return render_template("setup.html", state=serialize(generate_nonce()))
    return redirect(url_for("views.static_html"))
Esempio n. 59
0
def index():
    if 'username' in session:
        username = session['username']
        return redirect(url_for('indexs'))
    else:
        return render_template('login.html')
Esempio n. 60
0
 def wrapper(*args, **kwargs):
     if oauth.google.token and not oauth.google.token.get("refresh_token") \
             or not oauth.google.token:
         return redirect(url_for("home"))
     return f(*args, **kwargs)