Jump to content
Floatplane payments are migrating! Read more... ×
Phishing Emails - Fake Giveaway Read more... ×
Search In
  • More options...
Find results that contain...
Find results in...
DerpDiamonds1

Python file multiple users debugging

Recommended Posts

Posted · Original PosterOP

So my current code is:

def authentication():
    usernameInput = input("Please enter your username")
    passwordInput = input("Please enter your password")  
    for line in open("users.txt","r").readlines():
        login_info = line.split()
        if usernameInput == login_info[0] and passwordInput == login_info[1]:
            print("Correct credentials!")
            return True
    if usernameInput != login_info[0]:
       newUsernameInput = input("That username is not in the system, would you like to create a new user by that name? (Y/N): ")
       if newUsernameInput == "Y":
          file = open("users.txt", "a")
          newUsernamePasswordInput = input("Please enter your password?: ")
          file.write("\n" + usernameInput + " " + newUsernamePasswordInput)
          file.close()
          print("New username and password registered, please run the program again!")
          sys.exit()
       elif newUsernameInput == "N":
          print("Okay, wrong username, please try again!")
          sys.exit()
       else:
          print("That is not an input, please try again!")
          sys.exit()
    elif passwordInput != login_info[1]:
       print("Invalid password")
       sys.exit()

def users():
  print('User 1, Please log in.')
  user1 = authentication()
  print('User 2, Please log in.')
  user2 = authentication()
  print("User 1 is", user1, "and user 2 is", user2)
  
users()

But I will only let me type username of user1 and if i got that password wrong then it will ask for a new username to be created. However, this won't happen for user2 (which is weird) and it won't let me assign the usernameInput to user1 and user2. Can I have some help!

 

This is probably really simple, but I am not seeing the solution.

 

Thanks!


Specs:

Motherboard: Gigabyte Z97X Gaming 3

CPU: Intel Core I7 4790K

GPU: Gigabyte G1 Gaming GTX 970

RAM: HyperX Fury 16GB

HDD: Seagate ST3000DM001 3TB

SSD: KINGSTON SV300S37A480G 450GB

Cooler: Corsair H100i GTX

Case: NZXT H440 Red

Monitor: DELL U2412M

Keyboard: Gigabyte Force K7

Mouse: Corsair Sabre RGB

 

Link to post
Share on other sites

I do not completely understand what you mean with "won't let me assign the usernameInput to user1 and user2". But some things that I noticed wrong in your code:

 

- login_info is only available in the for-block (scoped variable). You are trying to use it outside, in the next if-statements.

- If user1 fails, the program quits (sys.exit()), not asking for user2 at all.

 

Other suggestions:

- Use with structures for files (with open('file.txt') as f), less worries with having to closing files.

- sys.exit() is duplicated in multiple places, can simply put it after the else block.

- Indentation is not consistent. Python can be very picky regarding that (I see mixed use of 2, 3 and 4 spaces).

As a side note, if you are building a real application, don't store plain-text credentials, mkay. If you're just learning/testing, then it's fine.


Skynet: MacBook Pro Late 2016 Space Gray | i7-6820HQ 2.7 GHz | 16 GB LPDDR3 | Radeon Pro 455 2048 MB | 512 GB NVMe SSD | 15" 2880x1800 | LG 34UM95 34" 3440x1440

HAL9000: HP EliteBook 840 G5 | i5-8250U 1.6 GHz | 16 GB DDR4 |  256 GB NVMe SSD | 14" 1920x1080 | Gigabyte GTX 1070

Hydrogen server: Xeon E5-2675 v3 | Cooler Master Hyper 212X | 64 GB Kingston/Samsung DDR4 ECC | Asus Z10PA-D8 | Asus GTX 1070 | Corsair AX860 | 256 GB Samsung 850 EVO + 3x 3 TB WD Red + 2 TB Seagate | Fractal Design Define R5 | unRAID 6.5.3

Carbon server: Fujitsu PRIMERGY RX100 S7p | Xeon E3-1230 v2 | 16 GB DDR3 ECC | 60 GB Corsair SSD & 250 GB Samsung 850 Pro | Intel i340-T4 | ESXi 6.5.1

Big Mac cluster: 2x Raspberry Pi 2 Model B | 1x Raspberry Pi 3 Model B | 2x Raspberry Pi 3 Model B+

Link to post
Share on other sites
Posted · Original PosterOP
1 minute ago, jj9987 said:

I do not completely understand what you mean with "won't let me assign the usernameInput to user1 and user2"

I want whatever username they input to be assigned to user1, then when it is run again to be assigned to user2.

 

2 minutes ago, jj9987 said:

- login_info is only available in the for-block (scoped variable). You are trying to use it outside, in the next if-statements.

What do you mean?

2 minutes ago, jj9987 said:

Other suggestions:

- Use with structures for files (with open('file.txt') as f), less worries with having to closing files.

- sys.exit() is duplicated in multiple places, can simply put it after the else block.

I put sys.exit() there so it doesn't repeat onto the next user.

3 minutes ago, jj9987 said:

As a side note, if you are building a real application, don't store plain-text credentials, mkay. If you're just learning/testing, then it's fine.

I am doing this for my project at school, so we don't really need to encrypt the passwords, but if I was going to do this for real world deployment I would use something like SHA1 or SHA2.


Specs:

Motherboard: Gigabyte Z97X Gaming 3

CPU: Intel Core I7 4790K

GPU: Gigabyte G1 Gaming GTX 970

RAM: HyperX Fury 16GB

HDD: Seagate ST3000DM001 3TB

SSD: KINGSTON SV300S37A480G 450GB

Cooler: Corsair H100i GTX

Case: NZXT H440 Red

Monitor: DELL U2412M

Keyboard: Gigabyte Force K7

Mouse: Corsair Sabre RGB

 

Link to post
Share on other sites
13 minutes ago, DerpDiamonds1 said:

I want whatever username they input to be assigned to user1, then when it is run again to be assigned to user2.

Your current code requires you to have a successful login with user1, otherwise the application quits (sys.exit) and you won't deal with user2 at all. If you want to print the user1 and user2 values, both logins must be successful.

13 minutes ago, DerpDiamonds1 said:

What do you mean?

Scratch that, I messed up.

 

But what I did notice, is that there is no check for the case, where the username exists, but incorrect password is used. It is simply skipped. And then it says, that the username is not in the system, but it could be. It was simply not used because incorrect password was used. This can result in case, that there are multiple rows with same username.

 

So, what your code does, is the following
- Asks username and password as input

- Checks every row in the file, checks username and password together. If one of them is wrong, the row is "skipped". If both are correct, function returns True (function exits).

- If all rows are "skipped", application checks if usernameInput and last row's username are equal.

-- If not, it tells that user is not in the system. Then asks the user if it wants to create/save a new account. Won't go into details here, as this looks fine to me.

-- If they are equal, application checks the password. If they are equal, function exits and returns None. This final elif block is redundant, as if the last row did not match both username and password, then this block can't be reached either, as username and password did not match.

13 minutes ago, DerpDiamonds1 said:

I am doing this for my project at school, so we don't really need to encrypt the passwords, but if I was going to do this for real world deployment I would use something like SHA1 or SHA2.

SHA functions are hashing functions, not encrypting. SHA1 is insecure anyway. Use Bcrypt or Argon2, these are designed to be slow for storing passwords.


Skynet: MacBook Pro Late 2016 Space Gray | i7-6820HQ 2.7 GHz | 16 GB LPDDR3 | Radeon Pro 455 2048 MB | 512 GB NVMe SSD | 15" 2880x1800 | LG 34UM95 34" 3440x1440

HAL9000: HP EliteBook 840 G5 | i5-8250U 1.6 GHz | 16 GB DDR4 |  256 GB NVMe SSD | 14" 1920x1080 | Gigabyte GTX 1070

Hydrogen server: Xeon E5-2675 v3 | Cooler Master Hyper 212X | 64 GB Kingston/Samsung DDR4 ECC | Asus Z10PA-D8 | Asus GTX 1070 | Corsair AX860 | 256 GB Samsung 850 EVO + 3x 3 TB WD Red + 2 TB Seagate | Fractal Design Define R5 | unRAID 6.5.3

