Registration error

Asked

Viewed 338 times

2

Well, I’m a beginner in python, I was trying to make a basic registration/login system. However I had a problem creating accounts, the accounts are created in the database normally, but I can only log in with the first account created, the other accounts as non-existent.

Obs: I am using sqlite

Files: db.py, connected.py, login.py

db.py

#importando módulo do SQlite
import sqlite3

class db():
    def __init__(self):
        self.conexao = sqlite3.connect('db1.db')
        self.createTable()

    def createTable(self):
        c = self.conexao.cursor()

        c.execute("""create table if not exists usuarios (
                     usuario text,
                     senha text)""")
        self.conexao.commit()
        c.close()

py connection.

from db import db
from tkinter import *
import subprocess
import sys


class conexao(object):
    def __init__(self, usuario="", senha=""):
        self.info = {}
        self.usuario = usuario
        self.senha = senha

    def inserirDatabase(self):

        banco = db()
        try:

            c = banco.conexao.cursor()

            c.execute("""
            INSERT INTO usuarios (usuario, senha)
            VALUES (?,?)
            """, (self.usuario, self.senha))

            banco.conexao.commit()
            c.close()

            return "Usuário cadastrado com sucesso!"
        except:
            return "Ocorreu um erro na inserção do usuário"


    def verificarDatabase(self, usuario, senha):

        banco = db()
        try:

            c = banco.conexao.cursor()

            c.execute("SELECT * FROM usuarios")
            result = c.fetchall()

            for record in result:
                if usuario != record[0]:
                    print(record)
                    return 'Usuario incorreto'
                elif senha != record[1]:
                    print(record)
                    return 'Senha incorreta'
                else:
                    subprocess.Popen([sys.executable, "logado.py"])

            banco.conexao.commit()
            c.close()
            return 0
        except:
            return 'Error'

login py.

from conexao import conexao
from tkinter import *
from db import db

class Application:
    def __init__(self, master=None):
        self.fonte = ("Verdana", "8")

        self.container6 = Frame(master)
        self.container6["padx"] = 20
        self.container6["pady"] = 5
        self.container6.pack()

        self.container7 = Frame(master)
        self.container7["padx"] = 20
        self.container7["pady"] = 5
        self.container7.pack()

        self.container2 = Frame(master)
        self.container2["padx"] = 20
        self.container2["pady"] = 5
        self.container2.pack()

        self.container9 = Frame(master)
        self.container9["pady"] = 15
        self.container9.pack()

        self.container10 = Frame(master)
        self.container10["pady"] = 10
        self.container10.pack()

        self.lblmsg = Label(self.container9, text="")
        self.lblmsg["font"] = ("Verdana", "9", "italic")
        self.lblmsg.pack()

        self.lblusuario = Label(self.container6, text="Usuário:", font=self.fonte, width=10)
        self.lblusuario.pack(side=LEFT)

        self.txtusuario = Entry(self.container6)
        self.txtusuario["width"] = 25
        self.txtusuario["font"] = self.fonte
        self.txtusuario.pack(side=LEFT)

        self.lblsenha = Label(self.container7, text="Senha:", font=self.fonte, width=10)
        self.lblsenha.pack(side=LEFT)

        self.txtsenha = Entry(self.container7)
        self.txtsenha["width"] = 25
        self.txtsenha["show"] = "*"
        self.txtsenha["font"] = self.fonte
        self.txtsenha.pack(side=LEFT)

        self.btnBuscar = Button(self.container2, text="Logar", font=self.fonte, width=10)
        self.btnBuscar["command"] = self.fazerLogin
        self.btnBuscar.pack(side=RIGHT)

        self.btnBuscar = Button(self.container2, text="Cadastrar", font=self.fonte, width=10)
        self.btnBuscar["command"] = self.inserirCadastro
        self.btnBuscar.pack(side=RIGHT)

        self.container1 = Frame(master)
        self.container1["pady"] = 10
        self.container1.pack()

    def fazerLogin(self):
        user = conexao()

        usuario = self.txtusuario.get()
        senha = self.txtsenha.get()

        self.lblmsg["text"] = user.verificarDatabase(usuario, senha)

        self.txtusuario.delete(0, END)
        self.txtsenha.delete(0, END)

        # Checar conta
        banco = db()
        c = banco.conexao.cursor()

        # lendo os dados
        c.execute("""
        SELECT * FROM usuarios;
        """)
        result = c.fetchall()

        for linha in result:
            if usuario == linha[0]:
                if senha == linha[1]:
                    quit()
        c.close()

    def inserirCadastro(self):
        user = conexao()

        user.usuario = self.txtusuario.get()
        user.senha = self.txtsenha.get()

        self.lblmsg["text"] = user.inserirDatabase()

        self.txtusuario.delete(0, END)
        self.txtsenha.delete(0, END)

root = Tk()
Application(root)
root.mainloop()

1 answer

4


In this stretch here:

for record in result:
    if usuario != record[0]:
        print(record)
        return 'Usuario incorreto'
    elif senha != record[1]:
        print(record)
        return 'Senha incorreta'
    else:
        subprocess.Popen([sys.executable, "logado.py"])

is that’s your problem. " Translating" from Python to English you say there:

para cada record nos resultados:
     se usuario for diferente de record[0]:
          pare a busca aqui e retorne "usuário incorreto"

So - the program does exactly and what you sent it: it compares user and password with all that are recorded in the bank, from the first. If the first one is different than the sent user/snha pair, its function already returns error.

The correct thing to do is to ask the bank to search for the past user, and then compare a password transformation (yes-you should not save the password as it comes from the user in the bank, but a transformation of it, which allows comparisons, but does not recover the original password - but this can wait until after you make it work)

So instead of:

c.execute("SELECT * FROM usuarios")
result = c.fetchall()

Do:

c.execute("SELECT * FROM usuarios WHERE usuario=?", (usuario,))
result = c.fetchall()
if not result: 
    return 'Usuario incorreto'
usuario, senha = result[0]
if senha != senha:
    return 'Senha incorreta'
...

The big difference is that with this search, the query to the database should return only ONE user, and the name I already know will be right - just compare the password.

Another tip unrelated to your question, is that the next line is a very impractical practice anyway:

 subprocess.Popen([sys.executable, "logado.py"])

All this work for autenditca rum suário, to then rexecute an external process, without even passing a parameter about which user is logged in?

In general, you will want to run what is in the "logged in.py" file in the same program you did Logi, you do not need a separate program. Relentlessly import the file with import logado, and instacing the class and/or invoking functions that are in that file.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.