Commit 7f57dce4 by Luciano Barletta

style changes, login

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