Error in registering

1

Well, I'm a beginner in python, I was trying to make a basic login / login system. However I have been a problem in creating accounts, accounts are created in the database normally, but I can only log in with the first account created, the other accounts as nonexistent.

obs: I'm using sqlite

Files: db.py, connection.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()

connection.py

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()
    
asked by anonymous 07.02.2017 / 03:54

1 answer

4

In this section 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 what your problem is. "Translating" from Python to Portuguese 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 have: it compares user and password with all that have been stored in the bank since the first. If the first one is different than the user / snha pair, its function already returns error.

The correct one is to already ask the user for the last user to search the bank, and then to compare a password transformation (yes -vocẽ should not record the password as it comes from the user in the bank, but a transformation of it, but not recovering the original password - but that can be left unattended after it works)

So, instead of:

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

Make:

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 bank should return only ONE user, and the name I already know will be right - I only compare the password.

Another tip unrelated to your question is that the following line is a poorly recommended practice anyway:

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

All this work for authenticating rum, then re-executing an external process, without even passing a parameter on which user is logged in?

In general, you will want to run that is in the file "logado.py" in the same program where you did the logi, you do not need a separate program. Immediately import the file with import logado , and instantiate the class and / or invoke functions that are in that file.

    
07.02.2017 / 06:00