def addToCart(product_id):
    try:
        current_user.get_username()
    except:
        return redirect(url_for('user.signin'))

    if 'cart' in session:
        cart = session['cart']
    else:
        cart = []

    conn = sqlite3.connect(os.path.join(file_directory, "storage.db"))
    c = conn.cursor()
    c.execute(
        " SELECT product_id, name, image, description, selling_price, category, status FROM products WHERE product_id=? ",
        (product_id, ))
    item = c.fetchone()
    # Check if product is inactive
    # If product not active, display error 404 page
    if item is None or item[6] == "inactive":
        abort(404)
    else:
        cart.append(item)
        session['cart'] = cart

    return redirect(url_for('shopping.ShoppingCart'))
Пример #2
0
def authorize():
    '''
    This method finds out if the current user is authorized to -
        - perform the action specified in 'method' header
        - on the resource specified in 'URI header'
    The request body and content_type are also required for ths purpose.

    Note:
    Because of the @login_required decorator authentication should be already complete
    using one of the supported methods by the time we reach this method. So, let's just
    worry about authorizaton.
    '''
    user = current_user.get_username()
    actas = _find_actas_from_request(request) or current_user.get_username()

    resource = request.headers.get('URI','')
    data = request.get_data()
    content_type = request.headers.get('content-type', '')
    action = request.headers.get('method', '')

    if action.lower() in [ "get", "head", "connect", "trace" ]:
        app.logger.info("Received {} on {} with user acting as {}".format(action, resource, actas))
    else:
        app.logger.warning("Received {} on {} with user acting as {}".format(action, resource, actas))

    auth_result = FileAuthorizer().instance.authorize(user=user, act_as=actas, resource=resource, data=data, content_type=content_type, action=action)
    if not auth_result:
        if not auth_result.messages:
            abort(403)
        else:
            return json.dumps({'success':False, 'messages':auth_result.messages}), 403, {'ContentType':'application/json'}

    return json.dumps({'success':True}), 200, {'ContentType':'application/json'}
def reviews(productid):
    try:
        current_user.get_username()
        user = current_user
    except:
        user = None

    reviewsform = Reviews(request.form)
    conn = sqlite3.connect(os.path.join(file_directory, "storage.db"))
    c = conn.cursor()
    c.execute("SELECT * FROM products WHERE product_id=?", (productid, ))
    product = c.fetchone()

    c.execute("SELECT * FROM reviews")
    reviews = c.fetchall()

    if request.method == "POST" and reviewsform.validate():
        c.execute("""INSERT INTO reviews VALUES (?, ?, ?)""",
                  (product[0], user.get_username(), reviewsform.reviews.data))
        conn.commit()
        return redirect(url_for('main.reviews', productid=productid))

    return render_template("main/Reviews.html",
                           user=user,
                           product=product,
                           reviews=reviews,
                           form=reviewsform)
Пример #4
0
def updateAccount():
    query = UserAccount.query.filter_by(
        username=current_user.get_username()).first()
    form = UpdateAccountDetails(request.form)

    if request.method == 'POST':  #and form.validate()
        # Update account
        UserAccount.query.filter_by(
            username=current_user.get_username()).update({
                'title':
                request.form['title'],
                'firstName':
                request.form['firstName'],
                'surName':
                request.form['surName'],
                'email':
                request.form['email'],
                'phone':
                request.form['phone'],
            })

        # Commit to DB
        db.session.commit()

        # Close connection
        db.session.close()

        flash('You successfully updated your account', 'success')

        return redirect(url_for('call.CoveredCallsResults'))
    return redirect(url_for('account.myAccount'))