Carbon server: Fujitsu PRIMERGY RX100 S7p | Xeon E3-1230 v2 | 16 GB DDR3 ECC | 60 GB Corsair SSD & 250 GB Samsung 850 Pro | Intel i340-T4 | ESXi 6.5.1

Big Mac cluster: 2x Raspberry Pi 2 Model B | 1x Raspberry Pi 3 Model B | 2x Raspberry Pi 3 Model B+

Link to post
Share on other sites
Posted · Original PosterOP
2 minutes ago, jj9987 said:

So, what your code does, is the following
- Asks username and password as input

- Checks every row in the file, checks username and password together. If one of them is wrong, the row is "skipped". If both are correct, function returns True (function exits).

- If all rows are "skipped", application checks if usernameInput and last row's username are equal.

-- If not, it tells that user is not in the system. Then asks the user if it wants to create/save a new account. Won't go into details here, as this looks fine to me.

-- If they are equal, application checks the password. If they are equal, function exits and returns None. This final elif block is redundant, as if the last row did not match both username and password, then this block can't be reached either, as username and password did not match.

How could I correct it then?

2 minutes ago, jj9987 said:

SHA functions are hashing functions, not encrypting. SHA1 is insecure anyway. Use Bcrypt or Argon2, these are designed to be slow for storing passwords.

My bad.


Specs:

Motherboard: Gigabyte Z97X Gaming 3

CPU: Intel Core I7 4790K

GPU: Gigabyte G1 Gaming GTX 970

RAM: HyperX Fury 16GB

HDD: Seagate ST3000DM001 3TB

SSD: KINGSTON SV300S37A480G 450GB

Cooler: Corsair H100i GTX

Case: NZXT H440 Red

Monitor: DELL U2412M

Keyboard: Gigabyte Force K7

Mouse: Corsair Sabre RGB

 

Link to post
Share on other sites
9 minutes ago, DerpDiamonds1 said:

How could I correct it then?

I gave it a shot, but didn't test it out.

 

- Generally usernames should be unique (no duplicates in the database), therefore I changed it so that if a username is found, function will return True or False there and subsequent rows are not checked.

- Left out sys.exit(), didn't seem necessary. You don't need to quit the complete application, file is read on every authentication attempt anyway.

- Minor tweaks here and there, clarifying some variable names etc.

 

def authentication():
    usernameInput = input("Please enter your username: ")
    passwordInput = input("Please enter your password: ")

    with open("users.txt", "r") as f:
        for line in f:
            login_info = line.split()

            # Check if the username matches
            if usernameInput == login_info[0]:
                # If the password matches
                if passwordInput == login_info[1]:
                    print("Correct password")
                    return True
                else:
                    print("Incorrect password")
                    return False

    # If there is no user with the username, offer registration
    wantsCreate = input("That username is not in the system, would you like to create a new user by that name? (Y/N): ")
    if wantsCreate == "Y":
        newPassword = input("Please enter your password: ")
        with open("users.txt", "a") as f:
            f.write("\n" + usernameInput + " " + newPassword)
        print("New username and password registered, please run the function again!")
    elif wantsCreate == "N":
        print("Okay, not registering.")
    else:
        print("That is not an input, please try again!")

 


Skynet: MacBook Pro Late 2016 Space Gray | i7-6820HQ 2.7 GHz | 16 GB LPDDR3 | Radeon Pro 455 2048 MB | 512 GB NVMe SSD | 15" 2880x1800 | LG 34UM95 34" 3440x1440

HAL9000: HP EliteBook 840 G5 | i5-8250U 1.6 GHz | 16 GB DDR4 |  256 GB NVMe SSD | 14" 1920x1080 | Gigabyte GTX 1070

Hydrogen server: Xeon E5-2675 v3 | Cooler Master Hyper 212X | 64 GB Kingston/Samsung DDR4 ECC | Asus Z10PA-D8 | Asus GTX 1070 | Corsair AX860 | 256 GB Samsung 850 EVO + 3x 3 TB WD Red + 2 TB Seagate | Fractal Design Define R5 | unRAID 6.5.3

Carbon server: Fujitsu PRIMERGY RX100 S7p | Xeon E3-1230 v2 | 16 GB DDR3 ECC | 60 GB Corsair SSD & 250 GB Samsung 850 Pro | Intel i340-T4 | ESXi 6.5.1

