In my password manager prroject, I am trying to code a login function.
In this functtion, if the user's username and password match an account stored in this dictionary, it allows access to their object which has the following attributes: username, password, password_coll.
(The password_coll is a dictionary/collection of the users passwords as values to the website of use as keys).
So as a little stem from my original question, how would I also reference my
This is my first time using OOP approach and it is really frying my brain hahaha.
So I thought of using usernames as keys and the object as the value. But how do I structure this in code?
Any examples would be greatly appreciated.
I did try checking existing questions but they didn't answer my question closely enough. So here we are haha:)
The code block at the bottom is my attempt at testing the output of those methods to see if they return the data in the object. But the result was this message:
"<bound method User.return_pass of <main.User object at 0x0000023419597940>>"
import random
import secrets
import string
class User:
def __init__(self, username, password, password_dict=None) -> None:
self.username = username
self.password = password
self.password_dict = {}
def return_pass(self, password):
return self.password
def __str__(self, password) -> str:
return self.password
def get_creds(self, username, password):
usern = input('Enter username: ')
pwd = input('Enter password: ')
self.username = usern
self.password = pwd
def passGen(self, password_dict): # random password generator
n = int(input('Define password length. Longer passwords are safer.'))
source = string.ascii_letters + string.digits
password = ''.join((secrets.choice(source)) for i in range(n))
print('Password has been generated!')
print('Would you like to save this password? Type y or n: ')
yon = input()
if yon == 'y':
site = input('Please enter the site password is to be used:')
self.password_dict[site] = password
return self.password_dict
u1 = User('dave', 'pass', {})
user_logins = {'dave': u1}
print(user_logins['dave'].return_pass)
User.return_pass is a function, it has to be called:
print(user_logins['dave'].return_pass("password")) where the text "password" is the arg required in the function.
Hope this helps
def login(username, password, user_logins):
if username in user_logins:
user = user_logins[username]
if user.password == password:
return user.password_dict
else:
return "Incorrect password"
else:
return "Username not found"
print(login('dave', 'pass', user_logins))
In your code, you're trying to print the output of a function, but you forgot to actually run the function by adding parentheses at the end. So instead of just printing the function, you need to run it by adding () at the end. Also, the str method in the User class should not take any input, and it should return the value of self.password instead of just 'password'
print(user_logins['dave'].return_pass())
Related
import sys as s
import datetime
class LoginPage:
def __int__(self, username, password):
self.username = username
self.password = password
self.incorrectPass = 0
def loginProgrma(self):
while True:
while True:
nameInput = input("Enter your username: ➸")
if nameInput != self.username:
print("\t(Username is incorrect. Re-enter your username)")
elif nameInput == self.username:
print("\t(Enter your password)")
break
while True:
passInput = input("Enter your password: ➳")
if passInput != self.password:
self.incorrectPass += 1
print("\t(Incorrect password. Re-enter your password)")
if self.incorrectPass == 3:
s.exit('\nYou have been locked!')
elif passInput == self.password:
break
time = datetime.datetime.now()
print('You logged in', time)
return f"\n\t(Welcome back {nameInput}.)"
So I'm trying to make a short login program where where the program ask to enter the username and password. The problem I don't know how can I run this code, I tried by calling the class LoginPage and the pass 2 arguments(username, password) which is mot working I tried to find the solution on the internet but I couldn't find.
And how can I improve this code?.
You have typed __int__ instead of __init__. (You forgot an extra i) If you fixed that, you can after you called the class LoginPage call the loginProgrma function.
First of all remove the typo in __init__ from __int__ to __init__
Anyway there seem to be some typos in your code but to run the method you showed create an instance of the class and call the function like this:
#create instance
login_page = LoginPage(username='username', password='password')
#call method
login_page.loginProgrma()`
This should probably work
I am trying to ask a user for a username and password and check a file with user name and passwords to see if it exists if it does it just says welcome if it doesnt tells the user he put in the wrong info. The file is just a simple text file with format "username,password" as shown below
SSD,adgEgd
aegag,asdhasdh
here is my code
class Account():
def __init__(self, name, password):
self.name = name
self.password = password
username_input = input("Enter the name: ")
userpassword_input = input("Enter password: ")
file = open('account information.txt', 'r')
data = []
for lines in file:
temp = lines.split(',')
data.append(Account(temp[0], temp[1]))
file.close()
isExsits = ' '
for d in data:
if username_input == d.name and userpassword_input == d.password:
isExsits = 'huzzah'
print(isExsits)
It identifies the username but not the password
There is a newline character in the password and it looks like adgEgd\n after reading from file.
You can get rid from it by using rstrip
data.append(Account(temp[0], temp[1].rstrip()))
This works as you intended, it iterates over all accounts in the account_information.txt file and creates an Account object for each of them which is added to the data list.
Afterwards, we iterate through every account and check to see if the credentials provided by the user match any within the list.
class Account():
def __init__(self, name, password):
self.name = name
self.password = password
username_input = input("Enter the name: ")
userpassword_input = input("Enter password: ")
data = []
with open("account_information.txt") as file:
for line in file.readlines():
credentials = line.rstrip().split(",")
data.append(Account(credentials[0], credentials[1]))
accountExists = False
for account in data:
if (account.name == username_input) and (account.password == userpassword_input):
accountExists = True
print(accountExists)
It seems to working fine like this, so I would likewise say it's probably the newlines or other extraneous characters at the end of the lines that are throwing off the calculation.
user_pass_list = [
('SSD', 'adgEgd'),
('aegag', 'asdhasdh')
]
username = 'SSD'
password = 'adgEgd'
exists = False
for d in user_pass_list:
if username == d[0] and password == d[1]:
exists = True
print(exists) # True
Another approach can be to just do an in check, so that we don't need to iterate over user_pass_list for example:
user_pass_list = [
('SSD', 'adgEgd'),
('aegag', 'asdhasdh')
]
username = 'SSD'
password = 'adgegd' # casing is different
exists = (username, password) in user_pass_list
assert exists is False # True
With the Account class example from the original question, reformatted as a dataclass for slightly cleaner code:
from dataclasses import dataclass
# same as `#dataclass(eq=True)`, so an equals (__eq__) method
# is automatically generated for the class.
#dataclass
class Account:
name: str
password: str
user_pass_list = [
Account('SSD', 'adgEgd'),
Account('aegag', 'asdhasdh')
]
username = 'SSD'
password = 'adgEgd'
exists = Account(username, password) in user_pass_list
assert exists is True # True
So i'm trying to make a login and register program in Python i already made the register part, but now i'm struggling with the login part.
and a self made simple database, using classes to store the data.
there are two files:
one for database and register and login program and the register and login program reads database.
This is the current login code:
username = input("Enter your username: ")
if username == "(acc_info." + username + ".username)":
print("Valid username")
But it didn't work of course
and acc.info is the data base
This is the database
class Accounts:
def __init__(self, username, pw, is_admin):
self.username = username
self.pw = pw
self.is_admin = is_admin
def full_info(self):
return '{} {} {}'.format(self.username, self.pw, self.is_admin)
admin = Accounts('admin', '5555', True)
I was expecting the input called username gets a username like admin and when i press enter it runs (acc_info.admin.username) and the output would be admin and if the input is same as the output it would send me to the next part which is passwords but if i know how to do the username i can do the password part too.
but now the output is (acc.info.admin.username)
and the program checks if the input (which is admin) is the same as (acc.info.admin.username). and it doesnt work because the output (acc.info.admin.username) should run and give me a output of admin
The check if username == "(acc_info." + username + ".username)" is never going to pass. This is asking if the string entered by the user is the same string you get when you concatenate "(acc_info.", what the user entered, and ".username)". So if the user types in "bob" for example, it compares the strings "bob" and "(acc_info.bob.username)". Those two strings are obviously different.
It's not entirely clear to me how your "database" and "(acc_info ..." is supposed to fit into what you're trying to do. But here's a working example of doing some login and checks:
class Accounts:
def __init__(self, username, pw, is_admin):
self.username = username
self.pw = pw
self.is_admin = is_admin
def full_info(self):
return '{} {} {}'.format(self.username, self.pw, self.is_admin)
def __eq__(self, other):
return (self.username == other.username and self.pw == other.pw)
def check_account(entered, account_list):
for account in account_list:
if entered == account:
return account
return False
accounts = [ Accounts('admin', '5555', True),
Accounts('bob', '1234', False),
Accounts('jill', '4321', False),
Accounts('hacker', '123', False)]
entered_username = input("Enter your username: ")
entered_password = input("and your password: ")
entered_account = Accounts(entered_username, entered_password, None)
matched_account = check_account(entered_account, accounts)
if matched_account:
print("Welcome, %s" % matched_account.username)
if matched_account.is_admin:
print("And I see you're an actual admin! Wow!")
else:
print("Invalid username/password.")
Granted, this isn't the complete sort of approach I'd use in real life (e.g., some of these steps are not only insecure but not the most memory-efficient). But again, it's at least something that seems to fit what you're asking for.
I have a function :
def myFunc(**kwargs):
for username, password in kwargs.iteritems():
print "%s = %s" % (username, password)
I want to receive username and password using input like this :
username = input("Enter username : ")
password = input("Enter password : ")
Then pass username and password to myFunc :
myFunc(username = password)
I know that it's not gonna working, but what is the solution to handle this job ?
Note : both username and password may be different things in every iteration.
You need to use the ** syntax to expand a dict into its constituent key/value pairs. For example:
myFunc(**{username: password})
or
d = {}
d[username] = password
myFunc(**d)
You can just read them from kwargs if they exist:
def myFunc(**kwargs):
print("username = " + kwargs["username"])
print("password = " + kwargs["password"])
myFunc(username="jane", password="doe")
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"]]
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()
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()
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"