简体   繁体   中英

User authentication not working in flask and sqlite

What I am trying to do is to get the email id and compare against the SQLite table.
If email exists in the table then I update the table with the emailid and random generated password and mail them.
If email does not exists in the table then I use insert query to enter the email as well as random generated password into the table.
After the insert or the update query is fired I mail them the generated password using Flask-mail However I am unable to execute it

def sqliteconfig():
    try:
        conn = sqlite3.connect('auth.db',check_same_thread=False)
        cur = conn.cursor()
        conn.execute('CREATE TABLE IF NOT EXISTS auth (AID INTEGER PRIMARY KEY AUTOINCREMENT, emailid TEXT UNIQUE, otp TEXT, created_at TEXT DEFAULT CURRENT_TIMESTAMP)')
        cur.close()
    except Exception as e:
            print(e)
            return 'DatabaseDown'
            # return 'DatabaseDown'
    return conn 

@bp.route('/')
def index_redirect():
    return redirect(url_for('devcon.login'))


@bp.route('/login',methods=['GET','POST'])
def login():
    conn = sqliteconfig()
    cur = conn.cursor()

    if request.method == 'POST':
        emailid = request.form['emailid']
        if emailid != "":
            s = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"
            passlen = 8
            password =  "".join(random.sample(s,passlen ))
            conn.execute('select count(*) from auth where emailid=(?)',[emailid])
            rows = cur.fetchall();
            if len(rows) == 0:
                conn.execute('insert into auth(email,otp) values(?,?)',[emailid,password])
                conn.commit()
            elif len(rows)==1:
                conn.execute('update auth SET otp=(?) where emailid=(?)',[emailid,password])
                conn.commit()
            return str(rows)
    return render_template("login/login.html") 

The Particular problem I am facing right know is SELECT COUNT query returns nothing and INSERT query throws constraint violation error of unique emailid.
I am looking forward if there is any better way to do this

For the first error where SELECT COUNT returns nothing, in Sqlite3 select * is used instead of select count(*) . Therefore your code should be:

rows = conn.execute('SELECT * FROM auth WHERE emailid = ?',(emailid,)).fetchall()

For the second insertion error, you may already have an equivalent emailid value stored into auth . That is the only reason why you would have a constraint violation of an unique emailid.

Another (potential) error is that you set otp to emailid and password to emailid, while the order should be reversed:

conn.execute('update auth SET otp=(?) where emailid=(?)',[emailid,password])

Instead, do this:

conn.execute('UPDATE auth SET otp = ? WHERE emailid = ?',(password, emailid))

Final code:

def sqliteconfig():
    try:
        conn = sqlite3.connect('auth.db',check_same_thread=False)
        cur = conn.cursor()
        conn.execute('CREATE TABLE IF NOT EXISTS auth (AID INTEGER PRIMARY KEY AUTOINCREMENT, emailid TEXT UNIQUE, otp TEXT, created_at TEXT DEFAULT CURRENT_TIMESTAMP)')
        cur.close()
    except Exception as e:
            print(e)
            return 'DatabaseDown'
            # return 'DatabaseDown'
    return conn 

@bp.route('/')
def index_redirect():
    return redirect(url_for('devcon.login'))


@bp.route('/login',methods=['GET','POST'])
def login():
    conn = sqliteconfig()
    cur = conn.cursor()

    if request.method == 'POST':
        emailid = request.form['emailid']
        if emailid != "":
            s = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"
            passlen = 8
            password =  "".join(random.sample(s,passlen ))
            rows = conn.execute('SELECT * FROM auth WHERE emailid = ?',(emailid,)).fetchall()
            if len(rows) == 0:
                conn.execute('INSERT into auth (email, otp) VALUES (?, ?)',(emailid, password))
                conn.commit()
            elif len(rows)==1:
                conn.execute('UPDATE auth SET otp = ? WHERE emailid = ?',(emailid, password))
                conn.commit()
            return str(rows)
    return render_template("login/login.html") 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM