Exemplo n.º 1
0
def signin():
    ''' Save username on a Flask session after user submit the sign in form '''

    # Forget any username
    session.clear()

    username = request.form.get("username")

    if request.method == "POST":

        # Ensure username was submitted
        if not username:
            return error("Missing username", 400)
        # Check if username already exists
        if username in usersLogged:
            return error("Username already taken.", 400)

        usersLogged.append(username)

        session['username'] = username

        # Redirect user to home page
        return redirect("/")
    else:
        return render_template("signin.html")
Exemplo n.º 2
0
def login():
    # Forget any user_id
    session.clear()
    with sqlite3.connect("finance.db", check_same_thread=False) as con:
        db = con.cursor()
        if request.method == "POST":
            # Ensure username was submitted
            if not request.form.get("username"):
                return error("must provide username", 403)
            # Ensure password was submitted
            elif not request.form.get("password"):
                return error("must provide password", 403)
            # Query database for username
            db.execute("SELECT * FROM users WHERE username = :username",
                       dict(username=request.form.get("username")))
            rows = db.fetchall()
            # Ensure username exists and password is correct
            if len(rows) != 1 or not check_password_hash(
                    rows[0][5], request.form.get("password")):
                return error("invalid username or password", 403)
            # Remember which user has logged in
            session["user_id"] = rows[0][0]
            # Redirect user to index page
            return redirect("/")
        else:
            return render_template("login.html")
Exemplo n.º 3
0
def create():
    ''' Create new channel after user is logged in. '''

    newChannel = request.form.get("newChannel")

    if request.method == "POST":

        # Ensure channel name is submitted
        if not newChannel:
            return error("Missing channel name.", 400)

        if newChannel in channel_list:
            return error("Channel already exists.", 400)

        channel_list.append(newChannel)
        session['current_channel'] = newChannel

        # Add channel to a global dict of channels with messages. Every channel is a deque with maxlen of 100.
        # Once length of deque reach 100, when new items are added, a corresponding number of items are discarded from the opposite end.
        # https://docs.python.org/3/library/collections.html#collections.deque
        channelsMessages[newChannel] = deque(maxlen=100)

        # Redirect user to channel page
        return redirect(url_for('channel', curChannel=newChannel))

    else:
        return redirect("/")
Exemplo n.º 4
0
def register():
    # loads register page if the method is get
    if request.method == "GET":
        return render_template("register.html")
    else:
        # connect the finance database and set the cursor as "db"
        with sqlite3.connect("finance.db", check_same_thread=False) as con:
            db = con.cursor()
            username = request.form.get("username")
            name = request.form.get("name")
            email = request.form.get("email")
            if not username:
                return error("You must provide a username", 403)
            elif not name:
                return error("You must provide your Name", 403)
            elif not email:
                return error("You must provide your email", 403)
            db.execute("SELECT username FROM users WHERE username = :username",
                       dict(username=username))
            if db.fetchall() == username:
                return error("Username is taken, select another", 403)
            else:
                hash = generate_password_hash(request.form.get("password"))
                db.execute(
                    "INSERT INTO users (username, name, email, hash) VALUES (?, ?, ?, ?)",
                    (username, name, email, hash))
                con.commit()
                return redirect("/login")
Exemplo n.º 5
0
def create():

    data = requestJSON(request)

    if not all(param in data for param in ("email", "password")):
        return error(1, 'Missing email/password.')

    email = data['email']

    if not emailIsValid(email):
        return error(2, 'Invalid e-mail.')

    password = data['password']

    if not passwordIsValid(password):
        return error(3, 'Invalid password')

    accountToken = encodeJWT({
        'email': email,
        'password': password
    }, JWT_SECRET_KEY)

    try:

        newAccount = Account(email, accountToken)

        db.session.add(newAccount)
        db.session.commit()

        return success()

    except IntegrityError:

        return error(4, 'E-mail already in use.')
