1. 程式人生 > >多用戶登錄驗證

多用戶登錄驗證

輸入 文件中 stat ber abc 直接 don 退出程序 else

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
#
# Author:   Payne Zheng <[email protected]>
# Date:     2018-04-11 10:41:15
# Location: DongGuang
# Desc:     User login authentication
#


def CheckUserStatus(user):
    """檢查帳號是否在鎖定文件中"""
    try:
        with open(user_lock_file, ‘r‘, encoding="utf-8") as f1:
            lines = f1.readlines()
            for line in lines:
                if line.strip() == user:
                    return "lock"
    except FileNotFoundError:
        pass

"""設定變量"""
user_lock_file = "lock.txt"
retry_num = 3
user_pass_dict = {
    "jack": "abc123",
    "jushua": "123abc",
    "payne": "a1b2c3"
}
input_user = input("\033[34mPlease enter your account number:\033[0m")

"""檢查用戶帳號狀態,如在鎖定帳號文件則報錯退出"""
if CheckUserStatus(input_user) == "lock":
    print(
        """\033[31mError! %s user has been locked,"""
        """unable to login, please contact customer service phone 10086.\033[0m""")
    exit()

"""檢查用戶是否存在,不存在直接退出"""
if input_user not in user_pass_dict:
    print("\033[31mSrror! you enterd user <%s> does not exist.!\033[0m" % input_user)
    exit()

"""驗證密碼"""
while True:
    input_pass = input("\033[34mPlease enter your password:\033[0m")
    # 檢查用戶輸入密碼是否正確
    if user_pass_dict.get(input_user) == input_pass:
        print("\033[32mSuccessful login, welcome <%s>\033[0m" % input_user)
        break
    else:
        print(
            """\033[33mThe password entered is not correct,"""
            """please re-enter (you still have %s retry opportunity)!\033[0m""" % (retry_num - 1))
        retry_num -= 1
        if retry_num == 0:
            print(
                """\033[31mSorry, the password input error exceeds the number of retries"""
                """the account has been locked!\033[0m""")
            # 重輸密碼三次後將帳號存入鎖定文件進行鎖定
            with open(user_lock_file, ‘a‘, encoding="utf-8") as f:
                f.writelines(input_user + "\n")
            break
        else:
            continue

 

作業需求:

基礎需求:
讓用戶輸入用戶名密碼
認證成功後顯示歡迎信息
輸錯三次後退出程序

升級需求:
可以支持多個用戶登錄 (提示,通過列表存多個賬戶信息)
用戶3次認證失敗後,退出程序,再次啟動程序嘗試登錄時,還是鎖定狀態(提示:需把用戶鎖定的狀態存到文件裏)

 

多用戶登錄驗證