Commit e9fc91d3 by Luciano Barletta

done with routing and login

1 parent 7f57dce4
No preview for this file type
No preview for this file type
#-*- coding: utf-8 -*-
from flask import Flask, request, url_for, render_template
import os, requests, aux, json
from validation import Validation
app = Flask(__name__)
LOGIN_FIELDS = [
{
"title" : "Usuario",
"type" : "text",
"required" : True
},
{
"title" : "Contraseña",
"type" : "password",
"required" : True
}
]
JSON_FILES = "json"
@app.route('/load/<name>', methods = ['POST'])
def load(name):
try:
data = request.json
if data == None:
return aux.answer(False, "Ningún dato enviado")
with open(f"{JSON_FILES}/{name}.json", "+w") as f:
f.write(json.dumps(data))
return aux.answer(True)
except:
return aux.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 aux.answer(True)
except:
return aux.answer(False, "Error borrando archivo")
@app.route('/form/<name>', methods = ['GET'])
def iform(name):
return render_template("redirect.html",url=f"/form/{name}")
@app.route('/form/<name>/<token>', methods = ['GET'])
def form(name,token):
try:
validation = Validation()
# Not valid. When you finish loging in, go to this address
if not validation.check_token(token):
return login(f'/form/{name}')
if os.path.exists(f"{JSON_FILES}/{name}.json"):
with open(f"{JSON_FILES}/{name}.json") as f:
return aux.generate(json.loads(f.read()))
return aux.answer(False, "No existe el formulario")
except:
return aux.answer(False, "Error leyendo el formulario")
@app.route('/login', methods = ['GET'])
def login(redirect = None):
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 aux.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 aux.answer(False, "No hay dirección de validación => {'validate' : 'example.com'}")
if 'redirect' not in data:
return aux.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 = redirect if redirect != None else data['redirect']
)
return aux.answer(False, "No existe el formulario de login")
except:
return aux.answer(False, "Hubo un error en la generación del login")
@app.route('/validate', methods = ['POST'])
def ivalidate():
try:
data = request.json
except:
data = {}
return aux.validate(data)
if __name__ == "__main__":
app.run("0.0.0.0")
\ No newline at end of file
import json
from validation import Validation
from flask import render_template, url_for
def answer(succ, error = None):
if succ == True:
return json.dumps({
"success" : True
})
return json.dumps({
"success" : False,
"error" : error
})
COLOR_DEFAULT = "rgb(10,10,200)"
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")
def validate(data):
validation = Validation()
if 'url' in data:
url = data['url']
del data['url']
#r = requests.post(url, json = data)
#if r.text == "true":
if True:
return json.dumps({
'success' : True,
'cookie' : validation.make_token(),
})
else:
return answer(False,"")
return answer(False,"no validation address")
\ No newline at end of file
#-*- coding: utf-8 -*-
from flask import Flask, json, request, url_for, render_template
import random, os
app = Flask(__name__)
TOKEN_LENGTH = 128
TOKEN_STRING = "\
1234567890\
qwertyuiopasdfghjklzxcvbnm\
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
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",
"required" : True
},
{
"title" : "Contraseña",
"type" : "password",
"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('/login', methods = ['GET', 'POST'])
def login():
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": "black",
"title": "default",
"tabs": [
{
"title" : "generador de formularios",
"fields": [
{
"title" : "campo",
"type" : "text"
}
]
}
],
"send" : "192.168.15.119:5000/login"
}
\ No newline at end of file
{"color": "grey", "redirect": "/", "validate": "/"}
\ No newline at end of file
{"color": "grey", "redirect": "/form/default", "validate": "/"}
\ No newline at end of file
......@@ -13,8 +13,9 @@ var getDescendantByAttribute = (elem,attr,val) => {
}
function HabilitarTab(tc,n){
if (tc == null) return console.log("El contenedor no existe")
if (typeof n != "number") return console.log("El entero es invalido");
for (let it = 0; it < tc.children.length; it++) {
if (it == n) tc.children[it].style.display = "block";
else tc.children[it].style.display = "none";
......@@ -22,6 +23,7 @@ function HabilitarTab(tc,n){
}
function HabilitarButton(bc,n){
if (bc == null) return console.log("El contenedor no existe")
if (typeof n != "number") return console.log("El entero es invalido");
for (let it = 0; it < bc.children.length; it++) {
......@@ -48,16 +50,7 @@ var accessDataContainer = tab => getDescendantByAttribute(tab, "class", "FieldsC
function Boton(tc, url) {
button = document.createElement("button");
button.value = "Enviar";
button.setAttribute("onclick", "LeerYEnviar(document.getElementById('TabsContainer'),'" + url + "')");
button.setAttribute("class","SendButton");
button.innerText = "Enviar";
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("onclick", "Enviar(Leer(document.getElementById('TabsContainer')),'" + url + "')");
button.setAttribute("class","SendButton");
button.innerText = "Enviar";
tc.lastElementChild.children[0].appendChild(button);
......@@ -80,14 +73,6 @@ function CheckboxValidity(checkboxContainer){
);
}
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) {
let data = [];
Array.from(field.children).forEach( child => {
......@@ -98,12 +83,7 @@ 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){
function Leer(tc){
let data = {};
let valid = true;
Array.from(tc.children).forEach( tab =>
......@@ -135,7 +115,7 @@ function LeerYEnviar(tc,url){
if (input.checkValidity() == false) {
valid = false;
if (input.type == "email") NoValido(input, "Mail inválido");
else NoValido(input, "Mail inválido");
else NoValido(input, "Debe llenar este campo");
}
data[name] = input.value
......@@ -143,10 +123,13 @@ function LeerYEnviar(tc,url){
}
})
);
if (valid == false) return;
console.log(data);
if (valid == false) return valid;
return data;
}
function Enviar(data, url){
http = new XMLHttpRequest();
http.open("POST", url, true);
http.open("GET", url, true);
http.setRequestHeader("Content-Type", "application/json");
http.onload = () => { if (http.status == 200) alert("Enviado con éxito"); };
http.send(JSON.stringify(data));
......
class Ajax {
constructor(object){
if (typeof object !== "object") this.data = {};
else this.data = object;
this.http = new XMLHttpRequest();
}
default(){
if (!("url" in this.data)) throw "URL not set";
if (!("async" in this.data)) this.data.async = true;
if ("success" in this.data)
this.http.onload = () => { if (this.http.status == 200) this.data.success(this.http.response); }
if (this.data.async === false && "timeout" in this.data){
this.http.timeout = this.data.timeout;
if ("ontimeout" in this.data) this.http.ontimeout = (this.data.ontimeout).bind(this.http);
}
}
post(){
this.default();
this.http.open("POST", this.data.url, this.data.async);
if ("contentType" in this.data) this.http.setRequestHeader('Content-Type', this.data.contentType);
if ("data" in this.data) this.http.send(JSON.stringify(this.data.data));
else this.http.send();
}
get(){
this.default();
if ("data" in this.data) this.http.open("GET", this.data.url + "?" + this.data.data, this.data.async);
else this.http.open("GET", this.data.url, this.data.async);
if ("contentType" in this.data) this.http.setRequestHeader('Content-Type', this.data.contentType);
this.http.send();
}
}
\ No newline at end of file
class CookieHandler {
add(name, value, expiration) {
let d = new Date();
d.setTime(d.getTime() + expiration);
let expires = "expires="+ d.toUTCString();
document.cookie = name + "=" + value + ";" + expires + ";path=/";
}
get(name){
name = name + "=";
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(';');
for(let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}
remove(name){
this.add(name,"",0);
}
}
function LoginBoton(tc, validate, redirect) {
button = document.createElement("button");
button.value = "Enviar";
button.setAttribute("onclick", "if (validate('"+validate+"') == true) redirect('"+redirect+"')");
button.setAttribute("class","SendButton");
button.innerText = "Enviar";
tc.lastElementChild.children[0].appendChild(button);
}
function CreateErrorLogin(fc){
error = document.createElement("div");
error.id = "ErrorLogin";
error.innerText = "Usuario o Contraseña incorrectos";
error.className = "Error";
fc.appendChild(error);
}
function Redireccionar(bool, redirect){
if (bool == true) window.location.href = redirect;
else document.getElementById('ErrorLogin').style.display = "block";
}
function validate(url){
cookie = new CookieHandler;
data = Leer(document.getElementById('TabsContainer'))
if (data == false) return false;
let obj = {
"url" : "/validate",
"contentType" : "application/json",
"async" : false,
"data" : {
"url" : url,
"user" : data['Usuario'],
"password" : data['Contraseña'],
},
"success" : (response) => {
r = JSON.parse(response);
if (r.success == true) cookie.add("login", r.cookie, 8 * 60 * 60 * 1000); // 8 hours
}
}
ajax = new Ajax(obj);
ajax.post();
return true;
}
function redirect(url){
cookie = new CookieHandler;
window.location.href = url + "/" + cookie.get("login");
}
\ No newline at end of file
<html lang="en">
<head>
<script src="{{url_for('static',filename='Scripts/ajax.js')}}"></script>
<script src="{{url_for('static',filename='Scripts/cookie.js')}}"></script>
<script src="{{url_for('static',filename='Scripts/ArmadoDeForm.js')}}"></script>
<script src="{{url_for('static',filename='Scripts/login.js')}}"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
......
<html lang="en">
<head>
<script src="{{url_for('static',filename='Scripts/ajax.js')}}"></script>
<script src="{{url_for('static',filename='Scripts/cookie.js')}}"></script>
<script src="{{url_for('static',filename='Scripts/login.js')}}"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Redirect</title>
<link rel="icon" href="{{url_for('static',filename='Assets/ICONO ANACSOFT 48 SIN TRASNSF.png')}}" type="image/png">
</head>
<body onload="redirect('{{ url }}')">
</body>
</html>
\ No newline at end of file
["KWox6p3nNe4tSiYCbEB0NZVuClkFgiiMwM6r756iuTblzaQWSZeSM0J4OVH5ouxmR5oFpBRKkhXIVUx2NRJjjYnlQGNh2yMlAU8KsJjQ88QqUNm5Jv2bQLZC9wQhULQa", "fyAyDlJIkHGW7fM4wiC6iz1yMG7QvrNqtIaZdmpUKH25gW9Lo8cxluCTHO1lJWYHv8aBlfXPN53IgDqOappTDYbGXgEwkiwK55KYhXQp2cumyDR0rTN3TFY6hYyf5wAM", "hQzhUexJ8NbBGt8h5Ve3gcwzbdmD7YpAj9qC6e4yJCecocER39TbGTpceabzJSVawk8FDN0JG5Au2CTt88oy6woXdMjYYGf685Y4JDrfLU56AXt1A0yNSVKexM3rLBPw", "F3U4MRu6AmNpPXv6IETMZG26eN9DQfYVWlpM2OyW4CdOgpspCuTAhfQN5WdOVTz62ouby2IRcsq4DsezF3VtNj2drM7yAcQS13Prnlx3JiTTVRyOYuH69uPrnukGDdgi", "0HyLU9X28LnAVU8JzSlz21Bzhd1SRRFWHyAFaZm9gswZu3u8dVuIwql48krQY0FAWaKhXZbWXsnAS3VNn4ZYFa7LfpseqcVE5csRB2MLDVSDxs21LMhVISc5MLZFwUrx", "rvZWyrvsZg5FzM1apGF92hoKBLAGRdrW1M7GVTQe0YkgsmVbVuvWKyfKvhEY4beL4aPzdWKtzItxQT1LgKek3haHfyTpk0GBlJVUYp6pWChSSySVhAaKyWmZVmrPnZiH", "BMxAUA927m3XPQu3G8Mo8Lc1ego6wq6OrbuEWZA1QhB0eRinEpq3Pti5CjqQcxIW0FdgtITJvE0n05DCsnG1GCHDb5IU1NL8pGTZS0JMaVx03DsMB38Cla03XdxrrID4", "QPjzaeVin736JWMtulq35rqFMEz52Q2nPRLVAg26akZlyW05UXx0pzhrkCmIFM8mCiooCjsNpSupfs9HcCAmQJJq4WizuZo2w0KVlid0nwNqFapRL0GJWK9AtqMAa9Mj", "OjmrbqHYWQ2ChTM6Rm4WdbyrWL0Z09jrqnW1lox7xafb5iyRvSSW1TYkof0Fss8o0ROZRn2zzrTsK4Kej7AZvp02YypBPmdvoex66OqtnFNlYy266xggUkD3DUKx8LiN", "IeZTmqQcxaZ3W1kcKSqwAv657auXxg4SbeTbb3fAdZKzYvXxKuxn88MJ6XvSYt3o5sofxHTCeyIMSY3scPJZqXzNW8rxAJhTxkyaBTV5QiXTEUEfOFzhL2Kn6oAe8C0i", "IMopJBkFxJeMQeyrQZKl5Awp4R2pYLiiEqJaIMwdSY5k7P9VMPynaNaN2uvjENlAIOOfJQl2odY6A6XNE7r5a2PwNwvcyAHMAi2w3yCN2vMzyun2EeyWDAGHeFQSZbW8"]
\ No newline at end of file
import json, random
class Validation:
FILE = "tokens.json"
LENGTH = 128
STRING = "\
1234567890\
qwertyuiopasdfghjklzxcvbnm\
QWERTYUIOPASDFGHJKLZXCVBNM\
"
def __init__(self):
with open(self.FILE, "+r") as f:
self.data = f.read()
try:
self.data = set(json.loads(self.data))
except (ValueError, json.decoder.JSONDecodeError):
print ("malformed or empty JSON file, defaulting to empty dictionary...")
self.data = set()
def make_token(self):
s = ""
i = 0
while i < self.LENGTH:
s += self.STRING[random.randrange(0,len(self.STRING))]
i += 1
self.data.add(s)
return s
def check_token(self,token):
return token in self.data
def __del__(self):
with open(self.FILE, "+w") as f:
f.write(json.dumps(list(self.data)))
Styling with Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!