Пример #5
0
def login():
    actas = request.cookies.get(ACTAS_COOKIE_NAME) or request.headers.get(
        "act_as_user")
    redirect_url = request.args.get('next', '/')
    if request.method == 'POST':
        redirect_url = request.form.get(
            'redirect', redirect_url
        )  # Note: if auth succeeds we re-direct to this else we render it to index.html if auth fails
        username = request.form.get('user')
        passw = request.form.get('pass')
        if username and passw:
            if (FileAuthenticator().instance.authenticate(username, passw)):
                session_user = SessionUser.get(username)
                if session_user:
                    login_user(session_user, remember=True)
                    # if the user can act as only one user, auto update actas
                    actaslist = FileAuthorizer().instance.get_canactas_list(
                        current_user.get_username())
                    if len(actaslist) == 1:
                        actas = actaslist[0]
                else:
                    flash(
                        'Something didn\'t work! Please re-try with the right credentials.'
                    )
                    return make_response(
                        render_template('index.html', **locals()))
            else:
                flash('Authentication failed.')
                return make_response(render_template('index.html', **locals()))
        else:
            actas = request.form.get('act_as')

        if current_user.is_authenticated:
            if not actas:
                actas = current_user.get_username()
            if actas in FileAuthorizer().instance.get_canactas_list(
                    current_user.get_username()):
                # all's well, let's set cookie and redirect
                resp = make_response(redirect(redirect_url or '/'))
                resp.set_cookie(ACTAS_COOKIE_NAME, actas, domain=COOKIE_DOMAIN)
                return resp
            else:
                if actas:
                    flash('Not authorized to act as {}.'.format(actas))
                actas = None
                resp = make_response(render_template('index.html', **locals()))
                _clear_cookies(resp)
                return resp
        else:
            flash('Authentication required.')
            return make_response(render_template('index.html', **locals()))

    if request.args.get('resetactas', 'false').lower() in ['true', '1', 'yes']:
        actas = None

    if not current_user.is_authenticated:
        flash('Please log in.')

    return make_response(render_template('index.html', **locals()))
def vouchers():
    try:
        current_user.get_username()
        user = current_user
    except:
        user = None

    return render_template("shopping/Vouchers.html", user=user)
def About():
    try:
        current_user.get_username()
        user = current_user
    except:
        user = None

    return render_template("main/About.html", user=user)
Пример #8
0
def ensure_workspace_is_initialized():
    available_workspaces = data_graph.workspaces_for_user(
        current_user.get_username())
    if available_workspaces is None or len(available_workspaces) == 0:
        new_workspace = data_graph.create_workspace(
            current_user.get_username(), defaultWorkspaceName(), True)
        session['workspace_id'] = new_workspace.id
    else:
        session['workspace_id'] = available_workspaces[0].id
Пример #9
0
def log_error(error):
    if current_user and hasattr(current_user, 'get_username'):
        logger.error(error, USER=current_user.get_username())
        if hasattr(error, 'original_exception'):
            logger.error(error.original_exception,
                         USER=current_user.get_username())
    else:
        logger.error(error)
        if hasattr(error, 'original_exception'):
            logger.error(error.original_exception)
Пример #10
0
def Profile():
    try:
        current_user.get_username()
    except:
        abort(404)
    user = current_user
    conn = sqlite3.connect(os.path.join(file_directory, "storage.db"))
    c = conn.cursor()
    c.execute("SELECT * FROM paymentdetails WHERE user_id=? ", (user.id, ))
    # self define paymentinformation and fetch one and return into payment information variable.
    paymentinformation = c.fetchone()
    if paymentinformation:
        payment_details = PaymentInfo(paymentinformation[1],
                                      paymentinformation[2],
                                      paymentinformation[3],
                                      int(paymentinformation[4]))
    else:
        payment_details = PaymentInfo("", "", "", "")

    payment_form = PaymentOptions(request.form)
    if request.method == "POST" and payment_form.validate():
        conn = sqlite3.connect(os.path.join(file_directory, "storage.db"))
        c = conn.cursor()
        c.execute("SELECT * FROM paymentdetails WHERE user_id=? ", (user.id, ))
        result = c.fetchone()
        if not result:
            e1 = pyffx.Integer(
                b'12376987ca98sbdacsbjkdwd898216jasdnsd98213912', length=16)
            e2 = pyffx.Integer(
                b'12376987ca98sbdacsbjkdwd898216jasdnsd98213912',
                length=len(str(payment_form.SecretNumber.data)))
            encrypted_card_no = e1.encrypt(payment_form.CreditCardno.data)
            encrypted_card_CVV = e2.encrypt(payment_form.SecretNumber.data)
            c.execute("INSERT INTO paymentdetails VALUES (?, ?, ?, ?, ?)",
                      (user.id, payment_form.Name.data, encrypted_card_no,
                       payment_form.ExpiryDate.data, encrypted_card_CVV))
            conn.commit()
            conn.close()
            return redirect(url_for('user.Profile'))
        else:
            flash('Only can store 1 card detail')
    if payment_details.get_full_name() != '':
        cn = payment_details.get_credit_card_number()
        e1 = pyffx.Integer(b'12376987ca98sbdacsbjkdwd898216jasdnsd98213912',
                           length=16)
        cn = e1.decrypt(cn)
        return render_template("user/Profile.html",
                               user=user,
                               payment_details=payment_details,
                               form=payment_form,
                               cn=str(cn))
    return render_template("user/Profile.html",
                           user=user,
                           payment_details=payment_details,
                           form=payment_form)
