Example #1
1
def index():
    result, data = initial_setup()
    if result is None:
        return render_template(const.HTML_ERROR)

        # print data[0][const.KEY_COMPONENT_BASIC].__dict__
    return render_template(const.HTML_INDEX, data=data)
Example #2
1
def validateLogin():
    try:
        _username = request.form["inputEmail"]
        _password = request.form["inputPassword"]

        # connect to mysql

        con = mysql.connect()
        cursor = con.cursor()
        cursor.callproc("sp_validateLogin", (_username,))
        data = cursor.fetchall()

        # Mine
        # print data[0][3]
        # print data[0][0]
        # print _password
        # print generate_password_hash(_password)
        # print check_password_hash(str(data[0][3]),_password)

        if len(data) > 0:
            if check_password_hash(str(data[0][3]), _password):
                session["user"] = data[0][0]
                return redirect("/showDashboard")
            else:
                return render_template("error.html", error="Wrong Email address or Password.")
        else:
            return render_template("error.html", error="Wrong Email address or Password.")

    except Exception as e:
        return render_template("error.html", error=str(e))
    finally:
        cursor.close()
        con.close()
Example #3
1
def addUpdateLike():
    try:
        if session.get("user"):
            _wishId = request.form["wish"]
            _like = request.form["like"]
            _user = session.get("user")

            conn = mysql.connect()
            cursor = conn.cursor()
            cursor.callproc("sp_AddUpdateLikes", (_wishId, _user, _like))
            data = cursor.fetchall()

            if len(data) is 0:
                conn.commit()
                cursor.close()
                conn.close()

                conn = mysql.connect()
                cursor = conn.cursor()
                cursor.callproc("sp_getLikeStatus", (_wishId, _user))

                result = cursor.fetchall()

                return json.dumps({"status": "OK", "total": result[0][0], "likeStatus": result[0][1]})
            else:
                return render_template("error.html", error="An error occurred!")

        else:
            return render_template("error.html", error="Unauthorized Access")
    except Exception as e:
        return render_template("error.html", error=str(e))
    finally:
        cursor.close()
        conn.close()
Example #4
1
def index():
    if current_user.is_authenticated():
        form = NoteForm()
        if form.validate_on_submit():
            note = Note(
                title=form.title.data,
                body=form.body.data,
                body_html=form.body_html.data,
                author=current_user._get_current_object(),
            )
            db.session.add(note)
            tags = []
            for tag in form.tags.data.split(","):
                tags.append(tag)
            note.str_tags = tags
            db.session.commit()
            return redirect(url_for(".index"))
        notes = Note.query.filter_by(author_id=current_user.id, is_deleted=False).order_by(Note.timestamp.desc()).all()
        return render_template("app/app.html", form=form, notes=notes)
    else:
        stats = []
        users = User.query.count()
        stats.append(users)
        notes = Note.query.count()
        stats.append(notes)
        return render_template("index.html", stats=stats)
Example #5
1
def getWishById():
    try:
        if session.get("user"):

            _id = request.form["id"]
            _user = session.get("user")

            conn = mysql.connect()
            cursor = conn.cursor()
            cursor.callproc("sp_GetWishById", (_id, _user))
            result = cursor.fetchall()

            wish = []
            wish.append(
                {
                    "Id": result[0][0],
                    "Title": result[0][1],
                    "Description": result[0][2],
                    "FilePath": result[0][3],
                    "Private": result[0][4],
                    "Done": result[0][5],
                }
            )

            return json.dumps(wish)
        else:
            return render_template("error.html", error="Unauthorized Access")
    except Exception as e:
        return render_template("error.html", error=str(e))
Example #6
1
def main_post():

    if "search" in request.form:
        search_input = request.form["search"].lower()

    if search_input == "":
        search_input = "Boston, MA"

    try:
        geolocator = Nominatim()
        location = geolocator.geocode(search_input + " USA", timeout=1000)
        input_addr = location.address
        input_lat, input_lng = location.latitude, location.longitude
        found = True
    except:
        found = False

    if found:
        input_day = time.localtime().tm_yday  # today
        location_specific_data = get_location_specific_data(input_day, input_lat, input_lng)
        return render_template(
            "index.html",
            found=True,
            showmap=False,
            input_addr=input_addr,
            input_lng=input_lng,
            input_lat=input_lat,
            input_day=input_day,
            location_specific_data=location_specific_data,
            num_tweets=get_num_tweets(),
            last_updated=get_last_updated(),
        )
    else:
        return render_template("index.html", found=False)
