Authentication script in PythonAJAX request authentication to PHP scriptAuthentication serviceLogin AuthenticationA Simple, One-Page PHP Admin Login (with prepared SQL statements)OpenVPN Authentication ScriptUser Authentication PHP script2-factor authentication code generator in Python 3Simple authentication and registration of usersAuthentication API scriptPython BruteForce Script

How to bake one texture for one mesh with multiple textures blender 2.8

What is this cable/device?

Non-trope happy ending?

If infinitesimal transformations commute why dont the generators of the Lorentz group commute?

A social experiment. What is the worst that can happen?

It grows, but water kills it

How do I find all files that end with a dot

How to indicate a cut out for a product window

Is there a single word describing earning money through any means?

Loading commands from file

On a tidally locked planet, would time be quantized?

Travelling outside the UK without a passport

Open a doc from terminal, but not by its name

Melting point of aspirin, contradicting sources

How should I respond when I lied about my education and the company finds out through background check?

When were female captains banned from Starfleet?

If a character has darkvision, can they see through an area of nonmagical darkness filled with lightly obscuring gas?

How to implement a feedback to keep the DC gain at zero for this conceptual passive filter?

Why is so much work done on numerical verification of the Riemann Hypothesis?

Lowest total scrabble score

WiFi Thermostat, No C Terminal on Furnace

How can Trident be so inexpensive? Will it orbit Triton or just do a (slow) flyby?

Offered money to buy a house, seller is asking for more to cover gap between their listing and mortgage owed

Count the occurrence of each unique word in the file



Authentication script in Python


AJAX request authentication to PHP scriptAuthentication serviceLogin AuthenticationA Simple, One-Page PHP Admin Login (with prepared SQL statements)OpenVPN Authentication ScriptUser Authentication PHP script2-factor authentication code generator in Python 3Simple authentication and registration of usersAuthentication API scriptPython BruteForce Script













-1












$begingroup$


I just finished working on a personal project, it is a sort of email type program where you create an account and you can message people, the code works (as far as I’m aware) but it requires review, different areas have different indents, I add more variable than I need, I print things that don’t need to be printed and probably way more than that.



(I realise that it will say import getpass ,and have nothing for it in the code , that is because i forgot to change the password inputs to getpass inputs before putting it on my drive.)



Where the code is located in your files you need a folder called Data with txt files: accountIDs, addCommandList, isAdmin, names, nicknames, passwords.



A folder called messages in it a folder called received.



import random
from random import *
import datetime
import string
import os
import getpass
global usernames
global passwords
global jointPassList
usernames = [line.strip()for line in open('Data/names.txt', 'r')]
passwords = [line.strip()for line in open('Data/passwords.txt', 'r')]
isAdmin = [line.strip()for line in open('Data/isAdmin.txt', 'r')]
accountIDs = [line.strip()for line in open('Data/accountIDs.txt', 'r')]
nicknames = [line.strip()for line in open('Data/nicknames.txt', 'r')]
jointPassList ='n'.join(map(str, passwords))

def main():
print('n')
print('n')
print('/help (1/2) for help')
currentUserIndex = usernames.index(ascname)
command =input('>>>')
if command =='/help':

print('/signout | sign outn/details | account detailsn/setpas | set passwordn/userlist | all usersn/mymessages | your messagesn/message | messagen/addcommand | add command')
input()
main()
if command =='/details':

print('Name: ', ascname)
print('AccountID: ', accountIDs[currentUserIndex])
print('Nickname: ', nicknames[currentUserIndex])
input()
main()
if command =='/setpas':

newpas =input('Enter your new password: ')
passwords[currentUserIndex] = newpas
jointPassList ='n'.join(map(str, passwords))
openfile =open('Data/passwords.txt', 'w')
openfile.write(jointPassList)
openfile.close()
input()
main()
if command =='/userlist':
userlist =open('Data/names.txt').read()
print(userlist)
input()
main()
if command =='/message':
whatuser =input('What user: ')
if whatuser in usernames:
message =input('What message would you like to send: ')
openfile =open('Data/messages/recieved/'+whatuser+'.txt', 'a')
date = str(datetime.datetime.now())
openfile.write(date + ' : ')
openfile.write(message+'n')
openfile.close()
input()
main()

elif whatuser not in usernames:
print('Nobody was found.')
input()
main()

if command =='/mymessages':
messagesList = [line.strip()for line in open('Data/messages/recieved/'+ascname+'.txt', 'r')]
messages = 'n'.join(messagesList)
print(messages)
input()
main()

if command =='/addcommand':
openfile =open('Data/addCommandList.txt', 'a')
addcommand =input('What would you like see added to this database: ')
openfile.write(addcommand+'n')
openfile.close()
input()
main()

if command =='/admin':
print(isAdmin[currentUserIndex])
if isAdmin[currentUserIndex] =='True':
print('Nice :)')
input()
main()

elif isAdmin[currentUserIndex] =='False':
print('You are not an Admin')
change =input()
if change =='False':
isAdmin[currentUserIndex] = True
main()
else:
main()

if isAdmin[currentUserIndex] =='False':
delete =input('Are you sure you would like to delete your account: ')
if delete =='y':
accountIDs.remove(accountIDs[currentUserIndex])
isAdmin.remove(isAdmin[currentUserIndex])
usernames.remove(usernames[currentUserIndex])
passwords.remove(passwords[currentUserIndex])
nicknames.remove(nicknames[currentUserIndex])
os.remove('Data/messages/recieved/'+ascname+'.txt')
openfile = open('Data/names.txt', 'w')
openfile.write(name + 'n')
openfile.close()

openfile = open('Data/accountIDs.txt', 'w')
openfile.write(str(accountID) + 'n')
openfile.close()

openfile = open('Data/nicknames.txt', 'w')
openfile.write(nickname + 'n')
openfile.close()

openfile = open('Data/passwords.txt', 'w')
openfile.write(password + 'n')
openfile.close()

openfile = open('Data/isAdmin.txt', 'w')
openfile.write(adminFalse + 'n')
openfile.close()
print('Complete...')
signin()


if command =='/signout':

areYouSure =input('Are you sure you would like to sign out(y/n): ')
if areYouSure =='y':
print('Signing outn.n.n.')
signin()
elif areYouSure =='n':
main()
else:
main()


else:
print(command, 'is not a command in our library, type /addcommand to request new command.')
input()
main()

def signin():
existingAccount =input('Do you have an existing account (y/n): ')
if existingAccount =='y':
global ascname
global ascpass
ascname =input('Enter your username: ')
currentUsername = ascname
if ascname in usernames:
userIndex = usernames.index(ascname)
print('Correct username.')
ascpass =input('Enter your password: ')
while ascpass in passwords:
passcheck = passwords.index(ascpass)
if userIndex == passcheck:
print('welcome back', ascname + '.')
main()

else:
wrongPass =input('Incorrect password.')
input()
signin()
print('Yes')
wrongPass =input('Incorrect password.')
input()
signin()
elif ascname not in usernames:
wrongName =input('Incorrect username.')
input()
signin()
else:
#debuging
print('Error')
singin()

