Beispiel #1
0
 def action(self, path, method, get_vars, post_vars, env=None):
     """action that handles all the HTTP requests for Auth"""
     env = env or {}
     if path.startswith("plugin/"):
         parts = path.split("/", 2)
         plugin = self.plugins.get(parts[1])
         if plugin:
             return plugin.handle_request(
                 self, parts[2], request.query, request.json
             )
         else:
             abort(404)
     if path.startswith("api/"):
         data = {}
         if method == "GET":
             # Should we use the username?
             if path == "api/use_username":
                 return {"use_username": self.use_username}
             if path == "api/config":
                 fields = [
                     dict(name=f.name, type=f.type)
                     for f in self.db.auth_user
                     if f.type in ["string", "bool", "integer", "float"]
                     and f.writable
                     and f.readable
                 ]
                 return {
                     "allowed_actions": self.allowed_actions,
                     "plugins": ["local"] + [key for key in self.plugins],
                     "fields": fields,
                 }
             # Otherwise, we assume the user exists.
             user = self.get_user(safe=True)
             if not user:
                 data = self._error("not authorized", 401)
             if path == "api/profile":
                 return {"user": user}
         elif method == "POST" and self.db:
             vars = dict(post_vars)
             user = self.get_user(safe=False)
             if path == "api/register":
                 data = self.register(vars, send=True).as_dict()
             elif path == "api/login":
                 # Prioritize PAM or LDAP logins if enabled
                 if "pam" in self.plugins or "ldap" in self.plugins:
                     plugin_name = "pam" if "pam" in self.plugins else "ldap"
                     username, password = vars.get("email"), vars.get("password")
                     check = self.plugins[plugin_name].check_credentials(
                         username, password
                     )
                     if check:
                         data = {
                             "username": username,
                             # "email": username + "@localhost",
                             "sso_id": plugin_name + ":" + username,
                         }
                         # and register the user if we have one, just in case
                         if self.db:
                             data = self.get_or_register_user(data)
                             self.session["user"] = {"id": data["id"]}
                             self.session["recent_activity"] = calendar.timegm(
                                 time.gmtime()
                             )
                             self.session["uuid"] = str(uuid.uuid1())
                     else:
                         data = self._error("Invalid Credentials")
                 # Else use normal login
                 else:
                     user, error = self.login(**vars)
                     if user:
                         self.session["user"] = {"id": user.id}
                         self.session["recent_activity"] = calendar.timegm(
                             time.gmtime()
                         )
                         self.session["uuid"] = str(uuid.uuid1())
                         user = {
                             f.name: user[f.name]
                             for f in self.db.auth_user
                             if f.readable
                         }
                         data = {"user": user}
                     else:
                         data = self._error(error)
             elif path == "api/request_reset_password":
                 if not self.request_reset_password(**vars):
                     data = self._error("invalid user")
             elif path == "api/reset_password":
                 if not self.reset_password(
                     vars.get("token"), vars.get("new_password")
                 ):
                     data = self._error("invalid token, request expired")
             elif user and path == "api/logout":
                 self.session["user"] = None
             elif user and path == "api/unsubscribe":
                 self.session["user"] = None
                 self.gdpr_unsubscribe(user, send=True)
             elif user and path == "api/change_password":
                 data = self.change_password(
                     user, vars.get("new_password"), vars.get("old_password")
                 )
             elif user and path == "api/change_email":
                 data = self.change_email(
                     user, vars.get("new_email"), vars.get("password")
                 )
             elif user and path == "api/profile":
                 data = self.update_profile(user, **vars)
             else:
                 data = {"status": "error", "message": "undefined"}
         if not "status" in data and data.get("errors"):
             data.update(status="error", message="validation errors", code=401)
         elif "errors" in data and not data["errors"]:
             del data["errors"]
         data["status"] = data.get("status", "success")
         data["code"] = data.get("code", 200)
         return data
     elif path == "logout":
         self.session.clear()
         # Somehow call revoke for active plugin
     elif path == "verify_email" and self.db:
         token = get_vars.get("token")
         if self.verify_email(token):
             next = b16d(token.split("/")[1])
             redirect(
                 next
                 or URL(
                     "auth",
                     "email_verified",
                     use_appname=self.use_appname_in_redirects,
                 )
             )
         else:
             redirect(
                 URL(
                     "auth",
                     "token_expired",
                     use_appname=self.use_appname_in_redirects,
                 )
             )
     env["path"] = path
     return Template("auth.html").transform(env)
Beispiel #2
0
 def test_template(self):
     t = Template("index.html", path=PATH)
     output = t.transform(dict(n=3), {})
     self.assertEqual(output, "0,1,2.\n")