Example #7
0
def home():
    try:
        if request.method == "GET":
            teamname = request.cookies.get("teamname")
            if not teamname:  # not set
                return render_template("team_login.html")

            return render_template(
                "home.html",
                puzzles=puzzmgr.puzzles,
                global_point_totals=puzzmgr.get_global_point_totals(),
                teamname=teamname,
            )
        else:
            # Post

            # Get the teamname from the form post
            teamname = request.form["teamname"]
            if not teamname:  # not set
                return render_template("team_login.html")

            resp = make_response(
                render_template(
                    "home.html",
                    puzzles=puzzmgr.puzzles,
                    global_point_totals=puzzmgr.get_global_point_totals(),
                    teamname=teamname,
                )
            )
            resp.set_cookie("teamname", teamname)

            return resp

    except Exception as ex:
        return render_template("error.html", error=str(ex)), 500
Example #8
0
def oauth():
    code = request.args.get("code", "")
    state = request.args.get("state", "")

    if not code:
        return "Couldn't get a code from Slack. Something must have gone wrong"

    r = requests.post(
        app.config["SLACK_API_BASE"] + "oauth.access",
        data={
            "client_id": app.config["OAUTH_CLIENT_ID"],
            "client_secret": app.config["OATUH_CLIENT_SECRET"],
            "code": code,
        },
    )

    if r.status_code == requests.codes.ok:
        r = r.json()
        team_id = r["team_id"]
        access_token = r["access_token"]
        # Get User ID
        r = requests.post(app.config["SLACK_API_BASE"] + "auth.test", data={"token": access_token})
        r = r.json()
        db.set(r["user_id"] + "-" + team_id, access_token)
    else:
        r.raise_for_status()
        return render_template("error.html")

    return render_template("authsuccess.html")
Example #9
0
def deleteCategoryItem(category_name, item_name):
    category = app.db.query(Category).filter(Category.name == category_name).one()
    item = app.db.query(Item).filter(Item.name == item_name, Item.category_id == category.id).one()
    categories = app.db.query(Category).all()
    if request.method == "POST":
        if login_session:
            if login_session["user_id"] == item.user_id:
                app.db.delete(item)
                app.db.commit()
                flash("The item was deleted successfully!")
            else:
                flash("You are not authorized to delete this item!")
        else:
            flash("You are not authorized to delete items!")
        items = app.db.query(Item).filter(Item.category_id == category.id).all()
        return render_template(
            "categoryitems.html",
            category_name=category.name,
            items=items,
            categories=categories,
            category=category,
            login_session=login_session,
        )
    else:
        return render_template(
            "deletecategorieitemmenu.html", category_name=category_name, item=item, login_session=login_session
        )
Example #10
0
def bthash_forward(bthash=None):
    # single hash
    if bthash is not None:
        db_report = get_report(db, bthash)
        if db_report is None:
            raise abort(404)

        if len(db_report.backtraces) < 1:
            return render_template("reports/waitforit.html")

        if db_report.problem is None:
            return render_template("problems/waitforit.html")

        return redirect(url_for("problems.item", problem_id=db_report.problem.id))
    else:
        # multiple hashes as get params
        hashes = request.values.getlist("bth")
        if hashes:
            problems = (
                db.session.query(Problem)
                .join(Report)
                .join(ReportHash)
                .filter(ReportHash.hash.in_(hashes))
                .distinct(Problem.id)
                .all()
            )
            if len(problems) == 0:
                abort(404)
            elif len(problems) == 1:
                return redirect(url_for("problems.item", problem_id=problems[0].id))
            else:
                return render_template("problems/multiple_bthashes.html", problems=problems)
        else:
            abort(404)
Example #11
0
def login():
    if request.method == "POST":
        username = request.form.get("username")
        password = request.form.get("password")
        if db.check_password(username, password):
            user_id = db.get_user_id(username)
            salt = db.get_user_salt(user_id)
            session["username"] = username
            session["user_id"] = user_id
            session["key"] = db.get_user_key(user_id, password, salt)
            session["salt"] = salt
            session["time"] = int(time.time()) + (db.get_user_session_time(user_id) * 60)
            session["refresh"] = db.get_user_session_time(session["user_id"]) * 60 + 30
            session["hide_passwords"] = db.get_user_hide_passwords(user_id)
            flash("You are logged in.")
            return redirect(url_for("index"))
        else:
            flash("Incorrect username or password.")
            return render_template("login.html")
    else:
        if db.is_new():
            flash("No users have been added yet. Add the first user.")
            return redirect(url_for("new_user"))
        else:
            return render_template("login.html")