Пример #11
0
def edit_list_title(code):
    if not current_user.is_authenticated:
        return abort(404)
    if not List().update_list_title(current_user.get_username(), code,
                                    request.form.get('list_name')):
        return abort(404)

    return redirect(
        url_for('main.list_page',
                user=current_user.get_username(),
                link_code=code))
Пример #12
0
def add_many_list_items(code, id):
    if (not current_user.is_authenticated) or (not List().check_correct_user(
            current_user.get_username(), code)):
        return abort(404)

    Item(list_id=id).add_many(request.form.get('list_items'))

    return redirect(
        url_for('main.list_page',
                user=current_user.get_username(),
                link_code=code))
Пример #13
0
def add_list_item(code, id):
    if (not current_user.is_authenticated) or (not List().check_correct_user(
            current_user.get_username(), code)):
        return abort(404)
    if not Item(item=request.form.get('list_item'), list_id=id).add_item():
        return 'Something went wrong'

    return redirect(
        url_for('main.list_page',
                user=current_user.get_username(),
                link_code=code))
Пример #14
0
def signInOTP(token):
    try:
        current_user.get_username()
        return redirect(url_for('main.home'))
    except:
        user = None

    s = Serializer('3d6f45a5fc12445dbac2f59c3b6c7cb1', 120)
    try:
        # Check if token is valid
        token = s.loads(token)
        username = token[0]
        otp = token[1]
        expired = False
    except:
        expired = True

    form = OTP(request.form)
    resetToken = ''
    if request.method == "POST" and not expired:
        if form.OTP.data == otp:
            conn = sqlite3.connect(os.path.join(file_directory, "storage.db"))
            c = conn.cursor()
            c.execute("SELECT * FROM users WHERE username=?", (username, ))
            user = c.fetchone()
            today = str(date.today())
            # Check if password has expired
            if datetime.strptime(today,
                                 "%Y-%m-%d").date() >= datetime.strptime(
                                     user[5], "%Y-%m-%d").date():
                # Generate Token
                s = Serializer('3d6f45a5fc12445dbac2f59c3b6c7cb1', 300)
                # Store username in token for authentication
                resetToken = s.dumps(user[1]).decode('UTF-8')
                user = None
                flash("Your password has expired!", "reset")
            else:
                # Sign in user
                userObj = User(user[0], user[1], user[2], user[3], user[4])
                if userObj.get_admin() == 'y':
                    login_user(userObj)
                    return redirect(url_for('admin.admin'))
                else:
                    login_user(userObj)
                    return redirect(url_for('main.home'))
        else:
            flash("Invalid OTP", "error")

    return render_template("user/OTP.html",
                           user=user,
                           form=form,
                           expired=expired,
                           token=resetToken)
Пример #15
0
def changeState(taskID):
    
    if request.method == 'GET':
         # Get tasks of the current user
        taskList = users[current_user.get_username()]["tasks"]

        # Make sure requested ID is in range if not the case, then redirect
        if taskID > len(taskList) or taskID < 1:
            return redirect("/")

        users[current_user.get_username()]["tasks"][taskID - 1][2] = not taskList[taskID - 1][2]
        
    return redirect("/")
Пример #16
0
def filter_response():
    '''
    This method filters the response (body) based on the access the current user has.
    Should typically be called by the proxy (internal) and not from outside.
    '''
    user = current_user.get_username()
    actas = _find_actas_from_request(request) or current_user.get_username()

    resource = request.headers.get('URI', '')
    data = request.get_data()

    response = FileAuthorizer().instance.filter_response(resource, data, actas)
    return Response(response=response, status=200, mimetype="application/json")
Пример #17
0
def filter_response():
    '''
    This method filters the response (body) based on the access the current user has.
    Should typically be called by the proxy (internal) and not from outside.
    '''
    user = current_user.get_username()
    actas = _find_actas_from_request(request) or current_user.get_username()

    resource = request.headers.get('URI','')
    data = request.get_data()

    response = FileAuthorizer().instance.filter_response(resource, data, actas)
    return Response(response=response, status=200, mimetype="application/json")