Big Mac cluster: 2x Raspberry Pi 2 Model B | 1x Raspberry Pi 3 Model B | 2x Raspberry Pi 3 Model B+

Link to post
Share on other sites
Posted · Original PosterOP
1 minute ago, jj9987 said:

I gave it a shot, but didn't test it out.

 

- Generally usernames should be unique (no duplicates in the database), therefore I changed it so that if a username is found, function will return True or False there and subsequent rows are not checked.

- Left out sys.exit(), didn't seem necessary. You don't need to quit the complete application, file is read on every authentication attempt anyway.

- Minor tweaks here and there, clarifying some variable names etc.

 


def authentication():
    usernameInput = input("Please enter your username: ")
    passwordInput = input("Please enter your password: ")

    with open("users.txt", "r") as f:
        for line in f:
            login_info = line.split()

            # Check if the username matches
            if usernameInput == login_info[0]:
                # If the password matches
                if passwordInput == login_info[1]:
                    print("Correct password")
                    return True
                else:
                    print("Incorrect password")
                    return False

    # If there is no user with the username, offer registration
    wantsCreate = input("That username is not in the system, would you like to create a new user by that name? (Y/N): ")
    if wantsCreate == "Y":
        newPassword = input("Please enter your password: ")
        with open("users.txt", "a") as f:
            f.write("\n" + usernameInput + " " + newPassword)
        print("New username and password registered, please run the function again!")
    elif wantsCreate == "N":
        print("Okay, not registering.")
    else:
        print("That is not an input, please try again!")

 

So how could I assign the user names they input to user1 and user2


Specs:

Motherboard: Gigabyte Z97X Gaming 3

CPU: Intel Core I7 4790K

GPU: Gigabyte G1 Gaming GTX 970

RAM: HyperX Fury 16GB

HDD: Seagate ST3000DM001 3TB

SSD: KINGSTON SV300S37A480G 450GB

Cooler: Corsair H100i GTX

Case: NZXT H440 Red

Monitor: DELL U2412M

Keyboard: Gigabyte Force K7

Mouse: Corsair Sabre RGB

 

Link to post
Share on other sites
1 minute ago, DerpDiamonds1 said:

So how could I assign the user names they input to user1 and user2

You can return the username instead of True, if the login is successful.

return usernameInput

 


Skynet: MacBook Pro Late 2016 Space Gray | i7-6820HQ 2.7 GHz | 16 GB LPDDR3 | Radeon Pro 455 2048 MB | 512 GB NVMe SSD | 15" 2880x1800 | LG 34UM95 34" 3440x1440

HAL9000: HP EliteBook 840 G5 | i5-8250U 1.6 GHz | 16 GB DDR4 |  256 GB NVMe SSD | 14" 1920x1080 | Gigabyte GTX 1070

Hydrogen server: Xeon E5-2675 v3 | Cooler Master Hyper 212X | 64 GB Kingston/Samsung DDR4 ECC | Asus Z10PA-D8 | Asus GTX 1070 | Corsair AX860 | 256 GB Samsung 850 EVO + 3x 3 TB WD Red + 2 TB Seagate | Fractal Design Define R5 | unRAID 6.5.3

Carbon server: Fujitsu PRIMERGY RX100 S7p | Xeon E3-1230 v2 | 16 GB DDR3 ECC | 60 GB Corsair SSD & 250 GB Samsung 850 Pro | Intel i340-T4 | ESXi 6.5.1

Big Mac cluster: 2x Raspberry Pi 2 Model B | 1x Raspberry Pi 3 Model B | 2x Raspberry Pi 3 Model B+

Link to post
Share on other sites
Posted · Original PosterOP
1 minute ago, jj9987 said:

You can return the username instead of True, if the login is successful.


return usernameInput

 

Then since the rest of my code relies on knowing what the user names are, how could I assign it from that.


Specs:

Motherboard: Gigabyte Z97X Gaming 3

CPU: Intel Core I7 4790K

GPU: Gigabyte G1 Gaming GTX 970

RAM: HyperX Fury 16GB

HDD: Seagate ST3000DM001 3TB

SSD: KINGSTON SV300S37A480G 450GB