Exemplo n.º 6
0
def marketoffer():
    if request.method == "POST":

        cId = session["user_id"]

        connection = sqlite3.connect('affo/aao.db')
        db = connection.cursor()

        resource = request.form.get("resource")
        amount = request.form.get("amount")
        price = request.form.get("price")

        if amount.isnumeric() == False or price.isnumeric() == False:
            return error(400, "You can only type numeric values into /marketoffer ")

        if int(amount) < 1:
            return error(400, "Amount must be greater than 0")

        rStatement = f"SELECT {resource} FROM resources WHERE id=(?)" # possible sql injection posibility TODO: look into thi
        realAmount = db.execute(rStatement, (cId,)).fetchone()[0]  #TODO: fix this not working

        if int(amount) > int(realAmount):
            return error("400", "Selling amount is higher than actual amount You have.")

        db.execute("INSERT INTO offers (user_id, resource, amount, price) VALUES (?, ?, ?, ?)", (cId, resource, int(amount), int(price)))

        connection.commit()
        return redirect("/market")
    else:
        return render_template("marketoffer.html")
Exemplo n.º 7
0
def create_project(location, name,  executable=False):
    """
    Creates a project folder given a env new_dir
    """
    new_dir = "{}/{}".format(location, name)
    
    if os.path.exists(new_dir):
        error("Folder {} already exists!".format(name))
        sys.exit(1)
    # Make boilerplate files
    try:
        os.mkdir(new_dir)
        os.mkdir(new_dir + "/.carpet/")
        os.chdir(new_dir)
        open("__init__.py", "a").close()
        open("Carpet.toml", "a").close()
        _repo = git.Repo.init(path=new_dir)
        config.build_default_config(new_dir, name=name)
        
        # If the project is meant to be executable,
        # add a __main__.py 
        if executable:
            main = open("__main__.py", "a")
            main.write("print('Hello World')")
            main.close()
        else:
            config.set_config(new_dir, "package/executable", False)
        
        virtualenv.create_environment(new_dir + "/.carpet/env")
    except Exception as e:
        shutil.rmtree(new_dir)
        colour("FAIL", "Failed to create project")
        echo("Have you checked your permissions?")

    colour("BLUE", "Created new project!")
Exemplo n.º 8
0
    def simulation(self):

        # report config
        self.config.report()

        # query for progress
        helpers.query('Continue?')

        # check for consistency
        if self.params.restart and self.params.proceed:
            helpers.error(
                'Both \'-r\' (--restart) and \'-p\' (--proceed) were specified.',
                advice='Use either of the options, not both.')

        # report scheduler
        self.config.scheduler.report()

        # initial phase
        if self.params.restart:
            self.init()

        # proceed with the existing simulation (no modification in setup)
        if self.params.proceed:
            self.proceed()

        # recursive updating phase
        self.update()

        # query for progress
        helpers.query('Quit simulation?')
Exemplo n.º 9
0
def login():
    """ Log user in """
    session.clear()
    # Login form post request
    if request.method == "POST":
        # Ensure username, password were received
        try:
            username = request.form.get("username")
            password = request.form.get("hash")
        except ValueError:
            return error("must provide username and password", 403)

        # Validate credentials
        rows = db.execute("SELECT * FROM users WHERE username = :username",
                          {'username': username}).fetchone()
        if rows is None or not check_password_hash(rows["hash"], password):
            return error("invalid username and/or password", 403)

        # Remember which user has logged in
        session["user_id"] = rows["id"]

        # Render home page
        return redirect("/")

    # GET request
    else:
        return render_template("login.html")
Exemplo n.º 10
0
def changeusername():

    if request.method == "POST":
        # Check all fields are filled
        if not request.form.get("newusername"):
            return error("Please introduce your new username.")
        elif not request.form.get("currentpassword"):
            return error("Please introduce your password.")

        # Check old password is correct
        rows = db.execute("SELECT * FROM users WHERE user_id = :user_id",
                          user_id=session["user_id"])

        if check_password_hash(rows[0]["hash"],
                               request.form.get("currentpassword")):
            username = request.form.get("newusername")
            db.execute(
                "UPDATE users SET username = :username WHERE user_id = :user_id",
                username=username,
                user_id=session["user_id"])
        else:
            return error("Password is not correct.")

        # Redirect to homepage after changing password
        success_msg = "Username changed. You shall be " + username + " from now on."
        return success(success_msg)

    else:
        return render_template("editaccount.html")
