Commit 7f57dce4 by Luciano Barletta

style changes, login

1 parent bbb9f7e9
#-*- coding: utf-8 -*- #-*- coding: utf-8 -*-
from flask import Flask, json, request, url_for, render_template from flask import Flask, json, request, url_for, render_template
import random import random, os
app = Flask(__name__) app = Flask(__name__)
TOKEN_LENGHT = 32 TOKEN_LENGTH = 128
TOKEN_STRING = "\ TOKEN_STRING = "\
1234567890\ 1234567890\
qwertyuiopasdfghjklzxcvbnm\ qwertyuiopasdfghjklzxcvbnm\
QWERTYUIOPASDFGHJKLZXCVBNM" QWERTYUIOPASDFGHJKLZXCVBNM\
sessions = {} "
TOKEN_FILE = "tokens.json"
def make_token():
s = ""
i = 0
while i < TOKEN_LENGTH:
s += TOKEN_STRING[random.randrange(0,TOKEN_LENGTH)]
i += 1
loginfields = [ data = ""
if os.path.exists(TOKEN_FILE):
with open(TOKEN_FILE,"r") as f:
data = f.read()
with open(TOKEN_FILE,"+w") as f:
if data == "":
data = {}
else:
data = json.loads(data)
data[s] = True
f.write(json.dumps(data))
return s
def check_token(token):
if os.path.exists(TOKEN_FILE):
with open(TOKEN_FILE,"r") as f:
data = f.read()
return token in data
return False
COLOR_DEFAULT = "rgb(10,10,200)"
LOGIN_FIELDS = [
{ {
"title" : "Usuario", "title" : "Usuario",
"type" : "text", "type" : "text",
...@@ -23,76 +58,124 @@ loginfields = [ ...@@ -23,76 +58,124 @@ loginfields = [
"required" : True "required" : True
} }
] ]
JSON_FILES = "json"
def answer(succ, error = None):
if succ == True:
return json.dumps({
"success" : True
})
return json.dumps({
"success" : False,
"error" : error
})
@app.route('/load/<name>', methods = ['POST'])
def load(name):
try:
data = request.json
if data == None:
return answer(False, "Ningún dato enviado")
with open(f"{JSON_FILES}/{name}.json", "+w") as f:
f.write(json.dumps(data))
return answer(True)
except:
return answer(False, "Error escribiendo archivo")
@app.route('/remove/<name>', methods = ['POST'])
def remove(name):
try:
if os.path.exists(f"{JSON_FILES}/{name}.json"):
os.remove(f"{JSON_FILES}/{name}.json")
return answer(True)
except:
return answer(False, "Error borrando archivo")
@app.route('/form/<name>', methods = ['GET'])
def form(name):
try:
if os.path.exists(f"{JSON_FILES}/{name}.json"):
with open(f"{JSON_FILES}/{name}.json") as f:
return generate(f.read())
return answer(False, "No existe el formulario")
except:
return answer(False, "Error leyendo el formulario")
@app.route('/datos', methods = ['GET', 'POST'])
def datos():
print(request.json)
return "OK"
@app.route('/login', methods = ['GET', 'POST']) @app.route('/login', methods = ['GET', 'POST'])
def login(): def login():
return render_template("login.html",title="Login",fields=loginfields,color="blue",send="http://192.168.15.119:5000/datos") try:
@app.route('/', methods = ['GET', 'POST']) if os.path.exists(f"{JSON_FILES}/login.json"):
def main(): with open(f"{JSON_FILES}/login.json","r") as f:
data = [ data = f.read()
{
"title" : "general", if data == "":
"fields" : [ return answer(False, "No hay datos para generar el login")
{
"title" : "nombre", data = json.loads(data)
"type" : "text",
"placeholder" : "Luciano", if 'color' not in data:
"required" : True data['color'] = COLOR_DEFAULT
},
{ if 'validate' not in data:
"title" : "mail", return answer(False, "No hay dirección de validación => {'validate' : 'example.com'}")
"type" : "email",
"placeholder" : "ejemplo@gmail.com", if 'redirect' not in data:
} return answer(False, "No hay dirección de redirección => {'redirect' : 'example.com'}")
]
}, return render_template(
{ "login.html",
"title" : "detalles", title = "Login",
"fields" : [ fields = LOGIN_FIELDS,
{ color = data['color'],
"title" : "género", validate = data['validate'],
"type" : "select", redirect = data['redirect']
"placeholder" : "Género", )
"options" : [
"Hombre", return answer(False, "No existe el formulario de login")
"Mujer",
"#other" except:
] return answer(False, "Hubo un error en la generación del login")
},
{
"title" : "Gusto", def generate(json):
"type" : "checkbox", try:
"options" : [
"Hombres", if json == None:
"Mujeres", return answer(False, "No hay datos para generar este formulario")
"#other"
], if 'color' not in json:
"required" : True json['color'] = COLOR_DEFAULT
}
] if 'send' not in json:
}, return answer(False, "No hay destino en el formulario => {'send' : 'example.com'}")
{
"title" : "Fecha y hora", if 'title' not in json:
"fields" : [ return answer(False, "No se ingresó título del formulario => {'title' : 'Título'}")
{
"title" : "Dia", return render_template(
"type" : "date", "form.html",
"placeholder" : "2019-12-10" tabs = json['tabs'],
}, title = json['title'],
{ color = json['color'],
"title" : "Hora", send = json['send']
"type" : "time" )
}
] except:
} return answer(False, "Hay un error en los datos de este formulario")
]
return render_template("form.html",tabs=data,title="Formulario de Prueba",color="#33aaff",send="http://192.168.15.119:5000/datos")
if __name__ == "__main__": if __name__ == "__main__":
app.run("0.0.0.0") app.run("0.0.0.0")
\ No newline at end of file \ No newline at end of file
{"color": "grey", "redirect": "/", "validate": "/"}
\ No newline at end of file \ No newline at end of file
...@@ -54,13 +54,22 @@ function Boton(tc, url) { ...@@ -54,13 +54,22 @@ function Boton(tc, url) {
tc.lastElementChild.children[0].appendChild(button); tc.lastElementChild.children[0].appendChild(button);
} }
function LoginBoton(tc, validate, redirect) {
button = document.createElement("button");
button.value = "Enviar";
button.setAttribute("onclick", "Redireccionar(LeerYEnviar(document.getElementById('TabsContainer'),'" + validate + "'),'" + redirect + "')");
button.setAttribute("class","SendButton");
button.innerText = "Enviar";
tc.lastElementChild.children[0].appendChild(button);
}
function NoValido(input,msg){ function NoValido(input,msg){
let tab = getAncestorByAttribute(input,"class","Tabs") let tab = getAncestorByAttribute(input,"class","Tabs");
let n = parseInt(tab.id[tab.id.length - 1]) let n = parseInt(tab.id[tab.id.length - 1]);
HabilitarTab(document.getElementById('TabsContainer'),n) HabilitarTab(document.getElementById('TabsContainer'),n);
HabilitarButton(document.getElementById('BotonesContainer'),n) HabilitarButton(document.getElementById('BotonesContainer'),n);
input.setCustomValidity(msg) input.setCustomValidity(msg);
input.reportValidity() input.reportValidity();
input.oninput = () => input.setCustomValidity(''); input.oninput = () => input.setCustomValidity('');
} }
...@@ -68,7 +77,15 @@ function CheckboxValidity(checkboxContainer){ ...@@ -68,7 +77,15 @@ function CheckboxValidity(checkboxContainer){
return Array.from(checkboxContainer.children).reduce( return Array.from(checkboxContainer.children).reduce(
(last,checkbox) => checkbox.className != "Checkbox" ? last : checkbox.lastElementChild.firstElementChild.checked || last, (last,checkbox) => checkbox.className != "Checkbox" ? last : checkbox.lastElementChild.firstElementChild.checked || last,
false false
) );
}
function CreateErrorLogin(fc){
error = document.createElement("div");
error.id = "ErrorLogin";
error.innerText = "Usuario o Contraseña incorrectos";
error.className = "Error";
fc.appendChild(error);
} }
function GetCheckboxes(field) { function GetCheckboxes(field) {
...@@ -81,6 +98,11 @@ function GetCheckboxes(field) { ...@@ -81,6 +98,11 @@ function GetCheckboxes(field) {
return data; return data;
} }
function Redireccionar(bool, redirect){
if (bool == true) window.location.href = redirect;
else document.getElementById('ErrorLogin').style.display = "block";
}
function LeerYEnviar(tc,url){ function LeerYEnviar(tc,url){
let data = {}; let data = {};
let valid = true; let valid = true;
......
...@@ -82,18 +82,19 @@ body { ...@@ -82,18 +82,19 @@ body {
margin: auto; margin: auto;
margin-top: 2%; margin-top: 2%;
margin-bottom: 2%; margin-bottom: 2%;
min-height: 70%;
text-align: center; text-align: center;
position: relative;
} }
.TabTitle { .TabTitle {
text-align: center; text-align: center;
font-size: 50px; height: 50px;
font-size: 30px;
font-weight: bolder; font-weight: bolder;
padding: inherit; padding: inherit;
margin-bottom: 20px; margin-bottom: 20px;
border-bottom: 3px solid rgb(120, 120, 120); border-bottom: 3px solid rgb(120, 120, 120);
vertical-align: middle;
line-height: 50px;
} }
.FieldsContainer { .FieldsContainer {
...@@ -111,10 +112,12 @@ body { ...@@ -111,10 +112,12 @@ body {
} }
.FieldTitle { .FieldTitle {
width: 20%; width: 30%;
text-align: center; text-align: center;
margin: auto; margin: auto;
font-size: 20px; font-size: 12px;
vertical-align: middle;
line-height: 20px;
font-weight: bold; font-weight: bold;
text-align: center; text-align: center;
margin-top: 50; margin-top: 50;
...@@ -122,7 +125,7 @@ body { ...@@ -122,7 +125,7 @@ body {
} }
.FieldInput { .FieldInput {
width: 70%; width: 60%;
text-align: center; text-align: center;
font-weight: bold; font-weight: bold;
margin: auto; margin: auto;
...@@ -130,8 +133,8 @@ body { ...@@ -130,8 +133,8 @@ body {
.FieldInput input, .FieldInput input,
.FieldInput select { .FieldInput select {
width: 70%; width: 60%;
font-size: 20px; font-size: 15px;
margin-top: 50; margin-top: 50;
margin-bottom: 50; margin-bottom: 50;
} }
...@@ -187,11 +190,10 @@ body { ...@@ -187,11 +190,10 @@ body {
} }
.SendButton { .SendButton {
position: absolute;
bottom: 5%;
left: 42%;
width: 16%;
height: 30px; height: 30px;
width: 30%;
margin-top: 20px;
margin-bottom: 10px;
font-size: 15px; font-size: 15px;
background-color: white; background-color: white;
border-radius: 2px; border-radius: 2px;
...@@ -203,6 +205,14 @@ body { ...@@ -203,6 +205,14 @@ body {
color: red; color: red;
} }
.Error {
display: none;
margin-top: 20px;
margin-bottom: 10px;
font-weight: bold;
color: red;
}
@media (max-width: 500px) { @media (max-width: 500px) {
.Checkbox { .Checkbox {
......
...@@ -11,8 +11,9 @@ ...@@ -11,8 +11,9 @@
</head> </head>
<body onload=" <body onload="
HabilitarTab(document.getElementById('TabsContainer'),0), HabilitarTab(document.getElementById('TabsContainer'),0),
document.documentElement.style.setProperty('--Color','{{ color }}'), document.documentElement.style.setProperty('--Color','{{ color }}'),
Boton(document.getElementById('TabsContainer'), '{{ send }}')"> CreateErrorLogin(document.getElementById('Tab0').firstElementChild),
LoginBoton(document.getElementById('TabsContainer'), '{{ validate }}', '{{ redirect }}')">
<section id="TabsContainer"> <section id="TabsContainer">
{% from "tab.html" import tab %} {% from "tab.html" import tab %}
......
Styling with Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!