Python-用戶登陸驗證程序

用戶登陸驗證程序:
主要功能:
   1) 用戶登陸
   2) 登陸失敗3次後鎖定賬戶,並記錄到文件
   3) 登陸成功之後判斷用戶類型,根據用戶類型顯示不同菜單
   4) 用戶類型分爲普通用戶和管理員權限用戶
      普通用戶權限功能:
                a: 搜索用戶
                b: 修改密碼
      管理員用戶權限功能:
                a: 搜索用戶
                b: 添加用戶
                c: 刪除用戶
                d: 解鎖用戶
設計思路:
    將用戶的個功能通過函數方式進行模塊化,登陸後通過用戶角色選擇不同菜單,
    所有數據保存到txt文本文件中,程序啓動後將所有數據加載到內存中,每次做修改後重新寫到txt文件中去

    由於測試需要,增加和刪除一些用戶,爲了免於每次都更改txt文件,就增加了刪除、添加、解鎖等模塊

流程圖:


源碼:

#!/usr/bin/env python
# -*- coding: utf-8 -*-


import os,json,getpass
from datetime import datetime


USER_INFO = []                    # 存放所有用戶信息列表變量
LOGIN_USER = ""                  # 存放登陸成功的用戶名
LOGIN_USER_ROLE = "admin"       # 存放登陸用戶的權限,初始值爲'admin'
LOGIN_MAX_ERR_COUNT = 3         # 允許輸入錯誤的最大次數
# 存放用戶信息的文件,    當前路徑下的 userinfo.txt
DB_TXT_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'userinfo.txt')


def init_data():
    """初始化數據,將文件數據加載到全局變量中,返回一個列表"""
    with open(DB_TXT_FILE,'r') as f:
        for record in f.readlines():
            user_info = json.loads(record.strip())  # 將str類型的數據轉成dict
            USER_INFO.append(user_info)
        return USER_INFO


def get_admin_menus():
    """ 顯示管理員菜單"""
    menu_list = (
        {'key': '1', 'menu': '[1] search  users ', 'function': 'user_search'},
        {'key': '2', 'menu': '[2] add new users ', 'function': 'user_add'},
        {'key': '3', 'menu': '[3] delete  users ', 'function': 'user_del'},
        {'key': '4', 'menu': '[4] unlock  users ', 'function': 'user_unlock'},
        {'key': '5', 'menu': '[5] exit system ', 'function': 'exit_sys'},
    )
    return menu_list

def get_user_menus():
    """顯示用戶菜單"""
    menu_list = (
        {'key': '1', 'menu': '[1] search  users ', 'function': 'user_search'},
        {'key': '2', 'menu': '[2] modify password ', 'function': 'user_modify_passwd'},
        {'key': '5', 'menu': '[5] exit system ', 'function': 'exit_sys'},
    )
    return menu_list

def user_unlock():
    """解鎖用戶"""
    i = 0
    while i < len(USER_INFO):
        if USER_INFO[i]["name"] == LOGIN_USER:
            USER_INFO[i]['islocked'] = "1"
            save_data()
            break
        else:
            i += 1



def user_del():
    """刪除用戶"""
    print("========== Delete Users ==========")
    name = ""
    while len(name) == 0:
        name = input("input the user name you want to delete:").strip().lower()
        # 檢查用戶是否存在
        is_exists = check_user_is_exists(name)
        if is_exists:
            for i in range(len(USER_INFO)):
                if USER_INFO[i]['name'] == name:
                    del USER_INFO[i]
                    save_data()
                    print("\033[1;32m\nuser %s delete successfull !\033[0m" % name)
                    break
        else:
            print("\033[1;31m\nThe user %s does not exists!\033[0m" % name)


def user_add():
    """增加用戶,添加完1個用戶後是否繼續添加標誌"""
    add_more_flag = True
    print('====== Add New Users ===========')
    while add_more_flag:
        name = ''
        password = ''
        #如果輸入用戶名爲空則不停止輸入,直到輸入不爲空
        while len(name) == 0:
            name = input('username :').strip().lower()
        while len(password) == 0:
            password = input('password: ').strip()
        # 選擇用戶角色
        role = input('user role number [1:admin / 2:user(default)] : ')
        if len(role) == 0 or role  == '2':
            user_role = 'user'
        if role == '1':
            user_role = 'admin'
        # 組合數據爲字典
        user_info_dic = {'createtime':datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                         'password':password,
                         'name':name,
                         'userrole':user_role,
                         'islocked':'0'
        }
        USER_INFO.append(user_info_dic)
        save_data()
        continue_flag = input('add user successfull, and more?(Y/N)').strip().lower()
        if continue_flag == 'n' :
            add_more_flag = False



def user_search():
    """查找用戶"""
    print("\n======== Search Users =============\n")
    name = input('Input user name to serach \033[0;32;31m[Enter to show all]\033[0m : ').strip().lower()
    if len(name) >0:
        print_search_user_info(name)
    else:
        print(" \033[0;32;31m Don't Search....\033[0m")
    return  True