Пример #18
0
def login():
    actas = request.cookies.get(ACTAS_COOKIE_NAME) or request.headers.get("act_as_user")
    redirect_url = request.args.get('next', '/')
    if request.method == 'POST':
        redirect_url = request.form.get('redirect', redirect_url) # Note: if auth succeeds we re-direct to this else we render it to index.html if auth fails
        username = request.form.get('user')
        passw = request.form.get('pass')
        if username and passw:
            if (FileAuthenticator().instance.authenticate(username, passw)):
                session_user = SessionUser.get(username)
                if session_user:
                    login_user(session_user, remember=True)
                    # if the user can act as only one user, auto update actas
                    actaslist = FileAuthorizer().instance.get_canactas_list(current_user.get_username())
                    if len(actaslist) == 1:
                        actas = actaslist[0]
                else:
                    flash('Something didn\'t work! Please re-try with the right credentials.')
                    return make_response(render_template('index.html', **locals()))
            else:
                flash('Authentication failed.')
                return make_response(render_template('index.html', **locals()))
        else:
            actas = request.form.get('act_as')

        if current_user.is_authenticated:
            if not actas:
                actas = current_user.get_username()
            if actas in FileAuthorizer().instance.get_canactas_list(current_user.get_username()):
                # all's well, let's set cookie and redirect
                resp = make_response(redirect(redirect_url or '/'))
                resp.set_cookie(ACTAS_COOKIE_NAME, actas, domain=COOKIE_DOMAIN)
                return resp
            else:
                if actas:
                    flash('Not authorized to act as {}.'.format(actas))
                actas = None
                resp = make_response(render_template('index.html', **locals()))
                _clear_cookies(resp)
                return resp
        else:
            flash('Authentication required.')
            return make_response(render_template('index.html', **locals()))

    if request.args.get('resetactas', 'false').lower() in ['true', '1', 'yes']:
        actas = None

    if not current_user.is_authenticated:
        flash('Please log in.')

    return make_response(render_template('index.html', **locals()))
Пример #19
0
def index():
    if current_user.is_authenticated:
        if session.get('workspace_id') is None:
            session['workspace_id'] = data_graph.default_workspace_for_user(
                current_user.get_username()).id

        session['workspaces'] = [{
            'name': w.name,
            'id': w.id
        } for w in data_graph.workspaces_for_user(current_user.get_username())]

        return render_template('infrastructure_graph.html')
    else:
        return render_template('login.html', form=LoginForm())
Пример #20
0
def signin():
    # Checks if user is logged in
    try:
        current_user.get_username()
        return redirect(url_for('main.home'))
    except:
        user = None

    signin = SignIn(request.form)
    if request.method == "POST" and signin.validate():
        pw_hash = hashlib.sha512(signin.password.data.encode()).hexdigest()
        conn = sqlite3.connect(os.path.join(file_directory, "storage.db"))
        c = conn.cursor()
        c.execute("SELECT * FROM users WHERE username=?",
                  (signin.username.data, ))
        user = c.fetchone()

        # Patched code: Gives ambiguous error message
        if user is None:
            flash("Incorrect username or password")
        else:
            if user[3] == pw_hash:
                # Generate OTP
                digits = "0123456789"
                otp = ""
                for i in range(8):
                    otp += digits[math.floor(random.random() * 10)]

                s = Serializer('3d6f45a5fc12445dbac2f59c3b6c7cb1', 120)
                # Store username and OTP in token for authentication
                token = s.dumps([user[1], otp]).decode('UTF-8')
                # Send Email to user
                mail.send_message(
                    'Indirect Home Gym Sign In',
                    sender='*****@*****.**',
                    recipients=[user[2]],
                    body=
                    "Hi {},\n\nYour 8 digit OTP is {}. It will expire in 2 minutes.\n\n If you did not request for this OTP, please reset your password as soon as possible.\n\nCheers!\nIndirect Home Gym Team"
                    .format(user[1], otp))
                return redirect(url_for('user.signInOTP', token=token))
            else:
                username = signin.username.data
                details = f"Failed login attempt with the username of {username}."
                Loggingtype = "Login"
                Logging(Loggingtype, details)
                user = None
                flash("Incorrect username or password")
        conn.close()
    return render_template("user/SignIn.html", form=signin, user=user)