Exemplo n.º 11
0
def login():
    # Log user in

    # Forget any user_id
    session.clear()

    if request.method == "POST":
        # Ensure username was submitted
        if not request.form.get("username"):
            return error("Username not provided", 403)

        # Ensure password was submitted
        elif not request.form.get("password"):
            return error("Password not provided", 403)

        # Query database for username
        rows = db.execute("SELECT * FROM users WHERE username = :username",
                          username=request.form.get("username"))

        # Ensure username exists and password is correct
        if len(rows) != 1 or not check_password_hash(
                rows[0]["hash"], request.form.get("password")):
            return error("Invalid username and/or password", 403)

        # Remember which user has logged in
        session["user_id"] = rows[0]["id"]

        # Redirect user to home page
        session["loginconfirm_show"] = True
        return redirect("/")

    else:
        return render_template("login.html", login_active="active")
Exemplo n.º 12
0
def expenses():
    # Reached page through GET (Clicking a link or redirect)
    if request.method == "GET":
        return render_template("expenses.html")
    # Else if page is reached route through POST (submitting a form)
    else:
        # Get information from form
        Amount = int(request.form.get("amount"))
        Expense = request.form.get("expense")
        Date = request.form.get("date")
        # Return error if negative number
        if Amount <= 0:
            return error(Amount)
        else:
            # Select cash from SQL
            cashs = db.execute("SELECT cash FROM cash WHERE 1")
            for cash in cashs:
                cash = cash['cash']
            # Return error if amount is greater than current cash
            if cash < Amount:
                return error(Amount)
            elif cash >= Amount:
                # Add transaction to expense history
                db.execute(
                    "INSERT INTO expenses (Amount, Expense, Date) VALUES \
                (:Amount, :Expense, :Date)",
                    Expense=Expense,
                    Amount=Amount,
                    Date=Date)
                # Update cash, subtracting cash from transaction
                db.execute("UPDATE cash SET Cash = Cash - :Amount",
                           Amount=Amount)
        # Redirect to homepage
        return redirect(url_for("homepage"))
Exemplo n.º 13
0
def changepassword():

    if request.method == "POST":
        # Check all fields are filled
        if not request.form.get("currentpassword"):
            return error("Please introduce your current password.")
        elif not request.form.get("newpassword"):
            return error("Please introduce your new password.")
        elif not request.form.get("confirmation"):
            return error(
                "Please introduce the confirmation of your new password.")
        elif request.form.get("newpassword") != request.form.get(
                "confirmation"):
            return error("New passwords don't match. Try again.")

        # Check old password is correct
        rows = db.execute("SELECT * FROM users WHERE user_id = :user_id",
                          user_id=session["user_id"])

        if check_password_hash(rows[0]["hash"],
                               request.form.get("currentpassword")):
            hash = generate_password_hash(request.form.get("newpassword"))
            db.execute(
                "UPDATE users SET hash = :hash WHERE user_id = :user_id",
                hash=hash,
                user_id=session["user_id"])
        else:
            return error("Current password is not correct.")

        # Redirect to homepage after changing password
        return success("Password changed successfully.")

    else:
        return render_template("editaccount.html")
Exemplo n.º 14
0
def search():
    # Display search results
    userid = session.get("user_id")
    content = dict()

    # Get query
    content["query"] = request.args.get("en")

    # If user manually visits "/search"
    if content["query"] is None:
        return error("Page not found", 404)

    # Too long query
    if len(content["query"]) > 45:
        return error("This search query is too long", 400)
    content["results"] = search_word("en", content["query"], userid, db)

    # No results on query
    if not content["results"]:
        return render_template("results.html",
                               found_results=False,
                               content=content)

    # Found results on query
    content["total"] = len(content["results"])
    return render_template("results.html", found_results=True, content=content)
Exemplo n.º 15
0
    def data(self,id,filename=None,size=None):
        """ returns the data for the media, only if your authed
            to view the media """
        cherrypy.log('getting media data: %s' % id)
        try:
            media = m.Media.get(id)
            if not media:
                raise cherrypy.HTTPError(404)
            if not filename:
                filename = media.get_safe_title()
            if size:
                data = media.create_thumbnail(size)
                m.session.commit()
            else:
                data = media.get_data()

            if not data:
                error(404)

            ext = media.extension.lower() if media.extension else None
            content_type = mimetypes.types_map.get(ext,None)
            cherrypy.response.headers['Content-Type'] = content_type or 'image/jpg'

            return data
        except Exception:
            raise
            error(404)