Beispiel #3
0
                    inserted =True
        else:
            if Glb['debug'] == True:
                print(f"     no entry inserted: (f0_fld is None) or (len(f0_fld) == 0)")
                print()

        return inserted
            
def put_json_messages(mess='mymess'):
    response.headers["Content-Type"] = "application/json"
    return json.dumps( {'messages' : f'{mess}'})
    
# ---------------------- Controllers  ------------------------------------------------

@action('tabs', method=["GET", "POST"] )
@action.uses(Template('tabs.html', delimiters='[%[ ]]',), db, session, T,)

def tabs():
    ctrl_info= "ctrl: tabs, view: tabs.html"
    page_url = "\'" + URL('tabs' ) + "\'"
    messages = []

    return locals()

@action('forms', method=["GET", "POST"] )
@action.uses(Template('forms.html', delimiters='[%[ ]]',), db, session, T,)

def forms():
    ctrl_info= "ctrl: forms, view: forms.html"
    page_url = "\'" + URL('forms' ) + "\'"
    messages = []
Beispiel #4
0
 def action(self, path, method, get_vars, post_vars):
     if path.startswith('plugin/'):
         parts = path.split('/', 2)
         plugin = self.plugins.get(parts[1])
         if plugin:
             return plugin.handle_request(self, parts[2], request.query,
                                          request.json)
         else:
             abort(404)
     if path.startswith('api/'):
         data = {}
         if method == 'GET':
             user = self.get_user(safe=True)
             if not user:
                 data = self._error('not authoried', 401)
             if path == 'api/profile':
                 return {'user': user}
         elif method == 'POST' and self.db:
             vars = dict(post_vars)
             user = self.get_user(safe=False)
             if path == 'api/register':
                 data = self.register(vars, send=True).as_dict()
             elif path == 'api/login':
                 # Prioritize PAM or LDAP logins if enabled
                 if 'pam' in self.plugins or 'ldap' in self.plugins:
                     plugin_name = 'pam' if 'pam' in self.plugins else 'ldap'
                     username, password = vars.get('email'), vars.get(
                         'password')
                     check = self.plugins[plugin_name].check_credentials(
                         username, password)
                     if check:
                         data = {
                             'username': username,
                             'email': username + '@localhost',
                             'sso_id': plugin_name + ':' + username,
                         }
                         # and register the user if we have one, just in case
                         if self.db:
                             data = self.get_or_register_user(data)
                     else:
                         data = self._error('Invalid Credentials')
                 # Else use normal login
                 else:
                     user, error = self.login(**vars)
                     if user:
                         self.session['user'] = {'id': user.id}
                         user = {
                             f.name: user[f.name]
                             for f in self.db.auth_user if f.readable
                         }
                         data = {'user': user}
                     else:
                         data = self._error(error)
             elif path == 'api/request_reset_password':
                 if not self.request_reset_password(**vars):
                     data = self._error('invalid user')
             elif path == 'api/reset_password':
                 if not self.reset_password(vars.get('token'),
                                            vars.get('new_password')):
                     data = self._error('invalid token, request expired')
             elif user and path == 'api/logout':
                 self.session['user'] = None
             elif user and path == 'api/unsubscribe':
                 self.session['user'] = None
                 self.gdpr_unsubscribe(user, send=True)
             elif user and path == 'api/change_password':
                 data = self.change_password(user, vars.get('new_password'),
                                             vars.get('password'))
             elif user and path == 'api/change_email':
                 data = self.change_email(user, vars.get('new_email'),
                                          vars.get('password'))
             elif user and path == 'api/profile':
                 data = self.update_profile(user, **vars)
             else:
                 data = {'status': 'error', 'message': 'undefined'}
         if not 'status' in data and data.get('errors'):
             data.update(status='error',
                         message='validation errors',
                         code=401)
         elif 'errors' in data and not data['errors']:
             del data['errors']
         data['status'] = data.get('status', 'success')
         data['code'] = data.get('code', 200)
         return data
     elif path == 'logout':
         self.session['user'] = None
         # Somehow call revoke for active plugin
     elif path == 'verify_email' and self.db:
         if self.verify_email(get_vars.get('token')):
             redirect(URL('auth/email_verified'))
         else:
             redirect(URL('auth/token_expired'))
     return Template('auth.html').transform({'path': path})
Beispiel #5
0
 def test_template(self):
     t = Template("index.html", path=PATH)
     context = dict(output=dict(n=3))
     t.on_success(context)
     output = context['output']
     self.assertEqual(output, "0,1,2.\n")
Beispiel #6
0
from .common import db, session, T, cache, authenticated, unauthenticated, auth
import bottle