Example #12
0
def list():
    pagination = Pagination(request)

    filter_form = ProblemFilterForm(request.args)
    if filter_form.validate():
        if request_wants_json():
            p = get_problems(filter_form, pagination)
        else:
            list_table_rows, problem_count = problems_list_table_rows_cache(filter_form, pagination)

            return render_template(
                "problems/list.html",
                list_table_rows=list_table_rows,
                problem_count=problem_count,
                filter_form=filter_form,
                pagination=pagination,
            )
    else:
        p = []

    if request_wants_json():
        return jsonify(dict(problems=p))

    return render_template(
        "problems/list.html", problems=p, problem_count=len(p), filter_form=filter_form, pagination=pagination
    )
Example #13
0
 def add(model_name):
     """Create a new instance of a model."""
     if not model_name in datastore.list_model_names():
         return "%s cannot be accessed through this admin page" % (model_name)
     model_class = datastore.get_model_class(model_name)
     model_form = datastore.get_model_form(model_name)
     model_instance = model_class()
     if request.method == "GET":
         form = model_form()
         form._has_file_field = has_file_field(form)
         return render_template(
             "admin/add.html", model_names=datastore.list_model_names(), model_name=model_name, form=form
         )
     elif request.method == "POST":
         form = model_form(request.form)
         form._has_file_field = has_file_field(form)
         if form.validate():
             model_instance = datastore.update_from_form(model_instance, form)
             datastore.save_model(model_instance)
             flash("%s added: %s" % (model_name, model_instance), "success")
             return redirect(url_for(".list_view", model_name=model_name))
         else:
             flash(
                 "There was an error processing your form. This " "%s has not been saved." % model_name, "error"
             )
             return render_template(
                 "admin/add.html", model_names=datastore.list_model_names(), model_name=model_name, form=form
             )
Example #14
0
def search(query):
    results = data_search(query)
    print query
    if results:
        return render_template("index.html", notes=results, tagsinfo=get_tagsinfo())
    else:
        return render_template("not_found.html", what="search results", tagsinfo=get_tagsinfo())
Example #15
0
def index():
    if request.method == "GET":
        return render_template("index.html")
    else:
        r = request.form
        stock = r["ticker_name"]
        options = ["Close", "Adj. Close", "Open", "Adj. Open"]
        selectoptions = []
        for item in options:
            if item in r:
                selectoptions.append(item)

        with open("Quandl.json.nogit") as fh:
            secrets = json.loads(fh.read())
        api_key = secrets["api_key"]
        mydata = Quandl.get("WIKI/" + stock, authtoken=api_key)

        plot = figure(
            # tools=TOOLS,
            title="Data from Quandle WIKI set",
            x_axis_label="date",
            x_axis_type="datetime",
        )

        colorselect = dict([("Close", "blue"), ("Adj. Close", "green"), ("Open", "orange"), ("Adj. Open", "red")])
        for item in selectoptions:
            plot.line(x=mydata.index.tolist(), y=mydata[item], line_color=colorselect[item], legend=stock + ": " + item)
        # plot.legend.orientation = "top_left"

        # print(r)
        # print(selectoptions)

        script, div = components(plot)
        return render_template("graph.html", script=script, div=div, stock=stock)
Example #16
0
def create_page():
    """ Main view to present the user with a form to create a signup page. """
    form = forms.PageForm(request.form)
    error = None

    if request.method == "POST" and form.validate():

        # if password incorrect or not entered, show an error
        if not valid_password(form.password.data):
            error = "Must enter correct password."
            return render_template("main.html", form=form, error=error)

        # password was correct; render and upload the signup page
        event = models.Event(
            form.title.data, form.description.data, form.date.data, form.time.data, form.address.data, form.entry.data
        )
        page_to_upload = render_template("signup_page.html", event=event)
        bucket = settings.PRODUCTION_BUCKET if form.production.data else settings.STAGING_BUCKET
        key = clean_key(form.filename.data)
        upload(bucket, key, page_to_upload)
        url = settings.S3_URL % (bucket, key)
        return render_template("main.html", form=form, success=True, url=url)

    # if request was a GET just return the main page
    return render_template("main.html", form=form, error=error)