Exemplo n.º 16
0
def login():

    if request.method == "POST":

        connection = sqlite3.connect('affo/aao.db') # connects to db
        db = connection.cursor() # creates the cursor for db connection

        password = request.form.get("password") # gets the password input from the form
        username = request.form.get("username") # gets the username input from the forms

        if not username or not password: # checks if inputs are blank
            return error(400, "No Password or Username")

        user = db.execute("SELECT * FROM users WHERE username = (?)", (username,)).fetchone() # selects data about user, from users
        connection.commit()

        if user is not None and check_password_hash(user[3], password): # checks if user exists and if the password is correct
            session["user_id"] = user[0] # sets session's user_id to current user's id
            session["logged_in"] = True
            print('User has succesfully logged in.')
            connection.commit()
            connection.close()
            return redirect("/") # redirects user to homepage

        return error(403, "Wrong password")

    else:
        return render_template("login.html") # renders login.html when "/login" is acessed via get
Exemplo n.º 17
0
def book(isbn):
    """ Display book page """

    # get book's rating
    rating = get_book_data("bBypFUkpDHox5Z5fjzJqg", isbn)

    # get book info
    try:
        query = "SELECT * FROM books WHERE isbn = :isbn;"
        book = db.execute(query, {"isbn": isbn})
    except:
        error("Book not found", 404)

    # get review data
    q_reviews = "SELECT * FROM reviews WHERE isbn = :isbn LIMIT 10;"
    reviews = db.execute(q_reviews, {"isbn": isbn})

    # check if book have any review
    if reviews.rowcount == 0:
        return render_template("book.html",
                               book=book.fetchone(),
                               rating=rating,
                               display_review=False,
                               reviews=reviews.fetchall())

    return render_template("book.html",
                           book=book.fetchone(),
                           rating=rating,
                           display_review=True,
                           reviews=reviews.fetchall())
Exemplo n.º 18
0
def add():

    if request.method == "POST":
        # Check all fields are filled
        if not request.form.get("placename"):
            return error("Please add name of the place.")
        elif not request.form.get("latitude"):
            return error("Please add latitude of the place.")
        elif not request.form.get("longitude"):
            return error("Please add longitude of the place.")
        elif not request.form.get("country"):
            return error("Please add country of the place.")

        # Store new place into users database
        placeKeyId = db.execute(
            "INSERT INTO places (placename, latitude, longitude, register_user_id, country, ratings_avg, ratings_num) VALUES (:placename, :latitude, :longitude, :user_id, :country, :ratings_avg, :ratings_num)",
            placename=request.form.get("placename"),
            latitude=request.form.get("latitude"),
            longitude=request.form.get("longitude"),
            user_id=session["user_id"],
            country=request.form.get("country"),
            ratings_avg=0,
            ratings_num=0)

        if request.form.get("description"):
            db.execute(
                "UPDATE places SET description = :description WHERE placename = :placename",
                description=request.form.get("description"),
                placename=request.form.get("placename"))

        return success("Place added successfully.")

    else:
        return render_template("add.html")
Exemplo n.º 19
0
def login():

    # Forget any user_id
    session.clear()

    if request.method == "POST":

        # Check all fields are filled
        if not request.form.get("username"):
            return error("Please insert a username.")
        elif not request.form.get("password"):
            return error("Please insert a password.")

        # Query users database for user_id info
        rows = db.execute("SELECT * FROM users WHERE username = :username",
                          username=request.form.get("username"))

        # Check password is correct
        if len(rows) != 1 or not check_password_hash(
                rows[0]["hash"], request.form.get("password")):
            return error("Invalid username and/or password.")

        # Remember which user has logged in
        session["user_id"] = rows[0]["user_id"]

        # Redirect user to homepage
        return redirect("/")

    else:
        # Return to login page
        return render_template("login.html")
Exemplo n.º 20
0
def login():
    """ Log in the User """

    # Forget any user_id
    session.pop("user_id", None)

    # user reached the route via POST (as by submitting the form)
    if request.method == 'POST':
        # return an error message if userlogin field is empty
        if not request.form.get("userlogin"):
            return error(message="Missing Username or Email")
        # return an error message if password field is empty
        if not request.form.get("password"):
            return error(message="Missing Password")

        # query the database to check if the username or email is correct
        tmp_user = db.execute(
            "SELECT * FROM users WHERE username = :username or email = :email",
            {
                "username": request.form.get("userlogin"),
                "email": request.form.get("userlogin")
            }).fetchone()

        # return an error if the userlogin does not exist or the password isn't correct
        if not tmp_user or not check_password_hash(
                tmp_user["password_hash"], request.form.get("password")):
            return error(message="Login info or Password are wrong")

        # log in the user
        session["user_id"] = tmp_user["user_id"]
        flash("Welcome Back, " + tmp_user["username"])
        return redirect(url_for('index'))

    # user reached the route via GET
    return render_template("login.html")