elif existingAccount =='n':
name =str(input('Enter your name: '))
while len(name) == 0:
name =input("You haven't entered anything, try again.")
input()
signin()
if name in open('Data/names.txt').read():
name =input('That name already exists.')
input()
signin()
usernames.append(name)
password =input('Enter your new password: ')
while len(password) < 4:
password =input('Your password must be 5 characters long.')
input()
signin()
passwords.append(password)

nickname =input('Enter your nickname: ')
accountID =random()
while accountID in accountIDs:
accountID =random()

adminFalse = str(False)
isAdmin.append(adminFalse)

openfile = open('Data/messages/recieved/' +name+ '.txt', 'w+')
openfile.write('n')
openfile.close()

openfile = open('Data/names.txt', 'a')
openfile.write(name + 'n')
openfile.close()

openfile = open('Data/accountIDs.txt', 'a')
openfile.write(str(accountID) + 'n')
openfile.close()

openfile = open('Data/nicknames.txt', 'a')
openfile.write(nickname + 'n')
openfile.close()

openfile = open('Data/passwords.txt', 'a')
openfile.write(password + 'n')
openfile.close()

openfile = open('Data/isAdmin.txt', 'a')
openfile.write(adminFalse + 'n')
openfile.close()



signin()

else:
signin()

signin()









share|improve this question









New contributor




King_0_king is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$







  • 5




    $begingroup$
    Why don't you clean up the things that you know should be cleaned up (such as indentation) before asking for our advice?
    $endgroup$
    – 200_success
    12 hours ago










  • $begingroup$
    Thank you Emma for the edit, I am very new to this. There were no incorrect indents and i have added comments.
    $endgroup$
    – King_0_king
    8 hours ago







  • 1




    $begingroup$
    An answer was written while you proposed changes, invalidating the edit. This is not a forum where you should keep the most updated version in your question. Please see what you may and may not do after receiving answers. Feel free to incorporate the suggested changes and post a follow-up question instead. Please note, it may be beneficial to wait at least 2 days before doing so.
    $endgroup$
    – Mast
    8 hours ago















-1












$begingroup$


I just finished working on a personal project, it is a sort of email type program where you create an account and you can message people, the code works (as far as I’m aware) but it requires review, different areas have different indents, I add more variable than I need, I print things that don’t need to be printed and probably way more than that.



(I realise that it will say import getpass ,and have nothing for it in the code , that is because i forgot to change the password inputs to getpass inputs before putting it on my drive.)



Where the code is located in your files you need a folder called Data with txt files: accountIDs, addCommandList, isAdmin, names, nicknames, passwords.



A folder called messages in it a folder called received.



import random
from random import *
import datetime
import string
import os
import getpass
global usernames
global passwords
global jointPassList
usernames = [line.strip()for line in open('Data/names.txt', 'r')]
passwords = [line.strip()for line in open('Data/passwords.txt', 'r')]
isAdmin = [line.strip()for line in open('Data/isAdmin.txt', 'r')]
accountIDs = [line.strip()for line in open('Data/accountIDs.txt', 'r')]
nicknames = [line.strip()for line in open('Data/nicknames.txt', 'r')]
jointPassList ='n'.join(map(str, passwords))

def main():
print('n')
print('n')
print('/help (1/2) for help')
currentUserIndex = usernames.index(ascname)
command =input('>>>')
if command =='/help':

print('/signout | sign outn/details | account detailsn/setpas | set passwordn/userlist | all usersn/mymessages | your messagesn/message | messagen/addcommand | add command')
input()
main()
if command =='/details':

print('Name: ', ascname)
print('AccountID: ', accountIDs[currentUserIndex])
print('Nickname: ', nicknames[currentUserIndex])
input()
main()
if command =='/setpas':

newpas =input('Enter your new password: ')
passwords[currentUserIndex] = newpas
jointPassList ='n'.join(map(str, passwords))
openfile =open('Data/passwords.txt', 'w')
openfile.write(jointPassList)
openfile.close()
input()
main()
if command =='/userlist':
userlist =open('Data/names.txt').read()
print(userlist)
input()
main()
if command =='/message':
whatuser =input('What user: ')
if whatuser in usernames:
message =input('What message would you like to send: ')
openfile =open('Data/messages/recieved/'+whatuser+'.txt', 'a')
date = str(datetime.datetime.now())
openfile.write(date + ' : ')
openfile.write(message+'n')
openfile.close()
input()
main()

elif whatuser not in usernames:
print('Nobody was found.')
input()
main()

if command =='/mymessages':
messagesList = [line.strip()for line in open('Data/messages/recieved/'+ascname+'.txt', 'r')]
messages = 'n'.join(messagesList)
print(messages)
input()
main()

if command =='/addcommand':
openfile =open('Data/addCommandList.txt', 'a')
addcommand =input('What would you like see added to this database: ')
openfile.write(addcommand+'n')
openfile.close()
input()
main()

if command =='/admin':
print(isAdmin[currentUserIndex])
if isAdmin[currentUserIndex] =='True':
print('Nice :)')
input()
main()

elif isAdmin[currentUserIndex] =='False':
print('You are not an Admin')
change =input()
if change =='False':
isAdmin[currentUserIndex] = True
main()
else:
main()

if isAdmin[currentUserIndex] =='False':
delete =input('Are you sure you would like to delete your account: ')
if delete =='y':
accountIDs.remove(accountIDs[currentUserIndex])
isAdmin.remove(isAdmin[currentUserIndex])
usernames.remove(usernames[currentUserIndex])
passwords.remove(passwords[currentUserIndex])
nicknames.remove(nicknames[currentUserIndex])
os.remove('Data/messages/recieved/'+ascname+'.txt')
openfile = open('Data/names.txt', 'w')
openfile.write(name + 'n')
openfile.close()

openfile = open('Data/accountIDs.txt', 'w')
openfile.write(str(accountID) + 'n')
openfile.close()

openfile = open('Data/nicknames.txt', 'w')
openfile.write(nickname + 'n')
openfile.close()

openfile = open('Data/passwords.txt', 'w')
openfile.write(password + 'n')
openfile.close()

openfile = open('Data/isAdmin.txt', 'w')
openfile.write(adminFalse + 'n')
openfile.close()
print('Complete...')
signin()


if command =='/signout':

areYouSure =input('Are you sure you would like to sign out(y/n): ')
if areYouSure =='y':
print('Signing outn.n.n.')
signin()
elif areYouSure =='n':
main()
else:
main()


else:
print(command, 'is not a command in our library, type /addcommand to request new command.')
input()
main()

def signin():
existingAccount =input('Do you have an existing account (y/n): ')
if existingAccount =='y':
global ascname
global ascpass
ascname =input('Enter your username: ')
currentUsername = ascname
if ascname in usernames:
userIndex = usernames.index(ascname)
print('Correct username.')
ascpass =input('Enter your password: ')
while ascpass in passwords:
passcheck = passwords.index(ascpass)
if userIndex == passcheck:
print('welcome back', ascname + '.')
main()

else:
wrongPass =input('Incorrect password.')
input()
signin()
print('Yes')
wrongPass =input('Incorrect password.')
input()
signin()
elif ascname not in usernames:
wrongName =input('Incorrect username.')
input()
signin()
else:
#debuging
print('Error')
singin()