Example #17
0
def homework(courseid):
    cookies = request.cookies
    if "session" in cookies:
        session = cookies["session"]
        from lib import get_userid_by_session

        userid = get_userid_by_session(session)
        if userid == None:
            return redirect("/login")
        else:
            from lib import check_user_is_teacher

            isteacher = check_user_is_teacher(userid)

            from lib import check_attend_course

            res = check_attend_course(userid, courseid, isteacher)
            if res == False:
                return jsonify(res=PERMISSION_DENIED)

            if isteacher:
                return render_template("homework_teacher.html", courseid=courseid)
            else:
                return render_template("homework.html", courseid=courseid)
    else:
        return redirect("/login")
Example #18
0
def packager_info(packager):
    """ Display the information about the specified packager. """
    eol = flask.request.args.get("eol", False)

    packages_co = pkgdblib.get_package_maintained(SESSION, packager=packager, poc=False, eol=eol)

    packages = pkgdblib.get_package_maintained(SESSION, packager=packager, poc=True, eol=eol)

    packages_watch = pkgdblib.get_package_watch(SESSION, packager=packager, eol=eol)

    # Filter out from the watch list packaged where user has commit rights
    packages_obj = set([it[0] for it in packages_co])
    packages_obj = packages_obj.union(set([it[0] for it in packages]))
    packages_watch = [it for it in packages_watch if it[0] not in packages_obj]

    if not packages and not packages_co and not packages_watch:
        flask.flash("No packager of this name found.", "errors")
        return flask.render_template("msg.html")

    return flask.render_template(
        "packager.html",
        select="packagers",
        packager=packager,
        packages=packages,
        packages_co=packages_co,
        packages_watch=packages_watch,
    )
Example #19
0
def add_cs():
    """
    创建解题员和客服
    """
    if not current_user.is_authenticated():
        return redirect(url_for("general.index"))
    if current_user.type == Admin.ADMIN_TYPE.ADMIN:
        form = RegisterForm()
        if not form.validate_on_submit():
            print form.errors
            return render_template("admin/add_cs.html", form=form, nav_user_manage="active")
        try:
            if form.user_type.data == "0":
                cs = Admin(form.email.data, form.passwd.data, form.qq.data)
                ret = AdminBiz.add_CS(cs)
            else:
                solver = Admin(form.email.data, form.passwd.data, form.qq.data)
                ret = AdminBiz.add_solver(solver)
            success(ret)
        except DaixieError as e:
            fail(e)
            return render_template("admin/add_cs.html", form=form, nav_user_manage="active")
        return render_template("admin/add_cs.html", form=form, nav_user_manage="active")
    else:
        return redirect(url_for("general.index"))
Example #20
0
def xhr_sickbeard():
    params = "/?cmd=future&sort=date"

    try:
        sickbeard = sickbeard_api(params)

        compact_view = get_setting_value("sickbeard_compact") == "1"
        show_airdate = get_setting_value("sickbeard_airdate") == "1"

        if sickbeard["result"].rfind("success") >= 0:
            sickbeard = sickbeard["data"]
            for time in sickbeard:
                for episode in sickbeard[time]:
                    episode["image"] = get_pic(episode["tvdbid"], "banner")
    except:
        return render_template("sickbeard.html", sickbeard="")

    return render_template(
        "sickbeard.html",
        url=sickbeard_url_no_api(),
        sickbeard=sickbeard,
        missed=sickbeard["missed"],
        today=sickbeard["today"],
        soon=sickbeard["soon"],
        later=sickbeard["later"],
        compact_view=compact_view,
        show_airdate=show_airdate,
    )
Example #21
0
def next_departures(location):
    location_labels = {
        "templeton": "Templeton",
        "downtown": "Downtown",
        "fred_meyer": "Fred Meyer",
        "law_school": "Law School",
    }

    if location not in ["templeton", "downtown", "fred_meyer"]:
        return render_template("invalid_loc.html"), 404

    if request.is_xhr:
        # how many departures the client requested. We don't use this value
        # yet, but we will once we hook in the database.
        limit = int(request.args.get("limit", 5))

        # pull the data from the database
        schedule_model = Schedules(g.db)
        cur_schedule = schedule_model.get_schedule_for_date(date.today())

        entry_model = ScheduleEntries(g.db)
        schedule_entries = entry_model.get_entries_for_schedule_at_loc(schedule, location_labels[location])

        # TODO: actually pull this data from the database
        test_departure_data = [
            {"source": "Templeton", "destination": "Downtown", "depart_time": "2012-04-07 23:00:00"},
            {"source": "Templeton", "destination": "Downtown", "depart_time": "2012-04-07 23:05:00"},
            {"source": "Templeton", "destination": "Downtown", "depart_time": "2012-04-07 23:10:00"},
            {"source": "Templeton", "destination": "Downtown", "depart_time": "2012-04-07 23:30:00"},
            {"source": "Templeton", "destination": "Downtown", "depart_time": "2012-04-08 00:03:00"},
        ]
        return json.dumps(test_departure_data)

    else:
        return render_template("departures.html", location=location)