## exposes services necessary to access the db.thing via ajax
publisher = Publisher(db, policy=ALLOW_ALL_POLICY)

#
# AI-biorex, 14:37:27 19.11.2020 MSK
# src: https://github.com/creativetimofficial/material-dashboard-react
#


@action('index', method=["GET", "POST"])
@action.uses(
    Template(
        'index.html',
        delimiters='[%[ ]]',
    ),
    db,
    session,
    T,
)
#
def index(param=None):
    ctrl_info = "ctrl: index, view: index.html"
    if not param is None:
        print(param)
    return locals()


Glb = {'debug': True, 'my_app_name': "reatim", 'tte_path': '/static/tte'}
Beispiel #7
0
from .common import db, session, T, cache, authenticated, unauthenticated, auth
import bottle

## exposes services necessary to access the db.thing via ajax
publisher = Publisher(db, policy=ALLOW_ALL_POLICY)

#
# AI-biorex, 00:19:59 03.10.2020
# src: https://github.com/flatlogic/angular-material-admin 
#



@action('index', method=["GET", "POST"] )
@action.uses(Template('index.html', delimiters='[%[ ]]',), db, session, T, )
#
def index(param=None):
   ctrl_info= "ctrl: index, view: index.html"
   if not param is None:
       print (param)
   return locals()



Glb= {'debug': True , 'my_app_name' : "angflat", 'pp': '/static/tte' }

@bottle.error(404)
def error404(error):
    def find_app( maybe_app_root):
        for e in Reloader.ROUTES:
Beispiel #8
0
                f"     no entry inserted: (f0_fld is None) or (len(f0_fld) == 0)"
            )
            print()

    return inserted


def put_json_messages(mess='mymess'):
    response.headers["Content-Type"] = "application/json"
    return json.dumps({'messages': f'{mess}'})


@action('form', method=["GET", "POST"])
@action.uses(
    Template(
        'form.html',
        delimiters='[%[ ]]',
    ),
    db,
    session,
    T,
)
def form():
    ctrl_info = "ctrl: form, view: form.html"
    page_url = "\'" + URL('form') + "\'"
    messages = []

    fform0 = Form(db.dfform0, dbio=False, formstyle=FormStyleBulma)

    if fform0.accepted:
        prn_form_vars(fform0, db.dfform0)
        return put_json_messages('accepted: ' + str(fform0.form_name))
Beispiel #9
0
    def action(self, path, method, get_vars, post_vars, env=None):
        """action that handles all the HTTP requests for Auth"""
        env = env or {}
        # plugin/
        if path.startswith("plugin/"):
            parts = path.split("/", 2)
            plugin = self.plugins.get(parts[1])
            if plugin:
                return plugin.handle_request(
                    self, parts[2], request.query, request.json
                )
            else:
                abort(404)
        # api/
        elif path.startswith("api/"):
            vars = dict(post_vars or {})
            api_name = path[4:]
            api = self.api.get(api_name)
            cb = api and api.get(method)
            if not api:
                data = self._error('undefined', 401)
            elif not cb:
                data = self._error('method not allowed', 405)
            else: # route is OK
                data = cb(vars) or {}

            if not "status" in data and data.get("errors"):
                data.update(status="error", message="validation errors", code=401)
            elif "errors" in data and not data["errors"]:
                del data["errors"]
            data["status"] = data.get("status", "success")
            data["code"] = data.get("code", 200)
            return data
        # logout/
        elif path == "logout":
            self.session.clear()
            # Somehow call revoke for active plugin
        # verify_email/
        elif path == "verify_email" and self.db:
            token = get_vars.get("token")
            if self.verify_email(token):
                next = b16d(token.split("/")[1])
                redirect(
                    next
                    or URL(
                        "auth",
                        "email_verified",
                        use_appname=self.use_appname_in_redirects,
                    )
                )
            else:
                redirect(
                    URL(
                        "auth",
                        "token_expired",
                        use_appname=self.use_appname_in_redirects,
                    )
                )
        # else:  - abort(404)???
        env["path"] = path
        return Template("auth.html").transform(env)
Beispiel #10
0
    return inserted


def put_json_messages(mess='mymess'):
    response.headers["Content-Type"] = "application/json"
    return json.dumps({'messages': f'{mess}'})


# ---------------------- Controllers  ------------------------------------------------


@action('X404', method=["GET", "POST"])
@action.uses(
    Template(
        '404.html',
        delimiters='[%[ ]]',
    ),
    db,
    session,
    T,
)
def X404():
    ctrl_info = "ctrl: X404, view: 404.html"
    page_url = "\'" + URL('X404') + "\'"
    messages = []

    return locals()