def home():
    try:
        current_user.get_username()
        user = current_user
    except:
        user = None

    conn = sqlite3.connect(os.path.join(file_directory, "storage.db"))
    c = conn.cursor()

    c.execute("SELECT * FROM products")
    products = c.fetchall()
    conn.close()

    return render_template("main/Home.html", user=user, products=products)
Пример #22
0
def authorize():
    '''
    This method finds out if the current user is authorized to -
        - perform the action specified in 'method' header
        - on the resource specified in 'URI header'
    The request body and content_type are also required for ths purpose.

    Note:
    Because of the @login_required decorator authentication should be already complete
    using one of the supported methods by the time we reach this method. So, let's just
    worry about authorizaton.
    '''
    user = current_user.get_username()
    actas = _find_actas_from_request(request) or current_user.get_username()

    resource = request.headers.get('URI', '')
    data = request.get_data()
    content_type = request.headers.get('content-type', '')
    action = request.headers.get('method', '')

    if action.lower() in ["get", "head", "connect", "trace"]:
        app.logger.info("Received {} on {} with user acting as {}".format(
            action, resource, actas))
    else:
        app.logger.warning("Received {} on {} with user acting as {}".format(
            action, resource, actas))

    auth_result = FileAuthorizer().instance.authorize(
        user=user,
        act_as=actas,
        resource=resource,
        data=data,
        content_type=content_type,
        action=action)
    if not auth_result:
        if not auth_result.messages:
            abort(403)
        else:
            return json.dumps({
                'success': False,
                'messages': auth_result.messages
            }), 403, {
                'ContentType': 'application/json'
            }

    return json.dumps({'success': True}), 200, {
        'ContentType': 'application/json'
    }
Пример #23
0
def about():
    """Render the abount page for the project

    Returns:
        response: the flask response object representing the HTML page
    """
    if current_user.is_anonymous:
        # redirect to login page if not logged in
        return redirect(url_for('auth.login'))
    username = current_user.get_username()
    email = current_user.get_email()
    address = current_user.get_address()
    auth_attributes = get_auth_attributes()
    auth_user_attributes = auth_attributes[0]
    if not address:
        address = auth_user_attributes.get('address', None)
    phone_number = current_user.get_phone()
    if not phone_number:
        phone_number = auth_user_attributes.get('phone_number', None)

    policies = []
    for p in current_user.get_policy():
        cur = {'uid': p.get_uid(), 'location': p.get_location(), 'policy_json': p.get_policy_json()}
        policies.append(cur)
    print(policies)
    print(current_user.get_policy())
    return render_template("home/about.html",
                           username=username, email=email, address=address, phone_number=phone_number, policies=policies)
Пример #24
0
def get_jwt():
    """Generate jwt of the requested thing with minimal inforamtion in the payload`

    Args:
        This method receive arguments from HTTP request body, which must be JSON format containing following properties
        thing_id (str): uniquely identify the thing description to be deleted
        Also, user must be logged in for username attribute.
    Returns:
        HTTP Response: The response is a jwt in JSON format with corresponding HTTP status code indicating the result
        if the deletion is performed succesfully, or there is no such thing description in the target directory,
        the deletion is complete with HTTP status code 200 being returned. Otherwise HTTP status code 400 is returned.
    """

    thing_id = request.args.get('thing_id')
    username = user.get_username()
    timestamp = datetime.now().timestamp()
    payload = {
        "thing_id": thing_id,
        "username": username,
        "timestamp": timestamp
    }
    if not thing_id:
        return "Invalid input", 400
    if not username:
        return "Please login", 400

    encoded_jwt, priv_key, pub_key = generate_jwt(payload)
    # TODO: save priv_key and pub_key in server

    jwt_json = payload.copy()
    jwt_json['encoding'] = str(encoded_jwt)
    return jsonify(jwt_json), 200