Example #22
0
    def test_templates_and_static(self):
        app = moduleapp
        app.testing = True
        c = app.test_client()

        rv = c.get("/")
        self.assert_equal(rv.data, b"Hello from the Frontend")
        rv = c.get("/admin/")
        self.assert_equal(rv.data, b"Hello from the Admin")
        rv = c.get("/admin/index2")
        self.assert_equal(rv.data, b"Hello from the Admin")
        rv = c.get("/admin/static/test.txt")
        self.assert_equal(rv.data.strip(), b"Admin File")
        rv.close()
        rv = c.get("/admin/static/css/test.css")
        self.assert_equal(rv.data.strip(), b"/* nested file */")
        rv.close()

        with app.test_request_context():
            self.assert_equal(flask.url_for("admin.static", filename="test.txt"), "/admin/static/test.txt")

        with app.test_request_context():
            try:
                flask.render_template("missing.html")
            except TemplateNotFound as e:
                self.assert_equal(e.name, "missing.html")
            else:
                self.assert_true(0, "expected exception")

        with flask.Flask(__name__).test_request_context():
            self.assert_equal(flask.render_template("nested/nested.txt"), "I'm nested")
Example #23
0
def getAllWishes():
    try:
        if session.get("user"):
            _user = session.get("user")
            conn = mysql.connect()
            cursor = conn.cursor()
            cursor.callproc("sp_GetAllWishes", (_user,))
            result = cursor.fetchall()

            wishes_dict = []
            for wish in result:
                wish_dict = {
                    "Id": wish[0],
                    "Title": wish[1],
                    "Description": wish[2],
                    "FilePath": wish[3],
                    "Like": wish[4],
                    "HasLiked": wish[5],
                }
                wishes_dict.append(wish_dict)

            return json.dumps(wishes_dict)
        else:
            return render_template("error.html", error="Unauthorized Access")
    except Exception as e:
        return render_template("error.html", error=str(e))
Example #24
0
def do_post():
    post = {}
    errors = []
    field_map = [
        ("author", u"Не указано имя!"),
        ("email", u"Не указан E-Mail"),
        ("topic", u"Не указана тема сообщения"),
        ("content", u"Отправлено пустое сообщение"),
    ]

    for field in field_map:
        post[field[0]] = flask.request.form.get(field[0], "")
        if post[field[0]] == "":
            errors.append(field[1])

    if not email_regex.match(post["email"]) and post["email"]:
        errors.append(u"Неверный e-mail")

    if errors != []:
        return flask.render_template("error.html", errors=errors)

    with open("%s/log.json" % PATH, "a") as f:
        f.writelines([json.dumps(post, encoding="utf-8")])

    #  try:
    #       post_mail(post)
    # except:
    #   pass

    return flask.render_template("ok.html", name=post["author"])
Example #25
0
def getWish():
    try:
        if session.get("user"):
            _user = session.get("user")
            _limit = pageLimit
            _offset = request.form["offset"]
            _total_records = 0

            con = mysql.connect()
            cursor = con.cursor()
            cursor.callproc("sp_GetWishByUser", (_user, _limit, _offset, _total_records))

            wishes = cursor.fetchall()
            cursor.close()

            cursor = con.cursor()

            cursor.execute("SELECT @_sp_GetWishByUser_3")

            outParam = cursor.fetchall()

            response = []
            wishes_dict = []
            for wish in wishes:
                wish_dict = {"Id": wish[0], "Title": wish[1], "Description": wish[2], "Date": wish[4]}
                wishes_dict.append(wish_dict)
            response.append(wishes_dict)
            response.append({"total": outParam[0][0]})
            print ({"total": outParam[0][0]})
            return json.dumps(response)
        else:
            return render_template("error.html", error="Unauthorized Access")
    except Exception as e:
        return render_template("error.html", error=str(e))