Exemplo n.º 21
0
def register():

    # Determine if page request via 'POST' method
    if request.method == 'POST':

        # Store the form information in a variable (data is ImmutableMultiDict type)
        regi_info = request.form

        # Query database for existing username (using placeholder and tupple holding the argument)
        users_info_fetch = db.execute(
            'SELECT * FROM users WHERE usrs_user_nm = ?',
            (regi_info['user_nm'], )).fetchall()

        print('user name:', users_info_fetch)
        # Check if username already exists
        if not len(users_info_fetch) == 0:
            return error('User name exists', 403)

        # Check if passwords match
        if regi_info['pw'] != regi_info['pw_conf']:
            return error('Password do not match',
                         403)  ### NEED TO IMPLEMENT APLOGY PAGE ###

        ### TEST CODE - DELETE WHEN DONE ###
        for item in regi_info:
            print(item, ': ', regi_info[item])

        # Get a hash value of the password to store in the database
        pw_hash = generate_password_hash(regi_info['pw'])

        # Insert registration information into the 'users' table
        db.execute('INSERT INTO users (usrs_user_nm, usrs_pw_hash, usrs_first_nm, usrs_middle_nm, usrs_last_nm, usrs_address, usrs_phone, usrs_email) \
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?)'                                                    , \
                    (regi_info['user_nm'], pw_hash, regi_info['first_nm'], regi_info['middle_nm'], regi_info['last_nm'], regi_info['address'], regi_info['phone'], regi_info['email']))

        # Get user_id for new user
        user_id_new = db.execute(
            'SELECT usrs_id FROM users WHERE usrs_user_nm = ?',
            (regi_info['user_nm'], )).fetchall()

        # Update password to password history
        db.execute(
            'INSERT INTO password_hist (pw_hist_pw_hash, pw_hist_usrs_id) \
                    VALUES (?, ?)', (pw_hash, user_id_new[0][0]))

        # Save changes to sqlite database
        conn.commit()

        # Close connection to sqlite database
        #conn.close()

        return redirect('/')

    else:

        # Forget current user id
        session.clear()

        return render_template('register.html')
Exemplo n.º 22
0
 def decorated_function(*args, **kwargs):
     mu_session_id = request.headers["MU-SESSION-ID"]
     try:
         ensure_signinghub_session(mu_session_id)
         return f(*args, **kwargs)
     except AuthenticationException as ex:
         return error(ex.error_description, code="digital-signing.signinghub.{}".format(ex.error_id))
     except NoQueryResultsException as ex:
         return error(ex.args[0])
Exemplo n.º 23
0
def profile():

    # Determine if page request via 'POST' method
    if request.method == 'POST':

        profile_updt_info = request.form
        print('Test: ', profile_updt_info)

        if not profile_updt_info['pw']:
            return error('No password provided', 403)

        if not profile_updt_info['pw_conf']:
            return error('No password confirmation provided', 403)

        if profile_updt_info['pw'] != profile_updt_info['pw_conf']:
            return error('Passwords do not match', 403)

        pw_hash_new = generate_password_hash(profile_updt_info['pw'])

        db.execute(
            'INSERT INTO password_hist (pw_hist_pw_hash, pw_hist_usrs_id) \
                    VALUES (?, ?)', (pw_hash_new, session['user_id']))

        print('passed insert')

        # Save changes to sqlite database
        conn.commit()

        # Close connection to sqlite database
        #conn.close()

        return redirect('/profile')

    else:
        # Query the database for user profile information
        user_profile_info = db.execute('SELECT * FROM users WHERE usrs_id = ?',
                                       (session['user_id'], )).fetchall()

        # Check if user informtion exists
        if len(user_profile_info) == 0:
            return error('No users profile information found', 403)

        # Check if multiple users exits with the same information
        if len(user_profile_info) > 1:
            return error('Multiple user profiles found', 403)

        return render_template('profile.html',
                               user_nm=user_profile_info[0][1],
                               pw='*' * 10,
                               first_nm=user_profile_info[0][3],
                               middle_nm=user_profile_info[0][4],
                               last_nm=user_profile_info[0][5],
                               address=user_profile_info[0][6],
                               phone=user_profile_info[0][7],
                               email=user_profile_info[0][8])