Пример #25
0
def post_likes(item_id):
    conn = pymysql.connect(**dbparams)

    try:
        with conn.cursor() as cursor:
            query = 'SELECT likes FROM items WHERE id=%s'
            cursor.execute(query, (item_id,))
            app.logger.debug(cursor._last_executed)
            result = cursor.fetchone()

            if result is None:
                abort(404)

            username = current_user.get_username()
            likes = result['likes'] or ''
            if len(likes) == 0:
                likes_str = username
            else:
                current_likes_list = likes.split(',')

                if username not in current_likes_list:
                    current_likes_list.append(username)
                    likes_str = ','.join(list(current_likes_list))
                else:
                    likes_str = likes

            query = 'UPDATE items SET likes=%s WHERE id=%s'
            cursor.execute(query, (likes_str, item_id,))
            app.logger.debug(cursor._last_executed)
            conn.commit()
    finally:
        conn.close()

    return '', 204
Пример #26
0
def add_list():
    form = CreateListForm()
    if not form.validate_on_submit():
        flash(list(form.errors.values())[0])
        return redirect(url_for('main.create_list'))

    add = List(name=request.form.get('list_name'),
               user=current_user.get_username(),
               explore=request.form.get('exploreable'),
               link_code=List.generate_link_code()).add_list(
                   request.form.get('list_items'))

    return redirect(
        url_for('main.list_page',
                user=current_user.get_username(),
                link_code=add))
Пример #27
0
def contact():
    form = ContactForm()
    if form.validate_on_submit():
        if current_user.is_authenticated:
            user_id = ObjectId(current_user.get_id())
            user_name = current_user.get_username()
        else:
            user_id = "Anonymous"
            user_name = "Anonymous"
        user_id = ObjectId(current_user.get_id())
        send_to_admin(user_name, form.message.data)
        contact_dict = {
            "username": user_name,
            "user_id": user_id,
            "message": form.message.data,
            "datelogged": datetime.datetime.now()
        }
        db.reports.insert_one(contact_dict)
        flash(u"You have successfully contacted the website admin", "success")
        return redirect(url_for("latest"))
    elif form.errors:
        print(form.errors)
        error_message = "You have errors on the form"
        flash(u"You have errors on the form", "danger")
    return render_template('contact.html', form=form)
Пример #28
0
def ledgers_savenew_document():

    print("*** ledgers_savenew_document() ***")

    ledgerdocumentform = LedgerDocumentForm(request.form)

    print("Yritetään tallentaa uusi tosite tietokantaan")

    docnum = LedgerDocument.nextDocumentNumber(
        current_user.get_entity_id(), ledgerdocumentform.documenttype_id.data)

    doc = LedgerDocument(ledgerdocumentform.documenttype_id.data, docnum,
                         ledgerdocumentform.ledgerdate.data,
                         ledgerdocumentform.description.data,
                         current_user.get_username(), None,
                         current_user.get_entity_id())

    try:
        db.session().add(doc)
        db.session().commit()
        print("Tallennus onnistui")
    except:
        ## TÄHÄN VIRHETILANTEEN KÄSITTELY
        print("Tapahtui virhe lisättäessä tositetta tietokantaan")
        pass

    return redirect(url_for("ledgers_index"))
Пример #29
0
def index():
    name = "" if current_user.is_anonymous else current_user.get_username()
    user_list = [t[0] for t in va_query(db_name, "select username from user")]
    return render_template('index.html',
                           user_list=user_list,
                           logging=not current_user.is_anonymous,
                           name=name)
Пример #30
0
def route_get_cascaders_info():
    uun = current_user.get_username()

    return jsonify({
        "enabled": flask_redis.sismember("cascaders.users", uun),
        "tagline": flask_redis.hget("cascaders.taglines", uun),
    })
Пример #31
0
def login():
    if current_user.is_authenticated:
        flash(current_user.get_username() + ', you are already logged in...')
        return redirect(url_for('home.index'))
    # Process POST
    form = LoginForm()
    if form.validate_on_submit():
        domain = form.domain.data  # Never None
        user_dn = 'uid=' + form.username.data + ',' + Config.DOMAINS[domain]
        password = form.password.data
        user = None
        auth_token = User.authenticate(user_dn=user_dn, password=password)
        if auth_token is not None:
            user = User(auth_token=auth_token)
            login_user(user)
            initialize_user_data()
            next_page = request.args.get('next')
            if not next_page or url_parse(next_page).netloc != '':
                current_packageid = get_active_packageid()
                if current_packageid:
                    next_page = url_for('home.title',
                                        packageid=current_packageid)
                else:
                    next_page = url_for('home.index')
            return redirect(next_page)
        flash('Invalid username or password')
        return redirect(url_for('auth.login'))
    # Process GET
    return render_template('login.html', title='Sign In', form=form)
