Spaces:
Sleeping
Sleeping
Download app.py from fromnowoncoding/2fa_multiple: direct link, hf CLI and curl.
- Browser
- Download file 4.97 kB
-
https://huggingface.co/spaces/fromnowoncoding/2fa_multiple/resolve/main/app.py
- Command line
-
hf download hf://spaces/fromnowoncoding/2fa_multiple/app.py
-
curl -L -o app.py https://huggingface.co/spaces/fromnowoncoding/2fa_multiple/resolve/main/app.py
4.97 kB
| import base64 | |
| import hmac | |
| import hashlib | |
| import os | |
| import time | |
| import requests | |
| import json | |
| import binascii | |
| import gradio as gr | |
| from linebot import LineBotApi | |
| from linebot.models import TextSendMessage | |
| from linebot.exceptions import LineBotApiError | |
| from dotenv import load_dotenv | |
| # Base32 解碼 (類似於 PHP 中 Base32::decode) | |
| def base32_decode(encoded_secret): | |
| missing_padding = len(encoded_secret) % 8 | |
| if missing_padding != 0: | |
| encoded_secret += '=' * (8 - missing_padding) | |
| try: | |
| return base64.b32decode(encoded_secret) | |
| except binascii.Error as e: | |
| raise ValueError(f"Base32 解碼失敗: {e}") | |
| # HOTP 驗證碼生成 | |
| def generate_hotp(secret, counter): | |
| decoded_secret = base32_decode(secret) | |
| counter_bytes = counter.to_bytes(8, byteorder="big") | |
| hmac_hash = hmac.new(decoded_secret, counter_bytes, hashlib.sha1).digest() | |
| return dynamic_truncation(hmac_hash) % (10 ** 6) | |
| # 動態截斷算法 | |
| def dynamic_truncation(hmac_value): | |
| offset = hmac_value[-1] & 0x0F | |
| code = ( | |
| ((hmac_value[offset] & 0x7f) << 24) | |
| | ((hmac_value[offset + 1] & 0xff) << 16) | |
| | ((hmac_value[offset + 2] & 0xff) << 8) | |
| | (hmac_value[offset + 3] & 0xff) | |
| ) | |
| return code | |
| # 驗證碼生成 (基於時間的計數器,每 30 秒更新一次) | |
| def generate_otp(secret): | |
| counter = int(time.time() // 30) | |
| otp_code = generate_hotp(secret, counter) | |
| return f"{otp_code:06d}" | |
| # 發送訊息到 LINE | |
| def send_message_to_line(message): | |
| line_channel_access_token = os.getenv("LINE_CHANNEL_ACCESS_TOKEN") | |
| if not line_channel_access_token: | |
| raise ValueError("LINE_CHANNEL_ACCESS_TOKEN is not set in environment variables.") | |
| # 使用 LINE API 發送訊息 | |
| url = 'https://api.line.me/v2/bot/message/broadcast' | |
| headers = { | |
| 'Content-Type': 'application/json', | |
| 'Authorization': f'Bearer {line_channel_access_token}' | |
| } | |
| # 先嘗試廣播 | |
| broadcast_payload = { | |
| 'messages': [{ | |
| 'type': 'text', | |
| 'text': message | |
| }] | |
| } | |
| try: | |
| response = requests.post(url, headers=headers, json=broadcast_payload) | |
| print(f"Broadcast response: {response.status_code}") | |
| except Exception as e: | |
| print(f"Broadcast failed: {str(e)}") | |
| # 再使用 push message 發送到指定群組 | |
| push_url = 'https://api.line.me/v2/bot/message/push' | |
| group_ids = os.getenv("LINE_GROUP_ID", "").split(',') | |
| for group_id in group_ids: | |
| group_id = group_id.strip() | |
| if not group_id: | |
| continue | |
| push_payload = { | |
| 'to': group_id, | |
| 'messages': [{ | |
| 'type': 'text', | |
| 'text': message | |
| }] | |
| } | |
| try: | |
| response = requests.post(push_url, headers=headers, json=push_payload) | |
| if response.status_code == 200: | |
| print(f"Successfully sent message to group {group_id}") | |
| else: | |
| print(f"Failed to send message to group {group_id}: {response.text}") | |
| except Exception as e: | |
| print(f"Error sending to group {group_id}: {str(e)}") | |
| # Gradio 前端邏輯 | |
| def two_fa_interface(name, service_type, display_method, passphrase=""): | |
| if not name or not service_type: | |
| return "請填寫名稱和選擇服務類型" | |
| try: | |
| # 生成 2FA 驗證碼 | |
| secret = os.getenv('gmail_2fa') | |
| otp_code = generate_otp(secret) | |
| message = f"{name} 的驗證碼是:{otp_code}" | |
| if display_method == "發送到LINE": | |
| send_message_to_line(message) | |
| return "驗證碼已發送到 LINE" | |
| else: # 網頁顯示 | |
| stored_passphrase = os.getenv("PASSPHRASE", "") # 從環境變數獲取密碼 | |
| if passphrase == stored_passphrase: | |
| return message | |
| else: | |
| return "通關密語錯誤,請重試" | |
| except Exception as e: | |
| return f"發生錯誤:{str(e)}" | |
| # 初始化邏輯 | |
| def initialize(): | |
| load_dotenv() | |
| # Gradio 介面 | |
| service_options = ["ai@washinmura.jp"] | |
| display_methods = ["發送到LINE", "網頁顯示"] | |
| with gr.Blocks() as demo: | |
| gr.Markdown("# 和心村 2FA 驗證碼生成器") | |
| with gr.Row(): | |
| name = gr.Textbox(label="你的名稱") | |
| service_type = gr.Dropdown(choices=service_options, label="服務類型") | |
| with gr.Row(): | |
| display_method = gr.Radio(choices=display_methods, label="顯示方式", value="發送到LINE") | |
| passphrase = gr.Textbox(label="通關密語(僅網頁顯示需要)", type="password") | |
| submit_btn = gr.Button("生成驗證碼") | |
| output = gr.Textbox(label="結果") | |
| submit_btn.click( | |
| fn=two_fa_interface, | |
| inputs=[name, service_type, display_method, passphrase], | |
| outputs=output | |
| ) | |
| # 啟動應用 | |
| demo.launch(share=True) | |