Updating a Table by using Sqlite3 Module in Python - python

I am working on a project where i need to update the password column of a user table pointing userid as the primary key, whenever the user reset his/her password. I am passing username and password to update_table function based on the values entered by the user from console and below is my code snippet -
def sql_update_table(conn, username, reset_password):
c = conn.cursor()
#value = (username, reset_password)
#c.execute('''UPDATE user SET password = ? WHERE userid = ? ''', value)
c.execute('''UPDATE user SET password = reset_password WHERE userid = username''')
conn.commit()
I tried both case passing values with a tuple as mentioned in # and directly as mentioned without a #. However, for first case, there is no error but the table is not getting updated with the new value of password and for later one i am getting below error -
sqlite3.OperationalError: no such column: reset_password
Please help me to solve this.
Thanks in advance !

Can you please try replacing
c.execute('''UPDATE user SET password = reset_password WHERE userid = username''')
with
c.execute('''UPDATE user SET password = ? WHERE userid = ? ''', (username,reset_password))

Related

Accessing specific item in sqlite3 database when user and password matches

I've created a login GUI with sqlite in python and i've got it working correctly, however I want it to do something else as well when it logs in.
My sqlite database currently has the following columns;
Username, Email, Password, Workstation, Directory
I've found that you can take an item string in the table by using something like;
connection.fetchall()[index]
However, I don't know how to implement it into my code to check for the user that logged in.
username = "username"
password = "password"
# database information
connection = sqlite3.connect(databasepath+'\login.db')
result = connection.execute("SELECT * FROM USERS WHERE USERNAME = ? AND PASSWORD = ?", (username, password))
if (len(result.fetchall()) > 0):
#some code#
I want to access the 'Directory' item for the user that logged in

locating a password that corresponds to a username within an sqlite table

I am running a website using Flask microframework and sqlite3 to store user logins. Currently, I am having trouble with matching the username and password entered by the user from an HTML form, with the existing records within my database.
I am using the flask-login extension to help me with this, and when I try and match, I am receiving a TypeError:
list indices must be integers or slices, not str
here is my python code that is turning the SQLite table into a variable:
con = sql.connect("table.db")
cur = con.cursor()
cur.execute('SELECT * FROM users')
names = cur.fetchall()
I then have this code which is taking the password from the HTML form, and trying to match it with the password linked to the username in the table
user_name = request.form['username']
if request.form['password'] == names[user_name]['password']:
user = User()
user.id = user_name
flask_login.login_user(user)
this is what 'names' returns:
[(7, 'ValidName', 'ValidTest', 'User#test.com'), (8, 'User2', 'password2', 'User#test2.com')]
What needs to happen is the program will check the form input for 'password' and will match it with the 'password' that is related to the username. So as an example, if ValidName and ValidTest were entered into the form, they would be requested by the program, and matched with the records found in 'names'.
I assume you have not hashed your password which is something you should do. Without security in mind
here is my dirty approach
cur.execute('SELECT * FROM users WHERE name = %s AND password = %s', (request.form['username'], request.form['password']))
user = cur.fetchone()
This can be helpful
Here is the guilty: names[user_name]['password']
names is the return value of fetchall and hence is a plain list. To use it in above expression, it should be a mapping of mappings.
You should construct it that way:
names = {row[1]: {'id': row[0], 'password': row[2], 'mail': row[3]}
for row in cur.fetchall()}
But beware: this loads the full user database in memory. It only makes sense if you have few users...

How to pass variables in python flask to mysqldb?

Code in .py file:
cur = mysql.connection.cursor()
# Check if this user had voted for somebody
is_voted = cur.execute("SELECT TUTOR_VOTED FROM USERS WHERE USERNAME="+str(session["username"]))
session["username"] keep a user cookie. The user I already logged in names "admin"
But there might be something wrong with the MySQL command inside is_voted
Error:
MySQLdb._exceptions.OperationalError: (1054, "Unknown column 'admin' in 'where clause'")
But I got the correct return value while using
SELECT TUTOR_VOTED FROM USERS WHERE USERNAME='admin'
Is there anything wrong with my input format inside is_voted?
Your output string of the combination "SELECT TUTOR_VOTED FROM USERS WHERE USERNAME="+str(session["username"]) misses couple of single quote ''. You can change it to:
is_voted = cur.execute("SELECT TUTOR_VOTED FROM USERS WHERE USERNAME='%s'" % str(session["username"]))

How to substract a hashed password from database in Python

In data, coming from data = cursor.fetchone(), I have (id, 'user', 'email', 'pbkdf2:sha256:50000$') [A user from the db].
How can I do to get the crypted password?
I want to compare it with the entered password and do the login.
I tryed password = data['user_password'], but when I ckeck with app.logger.info(password) it shows me nothing.
'user_password' is the column from my database. This is why I did data['user_password']. Is this wrong?
Help me please! Thank you!
Another way to achieve your purpose is to get the column value by using its index.
password = data[3]
app.logger.info(password)

IntegrityError - Column 'user_id' cannot be null

I am trying to register a new user on the site,
class UserInfo(models.Model):
user = models.ForeignKey(User,primary_key=True)#user profile
email_id=models.CharField(max_length=32, null=True, blank=True)
When I am registering the user, I am getting stuck by Integrity Error, please help me to resolve the problem.
def registration(request):
registration_dict = {}
if 1==1 :
#if request.POST:
#username=request.POST['email']
#password=request.POST['password']
username="admin#admin.com"
password='123456'
#try:
UserInfo.objects.get_or_create(email_id=username,user__username=username,user__email=username,user__password=password)
#except:
# registration_dict["status"]="0"
# registration_dict["message"]="Username already present"
# return HttpResponse(simplejson.dumps(registration_dict),content_type="application/json")
registration_dict["status"]="1"
registration_dict["message"]="Thank You for registering"
return HttpResponse(simplejson.dumps(registration_dict),content_type="application/json")
else:
registration_dict["status"]="0"
registration_dict["message"]="Unable to process the request"
return HttpResponse(simplejson.dumps(registration_dict),content_type="application/json")
EDIT 1
I have tried changing
UserInfo.objects.get_or_create(email_id=username,user__username=username,user__email=username,user__password=password,user_id=1)
and then the error changes, to
'Cannot add or update a child row: a foreign key constraint fails (`app_info`.`appdata_userinfo`, CONSTRAINT `user_id_refs_id_b0fd803b` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`))')
From the limited information I would say the problem is
it does not find a UserInfo that matches. It then tries to create a new UserInfo, but it has no User to assign to the User ForeignKey. I would suggest the following:
user = authenticate(username=email, password=password)
if user is None:
user = User(username=email, password=password, email=email)
user_info = UserInfo.objects.get_or_create(user=user, email_id=email)
If the original User object doesn't exist, you'll run into all kinds of problems. So, you need to break the process down into two steps.
Check if a User object exists or not, if it doesn't create it.
Check if a UserInfo object exists for that user, if it doesn't create it.
As there is a ForeignKey, you cannot do it in one step:
username = "admin#admin.com"
password = '123456'
obj, created = User.objects.get_or_create(username=username)
obj.set_password(password) # the proper way to set the password
obj.save()
# Now fetch or create a UserInfo object
info, created = UserInfo.objects.get_or_create(email_id=username,user=obj)
I cant understand why you need UserInfo because email is already there in User.
Issue can be corrected by splitting the fetching process
username = "admin#admin.com"
password = '123456'
user,status = User.objects.get_or_create(username=username, password=password)
user_info = UserInfo.objects.get_or_create(user=user,email_id=username)

Categories

Resources