Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing User Login in Django using Selenium

In Django / Selenium, do you need to always input the username and password as strings since when you call the password from the user it outputs a hashed password, and then if Selenium inputs that into the window it won't let you login using the hashed password?

This code of mine works:

def test_admin_login(self):
    # users types in username and passwords and presses enter
    self.browser.get(self.live_server_url + '/admin/')
    username_field = self.browser.find_element_by_name('username')
    username_field.send_keys('admin')
    password_field = self.browser.find_element_by_name('password')
    password_field.send_keys('1234')
    password_field.send_keys(Keys.RETURN)


    # login credentials are correct, and the user is redirected to the main admin page
    body = self.browser.find_element_by_tag_name('body')
    self.assertIn('Site administration', body.text)

However, If I switch out "admin" for lets say

admin = User.objects.get(username="admin")

and call the admin password like so:

password_field.send_keys(admin.password)

It inputs the hashed password into the browser and won't let me login.

Any other way to do this then using the string of the password?

Thanks, Aaron

like image 247
Aaron Lelevier Avatar asked Jun 05 '26 15:06

Aaron Lelevier


2 Answers

If you work with test database, create set password for need user.

def login_as(self, browser, user):
    # change password
    password = 'q'
    user.set_password(password)
    user.save()

    browser.get(self.live_server_url + '/admin/')
    username_field = browser.find_element_by_css_selector('form input[name="username"]')
    password_field = browser.find_element_by_css_selector('form input[name="password"]')
    username_field.send_keys(user.username)
    password_field.send_keys(password)

    submit = browser.find_element_by_css_selector('form input[type="submit"]')
    submit.click()
like image 174
Анатолий Панин Avatar answered Jun 07 '26 15:06

Анатолий Панин


It seems to me that the answer to your questions is most likely No. The reason being that you never want to store a password in plain text without hashing it (and ideally also salting it). It IS POSSIBLE nevertheless to configure Django to not hash your password before storing it in your database. If you don't hash it then you can do what you want:

admin = User.objects.get(username="admin")
password_field.send_keys(admin.password)

I would NOT recommend this. Also, it's not possible to use the hashed version of the password in your login page to login either as the Django authentication backend will hash the already hashed input and it will NOT match.

Does this make sense?

like image 33
juanvilla Avatar answered Jun 07 '26 14:06

juanvilla