Пример #32
0
def delete_list_item(code, list_id, item):
    if (not current_user.is_authenticated) or (not List().check_correct_user(
            current_user.get_username(), code)):
        return abort(404)
    if not Item().delete_item(list_id, item):
        return ('', 400)
    return ('', 204)
Пример #33
0
def log_usage(action, *args):
    args = handle_special_cases(action, args)
    date = datetime.now().date().strftime('%Y-%m-%d')
    time = datetime.now().time().strftime('%H:%M:%S')
    if current_user and hasattr(current_user, 'get_username'):
        username = current_user.get_username()
        current_document = current_user.get_filename()
        if not current_document:
            current_document = ''
    else:
        username = ''
        current_document = ''
    NUM_DATA_COLS = 5
    data_cols = []
    for i in range(NUM_DATA_COLS):
        data_cols.append('')
    i = 0
    if args:
        for arg in args:
            data_cols[i] = str(arg)
            i += 1
    with open(USAGE_LOG_FILE, 'a') as log:
        data = ','.join(data_cols)
        line = f"{date},{time},{username},{action},{current_document},{data}\n"
        log.write(line)
Пример #34
0
def get_profile():
    info = dict()
    info["Status"] = 1
    info["username"] = current_user.get_username()
    info["email"] = current_user.get_email()
    info["age"] = current_user.get_age()
    info["gender"] = current_user.get_gender()
    return jsonify(info)
Пример #35
0
    def test_2_login(self):
        print ''
        print 'test login/logout process'

        with self.app:
            print 'get login page'
            rv = self.app.get('/login')
            assert '<form id="login"' in rv.data

            print 'login refused - credentials'
            rv = self.login('admin', 'default')
            assert 'Invalid credentials: username is unknown or password is invalid.' in rv.data

            print 'login refused - credentials'
            rv = self.login('admin', '')
            assert 'Invalid credentials: username is unknown or password is invalid.' in rv.data

            print 'login accepted - home page'
            rv = self.login('admin', 'admin')
            assert '<title>Home page</title>' in rv.data
            print 'login accepted - user attributes'
            assert current_user.username == 'admin'
            print 'user:'******'user name:', current_user.get_name()
            print 'token:', current_user.get_auth_token()
            print 'username:'******'user role:', current_user.get_role()
            print 'user picture:', current_user.get_picture()
            print 'admin:', current_user.can_admin()
            print 'action:', current_user.can_action()

            print 'reload home page'
            rv = self.app.get('/')
            assert '<title>Home page</title>' in rv.data

            print 'reload home page'
            rv = self.app.get('/?search=test')
            assert '<title>Home page</title>' in rv.data

            print 'reload home page'
            rv = self.app.get('/index')
            assert '<title>Home page</title>' in rv.data

            print 'refresh header'
            rv = self.app.get('/refresh_header')
            assert 'html_livesynthesis' in rv.data

            print 'refresh livestate'
            rv = self.app.get('/refresh_livestate')
            assert 'livestate' in rv.data

            print 'refresh livesynthesis'
            rv = self.app.get('/livesynthesis')
            assert 'livesynthesis' in rv.data

            print 'logout - go to login page'
            rv = self.logout()
            assert '<form id="login"' in rv.data
Пример #36
0
def before_request():
	print "IN FILTER WITH PATH %s" % request.path
	print "CURRENT USER %s" % current_user.get_username()
	print "ANONYMOUS? %r" % current_user.is_anonymous()
	banned = Banned.query.filter_by(poster_ip=request.remote_addr)
	if banned.count() > 0 and not request.path == '/banned' :
		banned = banned.one()
		return redirect(url_for('banned', reason=banned.reason))
	return
Пример #37
0
def register():
    form = RegisterForm()
    if form.validate_on_submit():
        user = User(
            username=form.username.data,
            password=form.password.data,
        )
        db.session.add(user)
        db.session.commit()

        login_user(user)
        return redirect(url_for('index'))
    if current_user.get_id() != None:
        if (current_user.get_username() == 'don'):
            return render_template('register.html', current_user=current_user, register_form=form)
        else:
            return render_template('permission.html')
    else:
        return render_template('permission.html')
Пример #38
0
def user_details():
    username = ''
    if current_user.is_authenticated:
        username = current_user.get_username()
    return jsonify({ 'username': username })