elif existingAccount =='n':
name =str(input('Enter your name: '))
while len(name) == 0:
name =input("You haven't entered anything, try again.")
input()
signin()
if name in open('Data/names.txt').read():
name =input('That name already exists.')
input()
signin()
usernames.append(name)
password =input('Enter your new password: ')
while len(password) < 4:
password =input('Your password must be 5 characters long.')
input()
signin()
passwords.append(password)

nickname =input('Enter your nickname: ')
accountID =random()
while accountID in accountIDs:
accountID =random()

adminFalse = str(False)
isAdmin.append(adminFalse)

openfile = open('Data/messages/recieved/' +name+ '.txt', 'w+')
openfile.write('n')
openfile.close()

openfile = open('Data/names.txt', 'a')
openfile.write(name + 'n')
openfile.close()

openfile = open('Data/accountIDs.txt', 'a')
openfile.write(str(accountID) + 'n')
openfile.close()

openfile = open('Data/nicknames.txt', 'a')
openfile.write(nickname + 'n')
openfile.close()

openfile = open('Data/passwords.txt', 'a')
openfile.write(password + 'n')
openfile.close()

openfile = open('Data/isAdmin.txt', 'a')
openfile.write(adminFalse + 'n')
openfile.close()



signin()

else:
signin()

signin()









share|improve this question









New contributor




King_0_king is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$







  • 5




    $begingroup$
    Why don't you clean up the things that you know should be cleaned up (such as indentation) before asking for our advice?
    $endgroup$
    – 200_success
    12 hours ago










  • $begingroup$
    Thank you Emma for the edit, I am very new to this. There were no incorrect indents and i have added comments.
    $endgroup$
    – King_0_king
    8 hours ago







  • 1




    $begingroup$
    An answer was written while you proposed changes, invalidating the edit. This is not a forum where you should keep the most updated version in your question. Please see what you may and may not do after receiving answers. Feel free to incorporate the suggested changes and post a follow-up question instead. Please note, it may be beneficial to wait at least 2 days before doing so.
    $endgroup$
    – Mast
    8 hours ago













-1












-1








-1





$begingroup$


I just finished working on a personal project, it is a sort of email type program where you create an account and you can message people, the code works (as far as I’m aware) but it requires review, different areas have different indents, I add more variable than I need, I print things that don’t need to be printed and probably way more than that.



(I realise that it will say import getpass ,and have nothing for it in the code , that is because i forgot to change the password inputs to getpass inputs before putting it on my drive.)



Where the code is located in your files you need a folder called Data with txt files: accountIDs, addCommandList, isAdmin, names, nicknames, passwords.



A folder called messages in it a folder called received.



import random
from random import *
import datetime
import string
import os
import getpass
global usernames
global passwords
global jointPassList
usernames = [line.strip()for line in open('Data/names.txt', 'r')]
passwords = [line.strip()for line in open('Data/passwords.txt', 'r')]
isAdmin = [line.strip()for line in open('Data/isAdmin.txt', 'r')]
accountIDs = [line.strip()for line in open('Data/accountIDs.txt', 'r')]
nicknames = [line.strip()for line in open('Data/nicknames.txt', 'r')]
jointPassList ='n'.join(map(str, passwords))

def main():
print('n')
print('n')
print('/help (1/2) for help')
currentUserIndex = usernames.index(ascname)
command =input('>>>')
if command =='/help':

print('/signout | sign outn/details | account detailsn/setpas | set passwordn/userlist | all usersn/mymessages | your messagesn/message | messagen/addcommand | add command')
input()
main()
if command =='/details':

print('Name: ', ascname)
print('AccountID: ', accountIDs[currentUserIndex])
print('Nickname: ', nicknames[currentUserIndex])
input()
main()
if command =='/setpas':

newpas =input('Enter your new password: ')
passwords[currentUserIndex] = newpas
jointPassList ='n'.join(map(str, passwords))
openfile =open('Data/passwords.txt', 'w')
openfile.write(jointPassList)
openfile.close()
input()
main()
if command =='/userlist':
userlist =open('Data/names.txt').read()
print(userlist)
input()
main()
if command =='/message':
whatuser =input('What user: ')
if whatuser in usernames:
message =input('What message would you like to send: ')
openfile =open('Data/messages/recieved/'+whatuser+'.txt', 'a')
date = str(datetime.datetime.now())
openfile.write(date + ' : ')
openfile.write(message+'n')
openfile.close()
input()
main()

elif whatuser not in usernames:
print('Nobody was found.')
input()
main()

if command =='/mymessages':
messagesList = [line.strip()for line in open('Data/messages/recieved/'+ascname+'.txt', 'r')]
messages = 'n'.join(messagesList)
print(messages)
input()
main()

if command =='/addcommand':
openfile =open('Data/addCommandList.txt', 'a')
addcommand =input('What would you like see added to this database: ')
openfile.write(addcommand+'n')
openfile.close()
input()
main()

if command =='/admin':
print(isAdmin[currentUserIndex])
if isAdmin[currentUserIndex] =='True':
print('Nice :)')
input()
main()

elif isAdmin[currentUserIndex] =='False':
print('You are not an Admin')
change =input()
if change =='False':
isAdmin[currentUserIndex] = True
main()
else:
main()

if isAdmin[currentUserIndex] =='False':
delete =input('Are you sure you would like to delete your account: ')
if delete =='y':
accountIDs.remove(accountIDs[currentUserIndex])
isAdmin.remove(isAdmin[currentUserIndex])
usernames.remove(usernames[currentUserIndex])
passwords.remove(passwords[currentUserIndex])
nicknames.remove(nicknames[currentUserIndex])
os.remove('Data/messages/recieved/'+ascname+'.txt')
openfile = open('Data/names.txt', 'w')
openfile.write(name + 'n')
openfile.close()

openfile = open('Data/accountIDs.txt', 'w')
openfile.write(str(accountID) + 'n')
openfile.close()

openfile = open('Data/nicknames.txt', 'w')
openfile.write(nickname + 'n')
openfile.close()

openfile = open('Data/passwords.txt', 'w')
openfile.write(password + 'n')
openfile.close()

openfile = open('Data/isAdmin.txt', 'w')
openfile.write(adminFalse + 'n')
openfile.close()
print('Complete...')
signin()


if command =='/signout':

areYouSure =input('Are you sure you would like to sign out(y/n): ')
if areYouSure =='y':
print('Signing outn.n.n.')
signin()
elif areYouSure =='n':
main()
else:
main()


else:
print(command, 'is not a command in our library, type /addcommand to request new command.')
input()
main()

def signin():
existingAccount =input('Do you have an existing account (y/n): ')
if existingAccount =='y':
global ascname
global ascpass
ascname =input('Enter your username: ')
currentUsername = ascname
if ascname in usernames:
userIndex = usernames.index(ascname)
print('Correct username.')
ascpass =input('Enter your password: ')
while ascpass in passwords:
passcheck = passwords.index(ascpass)
if userIndex == passcheck:
print('welcome back', ascname + '.')
main()

else:
wrongPass =input('Incorrect password.')
input()
signin()
print('Yes')
wrongPass =input('Incorrect password.')
input()
signin()
elif ascname not in usernames:
wrongName =input('Incorrect username.')
input()
signin()
else:
#debuging
print('Error')
singin()

