streamlitでログイン - matutosi/support-ac GitHub Wiki

元ネタ https://qiita.com/bassan/items/ed6d821e5ef680a20872

準備

  • ライブラリのインストール
pip install streamlit
pip install streamlit-authenticator
  • ユーザ名とパスワードのファイル(user_info.csv)
  • ハッシュ値の保存用ファイル(config.yaml)
  • create_yaml.py でハッシュ値の生成(config.yamlに追記される)
# user_info.csv
username,password
A12345,johndoepass
B23456,alicepass
C34567,bobjohnsonpass
D45678,emilypass
E56789,mikepass
F67890,sarahpass
G78901,davidpass
H89012,jenniferpass
I90123,danielpass
# config.yaml (hash生成前)
cookie:
  expiry_days: 1
  key: some_signature_key
  name: some_cookie_name
credentials:
  usernames:
"""
# create_yaml.py
# python create_yaml.py
パスワードからハッシュ値を生成
ハッシュ値は公開しても,パスワード自体は分からない

修正箇所
・パスワードのハッシュ化部分は,エラーのため修正(以下の部分)
  user["password"] = Hasher.hash(user["password"])
・nameとemailの出力は不要なので削除
"""

import csv
import yaml
from streamlit_authenticator.utilities.hasher import Hasher

users_csv_path = "user_info.csv"
config_yaml_path = "config.yaml"

## ユーザー設定の一覧が記述されたデータを読み込み
with open(users_csv_path, "r") as f:
    csvreader = csv.DictReader(f)
    users = list(csvreader)

## yaml 設定一覧が記述されたデータを読み込み
with open(config_yaml_path,"r") as f:
    yaml_data = yaml.safe_load(f)

## パスワードのハッシュ化
users_dict = {}
for user in users:
    user["password"] = Hasher.hash(user["password"])
    tmp_dict = {
        "password": user["password"],
    }
    users_dict[user["username"]] = tmp_dict

## yaml 書き込み
yaml_data["credentials"]["usernames"] = users_dict
with open(config_yaml_path, "w") as f:
    yaml.dump(yaml_data, f)
    print("完了")
# config.yaml (hash生成後)
cookie:
  expiry_days: 1
  key: some_signature_key
  name: some_cookie_name
credentials:
  usernames:
    A12345:
      password: $2b$12$9bbio0RHh6wAD3xgRI62T.VIEspIkatRnexuvh.TTThT0.QpZTF72
    B23456:
      password: $2b$12$WkWsnfvXQl0ZoaYUFsvv..UbDTQt.h3dyNgOdDmDt8eDzBkxDdOE.
    C34567:
      password: $2b$12$hp6yvT6wRH98XOFMdG8UvugtqtWNL6NiF8gHzAfLV72q0AItOOjHy
# (省略)

Streamlitの実行

  • user_info.csv のusernameとpasswordでログイン
"""
# streamlit_auth.py
# streamlit run streamlit_auth.py
ログインの練習コード
"""

import streamlit as st
import streamlit_authenticator as stauth

import yaml
from yaml.loader import SafeLoader

## ユーザー設定読み込み
yaml_path = "config.yaml"

with open(yaml_path) as file:
    config = yaml.load(file, Loader=SafeLoader)

authenticator = stauth.Authenticate(
    credentials=config['credentials'],
    cookie_name=config['cookie']['name'],
    cookie_key=config['cookie']['key'],
    cookie_expiry_days=config['cookie']['expiry_days'],
)

## UI 
authenticator.login()
if st.session_state["authentication_status"]:
    ## ログイン成功
    with st.sidebar:
        st.markdown(f'## Welcome *{st.session_state["username"]}*')
        authenticator.logout('Logout', 'sidebar')
        st.divider()
    st.write('# ログインしました!')

elif st.session_state["authentication_status"] is False:
    ## ログイン成功ログイン失敗
    st.error('Username/password is incorrect')

elif st.session_state["authentication_status"] is None:
    ## デフォルト
    st.warning('Please enter your username and password')