-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
230 lines (194 loc) · 7.94 KB
/
main.py
File metadata and controls
230 lines (194 loc) · 7.94 KB
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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
import os
import json
import streamlit as st
from ldap3 import Server, Connection, ALL, SUBTREE
from dotenv import load_dotenv
from enum import Enum
import hashlib
from pydantic import BaseModel
load_dotenv()
st.session_state.bopened = None
st.session_state.btype = None
def load_json_files_from_directory(directory_path):
json_dict = {}
# Listar todos los ficheros en el directorio
for filename in os.listdir(directory_path):
# Comprobar que es un fichero JSON
if filename.endswith(".json"):
full_path = os.path.join(directory_path, filename)
with open(full_path, "r", encoding="utf-8") as f:
content = json.load(f)
name_without_extension = os.path.splitext(filename)[0]
json_dict[name_without_extension] = content
return json_dict
class Query(str, Enum):
APPROVED = "APPROBADO"
ERROR_NOT_FOUND = "ERROR_NO_ENCONTRADO"
ERROR_PASSWORD = "ERROR_CONTRASEÑA"
ERROR_SERVICE = "ERROR_SERVICIO"
class User(BaseModel):
username: str
pasw: str
# DEFAULT_PASSWORD = "38d406a798688f99c83852840952c276eb7635f7ea9024babcde8648b0c37e31"
DEFAULT_PASSWORD = st.secrets["user"]["default_password"]
def hash_password(password):
"""Hash a password using SHA-256"""
return hashlib.sha256(password.encode()).hexdigest()
def check_user(user: User):
try:
server = Server(st.secrets["ldap"]["address"], get_info=ALL)
conn = Connection(
server,
f"cn={st.secrets["ldap"]["user"]},dc=uh,dc=cu",
st.secrets["ldap"]["passwd"],
auto_bind=True,
)
# 2. Buscar el DN del usuario
search_filter = f"(uid={user.username})" # Puede ser 'sAMAccountName', 'cn', etc. según tu LDAP
conn.search(
search_base="dc=uh,dc=cu",
search_filter=search_filter,
search_scope=SUBTREE,
attributes=["Title","cn","sn","ou"],
)
if not conn.entries:
return Query.ERROR_NOT_FOUND, {}
entry = conn.entries[0]
user_dn = entry.entry_dn
user_data = {
"Nombre": entry.cn.value,
"Apellidos": entry.sn.value,
"Area": entry.ou.value.upper(),
"Title": entry.title.value,
}
# 3. Intentar autenticar con las credenciales del usuario
user_conn = Connection(server, user_dn, user.pasw, auto_bind=True)
# Si llegamos aquí, la autenticación fue exitosa
user_conn.unbind()
return Query.APPROVED, user_data
except Exception as e:
if "invalidCredentials" in str(e):
return Query.ERROR_PASSWORD, {}
else:
return Query.ERROR_SERVICE, {}
def login():
st.title("Login")
with st.form("login_form"):
username = st.text_input("Usuario")
password = st.text_input("Contraseña", type="password")
submit = st.form_submit_button("Autenticarse")
if submit:
checking,user_data = check_user(User(username=username, pasw=password))
if checking is Query.APPROVED or (
username == st.secrets["user"]["default_user"]
and hash_password(password) == DEFAULT_PASSWORD
):
st.session_state.logged_in = True
st.session_state.username = username
st.session_state.user_data = user_data
st.success("Logged in successfully!")
st.rerun()
elif checking is Query.ERROR_NOT_FOUND:
st.error("Invalid username")
elif checking is Query.ERROR_PASSWORD:
st.error("Invalid password")
def logout():
st.session_state.logged_in = False
st.session_state.username = None
st.rerun()
def rebuild_articles_dict(all):
for art in all["articles"].values():
apb = int(art["begin"])
ape = int(art["end"])
art["book"] = None
for idb, book in all["books"].items():
if int(book["begin"]) <= apb and ape <= int(book["end"]):
art["book"] = int(idb) + 1
break
art["title"] = None
for idt, title in all["titles"].items():
if int(title["begin"]) <= apb and ape <= int(title["end"]):
art["title"] = idt
break
art["chapter"] = None
for idc, chapter in all["chapters"].items():
if int(chapter["begin"]) <= apb and ape <= int(chapter["end"]):
art["chapter"] = idc
break
art["section"] = None
for ids, section in all["sections"].items():
if int(section["begin"]) <= apb and ape <= int(section["end"]):
art["section"] = ids
break
def rebuild_simple_mapping(items):
res = {}
for item in items["pairs"]:
current = item["Project_Law"]
rids = [i["id"] for i in item["Actual_Law"]]
res[current["id"]] = rids
return res
def rebuild_complex_mapping(items):
res = {}
for item in items["pairs"]:
current = item["Project_Law"]
res[current["id"]] = []
for art in item["Actual_Law"]:
dart = {}
dart["id"] = art["id"]
dart["paragraphs"] = art["IDS_PAR_ACTUAL_LAW"]
res[current["id"]].append(dart)
return res
login_page = st.Page(login, title="Log in", icon=":material/login:")
logout_page = st.Page(logout, title="Log out", icon=":material/logout:")
intro_page = st.Page("pages/intro.py", title="Inicio", icon=":material/home:")
ideas_page = st.Page("pages/ideas.py", title="Fundamentos", icon=":material/layers:")
question_page = st.Page(
"pages/questions.py", title="Resumen", icon=":material/help_outline:"
)
project_page = st.Page(
"pages/project.py", title="Anteproyecto", icon=":material/menu_book:"
)
chat_page = st.Page("pages/chat.py", title="Asistente", icon=":material/chat_bubble:")
search_page = st.Page("pages/search.py", title="Buscar", icon=":material/search:")
docs_page = st.Page("pages/docs.py", title="Documentos", icon=":material/source:")
changes_page = st.Page("pages/changes.py", title="Propuesta de Cambios", icon=":material/display_settings:")
analytics_page = st.Page("pages/analytics.py",title="Analisis de Encuestas",icon=":material/analytics:")
# Initialize session state
if "logged_in" not in st.session_state:
st.session_state.logged_in = False
# Main app logic
if not st.session_state.logged_in:
pg = st.navigation([login_page])
else:
with st.spinner("Espere...", show_time=True):
project = load_json_files_from_directory(st.secrets["dirs"]["project"]["law"])
rebuild_articles_dict(project)
intro = load_json_files_from_directory(st.secrets["dirs"]["project"]["intro"])
mappings = load_json_files_from_directory(st.secrets["dirs"]["mappings"])
questions = load_json_files_from_directory(st.secrets["dirs"]["questions"])
current = load_json_files_from_directory(st.secrets["dirs"]["current"]["law"])
abstract = load_json_files_from_directory(st.secrets["dirs"]["project"]["abstract"])
st.session_state["project"] = project
st.session_state["intro"] = intro
st.session_state["questions"] = questions
st.session_state["current"] = current
st.session_state["mappings"] = mappings
st.session_state["mappings"]["policies"] = rebuild_simple_mapping(mappings["politicas_vs_articulo"])
st.session_state["mappings"]["diagnosis"] = rebuild_simple_mapping(mappings["diagnostico_vs_articulo"])
st.session_state["mappings"]["articles"] = rebuild_complex_mapping(mappings["articulo_vs_articulo"])
st.session_state["abstract"] = abstract
pg = st.navigation(
[
intro_page,
ideas_page,
question_page,
project_page,
chat_page,
search_page,
docs_page,
changes_page,
analytics_page,
logout_page,
]
)
pg.run()