Exemplo n.º 24
0
 def check (self, level, type, sample):
   directory = self.directory (level, type, sample)
   if not self.deterministic:
     present = os.path.exists (directory)
   else:
     label = self.label (level, type, sample)
     present = os.path.exists ( os.path.join (directory, self.jobfile % label) )
   if present:
     message = 'working directory is NOT clean!'
     details = 'Remove all directories like "%s"' % directory
     advice  = 'Alternatively, run PyMLMC with \'-o\' option to override or with \'-p\' option to proceed with simulations'
     helpers.error (message, details, advice)
Exemplo n.º 25
0
def new_word():
    # Adding (admin) or suggesting (regular user) new word
    userid = session.get("user_id")
    content = dict()

    if request.method == "POST":
        suhistdict = request.form.get("suhistdict")
        en = request.form.get("en").lower()
        bg = request.form.get("bg").lower()
        anbul = request.form.get("anbul")
        """Ensure a valid form was sent"""
        # Ensure none of the fields were empty
        if not (suhistdict and en and bg and anbul):
            return error("One or more of the fields have not been filled")

        # Ensure the link to SU dictionary is valid
        if not "histdict.uni-sofia.bg" in suhistdict:
            return error(
                'The link to SU dictionary entry is not valid (hint: the field should contain "histdict.uni-sofia.bg"). Feel free to copy-paste this (without the quotes) if you are just testing the website.'
            )

        # Ensure English field contains only Latin letters
        if not (only_lat_letters(en)):
            return error(
                'Only Latin (English) letters allowed in the English field.')

        # Ensure Bulgarian field contains only Cyrillic letters
        if not (only_cyr_letters(bg)):
            return error(
                '"Български (Bulgarian)" field (third one) should contain only (modern) Bulgarian /Cyrillic/ characters. Just want to test the website? Copy-paste "тест" (test in Bulgarian) in the field!'
            )

        # Ensure Ancient Bulgarian field contains only Ancient Bulgarian letters
        if not (only_anbul_letters(anbul)):
            return error(
                'Only Ancient Bulgarian letters allowed in the last field. Just want to test the website? Input random letters from the provided keyboard.'
            )
        """If all checks passed, add the new word to the database"""
        new_word_id = add_new_word(suhistdict, en, bg, anbul, userid, db)

        return redirect(url_for('.word', id=new_word_id))

    else:
        # If user is admin, use verb "Add";
        # otherwise, use verb "Suggest"
        if userid == 1:
            content["action"] = "Add"
        else:
            content["action"] = "Suggest"
        return render_template("new.html",
                               new_active="active",
                               content=content)
Exemplo n.º 26
0
def register():
    """Register user"""

    # Forget any user_id
    session.clear()

    # User reached route via POST (as by submitting a form via POST)
    if request.method == "POST":

        # Ensure username was submitted
        if not request.form.get("username"):
            return error("Missing username", 400)

        # Ensure password was submitted
        elif not request.form.get("password"):
            return error("Missing password", 400)

    # Ensure password confirmation was submitted
        elif not request.form.get("confirmation"):
            return error("Missing password confirmation", 400)

        # Ensure that password and password confirmation match
        if request.form.get("password") != request.form.get("confirmation"):
            return error("passwords do not match.", 400)

        # Generate hashed password
        hash = generate_password_hash(request.form.get("password"),
                                      method='pbkdf2:sha256',
                                      salt_length=8)

        # Insert user into database.
        db.execute(
            "INSERT INTO users (username, hash) VALUES (:username, :hash)", {
                "username": request.form.get("username"),
                "hash": hash
            })
        db.commit()
        result_id = db.execute(
            "SELECT id FROM users WHERE username = :username", {
                "username": request.form.get("username")
            }).fetchone()

        # Remember which user has logged in
        session["user_id"] = result_id[0]

        flash('Successfully registered!')
        # Redirect user to home page
        return redirect("/")

    # User reached route via GET (as by clicking a link or via redirect)
    else:
        return render_template("register.html")
