Login System - Python - python-3.9

I'm not that great at programming and so that is why I am here asking help. I am creating a login system for my Hotel Booking System but I am experiencing some problems with it.
This is what I have done for the Login Sytem through the help someone else's code. Link: Python Login and Register System using text files
def get_existing_users():
with open("login.txt", "r" ) as f:
for line in f.readlines():
# This expects each line of a file to be (name, pass) seperated by whitespace
username, password = line.split(',')
yield username, password
def is_authorized(username, password):
return any((user == (username, password) for user in get_existing_users()))
def user_exists(username):
return any((usr_name == username) for usr_name, _ in get_existing_users())
# above is equivalent of:
#
# for usr_name, _ in get_existing_users():
# if usr_name == username:
# return True
# return False
def ask_user_credentials():
count = 0
while count < 3:
username = input("Enter Username: ")
password = input("Enter a Password: ")
if is_authorized(username, password):
print ("Welcome to the Majestic Hotel Booking system ") + username
MainMenu()
if user_exists(username):
print("The password entered is wrong, please try again")
print("The username entered is wrong, please try again")
count = count + 1
def getdetails():
forename = input("Enter forename: ")
surname = input("Enter Surname: ")
year = input("Enter year you are born: ")
if year <= '2004':
print("You are old enough to register yourself")
username = forename[0]+surname[0:3]+year[3:4]
print("Username: ", username)
password = input("Enter a password: ")
file = open("login.txt","a")
file.write(username + "," + password + "\n")
file.close()
MainMenu()
else:
print("Sorry you are not old enough to register by yourself") enter code here
if account == "No":
print(getdetails())
if account == "Yes":
print(ask_user_credentials())
After creating or logging in to the account, the program will direct them to the main menu that is why you will see MainMenu() in the code.
I created an account, as shown below:
WELCOME TO THE MAJESTIC HOTEL lOGIN SYSTEM
************************************************
Do you have an account? Yes or No: No
Enter forename: Rose
Enter Surname: Moon
Enter year you are born: 2000
You are old enough to register yourself
Username: RMoo0
Enter a password: door
This was then saved in a text file called login.txt, like this:
RMoo0,door
However, although I created an account and it is saved into the text file but the output says this:
WELCOME TO THE MAJESTIC HOTEL lOGIN SYSTEM
************************************************
Do you have an account? Yes or No: Yes
Enter Username: RMoo0
Enter a Password: door
The password entered is wrong, please try again
The username entered is wrong, please try again
Enter Username:
Can someone please help me out and explain the solution in a way that I will understand it.

f.readlines() gives each line of txt file as :
line1\n
line2\n
.
.
.
So ,when you try to get username, password by split(",") , it look like this
("user1", "password1\n")
("user2", "password2\n")
..
Before splitting line with "," right strip each line with rstrip("\n")
def get_existing_users():
with open("login.txt", "r" ) as f:
for line in f.readlines():
username, password = line.rstrip("\n").split(',') #used rstrip here to remove the right ending "\n"
yield username, password