Cooler: Corsair H100i GTX

Case: NZXT H440 Red

Monitor: DELL U2412M

Keyboard: Gigabyte Force K7

Mouse: Corsair Sabre RGB

 

Link to post
Share on other sites
3 minutes ago, DerpDiamonds1 said:

Then since the rest of my code relies on knowing what the user names are, how could I assign it from that.

Not quite sure if I grasp what you are trying to do.

user1 = authentication()

The authentication function can return one of these three things:

- The username if login was successful (that is, if you used the return usernameInput row)

- False, if login was not successful due to incorrect password.

- None, if username was not found. Whether an account was created or not, doesn't matter as they do not affect the return value.

 

The return value of the function is assigned to the variable user1, which you can then use in succeeding code.


Skynet: MacBook Pro Late 2016 Space Gray | i7-6820HQ 2.7 GHz | 16 GB LPDDR3 | Radeon Pro 455 2048 MB | 512 GB NVMe SSD | 15" 2880x1800 | LG 34UM95 34" 3440x1440

HAL9000: HP EliteBook 840 G5 | i5-8250U 1.6 GHz | 16 GB DDR4 |  256 GB NVMe SSD | 14" 1920x1080 | Gigabyte GTX 1070

Hydrogen server: Xeon E5-2675 v3 | Cooler Master Hyper 212X | 64 GB Kingston/Samsung DDR4 ECC | Asus Z10PA-D8 | Asus GTX 1070 | Corsair AX860 | 256 GB Samsung 850 EVO + 3x 3 TB WD Red + 2 TB Seagate | Fractal Design Define R5 | unRAID 6.5.3

Carbon server: Fujitsu PRIMERGY RX100 S7p | Xeon E3-1230 v2 | 16 GB DDR3 ECC | 60 GB Corsair SSD & 250 GB Samsung 850 Pro | Intel i340-T4 | ESXi 6.5.1

Big Mac cluster: 2x Raspberry Pi 2 Model B | 1x Raspberry Pi 3 Model B | 2x Raspberry Pi 3 Model B+

Link to post
Share on other sites
Posted · Original PosterOP
1 minute ago, jj9987 said:

Not quite sure if I grasp what you are trying to do.


user1 = authentication()

The authentication function can return one of these three things:

- The username if login was successful (that is, if you used the return usernameInput row)

- False, if login was not successful due to incorrect password.

- None, if username was not found. Whether an account was created or not, doesn't matter as they do not affect the return value.

 

The return value of the function is assigned to the variable user1, which you can then use in succeeding code.

What I am trying to do is have user1 run the authentication function so it can validate its username and password and then assign that username to user1. Then do the same for user2, but assign the username they type in to user2.

 

Is that fine?


Specs:

Motherboard: Gigabyte Z97X Gaming 3

CPU: Intel Core I7 4790K

GPU: Gigabyte G1 Gaming GTX 970

RAM: HyperX Fury 16GB

HDD: Seagate ST3000DM001 3TB

SSD: KINGSTON SV300S37A480G 450GB

Cooler: Corsair H100i GTX

Case: NZXT H440 Red

Monitor: DELL U2412M

Keyboard: Gigabyte Force K7

Mouse: Corsair Sabre RGB

 

Link to post
Share on other sites
Posted · Original PosterOP

*bump* as i haven't gotten a reply


Specs:

Motherboard: Gigabyte Z97X Gaming 3

CPU: Intel Core I7 4790K

GPU: Gigabyte G1 Gaming GTX 970

RAM: HyperX Fury 16GB

HDD: Seagate ST3000DM001 3TB

SSD: KINGSTON SV300S37A480G 450GB

Cooler: Corsair H100i GTX

Case: NZXT H440 Red

Monitor: DELL U2412M

Keyboard: Gigabyte Force K7

Mouse: Corsair Sabre RGB

 

Link to post
Share on other sites

Is there any reason you're using a file rather than a hash?

 


{

    "user1":" password"

}

 

Save this as users.json 

 


with open('user.json', 'r') as json_file:  data = json.load(json_file)
	

 

then you can get user one with data["user1"] // this will return the value e.g password


                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to post
Share on other sites
Posted · Original PosterOP
2 minutes ago, vorticalbox said:

 


