2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【SQLite】DBを使った簡単なパスワード認証

Posted at

DBを使ったパスワード認証の方法を確認する

実行結果

$ python ./db.py

Please input user ID: mash
Please input user Password: xxxxx
-----------------------------------
Success! You are loged in as "MASH" 

  • 上記のように ユーザIDパスワード の入力を求められる

実行環境

  • macOSX Monterey
  • Python 3.10.6

Pythonコード

db.py
import hashlib
import sqlite3


# digest
def get_digest(password):
    pwd = bytes(password, 'utf-8')
    digest = hashlib.sha256(pwd).hexdigest()
    return digest


# DB connection
def get_id_pwd():
    ''' Connect to db and get id & pwd '''

    sqlite_path = 'user_db.sqlite'
    connection = sqlite3.connect(sqlite_path)
    cursor = connection.cursor()
    cursor.execute('select name, password from users')
    id_pwd_hash = dict(cursor.fetchall())
    connection.close()
    return id_pwd_hash


# Login check
def login_check():
    if user_id in id_pwd_hash.keys():
        if password == id_pwd_hash[user_id]:
            print('-' * 35)
            print(f'Success! You are loged in as "{ user_id.upper() }" \n')
    else:
        print('-' * 35)
        print('You are not permitted to login \n')


# Login input
user_id = input('Please input user ID: ')
pwd = input('Please input user Password: ')


# Execution
password = get_digest(pwd)
id_pwd_hash = get_id_pwd()
login_check()

Database (user_db.sqlite)

スクリーンショット 2022-09-14 15.17.42.png

ポイント

  • get_digest()関数で、引数としてターミナルで入力パスワードをハッシュ化する
  • SQLiteのDBに接続しIDとパスワードを取り出し、辞書(id_pwd_hash)の形にして返す
  • ハッシュ化されたパスワードをDBの値と照合する(DBのパスワードはハッシュ化された状態で保存されている前提)
  • ほぼこのまま、Flaskに実装可能
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?