When addressing this kind of problem your should take into account several aspects like for example escaping your separators (of course, if you hash your passwords this isn't necessary) and not utilizing white spaces, a very good approach like linux passwd file is to add separator at the end of line to avoid different EOL terminators like \r, \n or \r\n
for Example:
def get_existing_users():
"""
This expects each line of a file to be:
(start of line)name,pass,(end of line)
"""
with open("login.txt", "r" ) as f:
for line in f.readlines():
user = line.split(',')
yield user[0], user[1]

Related

Ruby is there a way to stop the user from calling a function/procedure through case before they have accessed a different function/procedure?

I have a text file that I want to open first for reading or writing, but want the user to manually enter the text_file name (which opens the file for reading) first like so:
def read_in_albums
puts "Enter file name: "
begin
file_name = gets().chomp
if (file_name == "albums.txt")
puts "File is open"
a_file = File.new("#{file_name}", "r")
puts a_file.gets
finished = true
else
puts "Please re-enter file name: "
end
end until finished
end
From this unfinished code below, selecting 1 would go to the above procedure. I want the user to select 1 first, and if they choose 2 without having gone through read_in_albums they just get some sort of message like "no file selected and sent back to menu screen.
def main()
finished = false
begin
puts("Main Menu:")
puts("1- Read in Album")
puts("2- Display Album Info")
puts("3- Play Album")
puts("4- Update Album")
puts("5- Exit")
choice = read_integer_in_range("Please enter your choice:", 1, 5)
case choice
when 1
read_in_albums
when 2
display_album_info
when 5
finished = true
end
end until finished
end
main()
The only thing I can think of is something like
when 2
if(read_in_albums == true)
display_album_info
and have it return true from read_in_albums.
which I don't want to do as it just goes through read_in_albums again, when I only want it to do that if the user pressed 1.
All of your application's functionality depends on whether the album data has been read. You are no doubt storing this data as an object in memory referenced by some variable.
$album_data = File.read 'album.txt'
You can test whether this data is present in order to determine whether the file data has been read:
if $album_data.nil?
# ask user for album file
else
# show album user interface
end
There is no need for a separate flag. The mere presence of the data in memory serves as a flag already.
You could either set a flag when option 1 was selcted
has_been_read = false
...
when 1
read_in_albums
has_been_read = true
when 2
if has_been_read
display_album_info
else
puts "Select Option 1 first"
end
Or just test if your file name is a valid string.

Highline padding inserted password with random number of *

I have a ruby script that ask for password using highline/import:
ask("Enter your password: ") { |q| q.echo = "*" }
I want to add a random number of * to the output once the user finishes to input their password. That's because the output is captured and I don't want to reveal the length of the password. As a requirement I can't disable the echo.
You can just multiply '*' by a random value. Import SecureRandom:
require 'securerandom'
Then in that block:
q.echo = '*' * SecureRandom.rand(5..15)

How to create a Roblox game where the player has to guess a randomly generated pin?

So, I've been working on this for the past week. I have tried everything (based on the knowledge I know) and yet nothing... my code didn't work the first time, the second time, the third time... the forth... etc... at the end, I let frustration take control of me and I ended up deleting the whole script. Luckily not the parts and models, otherwise I'm really screwed...
I need to create a game in which I have to create a keypad of sorts, at first I thought GUI would work... no, it needs to be SurfaceGUI, which I don't know how to handle well... Anyway, I needed to create a keypad using SurfaceGUI, and display it on a separate screen, as a typical keypad would...
The Player would first have to enter an "initial" number, meaning in order to enter the randomly generated number he first needed to input the static pin in order to "log in," after that, then he would try to guess the number...
I've literally tried everything I could but nothing... It's mainly because of my lack of experience in LUA, I'm more advanced in Python and barely know a thing in Java... If someone could assist me on how to do this, I would appreciate it greatly
First, download this and put it in a ScreenGui in StarterGui. Then, use the following LocalScript placed inside the PIN frame:
-- Script settings
local len = 4 -- replace this as needed...
local regen = false -- determines whether PIN will regenerate after a failed attempt
local regmes = "Enter PIN..." -- start message of PIN pad
local badmes = "Wrong PIN!" -- message displayed when PIN is wrong
local success = "Correct PIN!" -- message displayed when PIN is right
-- Script workings
local pin = script.Parent
local top = pin.Top
local txt = top.Numbers
local nums = top.NumKeys
local pin
local stpin
local nms
txt.Text = regmes
local see = game:GetStorage("ReplicatedStorage").PINActivate
local function activate()
if pin.Visible then
pin.Visible = false
for _, btn in pairs(nums:GetChildren()) do
btn.Active = false
end
return
else
pin.Visible = true
for _, btn in pairs(nums:GetChildren()) do
btn.Active = true
end
return
end
end
local function rand()
math.randomseed(os.time) -- better random numbers this way
return tostring(math.floor(math.random(0,9.9)))
end
local function gen()
nms = {rand()}
for i=2, len, 1 do
nms[#nms+1]=rand()
end
stpin = nms[1]
for i=2, #nms, 1 do
stpin = stpin..nms[i]
end
pin = tonumber(stpin) -- converts the number string into an actual number
end
gen()
local function activate(str)
if tonumber(str) ~= pin then
txt.Text = badmes
wait(2)
txt.Text = regmes
if regen then
gen()
wait(0.1)
end
return
else
txt.Text = success
wait(2)
activate()
-- insert code here...
end
end
for _, btn in pairs(nums:GetChildren()) do
btn.Activated:Connect(function()
if txt.Text == "Wrong PIN!" then return end
txt.Text = txt.Text..btn.Text
if string.len(txt.Text) >= len then
activate(txt.Text)
end
wait(0.1)
end)
end
see.OnClientEvent:Connect(activate)
And in a Script put this:
local Players = game:GetService("Players")
local see = game:GetService("ReplicatedStorage").PINActivate
local plr
-- replace Event with something like Part.Touched
Event:Connect(function(part)
if part.Parent.Head then
plr = Players:GetPlayerFromCharacter(part.Parent)
see:FireClient(plr)
end
end)
What this will do is bring up a ScreenGui for only that player so they can enter the PIN, and they can close it as well. You can modify as needed; have a great day! :D
There is an easier way, try this
First, Create a GUI in StarterGui, then, Create a textbox and postion it, after that, create a local script inside and type this.
local Password = math.random(1000, 9999)
print(Password)
game.ReplicatedStorage.Password.Value = Password
script.Parent.FocusLost:Connect(function(enter)
if enter then
if script.Parent.Text == tostring(Password) then
print("Correct!")
script.Parent.BorderColor3 = Color3.new(0, 255, 0)
Password = math.random(1000, 9999)
game.ReplicatedStorage.Correct1:FireServer()
print(Password)
game.ReplicatedStorage.Password.Value = Password
else
print("wrong!")
print(script.Parent.Text)
script.Parent.BorderColor3 = Color3.new(255, 0, 0)
end
end
end)
That's all in the textbox.
Or if you want a random username script, create a textlabel, then, create a local script in the textlabel and type in this.
local UserText = script.Parent
local Username = math.random(1,10)
while true do
if Username == 1 then
UserText.Text = "John"
elseif Username == 2 then
UserText.Text = "Thomas"
elseif Username == 3 then
UserText.Text = "Raymond"
elseif Username == 4 then
UserText.Text = "Ray"
elseif Username == 5 then
UserText.Text = "Tom"
elseif Username == 6 then
UserText.Text = "Kai"
elseif Username == 7 then
UserText.Text = "Lloyd"
elseif Username == 8 then
UserText.Text = "Jay"
elseif Username == 9 then
UserText.Text = "User"
else
UserText.Text = "Guest"
end
wait()
end
All of those if statments are checking what username has been chosen. I have made a roblox game like this recently, so I just took all the script from the game.
If you want to check out my game, Click Here

How to use handle(w, “flag”) with Julia, WebIO & Blink?

I'm trying to use Blink with Julia (1.02) to create a simple login page.
I have a working login_button and a handler function (I think) for button presses, but I cannot get the functions inside the "handle(w, "press") do args..." to do anything useful.
I'd like the handler function to run "body!(w, new_page)" after checking the username & password, but it just hangs after printing out "login_button pressed!" after which the button stops responding.
I've been struggling with this for some time now, any help is appreciated.
Old Julia Code:
using WebIO, Blink
page =
node(:div,
node(:p, "please login below.", attributes=Dict("class"=>"lead")),
node(:input, attributes=Dict("id"=>"username", "type"=>"text", "placeholder"=>"username")),
node(:input, attributes=Dict("id"=>"password", "type"=>"password", "placeholder"=>"password")),
node(:button, "LOGIN", attributes=Dict("id"=>"login_button")));
new_page = node(:div, "New page!");
w = Window()
body!(w, page)
#js_ w document.getElementById("login_button").onclick = () -> Blink.msg("press", "login")
handle(w, "press") do args...
println("login_button pressed!")
username = #js w document.querySelector("""input[id="username"]""").value
password = #js w document.querySelector("""input[id="password"]""").value
println("$username, $password")
if username == "user" && password == "pass"
body!(w, new_page)
else
#js alert("Incorrect username or password. Try again.")
end
end
New Code:
using WebIO, Blink, Interact
using ..User
function page_inputs()
username = textbox("enter username", attributes=Dict("size"=>50))
password = textbox("enter password", typ="password")
login_button = button("LOGIN")
Widget(["username"=>username,"password"=>password,"login_button"=>login_button])
end
inputs = page_inputs();
page =
node(:div,
node(:br),
node(:img, attributes=Dict("src"=>"https://elmordyn.files.wordpress.com/2012/07/20110223084209-beholder.gif")),
node(:h2, "beholder", attributes=Dict("class"=>"display-3")),
node(:p, "VERSION 0.2"),
node(:hr, attributes=Dict("class"=>"my-3")),
node(:p, "No unauthorized access. Please login below.", attributes=Dict("class"=>"lead")),
node(:div, inputs),
attributes=Dict(:align=>"middle"));
title = "LOGIN ~ beholdia"
size = (500, 600)
function validate_user(w, inputs)
if inputs["login_button"][] > 0
inputs["login_button"][] = 0
if inputs["username"][] in keys(User.users) && inputs["password"][] == User.users[inputs["username"][]]
println("""Logging $(inputs["username"][]) in...""")
return true
else
#js w alert("Incorrect username or password. Try again.")
return false
end
end
end
function events(w, inputs)
#async while true
validate_user(w, inputs) == true ? break : sleep(0.1)
end
end

ValueError: not enough values to pack (expected 2, got 1) syntax error

Hello I am taking an example from learn python the hard way and working to understand python. I have already caught one error in the book and realized you need () to print out strings. So maybe there could be some more mistakes in the syntax. when I ran this file I received an error that said
ValueError: not enough values to pack (expected 2, got 1) syntax error. And another general syntax error. So I can't set prompt to raw_input.
rom sys import argv
script, user_name = argv
prompt = '>'
print ("Hi %s, I'm the $s script.") % user_name, script
print ("I'd like to ask you a few questions.")
print ("Do you like %s?") % user_name
likes = raw_input(prompt)
print ("Where do you live %s") % user_name
lives = raw_input(prompt)
print """
(Alright, so you said %r about liking me.
You live in %r. Not sure where that is.
And you have a %r computer. Nice)
"""& (likes, lives, computer)
Is there a typo in the code example? $s instead of %s in the format string?
I suspect that your actual code has this:
print ("Hi %s, I'm the %s script.") % user_name, script
And you meant to write this:
print "Hi %s, I'm the %s script." % (user_name, script)
That is, print a single string which is the result of applying the format string to two arguments.

Resources