elif existingAccount =='n':
name =str(input('Enter your name: '))
while len(name) == 0:
name =input("You haven't entered anything, try again.")
input()
signin()
if name in open('Data/names.txt').read():
name =input('That name already exists.')
input()
signin()
usernames.append(name)
password =input('Enter your new password: ')
while len(password) < 4:
password =input('Your password must be 5 characters long.')
input()
signin()
passwords.append(password)

nickname =input('Enter your nickname: ')
accountID =random()
while accountID in accountIDs:
accountID =random()

adminFalse = str(False)
isAdmin.append(adminFalse)

openfile = open('Data/messages/recieved/' +name+ '.txt', 'w+')
openfile.write('n')
openfile.close()

openfile = open('Data/names.txt', 'a')
openfile.write(name + 'n')
openfile.close()

openfile = open('Data/accountIDs.txt', 'a')
openfile.write(str(accountID) + 'n')
openfile.close()

openfile = open('Data/nicknames.txt', 'a')
openfile.write(nickname + 'n')
openfile.close()

openfile = open('Data/passwords.txt', 'a')
openfile.write(password + 'n')
openfile.close()

openfile = open('Data/isAdmin.txt', 'a')
openfile.write(adminFalse + 'n')
openfile.close()



signin()

else:
signin()

signin()









share|improve this question









New contributor




King_0_king is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$




I just finished working on a personal project, it is a sort of email type program where you create an account and you can message people, the code works (as far as I’m aware) but it requires review, different areas have different indents, I add more variable than I need, I print things that don’t need to be printed and probably way more than that.



(I realise that it will say import getpass ,and have nothing for it in the code , that is because i forgot to change the password inputs to getpass inputs before putting it on my drive.)



Where the code is located in your files you need a folder called Data with txt files: accountIDs, addCommandList, isAdmin, names, nicknames, passwords.



A folder called messages in it a folder called received.



import random
from random import *
import datetime
import string
import os
import getpass
global usernames
global passwords
global jointPassList
usernames = [line.strip()for line in open('Data/names.txt', 'r')]
passwords = [line.strip()for line in open('Data/passwords.txt', 'r')]
isAdmin = [line.strip()for line in open('Data/isAdmin.txt', 'r')]
accountIDs = [line.strip()for line in open('Data/accountIDs.txt', 'r')]
nicknames = [line.strip()for line in open('Data/nicknames.txt', 'r')]
jointPassList ='n'.join(map(str, passwords))

def main():
print('n')
print('n')
print('/help (1/2) for help')
currentUserIndex = usernames.index(ascname)
command =input('>>>')
if command =='/help':

print('/signout | sign outn/details | account detailsn/setpas | set passwordn/userlist | all usersn/mymessages | your messagesn/message | messagen/addcommand | add command')
input()
main()
if command =='/details':

print('Name: ', ascname)
print('AccountID: ', accountIDs[currentUserIndex])
print('Nickname: ', nicknames[currentUserIndex])
input()
main()
if command =='/setpas':

newpas =input('Enter your new password: ')
passwords[currentUserIndex] = newpas
jointPassList ='n'.join(map(str, passwords))
openfile =open('Data/passwords.txt', 'w')
openfile.write(jointPassList)
openfile.close()
input()
main()
if command =='/userlist':
userlist =open('Data/names.txt').read()
print(userlist)
input()
main()
if command =='/message':
whatuser =input('What user: ')
if whatuser in usernames:
message =input('What message would you like to send: ')
openfile =open('Data/messages/recieved/'+whatuser+'.txt', 'a')
date = str(datetime.datetime.now())
openfile.write(date + ' : ')
openfile.write(message+'n')
openfile.close()
input()
main()

elif whatuser not in usernames:
print('Nobody was found.')
input()
main()

if command =='/mymessages':
messagesList = [line.strip()for line in open('Data/messages/recieved/'+ascname+'.txt', 'r')]
messages = 'n'.join(messagesList)
print(messages)
input()
main()

if command =='/addcommand':
openfile =open('Data/addCommandList.txt', 'a')
addcommand =input('What would you like see added to this database: ')
openfile.write(addcommand+'n')
openfile.close()
input()
main()

if command =='/admin':
print(isAdmin[currentUserIndex])
if isAdmin[currentUserIndex] =='True':
print('Nice :)')
input()
main()

elif isAdmin[currentUserIndex] =='False':
print('You are not an Admin')
change =input()
if change =='False':
isAdmin[currentUserIndex] = True
main()
else:
main()

if isAdmin[currentUserIndex] =='False':
delete =input('Are you sure you would like to delete your account: ')
if delete =='y':
accountIDs.remove(accountIDs[currentUserIndex])
isAdmin.remove(isAdmin[currentUserIndex])
usernames.remove(usernames[currentUserIndex])
passwords.remove(passwords[currentUserIndex])
nicknames.remove(nicknames[currentUserIndex])
os.remove('Data/messages/recieved/'+ascname+'.txt')
openfile = open('Data/names.txt', 'w')
openfile.write(name + 'n')
openfile.close()

openfile = open('Data/accountIDs.txt', 'w')
openfile.write(str(accountID) + 'n')
openfile.close()

openfile = open('Data/nicknames.txt', 'w')
openfile.write(nickname + 'n')
openfile.close()

openfile = open('Data/passwords.txt', 'w')
openfile.write(password + 'n')
openfile.close()

openfile = open('Data/isAdmin.txt', 'w')
openfile.write(adminFalse + 'n')
openfile.close()
print('Complete...')
signin()


if command =='/signout':

areYouSure =input('Are you sure you would like to sign out(y/n): ')
if areYouSure =='y':
print('Signing outn.n.n.')
signin()
elif areYouSure =='n':
main()
else:
main()


else:
print(command, 'is not a command in our library, type /addcommand to request new command.')
input()
main()

def signin():
existingAccount =input('Do you have an existing account (y/n): ')
if existingAccount =='y':
global ascname
global ascpass
ascname =input('Enter your username: ')
currentUsername = ascname
if ascname in usernames:
userIndex = usernames.index(ascname)
print('Correct username.')
ascpass =input('Enter your password: ')
while ascpass in passwords:
passcheck = passwords.index(ascpass)
if userIndex == passcheck:
print('welcome back', ascname + '.')
main()

else:
wrongPass =input('Incorrect password.')
input()
signin()
print('Yes')
wrongPass =input('Incorrect password.')
input()
signin()
elif ascname not in usernames:
wrongName =input('Incorrect username.')
input()
signin()
else:
#debuging
print('Error')
singin()

elif existingAccount =='n':
name =str(input('Enter your name: '))
while len(name) == 0:
name =input("You haven't entered anything, try again.")
input()
signin()
if name in open('Data/names.txt').read():
name =input('That name already exists.')
input()
signin()
usernames.append(name)
password =input('Enter your new password: ')
while len(password) < 4:
password =input('Your password must be 5 characters long.')
input()
signin()
passwords.append(password)

nickname =input('Enter your nickname: ')
accountID =random()
while accountID in accountIDs:
accountID =random()

