File size: 4,967 Bytes
89b9168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f26164
89b9168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
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)