Example #26
0
def consensi():
    form = ConsensiForm()

    if request.method == "GET":
        show_intro = True
        return render_template(
            "consensi.html",
            title="Consensus sequences",
            section_name="Consensus sequences",
            form=form,
            show_intro=show_intro,
        )

    if not form.validate_on_submit():
        show_intro = False
        flash("Select one region and one patient!")
        return render_template(
            "consensi.html",
            title="Consensus sequences",
            section_name="Consensus sequences",
            form=form,
            show_intro=show_intro,
        )

    pname = form.patient.data
    region = form.region.data
    return redirect("/download/consensi/" + pname + "_" + region + ".fasta")
Example #27
0
def temp():
    if request.method == "POST":
        print request.data
        result = json.loads(request.data)
        print result
        print result["email"]
        print result["password"]
        return render_template("chartj.html")
        # return redirect('/')
    else:

        con = mysql.connect()
        cursor = con.cursor()
        # cursor.callproc('sp_temp')
        cursor.execute(
            """
				SELECT wish_id, wish_title 
				FROM tbl_wish
				"""
        )
        datas = cursor.fetchall()

        objects_list = []
        for row in datas:
            d = collections.OrderedDict()
            d["id"] = row[0]
            d["Title"] = row[1]
            objects_list.append(d)
        j = json.dumps(objects_list)
        # return json.dumps(response)
        # return render_template('c.html', datas=json.dumps(objects_list))
        return render_template("AngularJsTutorial.html", datas=json.dumps(objects_list))
        cursor.close()
        con.close()
Example #28
0
def user_groups(username):

    admin, message = check_user_is_admin(request.environ.get("REMOTE_USER"))
    if not admin:
        # User is not admin or admin group does exist. Ciao
        return render_template("message.html", message=message)

    with htpasswd.Basic(CONF["PWD_FILE"], mode="md5") as userdb:
        with htpasswd.Group(CONF["GROUP_FILE"]) as groupdb:
            if request.method == "GET":
                groups = dict()
                for group in groupdb.groups:
                    if groupdb.is_user_in(username, group):
                        groups[group] = True
                    else:
                        groups[group] = False
                return render_template("groups.html", groups=groups)
            else:
                # POST Request
                print request.form.items()
                checked_groups = [g.split("_", 1)[1] for g in request.form.keys() if g.startswith("group_")]
                print checked_groups
                for group in groupdb.groups:
                    if group in checked_groups:
                        if not groupdb.is_user_in(username, group):
                            print "add user to group %s" % group
                            groupdb.add_user(username, group)
                    else:
                        if groupdb.is_user_in(username, group):
                            print "remove user from group %s" % group
                            groupdb.delete_user(username, group)
                return render_template("message.html", message="User groups changed", success=True)
Example #29
0
def gdisconnect():
    access_token = login_session["access_token"]
    print "In gdisconnect access token is %s", access_token
    print "User name is: "
    print login_session["username"]
    if access_token is None:
        print "Access Token is None"
        response = make_response(json.dumps("Current user not connected."), 401)
        response.headers["Content-Type"] = "application/json"
        return response
    url = "https://accounts.google.com/o/oauth2/revoke?token=%s" % login_session["access_token"]
    h = httplib2.Http()
    result = h.request(url, "GET")[0]
    print "result is "
    print result
    if result["status"] == "200":
        del login_session["access_token"]
        del login_session["gplus_id"]
        del login_session["username"]
        del login_session["email"]
        del login_session["picture"]
        response = "Successfully disconnected."
        return render_template("logout.html", response=response)
    else:
        response = "Failed to revoke token for given user."
        return render_template("logout.html", response=response)
Example #30
0
def index():
    if "username" in session:
        user_id = session["user_id"]
        models = IATIModel.query.filter_by(model_owner=unicode(user_id))
        if "admin" in session:

            class FakeUser(object):
                def __init__(self, id, username):
                    self.id = id
                    self.username = username

            all_users = [FakeUser("0", "Master admin user")] + User.query.all() + [FakeUser("-1", "Deleted models")]
            all_models = []
            for user in all_users:
                this_user_data = []
                x = "1"
                user_models = IATIModel.query.filter_by(model_owner=unicode(user.id))
                this_user_data = dict({"user_id": user.id, "username": user.username, "user_models": user_models})
                all_models.append(this_user_data)
        else:
            all_models = ""
            all_users = ""
        return render_template(
            "dashboard.html",
            username=username(),
            user_id=escape(session["user_id"]),
            user_name=user_name(),
            admin=is_admin(),
            logged_in=is_logged_in(),
            models=all_models,
            users=all_users,
            user_models=models,
        )
    return render_template("form.html")