adminFalse = str(False)
isAdmin.append(adminFalse)

openfile = open('Data/messages/recieved/' +name+ '.txt', 'w+')
openfile.write('n')
openfile.close()

openfile = open('Data/names.txt', 'a')
openfile.write(name + 'n')
openfile.close()

openfile = open('Data/accountIDs.txt', 'a')
openfile.write(str(accountID) + 'n')
openfile.close()

openfile = open('Data/nicknames.txt', 'a')
openfile.write(nickname + 'n')
openfile.close()

openfile = open('Data/passwords.txt', 'a')
openfile.write(password + 'n')
openfile.close()

openfile = open('Data/isAdmin.txt', 'a')
openfile.write(adminFalse + 'n')
openfile.close()



signin()

else:
signin()

signin()






python python-3.x authentication






share|improve this question









New contributor




King_0_king is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




King_0_king is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 11 mins ago









Jamal

30.4k11121227




30.4k11121227






New contributor




King_0_king is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked yesterday









King_0_kingKing_0_king

121




121




New contributor




King_0_king is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





King_0_king is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






King_0_king is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







  • 5




    $begingroup$
    Why don't you clean up the things that you know should be cleaned up (such as indentation) before asking for our advice?
    $endgroup$
    – 200_success
    12 hours ago










  • $begingroup$
    Thank you Emma for the edit, I am very new to this. There were no incorrect indents and i have added comments.
    $endgroup$
    – King_0_king
    8 hours ago







  • 1




    $begingroup$
    An answer was written while you proposed changes, invalidating the edit. This is not a forum where you should keep the most updated version in your question. Please see what you may and may not do after receiving answers. Feel free to incorporate the suggested changes and post a follow-up question instead. Please note, it may be beneficial to wait at least 2 days before doing so.
    $endgroup$
    – Mast
    8 hours ago












  • 5




    $begingroup$
    Why don't you clean up the things that you know should be cleaned up (such as indentation) before asking for our advice?
    $endgroup$
    – 200_success
    12 hours ago










  • $begingroup$
    Thank you Emma for the edit, I am very new to this. There were no incorrect indents and i have added comments.
    $endgroup$
    – King_0_king
    8 hours ago







  • 1




    $begingroup$
    An answer was written while you proposed changes, invalidating the edit. This is not a forum where you should keep the most updated version in your question. Please see what you may and may not do after receiving answers. Feel free to incorporate the suggested changes and post a follow-up question instead. Please note, it may be beneficial to wait at least 2 days before doing so.
    $endgroup$
    – Mast
    8 hours ago







5




5




$begingroup$
Why don't you clean up the things that you know should be cleaned up (such as indentation) before asking for our advice?
$endgroup$
– 200_success
12 hours ago




$begingroup$
Why don't you clean up the things that you know should be cleaned up (such as indentation) before asking for our advice?
$endgroup$
– 200_success
12 hours ago












$begingroup$
Thank you Emma for the edit, I am very new to this. There were no incorrect indents and i have added comments.
$endgroup$
– King_0_king
8 hours ago





$begingroup$
Thank you Emma for the edit, I am very new to this. There were no incorrect indents and i have added comments.
$endgroup$
– King_0_king
8 hours ago





1




1




$begingroup$
An answer was written while you proposed changes, invalidating the edit. This is not a forum where you should keep the most updated version in your question. Please see what you may and may not do after receiving answers. Feel free to incorporate the suggested changes and post a follow-up question instead. Please note, it may be beneficial to wait at least 2 days before doing so.
$endgroup$
– Mast
8 hours ago




$begingroup$
An answer was written while you proposed changes, invalidating the edit. This is not a forum where you should keep the most updated version in your question. Please see what you may and may not do after receiving answers. Feel free to incorporate the suggested changes and post a follow-up question instead. Please note, it may be beneficial to wait at least 2 days before doing so.
$endgroup$
– Mast
8 hours ago










1 Answer
1






active

oldest

votes


















3












$begingroup$


  1. Ban yourself from recursion. If you're in the function main don't call main. What you want is to have a while True loop and to use continue.



    while True:
    ...
    if invalid_username:
    continue
    ...


  2. json is likely to make your code much easier to use. As you don't have to have 5 lists for five attributes on a user.



  3. cmd.Cmd is probably what you want to use. This is as you can put all your functions in their own functions and you can focus on what the code does.

  4. Your code has a lot of useless print input and other nonsense statements. Follow he Unix way and remove them.

  5. Global variables are bad. Whilst the changes I'll recommend still use them, I've hidden them behind properties on a class. Which encourages safer programming practices.

  6. You should keep the database in memory, and ensure it's written to when the program ends. You can do this via try finally.

  7. I've partially changed your program to use cmd.Cmd, changing signin to also be one is up to you. I encourage you to look at the docs as the builtin help command is nice.

  8. Wrap your main code in an if __name__ == '__main__' guard.

import random
from random import *
import datetime
import cmd
import json
from pprint import pprint

try:
f = open('Data.json')
except FileNotFoundError:
with open('Data.json', 'w') as w:
json.dump(, w)
f = open('Data.json')
finally:
with f:
database = json.load(f)
database.setdefault('users', [])
data = database.setdefault('data', )
data.setdefault('command_list', [])
user = None


def find_user_name(database, name):
for user in database['users']:
if user['name'] == name:
return user
return None


class Main(cmd.Cmd):
prompt = '>>> '

@property
def user(self):
return user

@property
def database(self):
return database

def do_details(self, arg):
print('Name: ', self.user['name'])
print('AccountID: ', self.user['id'])
print('Nickname: ', self.user['nickname'])

def do_setpas(self, arg):
self.user['password'] = input('Enter your new password: ')

def do_userlist(self, arg):
pprint([u['name'] for u in self.database['users']])

def do_message(self, target_user):
t_user = find_user_name(self.database, target_user)
if t_user is None:
return

message = input('Message: ')
t_user['messages'].append(
'from': self.user['name'],
'date': str(datetime.datetime.now()),
'message': message
)

def do_mymessages(self, arg):
pprint(self.user['messages'])

def do_addcommand(self, arg):
self.database['data']['command_list'].append(arg)

def do_admin(self, arg):
if not self.user['admin'] and arg == 'True':
self.user['admin'] = True

def do_delete(self, arg):
if self.user['admin']:
return

delete = input('Are you sure you would like to delete your account: ')
if delete != 'y':
return

i = self.database.index(self.user)
self.database.pop(i)

return True

def do_signout(self, arg):
return True


def signin():
global user

while True:
existing_account = input('Do you have an existing account (y/n): ')
if existing_account == 'y':
username = input('Username: ')
user = find_user_name(database, username)
if user is None:
print('Invalid username')
continue

password = input('Password: ')
if password != user['password']:
print('Invalid password')
continue

Main().cmdloop()
else:
username = str(input('Username: '))
while not username:
username = input("You haven't entered anything, try again.")

user = find_user_name(database, username)
if user is not None:
print('That name already exists.')
user = None
continue

password = input('Password: ')
while len(password) < 4:
print('Your password must be 5 characters long.')
password = input('Password: ')

nickname = input('Enter your nickname: ')
id_ = random()
while id_ in [u['id'] for u in database['users']]:
id_ = random()