def print_search_user_info(name):
    """打印查找到的信息,並高亮顯示"""
    search_user = name
    i = 0
    record_count = 0

    #開始在列表中循環查找
    for i in range(len(USER_INFO)):
        user = USER_INFO[i]
        # 如果記錄的用戶包含要查找的名字
        if user['name'].count(search_user) > 0:
            name = user['name'].replace(search_user, '\033[1;31m' + search_user + '\033[0m')
            role = user['userrole']
            cdate = user['createtime']
            lockstat = user['islocked']
            print('name: %-25s | user role:%-7s | create time: %s | lockstatus: %s \n' % (
                name, role, cdate, lockstat)).strip()
            record_count += 1
    print('\n%s records found ' % str(record_count))


def check_user_is_exists(name):
    """檢查用戶是否存在(True/False)"""
    user_exists_status = False
    for i in range(len(USER_INFO)):
        user = USER_INFO[i]
        if user['name'] == name:
            user_exists_status = True
            break
    return user_exists_status


def user_modify_passwd(name):
    """修改密碼"""
    print("========== Modify User's Password ==========\n")
    i = 0
    flag = True
    while flag:
        new_password = getpass.getpass('input new password: ')
        renew_password = getpass.getpass('input new password again :').strip()
        if new_password ==renew_password:
            for i in range(USER_INFO):
                if USER_INFO[i]['name'] == name:
                    USER_INFO[i]['password'] = new_password
                    save_data()
                    flag = False
                    break

        else:
            print('new password and confirm password does not match! try again\n')


def user_lock(name):
    """鎖定賬戶"""
    for i in range(len(USER_INFO)):
        if USER_INFO[i]['name'] == name:
            USER_INFO[i]['islocked'] = '1'
            save_data()
            break

def save_data():
    """將數據寫入文件"""
    try:
        with open(DB_TXT_FILE,'w+') as f:
            for i in range(len(USER_INFO)):
                user = json.dumps(USER_INFO[i])
                f.write(user + '\n')
    except Exception as e:
        print(e.message)

def user_unlocked():
    """解鎖用戶"""
    print("======== Unlock Users ============\n")
    unlock_user = input("input the user name to be unlock:").strip().lower()
    for i in range(len(USER_INFO)):
        if USER_INFO[i]['name'] == unlock_user:
            USER_INFO[i]['islocked'] = '0'
            save_data()
            print('unlocked success')
            break
        else:
            print("no user called %s found!" % unlock_user)

def return_function_by_menu(menu_list):
    """# 根據輸入的按鍵返回函數名稱 ,如果選擇按鍵不存在則返回False"""
    print("========= Choose Menu ========== \n")
    for menu in menu_list:
        print(menu['menu'])
    choose = input('choose what do yo want to do :')
    # 獲取要執行的函數名稱
    for keys in menu_list:
        if keys['key'] == choose:
            return keys['function']
    else:
        print('\n\033[1;31m Error choose\033[0m')
        return False



def user_login():
    """ 用戶登錄"""
    try_failed_count = 0  # 重試失敗次數
    print("========= Login system ===========\n")
    while try_failed_count < LOGIN_MAX_ERR_COUNT:
        i = 0
        uname = input('user name:').strip().lower()
        upasswd = input('password: ').strip()
        while i < len(USER_INFO):
            # 如果找到搜索的用戶
            if USER_INFO[i]['name'] == uname:
                LOGIN_USER = uname
                # 如果正確,檢查用戶是否鎖定,如果鎖定
                if USER_INFO[i]['islocked'] == "1":
                        print("Sorry,your accout is locked,contact administrator to unlock")
                        exit()
                else:
                    # 用戶存在,檢查輸入密碼是否正確
                    if USER_INFO[i]['password'] == upasswd:
                        LOGIN_USER_ROLE = USER_INFO[i]['userrole']
                        print("\033[1;32m\nwelcome %s!\033[0m" % uname)
                        return True
                        # 用戶正確,密碼驗證失敗
                    else:
                        print("login failed,name and password is not avaible,try again!")
                        try_failed_count += 1
                        break
            # 沒找到? 下一條繼續找...
            else:
                i += 1
        # 搜索一圈都沒有找到搜索的用戶
        else:
            print("user does not found! try again.")

    else:
        # 密碼超過3次啦,賬戶要鎖定了
        user_lock()
        print('sorry , you try more then 3 times, i locked  this account!')
        return False


if __name__ == "__main__":
    init_data()

    if user_login():
        # 根據用戶角色加載菜單
        if LOGIN_USER_ROLE == "admin":
            menu_list = get_admin_menus()
        if LOGIN_USER_ROLE == "user":
            menu_list = get_user_menus()
            # 根據菜單選擇執行函數
        while True:
            func = False
            while not func:
                func = return_function_by_menu(menu_list)

            if func == "user_search":
                user_search()
            elif func == "user_add":
                user_add()
            elif func == "user_del":
                user_del()
            elif func == "user_modify_passwd":
                user_modify_password()
            elif func == "user_unlock":
                user_unlock()
            elif func == "exit_sys":
                exit()















發佈了35 篇原創文章 · 獲贊 9 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章