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)
Related
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))
I want to delete a row using Python with MySQL but when I delete it I have to use this command:
cursor.execute("DELETE FROM users WHERE username= jazzar")
But I want to check for multiple things like the email and password
You can use multiple conditions in query.
cursor.execute("DELETE FROM users WHERE username = jazzar AND email = jazzar#example.com AND password = YOUR_PASSWORD")
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...
Here is my signup form,
class SignupForm(forms.ModelForm):
class Meta:
model = User
fields = ['first_name', 'last_name','username', 'email', 'password']
def clean_username(self):
username = self.cleaned_data.get('username')
email = self.cleaned_data.get('email')
if username and User.objects.filter(username=username).exclude(email=email).count():
raise forms.ValidationError('This username has already been taken!')
return username
This works well to check if there is same username presents or not. However it does not check for case insensitivity. If there is a username e.g. 'userone', then it also accepts a username with 'Userone'. Although it does not break any functionality, but looks very unprofessional.
My question is how can I check for case insensitive right in the forms, and raise error?
Sometimes I faced the same issue. Django considers username unique different in lower or upper case. Like if I enter John, it a unique username and if I enter john, it's a new username. I need to consider John and john not in the database. As simple as facebook do, both uppercase and lower case username name is same, unique.
So I achieve this just changing my signup code like this.
username = self.cleaned_data.get('username').lower()
Also, in my login code, I convert my username to lower.
So that, all time it saves username lower in the database and log in with lower case username. Although a user tries to login with upper case username, then it saves to the database by converting to lower case.
You can use __iexact here:
User.objects.filter(username__iexact=username).exclude(email=email).exists() # instead of count, used exists() which does not make any DB query
Simplest method I think is:
Use .exists() method, if true then validation error else return ❤
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)