user =
'name': username,
'password': password,
'nickname': nickname,
'id': id_,
'messages': [],
'admin': False

database['users'].append(user)
Main().cmdloop()


if __name__ == '__main__':
try:
signin()
finally:
with open('Data.json', 'w') as f:
json.dump(database, f)


Example usage:



Do you have an existing account (y/n): n
Username: Peilonrayz
Password: abcde
Enter your nickname: Peilonrayz
>>> help

Documented commands (type help <topic>):
========================================
help

Undocumented commands:
======================
addcommand delete message setpas userlist
admin details mymessages signout

>>> details
Name: Peilonrayz
AccountID: 0.5494927696334424
Nickname: Peilonrayz
>>> admin
>>> admin True
>>> delete
>>> userlist
['Peilonrayz']
>>> signout
Do you have an existing account (y/n):





share|improve this answer











$endgroup$












    Your Answer





    StackExchange.ifUsing("editor", function ()
    return StackExchange.using("mathjaxEditing", function ()
    StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
    StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
    );
    );
    , "mathjax-editing");

    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "196"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );






    King_0_king is a new contributor. Be nice, and check out our Code of Conduct.









    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f216022%2fauthentication-script-in-python%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    3












    $begingroup$


    1. Ban yourself from recursion. If you're in the function main don't call main. What you want is to have a while True loop and to use continue.



      while True:
      ...
      if invalid_username:
      continue
      ...


    2. json is likely to make your code much easier to use. As you don't have to have 5 lists for five attributes on a user.



    3. cmd.Cmd is probably what you want to use. This is as you can put all your functions in their own functions and you can focus on what the code does.

    4. Your code has a lot of useless print input and other nonsense statements. Follow he Unix way and remove them.

    5. Global variables are bad. Whilst the changes I'll recommend still use them, I've hidden them behind properties on a class. Which encourages safer programming practices.

    6. You should keep the database in memory, and ensure it's written to when the program ends. You can do this via try finally.

    7. I've partially changed your program to use cmd.Cmd, changing signin to also be one is up to you. I encourage you to look at the docs as the builtin help command is nice.

    8. Wrap your main code in an if __name__ == '__main__' guard.

    import random
    from random import *
    import datetime
    import cmd
    import json
    from pprint import pprint

    try:
    f = open('Data.json')
    except FileNotFoundError:
    with open('Data.json', 'w') as w:
    json.dump(, w)
    f = open('Data.json')
    finally:
    with f:
    database = json.load(f)
    database.setdefault('users', [])
    data = database.setdefault('data', )
    data.setdefault('command_list', [])
    user = None


    def find_user_name(database, name):
    for user in database['users']:
    if user['name'] == name:
    return user
    return None


    class Main(cmd.Cmd):
    prompt = '>>> '

    @property
    def user(self):
    return user

    @property
    def database(self):
    return database

    def do_details(self, arg):
    print('Name: ', self.user['name'])
    print('AccountID: ', self.user['id'])
    print('Nickname: ', self.user['nickname'])

    def do_setpas(self, arg):
    self.user['password'] = input('Enter your new password: ')

    def do_userlist(self, arg):
    pprint([u['name'] for u in self.database['users']])

    def do_message(self, target_user):
    t_user = find_user_name(self.database, target_user)
    if t_user is None:
    return

    message = input('Message: ')
    t_user['messages'].append(
    'from': self.user['name'],
    'date': str(datetime.datetime.now()),
    'message': message
    )

    def do_mymessages(self, arg):
    pprint(self.user['messages'])

    def do_addcommand(self, arg):
    self.database['data']['command_list'].append(arg)

    def do_admin(self, arg):
    if not self.user['admin'] and arg == 'True':
    self.user['admin'] = True

    def do_delete(self, arg):
    if self.user['admin']:
    return

    delete = input('Are you sure you would like to delete your account: ')
    if delete != 'y':
    return

    i = self.database.index(self.user)
    self.database.pop(i)

    return True

    def do_signout(self, arg):
    return True


    def signin():
    global user

    while True:
    existing_account = input('Do you have an existing account (y/n): ')
    if existing_account == 'y':
    username = input('Username: ')
    user = find_user_name(database, username)
    if user is None:
    print('Invalid username')
    continue

    password = input('Password: ')
    if password != user['password']:
    print('Invalid password')
    continue

    Main().cmdloop()
    else:
    username = str(input('Username: '))
    while not username:
    username = input("You haven't entered anything, try again.")

    user = find_user_name(database, username)
    if user is not None:
    print('That name already exists.')
    user = None
    continue

    password = input('Password: ')
    while len(password) < 4:
    print('Your password must be 5 characters long.')
    password = input('Password: ')

    nickname = input('Enter your nickname: ')
    id_ = random()
    while id_ in [u['id'] for u in database['users']]:
    id_ = random()

    user =
    'name': username,
    'password': password,
    'nickname': nickname,
    'id': id_,
    'messages': [],
    'admin': False

    database['users'].append(user)
    Main().cmdloop()


    if __name__ == '__main__':
    try:
    signin()
    finally:
    with open('Data.json', 'w') as f:
    json.dump(database, f)


    Example usage:



    Do you have an existing account (y/n): n
    Username: Peilonrayz
    Password: abcde
    Enter your nickname: Peilonrayz
    >>> help

    Documented commands (type help <topic>):
    ========================================
    help

    Undocumented commands:
    ======================
    addcommand delete message setpas userlist
    admin details mymessages signout

    >>> details
    Name: Peilonrayz
    AccountID: 0.5494927696334424
    Nickname: Peilonrayz
    >>> admin
    >>> admin True
    >>> delete
    >>> userlist
    ['Peilonrayz']
    >>> signout
    Do you have an existing account (y/n):





    share|improve this answer











    $endgroup$

















      3












      $begingroup$


      1. Ban yourself from recursion. If you're in the function main don't call main. What you want is to have a while True loop and to use continue.



        while True:
        ...
        if invalid_username:
        continue
        ...


      2. json is likely to make your code much easier to use. As you don't have to have 5 lists for five attributes on a user.



      3. cmd.Cmd is probably what you want to use. This is as you can put all your functions in their own functions and you can focus on what the code does.

      4. Your code has a lot of useless print input and other nonsense statements. Follow he Unix way and remove them.

      5. Global variables are bad. Whilst the changes I'll recommend still use them, I've hidden them behind properties on a class. Which encourages safer programming practices.

      6. You should keep the database in memory, and ensure it's written to when the program ends. You can do this via try finally.

      7. I've partially changed your program to use cmd.Cmd, changing signin to also be one is up to you. I encourage you to look at the docs as the builtin help command is nice.

      8. Wrap your main code in an if __name__ == '__main__' guard.

      import random
      from random import *
      import datetime
      import cmd
      import json
      from pprint import pprint

      try:
      f = open('Data.json')
      except FileNotFoundError:
      with open('Data.json', 'w') as w:
      json.dump(, w)
      f = open('Data.json')
      finally:
      with f:
      database = json.load(f)
      database.setdefault('users', [])
      data = database.setdefault('data', )
      data.setdefault('command_list', [])
      user = None


      def find_user_name(database, name):
      for user in database['users']:
      if user['name'] == name:
      return user
      return None


      class Main(cmd.Cmd):
      prompt = '>>> '

      @property
      def user(self):
      return user

      @property
      def database(self):
      return database

      def do_details(self, arg):
      print('Name: ', self.user['name'])
      print('AccountID: ', self.user['id'])
      print('Nickname: ', self.user['nickname'])

      def do_setpas(self, arg):
      self.user['password'] = input('Enter your new password: ')

      def do_userlist(self, arg):
      pprint([u['name'] for u in self.database['users']])

      def do_message(self, target_user):
      t_user = find_user_name(self.database, target_user)
      if t_user is None:
      return

      message = input('Message: ')
      t_user['messages'].append(
      'from': self.user['name'],
      'date': str(datetime.datetime.now()),
      'message': message
      )

      def do_mymessages(self, arg):
      pprint(self.user['messages'])

      def do_addcommand(self, arg):
      self.database['data']['command_list'].append(arg)

      def do_admin(self, arg):
      if not self.user['admin'] and arg == 'True':
      self.user['admin'] = True

      def do_delete(self, arg):
      if self.user['admin']:
      return

      delete = input('Are you sure you would like to delete your account: ')
      if delete != 'y':
      return

      i = self.database.index(self.user)
      self.database.pop(i)

      return True

      def do_signout(self, arg):
      return True


      def signin():
      global user

      while True:
      existing_account = input('Do you have an existing account (y/n): ')
      if existing_account == 'y':
      username = input('Username: ')
      user = find_user_name(database, username)
      if user is None:
      print('Invalid username')
      continue

      password = input('Password: ')
      if password != user['password']:
      print('Invalid password')
      continue

      Main().cmdloop()
      else:
      username = str(input('Username: '))
      while not username:
      username = input("You haven't entered anything, try again.")

      user = find_user_name(database, username)
      if user is not None:
      print('That name already exists.')
      user = None
      continue

      password = input('Password: ')
      while len(password) < 4:
      print('Your password must be 5 characters long.')
      password = input('Password: ')

      nickname = input('Enter your nickname: ')
      id_ = random()
      while id_ in [u['id'] for u in database['users']]:
      id_ = random()

      user =
      'name': username,
      'password': password,
      'nickname': nickname,
      'id': id_,
      'messages': [],
      'admin': False

      database['users'].append(user)
      Main().cmdloop()


      if __name__ == '__main__':
      try:
      signin()
      finally:
      with open('Data.json', 'w') as f:
      json.dump(database, f)


      Example usage:



      Do you have an existing account (y/n): n
      Username: Peilonrayz
      Password: abcde
      Enter your nickname: Peilonrayz
      >>> help

      Documented commands (type help <topic>):
      ========================================
      help

      Undocumented commands:
      ======================
      addcommand delete message setpas userlist
      admin details mymessages signout

      >>> details
      Name: Peilonrayz
      AccountID: 0.5494927696334424
      Nickname: Peilonrayz
      >>> admin
      >>> admin True
      >>> delete
      >>> userlist
      ['Peilonrayz']
      >>> signout
      Do you have an existing account (y/n):





      share|improve this answer











      $endgroup$















        3












        3








        3





        $begingroup$


        1. Ban yourself from recursion. If you're in the function main don't call main. What you want is to have a while True loop and to use continue.



          while True:
          ...
          if invalid_username:
          continue
          ...


        2. json is likely to make your code much easier to use. As you don't have to have 5 lists for five attributes on a user.



        3. cmd.Cmd is probably what you want to use. This is as you can put all your functions in their own functions and you can focus on what the code does.

        4. Your code has a lot of useless print input and other nonsense statements. Follow he Unix way and remove them.

        5. Global variables are bad. Whilst the changes I'll recommend still use them, I've hidden them behind properties on a class. Which encourages safer programming practices.

        6. You should keep the database in memory, and ensure it's written to when the program ends. You can do this via try finally.

        7. I've partially changed your program to use cmd.Cmd, changing signin to also be one is up to you. I encourage you to look at the docs as the builtin help command is nice.

        8. Wrap your main code in an if __name__ == '__main__' guard.

        import random
        from random import *
        import datetime
        import cmd
        import json
        from pprint import pprint

        try:
        f = open('Data.json')
        except FileNotFoundError:
        with open('Data.json', 'w') as w:
        json.dump(, w)
        f = open('Data.json')
        finally:
        with f:
        database = json.load(f)
        database.setdefault('users', [])
        data = database.setdefault('data', )
        data.setdefault('command_list', [])
        user = None


        def find_user_name(database, name):
        for user in database['users']:
        if user['name'] == name:
        return user
        return None


        class Main(cmd.Cmd):
        prompt = '>>> '

        @property
        def user(self):
        return user

        @property
        def database(self):
        return database

        def do_details(self, arg):
        print('Name: ', self.user['name'])
        print('AccountID: ', self.user['id'])
        print('Nickname: ', self.user['nickname'])

        def do_setpas(self, arg):
        self.user['password'] = input('Enter your new password: ')

        def do_userlist(self, arg):
        pprint([u['name'] for u in self.database['users']])

        def do_message(self, target_user):
        t_user = find_user_name(self.database, target_user)
        if t_user is None:
        return

        message = input('Message: ')
        t_user['messages'].append(
        'from': self.user['name'],
        'date': str(datetime.datetime.now()),
        'message': message
        )

        def do_mymessages(self, arg):
        pprint(self.user['messages'])

        def do_addcommand(self, arg):
        self.database['data']['command_list'].append(arg)

        def do_admin(self, arg):
        if not self.user['admin'] and arg == 'True':
        self.user['admin'] = True

        def do_delete(self, arg):
        if self.user['admin']:
        return

        delete = input('Are you sure you would like to delete your account: ')
        if delete != 'y':
        return

        i = self.database.index(self.user)
        self.database.pop(i)

        return True

        def do_signout(self, arg):
        return True


        def signin():
        global user

        while True:
        existing_account = input('Do you have an existing account (y/n): ')
        if existing_account == 'y':
        username = input('Username: ')
        user = find_user_name(database, username)
        if user is None:
        print('Invalid username')
        continue

        password = input('Password: ')
        if password != user['password']:
        print('Invalid password')
        continue

        Main().cmdloop()
        else:
        username = str(input('Username: '))
        while not username:
        username = input("You haven't entered anything, try again.")

        user = find_user_name(database, username)
        if user is not None:
        print('That name already exists.')
        user = None
        continue

        password = input('Password: ')
        while len(password) < 4:
        print('Your password must be 5 characters long.')
        password = input('Password: ')

        nickname = input('Enter your nickname: ')
        id_ = random()
        while id_ in [u['id'] for u in database['users']]:
        id_ = random()

        user =
        'name': username,
        'password': password,
        'nickname': nickname,
        'id': id_,
        'messages': [],
        'admin': False

        database['users'].append(user)
        Main().cmdloop()


        if __name__ == '__main__':
        try:
        signin()
        finally:
        with open('Data.json', 'w') as f:
        json.dump(database, f)


        Example usage:



        Do you have an existing account (y/n): n
        Username: Peilonrayz
        Password: abcde
        Enter your nickname: Peilonrayz
        >>> help

        Documented commands (type help <topic>):
        ========================================
        help

        Undocumented commands:
        ======================
        addcommand delete message setpas userlist
        admin details mymessages signout

        >>> details
        Name: Peilonrayz
        AccountID: 0.5494927696334424
        Nickname: Peilonrayz
        >>> admin
        >>> admin True
        >>> delete
        >>> userlist
        ['Peilonrayz']
        >>> signout
        Do you have an existing account (y/n):





        share|improve this answer











        $endgroup$




        1. Ban yourself from recursion. If you're in the function main don't call main. What you want is to have a while True loop and to use continue.



          while True:
          ...
          if invalid_username:
          continue
          ...


        2. json is likely to make your code much easier to use. As you don't have to have 5 lists for five attributes on a user.



        3. cmd.Cmd is probably what you want to use. This is as you can put all your functions in their own functions and you can focus on what the code does.

        4. Your code has a lot of useless print input and other nonsense statements. Follow he Unix way and remove them.

        5. Global variables are bad. Whilst the changes I'll recommend still use them, I've hidden them behind properties on a class. Which encourages safer programming practices.

        6. You should keep the database in memory, and ensure it's written to when the program ends. You can do this via try finally.

        7. I've partially changed your program to use cmd.Cmd, changing signin to also be one is up to you. I encourage you to look at the docs as the builtin help command is nice.

        8. Wrap your main code in an if __name__ == '__main__' guard.

        import random
        from random import *
        import datetime
        import cmd
        import json
        from pprint import pprint

        try:
        f = open('Data.json')
        except FileNotFoundError:
        with open('Data.json', 'w') as w:
        json.dump(, w)
        f = open('Data.json')
        finally:
        with f:
        database = json.load(f)
        database.setdefault('users', [])
        data = database.setdefault('data', )
        data.setdefault('command_list', [])
        user = None


        def find_user_name(database, name):
        for user in database['users']:
        if user['name'] == name:
        return user
        return None


        class Main(cmd.Cmd):
        prompt = '>>> '

        @property
        def user(self):
        return user

        @property
        def database(self):
        return database

        def do_details(self, arg):
        print('Name: ', self.user['name'])
        print('AccountID: ', self.user['id'])
        print('Nickname: ', self.user['nickname'])

        def do_setpas(self, arg):
        self.user['password'] = input('Enter your new password: ')

        def do_userlist(self, arg):
        pprint([u['name'] for u in self.database['users']])

        def do_message(self, target_user):
        t_user = find_user_name(self.database, target_user)
        if t_user is None:
        return

        message = input('Message: ')
        t_user['messages'].append(
        'from': self.user['name'],
        'date': str(datetime.datetime.now()),
        'message': message
        )

        def do_mymessages(self, arg):
        pprint(self.user['messages'])

        def do_addcommand(self, arg):
        self.database['data']['command_list'].append(arg)

        def do_admin(self, arg):
        if not self.user['admin'] and arg == 'True':
        self.user['admin'] = True

        def do_delete(self, arg):
        if self.user['admin']:
        return

        delete = input('Are you sure you would like to delete your account: ')
        if delete != 'y':
        return

        i = self.database.index(self.user)
        self.database.pop(i)

        return True

        def do_signout(self, arg):
        return True


        def signin():
        global user

        while True:
        existing_account = input('Do you have an existing account (y/n): ')
        if existing_account == 'y':
        username = input('Username: ')
        user = find_user_name(database, username)
        if user is None:
        print('Invalid username')
        continue

        password = input('Password: ')
        if password != user['password']:
        print('Invalid password')
        continue

        Main().cmdloop()
        else:
        username = str(input('Username: '))
        while not username:
        username = input("You haven't entered anything, try again.")

        user = find_user_name(database, username)
        if user is not None:
        print('That name already exists.')
        user = None
        continue

        password = input('Password: ')
        while len(password) < 4:
        print('Your password must be 5 characters long.')
        password = input('Password: ')

        nickname = input('Enter your nickname: ')
        id_ = random()
        while id_ in [u['id'] for u in database['users']]:
        id_ = random()

        user =
        'name': username,
        'password': password,
        'nickname': nickname,
        'id': id_,
        'messages': [],
        'admin': False

        database['users'].append(user)
        Main().cmdloop()


        if __name__ == '__main__':
        try:
        signin()
        finally:
        with open('Data.json', 'w') as f:
        json.dump(database, f)


        Example usage:



        Do you have an existing account (y/n): n
        Username: Peilonrayz
        Password: abcde
        Enter your nickname: Peilonrayz
        >>> help

        Documented commands (type help <topic>):
        ========================================
        help

        Undocumented commands:
        ======================
        addcommand delete message setpas userlist
        admin details mymessages signout

        >>> details
        Name: Peilonrayz
        AccountID: 0.5494927696334424
        Nickname: Peilonrayz
        >>> admin
        >>> admin True
        >>> delete
        >>> userlist
        ['Peilonrayz']
        >>> signout
        Do you have an existing account (y/n):






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited 7 hours ago









        Mast

        7,57963788




        7,57963788










        answered 8 hours ago









        PeilonrayzPeilonrayz

        26.2k338110




        26.2k338110




















            King_0_king is a new contributor. Be nice, and check out our Code of Conduct.









            draft saved

            draft discarded


















            King_0_king is a new contributor. Be nice, and check out our Code of Conduct.












            King_0_king is a new contributor. Be nice, and check out our Code of Conduct.











            King_0_king is a new contributor. Be nice, and check out our Code of Conduct.














            Thanks for contributing an answer to Code Review Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            Use MathJax to format equations. MathJax reference.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f216022%2fauthentication-script-in-python%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            名間水力發電廠 目录 沿革 設施 鄰近設施 註釋 外部連結 导航菜单23°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.7113923°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.71139計畫概要原始内容臺灣第一座BOT 模式開發的水力發電廠-名間水力電廠名間水力發電廠 水利署首件BOT案原始内容《小檔案》名間電廠 首座BOT水力發電廠原始内容名間電廠BOT - 經濟部水利署中區水資源局

            Prove that NP is closed under karp reduction?Space(n) not closed under Karp reductions - what about NTime(n)?Class P is closed under rotation?Prove or disprove that $NL$ is closed under polynomial many-one reductions$mathbfNC_2$ is closed under log-space reductionOn Karp reductionwhen can I know if a class (complexity) is closed under reduction (cook/karp)Check if class $PSPACE$ is closed under polyonomially space reductionIs NPSPACE also closed under polynomial-time reduction and under log-space reduction?Prove PSPACE is closed under complement?Prove PSPACE is closed under union?

            Is my guitar’s action too high? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)Strings too stiff on a recently purchased acoustic guitar | Cort AD880CEIs the action of my guitar really high?Μy little finger is too weak to play guitarWith guitar, how long should I give my fingers to strengthen / callous?When playing a fret the guitar sounds mutedPlaying (Barre) chords up the guitar neckI think my guitar strings are wound too tight and I can't play barre chordsF barre chord on an SG guitarHow to find to the right strings of a barre chord by feel?High action on higher fret on my steel acoustic guitar