Can I please get some reviews and suggestions?

This is what this app does:

It picks user login from Users table and compare it with the post in the login function. Then it logs in. You can query the payments table for payments in the database and also can update records using the add_rec() function.

It's a simple payment app that checks if there is any record of the person and how much he owes, then one can proceed to accept payment. The tail end function (add_login) allows the users to be added to the Users table.

I am relatively new to Flask.

The code:

from flask import Flask, render_template, request, url_for, redirect, session, flash, g
from flask_security import Security, SQLAlchemyUserDatastore, UserMixin, RoleMixin, login_required 
from flask_sqlalchemy import SQLAlchemy
from functools import wraps
import datetime, models

#creating the application object
app = Flask(__name__)
db = SQLAlchemy(app)

# Create a user to test with
def create_user():
    db.session.add(username='saviour', password='saviour')

#login check point decorator
def login_required(f):
    def wrap(*args, **kwargs):
        if 'logged_in' in session:
            return f(*args, **kwargs)
            flash('Please Login in First')
            return redirect(url_for('login'))
    return wrap

# Loggin route
@app.route('/', methods=['GET', 'POST'])
def login():
    error = None
    global username
    if request.method == 'POST':
        username = request.form['username'].strip()
        password = request.form['password'].strip()
        #search database for the record
        session['username'] = username #store username, submitted with form on line 84
        u_login = User.query.filter_by(username=username)       
        for i in u_login:
            if username != i.username or password != i.password:
                error = 'Invalid Credentials, Please try again'
                flash('Invalid Credentials')
                session['logged_in'] = True
                flash('you are logged In')
                return redirect(url_for('index'))
    return render_template('login.html', error=error)

#logging out
def logout():
    session.pop('logged_in', None)
    flash("Thanks for using our service. \n You are Logged Out")
    return redirect(url_for('login'))

#home route
def index():
    data_rec = PAYMENTS.query.all()
    return render_template('index.html', data_rec=data_rec)

#add record/post user
@app.route('/add_rec', methods=['POST', 'GET'])
def add_rec():
    if request.method == 'POST':
        Account = request.form['Account']
        GCR_No = request.form['GCR_No']
        Payments = request.form['Payments']
        PaymentType = request.form['PaymentType'].strip('`')
        PaidBy = request.form['PaidBy']
        PaidByTele = request.form['PaidByTele']
        Cashier = session['username']
        pc_name = os.environ.get('USERNAME')
        PostData = [Account, GCR_No, Payments, PaymentType, PaidBy, PaidByTele, Cashier]
        result = request.form
        entry = PAYMENTS(Account, GCR_No, Payments, PaymentType, PaidBy, PaidByTele, Cashier, pc_name)  
        return render_template('print_page.html', result=result, Cashier=Cashier)
    return render_template('add_new.html')

#search function
@app.route('/search', methods=['POST'])
def search():
    error = None
    query_tag = request.form['search']
        search_tag = PAYMENTS.query.filter_by(Account=query_tag).all()
        error = 'Record does not exist, Contact administrator'
    return render_template('search.html', search_tag=search_tag, error=error)

@app.route('/add_login', methods=['POST', 'GET'])
def add_login():
    if request.method == 'POST':
            username = request.form['username']
            password = request.form['password']
            login_details = User(username, password)
            flash('User added succesfully')
            return redirect(url_for('index'))
            return redirect(url_for(error))
    return render_template('add_login.html')

#error handling
def error():
    return render_template('404.html')

if __name__ == '__main__':

This is my model.py

#payments db 

import app

class PAYMENTS(db.Model):
    __tablename__ = 'PAYMENTS'
    id = db.Column(db.Integer, primary_key=True)
    Account = db.Column(db.Integer)
    GCR_No = db.Column(db.String(60))
    Payments = db.Column(db.Integer)
    PaymentType = db.Column(db.String(20))
    PaidBy = db.Column(db.String(60))
    PaidByTele = db.Column(db.String(10))
    Cashier = db.Column(db.String(25))
    Pc_name = db.Column(db.String(25))
    DatePaid = db.Column(db.DateTime(), default=datetime.datetime.utcnow())
    DatePaid = db.Column(db.DateTime(), default=datetime.datetime.today())

    def __init__(self, Account, GCR_No, Payments, PaymentType, PaidBy, PaidByTele, Cashier):
        self.Account = Account
        self.GCR_No = GCR_No
        self.Payments = Payments
        self.PaymentType = PaymentType
        self.PaidBy = PaidBy
        self.PaidByTele = PaidByTele
        self.Pc_name = Pc_name
        self.Cashier = Cashier

    def __repr__(self):
        return '<records %r>' % self.Account

#users db
class User(db.Model):
    __tablename__ = 'User'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(10), unique=True)
    password = db.Column(db.String(10), unique=True)

    def __init__(self, username, password):
        self.username = username
        self.password = password

    def __repr__(self):
        return '<User %r>' % self.username
  • \$\begingroup\$ Why do all your users on the server have the same global username? That looks like an obvious security hole. \$\endgroup\$ Apr 20 '19 at 5:30
  • \$\begingroup\$ I was looking for a way to get current user login, I then set it as a global. But I realized the session, g and app_context are for this purpose, \$\endgroup\$
    – saviour123
    May 5 '19 at 18:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.