@action('X500', method=["GET", "POST"])
@action.uses(
Beispiel #11
0
    return inserted


def put_json_messages(mess='mymess'):
    response.headers["Content-Type"] = "application/json"
    return json.dumps({'messages': f'{mess}'})


# ---------------------- Controllers  ------------------------------------------------


@action('tabs', method=["GET", "POST"])
@action.uses(
    Template(
        'tabs.html',
        delimiters='[%[ ]]',
    ),
    db,
    session,
    T,
)
def tabs():
    ctrl_info = "ctrl: tabs, view: tabs.html"
    page_url = "\'" + URL('tabs') + "\'"
    messages = []

    rows_ttabs0 = db(db.ttabs0).select()
    return locals()


@action('hero', method=["GET", "POST"])
Beispiel #12
0
            THEAD(
                TR(*[
                    TD(H6(h_func(hh[j], j))) for j in range(ij_start, len(hh))
                ])) if show_thead else "",
            TBODY(*[
                TR(*[
                    TD(r_func(row[ff[i]], i, row, tbl, ff[i]))
                    for i in range(ij_start, len(ff))
                ]) for row in rows
            ]),
        ),
    )


@action("mytab_grid", method=["GET", "POST"])
@action.uses(Template("mytab_grid.html", delimiters="[[ ]]"), db, session, T)
def mytab_grid():
    def xfunc(tt, rr_id):
        return f"{tt}:id={rr_id}"

    hlinks = ["+img", "+r_id", "+xfunc"]
    links = [
        lambda tx, r_id: A(
            IMG(_width="30px", _height="30px", _src=URL("static/favicon.ico")),
            _title="run some_func",
            _href=URL(f"some_func", vars=dict(t_=tx, id_=r_id)),
        ),
        lambda tx, r_id: A(
            f"myf2-id:[{r_id}]",
            _title="run some3_func",
            _href=URL(f"some3_func", vars=dict(t_=tx, id_=r_id)),
Beispiel #13
0
    return inserted


def put_json_messages(mess='mymess'):
    response.headers["Content-Type"] = "application/json"
    return json.dumps({'messages': f'{mess}'})


# ---------------------- Controllers  ------------------------------------------------


@action('ui', method=["GET", "POST"])
@action.uses(
    Template(
        'ui.html',
        delimiters='[%[ ]]',
    ),
    db,
    session,
    T,
)
def ui():
    ctrl_info = "ctrl: ui, view: ui.html"
    page_url = "\'" + URL('ui') + "\'"
    messages = []

    return locals()


@action('X404', method=["GET", "POST"])
@action.uses(
Beispiel #14
0
    return inserted


def put_json_messages(mess='mymess'):
    response.headers["Content-Type"] = "application/json"
    return json.dumps({'messages': f'{mess}'})


# ---------------------- Controllers  ------------------------------------------------


@action('forms', method=["GET", "POST"])
@action.uses(
    Template(
        'forms.html',
        delimiters='[%[ ]]',
    ),
    db,
    session,
    T,
)
def forms():
    ctrl_info = "ctrl: forms, view: forms.html"
    page_url = "\'" + URL('forms') + "\'"
    messages = []

    fforms0 = Form(db.dfforms0,
                   dbio=False,
                   keep_values=True,
                   formstyle=FormStyleBulma)
Beispiel #15
0
    return inserted


def put_json_messages(mess='mymess'):
    response.headers["Content-Type"] = "application/json"
    return json.dumps({'messages': f'{mess}'})


# ---------------------- Controllers  ------------------------------------------------


@action('login', method=["GET", "POST"])
@action.uses(
    Template(
        'login.html',
        delimiters='[%[ ]]',
    ),
    db,
    session,
    T,
)
def login():
    ctrl_info = "ctrl: login, view: login.html"
    page_url = "\'" + URL('login') + "\'"
    messages = []

    return locals()


@action('index', method=["GET", "POST"])
@action.uses(
Beispiel #16
0
    return inserted


def put_json_messages(mess='mymess'):
    response.headers["Content-Type"] = "application/json"
    return json.dumps({'messages': f'{mess}'})


# ---------------------- Controllers  ------------------------------------------------


@action('X404', method=["GET", "POST"])
@action.uses(
    Template(
        '404.html',
        delimiters='[%[ ]]',
    ),
    db,
    session,
    T,
)
def X404():
    ctrl_info = "ctrl: X404, view: 404.html"
    page_url = "\'" + URL('X404') + "\'"
    messages = []

    fX4040 = Form(db.dfX4040, dbio=False, formstyle=FormStyleBulma)

    if fX4040.accepted:
        prn_form_vars(fX4040, db.dfX4040)
        return put_json_messages('accepted: ' + str(fX4040.form_name))