{

    "user1":" password"

}

 


with open('user.json', 'r') as json_file:  data = json.load(json_file)
	

Then you can get user one with data["user1"] // this will return the value e.g password

What do you mean?


Specs:

Motherboard: Gigabyte Z97X Gaming 3

CPU: Intel Core I7 4790K

GPU: Gigabyte G1 Gaming GTX 970

RAM: HyperX Fury 16GB

HDD: Seagate ST3000DM001 3TB

SSD: KINGSTON SV300S37A480G 450GB

Cooler: Corsair H100i GTX

Case: NZXT H440 Red

Monitor: DELL U2412M

Keyboard: Gigabyte Force K7

Mouse: Corsair Sabre RGB

 

Link to post
Share on other sites
Just now, DerpDiamonds1 said:

What do you mean?

A JSON object or a hash in python is an object of key-value pairs.

 

Not only will this let you select the information you're after without needing to loop a file and slip it is also much closer to a database would be.

 

I highly recommend you look into them for this sort of thing.


                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to post
Share on other sites

The structure of your program is not very good. Authentication should only authenticate, adding a new user should be its own function as should the whole menu options thing. Simply put:

users = {'user1':'password1', 'user2':'password2'}

def authentication(usr, pwd):
    try:
        password = users[usr]
        if password == pwd:
            return usr + ' successfully logged in'
        else:
            return 'Wrong password'
    except:
        return 'User not found'

def newUser(usr, pwd):
    if usr in users:
        return usr + ' already exists'
    users[usr] = pwd
    return usr + ' successfully created'

Both functions return a string for demonstration purposes. You can add your menu and then call authentication or newUser depending on what the user wants to do. Saving the users dict to a file is left as en exercise for the reader. 

Link to post
Share on other sites
Posted · Original PosterOP
21 minutes ago, Umberto said:

The structure of your program is not very good. Authentication should only authenticate, adding a new user should be its own function as should the whole menu options thing. Simply put:


users = {'user1':'password1', 'user2':'password2'}

def authentication(usr, pwd):
    try:
        password = users[usr]
        if password == pwd:
            return usr + ' successfully logged in'
        else:
            return 'Wrong password'
    except:
        return 'User not found'

def newUser(usr, pwd):
    if usr in users:
        return usr + ' already exists'
    users[usr] = pwd
    return usr + ' successfully created'

Both functions return a string for demonstration purposes. You can add your menu and then call authentication or newUser depending on what the user wants to do. Saving the users dict to a file is left as en exercise for the reader. 

My usernames are stored in a file


Specs:

Motherboard: Gigabyte Z97X Gaming 3

CPU: Intel Core I7 4790K

GPU: Gigabyte G1 Gaming GTX 970

RAM: HyperX Fury 16GB

HDD: Seagate ST3000DM001 3TB

SSD: KINGSTON SV300S37A480G 450GB

Cooler: Corsair H100i GTX

Case: NZXT H440 Red

Monitor: DELL U2412M

Keyboard: Gigabyte Force K7

Mouse: Corsair Sabre RGB

 

Link to post
Share on other sites
Posted · Original PosterOP
1 hour ago, vorticalbox said:

A JSON object or a hash in python is an object of key-value pairs.

 

Not only will this let you select the information you're after without needing to loop a file and slip it is also much closer to a database would be.

 

I highly recommend you look into them for this sort of thing.

How could I do that for this application then?


Specs:

Motherboard: Gigabyte Z97X Gaming 3

CPU: Intel Core I7 4790K

GPU: Gigabyte G1 Gaming GTX 970

RAM: HyperX Fury 16GB

HDD: Seagate ST3000DM001 3TB

SSD: KINGSTON SV300S37A480G 450GB

Cooler: Corsair H100i GTX

Case: NZXT H440 Red

Monitor: DELL U2412M

Keyboard: Gigabyte Force K7

Mouse: Corsair Sabre RGB

 

Link to post
Share on other sites
37 minutes ago, DerpDiamonds1 said:

My usernames are stored in a file

I can see that. 

You can read your file at the start and store the values in the dict, and write the new values to the file at an appropriate time. 

 

JSON is a data format and a hash is the output of a hash function, just so that there are no confusion there. 