Exemplo n.º 27
0
 def decorated_function(*args, **kwargs):
     try:
         ensure_signinghub_machine_user_session()
         return f(*args, **kwargs)
     except AuthenticationException as ex:
         logger.exception("Authentication Error")
         return error(ex.error_description, code="digital-signing.signinghub.{}".format(ex.error_id))
     except NoQueryResultsException as ex:
         logger.exception("No Query Results Error")
         return error(ex.args[0])
     except BaseException as ex:
         logger.exception("Internal Server Error")
         return error("Internal Server Error", 500)
Exemplo n.º 28
0
def book(isbn):
    #Identify current User
    currUser = db.execute("SELECT name FROM users WHERE id = :id", {
        "id": session["user_id"]
    }).fetchall()
    currUser = currUser[0]["name"]
    goodread = goodreads(isbn)
    #get book data
    res = db.execute("SELECT * FROM books WHERE isbn = :isbn", {
        "isbn": isbn
    }).fetchall()
    if res == []:
        return error("Book page not found")
    #get all reviews and check if current user provided review
    userrev = rev = db.execute(
        "SELECT rating, comment FROM userreviews \
    WHERE userid = :id AND bookisbn = :isbn", {
            "id": session["user_id"],
            "isbn": res[0]["isbn"]
        }).fetchall()
    allrev = db.execute(
        "SELECT rating, comment, usname FROM userreviews \
    WHERE bookisbn = :isbn", {
            "isbn": res[0]["isbn"]
        }).fetchall()
    #boolean condition for dynamic html, false when no review was submitted by user
    checkrev = False
    # If user already has submitted a review, change boolean so no form will be displayed
    if userrev != []:
        checkrev = True

    #if book review was submitted
    if request.method == "POST":
        rating = request.form.get("rating") or None
        comment = request.form.get("comment") or None
        if rating == None or comment == None:
            return error("No review provided")
        rating = int(rating)
        if userrev == []:
            db.execute("INSERT INTO userreviews (rating, comment, bookisbn, userid, usname)\
            VALUES (:rating, :comment, :bookisbn, :userid, :usname)"                                                                    , \
            {"rating": rating, "comment": comment, "bookisbn": res[0]["isbn"], "userid": session["user_id"], "usname": currUser})
            db.commit()
            checkrev = True
            return book(isbn)
    return render_template("book.html",
                           result=res,
                           checkrev=checkrev,
                           rev=userrev,
                           allrev=allrev,
                           goodread=goodread)
Exemplo n.º 29
0
def exsearch():
    # More advanced search queries
    userid = session.get("user_id")
    content = dict()

    # On extended search form submission
    if request.method == "POST":
        lang = request.form.get("lang")
        method = request.form.get("method")
        term = request.form.get("term")
        all_words = bool(request.form.get("all_words"))

        if not lang:
            return error("Please select a language")

        if method == "contains":
            content["query"] = term
            if lang == "en" and not all_words:  # this is the standard search
                return redirect(url_for('.search', en=term))
            else:
                content["results"] = search_word(lang,
                                                 term,
                                                 userid,
                                                 db,
                                                 all_words=all_words)

        else:
            content["query"] = term + " (exact)"
            content["results"] = search_word(lang,
                                             term,
                                             userid,
                                             db,
                                             contains=False,
                                             all_words=all_words)

        # No results on query
        if not content["results"]:
            return render_template("results.html",
                                   found_results=False,
                                   content=content)

        # Found results on query
        content["total"] = len(content["results"])
        return render_template("results.html",
                               found_results=True,
                               content=content)

        return error("TODO")

    else:
        return render_template("exsearch.html", exsearch_active="active")
Exemplo n.º 30
0
def check_active_login(skip=False,login=True):
    """
    checks that there is an active user or sends back a 403
    """

    cherrypy.log('checking active login %s %s' % (skip,login))

    try:
        if skip:
            return True


        # make sure there is a handle
        if not cherrypy.session.get('user_handle'):
            error(403)

        # make sure there's a hash in the session
        if not cherrypy.session.get('user_hash'):
            error(403)

        # find the user and check the hash against his password
        user = m.User.get_by(handle=cherrypy.session.get('user_handle'))
        if not user:
            error(403)
        if hash_password(user.password) != cherrypy.session.get('user_hash'):
            error(403)

    except HTTPError:
        if login:
            redirect('/login')
        else:
            raise

    return user
