0

I'm currently using JSON to make a username/password program but I have a problem with duplicate accounts. I tried to code a way to prevent users from creating usernames that the JSON database already contains, but it doesn't quite work.

Problems:

  • Asks for the username, doesn't ask for the password even when the file tried is empty

  • Sometimes says the username already exists, but creates the account duplicate anyway.

What I want the program to do:

  • Ask for the new username/password
  • If the username is unique, place the new account in the file
  • If the username is already owned, don't add the new account and go to the start of the function.

How would I do this efficiently? This is the code I've tried, but the problems I mentioned make it invalid

def createUser():
    global accounts
    nUsername = input("Create Username »  ")
    for item in accounts:
        if item[0] == nUsername:
            return "Already Exsists!"
        else:
            nPassword = input("Create Password » ")
            entry = [nUsername, nPassword]
            accounts.append(entry)
            accounts = accounts[:500000]
            autoSave()

For anyone wondering, this is what the autosave() function is:

def autoSave():
    with open("Accounts.json", "w") as outfile:
        json.dump(accounts, outfile)

And this is what the inside of the JSON file looks like:

[["ExampleUsername", "BadPasswrdo14130"]]

3 Answers 3

2

There is many mistakes so I will use comment to explain changes:

# you file containt utf8 chars, you need to specify encoding
# coding=utf-8

import os
import json

# I use a dict structure instead of a list for easier retrieval
# you can easily see if an account exist and get its password
# also global keyword is to avoid, so prefer declaring in the global context instead of pushing to the global context
accounts = {}

# if we have a file, deserialize content
if os.path.exists("/tmp/Accounts.json"):
    try:
        with open("/tmp/Accounts.json") as f:
            accounts = dict(json.loads(f.read()))
    except:
        pass

def createUser():
    # input is equivalent to eval(raw_input(... which is not the goal here
    nUsername = raw_input("Create Username »  ")

    # with a dict, no need to iterate through, simply use `in`
    if nUsername in accounts.keys():
        return createUser()

    nPassword = raw_input("Create Password » ")
    # this is how you assign the new account
    accounts[nUsername] = nPassword
    autoSave()

def autoSave():
    with open("/tmp/Accounts.json", "w") as outfile:
        # we convert here the dict to your list structure
        json.dump(list(accounts.iteritems()), outfile)

def existingUser():
    eUsername = raw_input("Your Username » ")
    ePassword = raw_input("Your Password » ")

    for item in accounts:
        if eUsername in accounts and accounts[eUsername] == ePassword:
            return 'Processing Sucessfully logged into your account!'
        else:
            return "Login failed"

createUser()
Sign up to request clarification or add additional context in comments.

8 Comments

This works! Only one problem, when a new account is created the JSON file is replaced with only that new account, it doesent contain any others. In other words, its only allowing one account?
Edit: Mistake on my part. Fixed
I also edit to save as a json list, so it looks like what you expect.
I don't think you fixed the problem. JSON supports dict-like structures so I don't see why you would need to convert it into a list. But I think you need to import the file at the beginning of your script instead of initializing an empty dict (accounts = {}).
I will add an edit to allow retrieval of serialized accounts.
|
0

I would do it this way:

# This function will help us to check if the user already exists
def alreadyExist(nUsername):
    global accounts
    for account in accounts:
        if account[0] == nUsername
            return True
    return False


def createUser():
    global accounts

    # We declarate nUsername first as None
    nUsername = None

    # While the username exists, we have to ask the user for the username
    while not nUsername or alreadyExist(nUsername):
        nUsername = input("Create Username »  ")

    # We are out of the bucle. The username doesn't exist, we can ask for the password
    nPassword = input("Create Password » ")
    entry = [nUsername, nPassword]
    accounts.append(entry)
    accounts = accounts[:500000]
    autoSave()

1 Comment

Tried this.. Doesen't end. Repeats asking for nUsername + nPassword. Does create the account in the file though. Also doesent prevent dups.
0

Fixed one issue of my code, but made another. This section was working fine before the chances from @CyrBill

def existingUser():
eUsername = input("Your Username » ")
ePassword = input("Your Password » ")

for item in accounts: #no need for braces
    if item[0] == eUsername and item[1] == ePassword:
        return 'Processing Sucessfully logged into your account!'
    else:
        return "Login failed"

4 Comments

I edit my answer, avoid reply to your question with another question. Prefer editing your post or, better, creating a new one.
Oh, and you misspelled my name ! :(
Sorry about your name! xD. Thanks, though. Code's working perfect now.
Still misspelled, If we are done with your problem, please accept an answer to close the topic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.