Link to post
Share on other sites
Posted · Original PosterOP
1 hour ago, Umberto said:

I can see that. 

You can read your file at the start and store the values in the dict, and write the new values to the file at an appropriate time. 

 

JSON is a data format and a hash is the output of a hash function, just so that there are no confusion there. 

Oh I get it now, but how exactly do you write that?


Specs:

Motherboard: Gigabyte Z97X Gaming 3

CPU: Intel Core I7 4790K

GPU: Gigabyte G1 Gaming GTX 970

RAM: HyperX Fury 16GB

HDD: Seagate ST3000DM001 3TB

SSD: KINGSTON SV300S37A480G 450GB

Cooler: Corsair H100i GTX

Case: NZXT H440 Red

Monitor: DELL U2412M

Keyboard: Gigabyte Force K7

Mouse: Corsair Sabre RGB

 

Link to post
Share on other sites
20 hours ago, DerpDiamonds1 said:

Oh, I get it now, but how exactly do you write that?

Once I get to work tomorrow ill throw some code together in a break.

 

 


                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to post
Share on other sites
Posted · Original PosterOP
26 minutes ago, vorticalbox said:

Once I get to work tomorrow ill throw some code together in a break.

 

 

Thanks a lot!


Specs:

Motherboard: Gigabyte Z97X Gaming 3

CPU: Intel Core I7 4790K

GPU: Gigabyte G1 Gaming GTX 970

RAM: HyperX Fury 16GB

HDD: Seagate ST3000DM001 3TB

SSD: KINGSTON SV300S37A480G 450GB

Cooler: Corsair H100i GTX

Case: NZXT H440 Red

Monitor: DELL U2412M

Keyboard: Gigabyte Force K7

Mouse: Corsair Sabre RGB

 

Link to post
Share on other sites
11 hours ago, DerpDiamonds1 said:

Thanks a lot!

users.json

{
  "vorticalbox": "qaz123"
}

 

python

import json

def check_password(valid, password):
  return valid == password


def auth(username, password):
  with open('users.json') as json_file:  
      data = json.load(json_file)
      try:
        return check_password(data[username], password)
      except KeyError:
        return 'user does not exist'
      except:
        return 'Something went wrong'


print(auth('vorticalbox', '')) #false
print(auth('vorticalbox', 'qaz123')) #true
print(auth('test', '')) # user does not exist

 


                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to post
Share on other sites
Posted · Original PosterOP
6 hours ago, vorticalbox said:

users.json


{
  "vorticalbox": "qaz123"
}

 

python


import json

def check_password(valid, password):
  return valid == password


def auth(username, password):
  with open('users.json') as json_file:  
      data = json.load(json_file)
      try:
        return check_password(data[username], password)
      except KeyError:
        return 'user does not exist'
      except:
        return 'Something went wrong'


print(auth('vorticalbox', '')) #false
print(auth('vorticalbox', 'qaz123')) #true
print(auth('test', '')) # user does not exist

 

Thanks thats great, but could this be done with a .txt file. If you could you explain how each line works as I am not familiar wITH .json files in python.

 

Also why .json files over .txt files?


Specs:

Motherboard: Gigabyte Z97X Gaming 3

CPU: Intel Core I7 4790K

GPU: Gigabyte G1 Gaming GTX 970

RAM: HyperX Fury 16GB

HDD: Seagate ST3000DM001 3TB

SSD: KINGSTON SV300S37A480G 450GB

Cooler: Corsair H100i GTX

Case: NZXT H440 Red

Monitor: DELL U2412M

Keyboard: Gigabyte Force K7

Mouse: Corsair Sabre RGB

 

Link to post
Share on other sites
33 minutes ago, DerpDiamonds1 said:

Thanks thats great, but could this be done with a .txt file. If you could you explain how each line works as I am not familiar wITH .json files in python.

 

Also why .json files over .txt files?

json is universal meaning I could take this data and load into node or c# and still beable to work with the data. it's faster then a txt as you don't have to loop over every line, check if the user names match then check if the password matches.

 

It also stops you have duplicate names as you can only have a key once.

 


data[username]

 

data is the hash object and username, in this case vorticalbox is the key. JSON is a key value pair.


                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


×