app.py 3.34 KB
#-*- 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"

ROOT_DEFAULT = "/form/default"

@app.route('/', methods = ['GET'])
def main():
  return render_template('redirect.html',url = ROOT_DEFAULT)

@app.route('/load/<name>', methods = ['POST'])
def load(name):
  import ipdb; ipdb.set_trace()
  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)

@app.route('/remove-session', methods = ['POST'])
def removesession():
  try:
    validation = Validation()
    validation.remove_roken(request.json)
    aux.answer(True)
  except:
    aux.answer(False, "Error borrando sesión")

if __name__ == "__main__":
  app.run("0.0.0.0")