Exemplo n.º 31
0
def posts(postid):
    """ Show a post content or submit a comment """

    # user reached the route via POST (by submitting the comment form)
    if request.method == "POST":
        # if the user is not logged in redirect him to login page
        if session.get("user_id") is None:
            return redirect(url_for('login'))
        # if the user is logged in, we try to submit the content
        comment = db.execute(
            "INSERT INTO comment (comment_content,comment_post,comment_writer) VALUES (:content,:postid,:userid)",
            {
                "content": request.form.get("mycomment"),
                "postid": postid,
                "userid": session["user_id"]
            })
        # if there is an error inserting the comment, return an error
        if not comment:
            return error(message="Error inserting the comment")
        # else, commit the query
        db.commit()

    # user reached the route via GET
    # query database to get post detail
    post_detail = db.execute(
        "SELECT * FROM users,post WHERE users.user_id = post.post_publisher AND post.post_id=:postid",
        {
            "postid": postid
        }).fetchone()
    if not post_detail:
        # return an error
        return error(message="This Post dosen't exist")
    # query database to get the post's comments if any
    comments = db.execute(
        "SELECT * FROM users,comment WHERE users.user_id = comment.comment_writer AND comment_post = :post_id",
        {
            "post_id": postid
        }).fetchall()
    if not comments:
        # render template without comments if there is no comments
        return render_template("posts.html",
                               thepost=post_detail,
                               comments=None)

    # render template with post detail and its comments
    return render_template("posts.html",
                           thepost=post_detail,
                           comments=comments)
Exemplo n.º 32
0
def channel(channel_name):
    """ Channel page """
    # check if channels_name is valid
    if channel_name not in channels_list:
        return error("No such channel exists")
    session["current_channel"] = channel_name
    return render_template("channel.html", channel_name=channel_name)
Exemplo n.º 33
0
 def decorator(*args, **kwargs):
     start = time.time()
     result = func(*args, **kwargs)
     end = time.time()
     if not isinstance(result, types.DictType):
         result = error("Route providers must return a dictionary.")
     result.update(dict(_runtime=end - start))
     return result
Exemplo n.º 34
0
 def decorator(*args, **kwargs):
     try:
         return f(*args, **kwargs)
     # XXX we should create a custom Exception class
     except Exception, e:
         # Print out the exception to the console
         traceback.print_exc()
         return error(str(e))
Exemplo n.º 35
0
	min_err = np.inf

	# Iteratively add new distribution centers and find their optimal location 
	# until either tol, or max_clusters, is reached
	while (min_err > float(tol)/scale) and (num_clusters < max_clusters):
		num_clusters += 1
		min_err = np.inf

		# Perform clustering tries_per_iter times choosing random starting points 
		# At each iteration, save the best result 
		for i in range(tries_per_iter):

			# Find optimal placement for number of distribution centers specified.
			centers, clusters = find_centers(test_array, num_clusters, wt=i_weight, scale=scale, threshold=thres)
			# Measure average consumer distance from distribution center
			err = error(centers, test_array[:,:2], test_pop, avg=True, wt=i_weight, scale=scale, max_pop=max_pop, threshold=thres)

			if min_err > err: # Check whether current soln has improved the previous soln
				min_err = err
				min_centers = centers
				min_clusters = clusters

		print num_clusters, min_err # Keep the user updated

	print "Found solution! With weighting function {0}, there are {1} clusters with error {2}. Plotting result now...".format(i_weight, num_clusters, min_err)

	if i_weight == 'lin': validation_scale = float(np.sum(validation_pop))
	elif i_weight == 'sq': validation_scale = np.sum(validation_pop**2)
	elif i_weight == 'sqrt': validation_scale = np.sum(np.sqrt(validation_pop))
	elif i_weight == 'log': validation_scale = np.sum(np.log(validation_pop))
	elif i_weight == 'max': validation_scale = max_pop
Exemplo n.º 36
0
 def decorator(*args, **kwargs):
     try:
         return f(*args, **kwargs)
     # XXX we should create a custom Exception class
     except Exception, e:
         return error(str(e), error=str(traceback.format_exc()))
 def decorator(*args, **kwargs):
     try:
         return f(*args, **kwargs)
     # XXX we should create a custom Exception class
     except Exception, e:
         return error(str(e))