Skip to content
module.py 99.5 KiB
Newer Older
#!/usr/bin/python
# -*- coding: UTF-8 -*-

from cStringIO import StringIO
Marco De Donno's avatar
Marco De Donno committed
from datetime import datetime, timedelta
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from threading import Thread
from uuid import uuid4
Marco De Donno's avatar
Marco De Donno committed
import cPickle
from PIL import Image, ImageDraw, ImageFont
from flask import Flask
from flask import jsonify
from flask import render_template, send_from_directory 
from flask import request
from flask import send_file
from flask import session
from flask import url_for
from flask_compress import Compress
from flask_session import Session
from werkzeug import abort, redirect
import gnupg
Marco De Donno's avatar
Marco De Donno committed
import pyotp
import webauthn
from NIST import NISTf
from PiAnoS import caseExistsInDB
from const import pfsp
Marco De Donno's avatar
Marco De Donno committed
from functions import float_or_null
from functions import pbkdf2, AESCipher
Marco De Donno's avatar
Marco De Donno committed
from functions import pil2buffer
from functions import random_data
from functions import render_jinja_html
from functions import rotate_image_upon_exif
import config
################################################################################

from version import __version__, __branch__, __commit__, __commiturl__, __treeurl__

################################################################################

Image.MAX_IMAGE_PIXELS = 1 * 1024 * 1024 * 1024

################################################################################

app = Flask( __name__ )
app.config.from_pyfile( "config.py" )
Compress( app )
Session( app )

baseurl = os.environ.get( "BASEURL", "" )
envtype = os.environ.get( "ENVTYPE", "" )
################################################################################

gnupg._parsers.Verify.TRUST_LEVELS[ "ENCRYPTION_COMPLIANCE_MODE" ] = 23

################################################################################
def session_field_required( field, value ):
    def decorator( func ):
        @functools.wraps( func )
        def wrapper_login_required( *args, **kwargs ):
            if not field in session:
                return redirect( url_for( "login" ) )
            
            elif not session.get( field ) == value:
                return redirect( url_for( "login" ) )
            
            return func( *args, **kwargs )
    
        return wrapper_login_required
    
    return decorator

def login_required( func ):
    @functools.wraps( func )
    def wrapper_login_required( *args, **kwargs ):
        if not session.get( "logged", False ) :
            return redirect( url_for( "login" ) )
        
        return func( *args, **kwargs )

    return wrapper_login_required

def referer_required( func ):
    @functools.wraps( func )
    def wrapper_login_required( *args, **kwargs ):
        if not request.headers.get( "Referer", False ):
            return "referrer needed", 404
        
        return func( *args, **kwargs )

    return wrapper_login_required

def admin_required( func ):
    @functools.wraps( func )
    def wrapper_login_required( *args, **kwargs ):
        if not session.get( "logged", False ) or not session.get( "account_type", None ) == 1:
            return redirect( url_for( "login" ) )
        
        return func( *args, **kwargs )

    return wrapper_login_required

def redis_cache( ttl = 3600 ):
    def decorator( func ):
        @functools.wraps( func )
        def wrapper_cache( *args, **kwargs ):
            lst = []
            lst.append( func.__name__ )
            lst.extend( args )
            index = "_".join( lst )
            index = hashlib.sha256( index ).hexdigest()
            
            d = config.redis_shared.get( index )
            
            if d != None:
                buff = StringIO()
                buff.write( base64.b64decode( d ) )
                buff.seek( 0 )
                
Marco De Donno's avatar
Marco De Donno committed
                return cPickle.load( buff )
Marco De Donno's avatar
Marco De Donno committed
                cPickle.dump( d, buff )
                buff.seek( 0 )
                d_cached = base64.b64encode( buff.getvalue() )
                
                config.redis_shared.set( index, d_cached, ex = ttl )
                
                return d
    
        return wrapper_cache
    return decorator

################################################################################
#    Generic routing

@app.route( "/ping" )
@app.route( baseurl + "/ping" )
    """
        Ping function to check if the web application is healthy.
        This function need to check all important element of the web application, i.e. the flask app and the postgresql database.

        If the application report a error 500, the healthcheck done by the container orchestrator will fail, hence re-scheduling the container as needed.
    """
    if not config.db.check():
        config.db.connect() # Try to re-connect to the database to try to serve the requests before the rescheduling
        return abort( 500 )
    else:
        return "pong"
@app.route( baseurl + "/version" )
Marco De Donno's avatar
Marco De Donno committed
def version():
    """
        Function to report the version of the web app.
        The version.py file is re-generated by the CI/CD for production.
    """
    try:
        return jsonify( {
            "error": False,
            "version": __version__,
            "branch": __branch__,
            "commit": __commit__,
            "commiturl": __commiturl__,
            "treeurl": __treeurl__
        } )

    except:
        return jsonify( {
            "error": True
        } )
################################################################################
#   CDN serving

@app.route( baseurl + "/cdn/<path:subpath>" )
def send_cdn_files( subpath ):
    """
        Serve the files from the cdn directory.
Loading
Loading full blame...