Commit 6df84660 authored by Jens Melgard Churchill's avatar Jens Melgard Churchill
Browse files

Added auth-router

parent 071fc1ce
Showing with 174 additions and 4 deletions
+174 -4
......@@ -2,6 +2,10 @@ from datetime import datetime
from fastapi import APIRouter, Form
from typing import Optional
# Import the getProducts function
from db2 import getProducts
router = APIRouter()
......@@ -15,10 +19,6 @@ def read_item(item_id: int, q: Optional[str] = Form(...)):
}
# Import the getProducts function
from db2 import getProducts
# And define an endpoint to use it.
@router.post("/query")
def read_item(query: Optional[str] = Form(...)):
......
from fastapi import APIRouter, Form, Request
from fastapi_chameleon import global_init, template
from typing import Optional
from starlette.responses import RedirectResponse, Response, JSONResponse
# Import the getProducts function
from db2_auth import authUser
import uuid
router = APIRouter()
sessions = ()
# Instruct the templating system, where it should look for template files.
global_init('templates')
@router.get("/logout")
async def logout(request: Request):
host: str = request.headers.get('host')
hostname, _ = host.split(':')
response = RedirectResponse(url="/auth/login")
response.delete_cookie("id", domain=hostname)
return response
@router.get("/login")
@template(template_file='login.html')
async def login(request: Request, msg: Optional[str] = None):
prefix = request.scope.get("root_path")
return {
"id": prefix if prefix else 0,
"prefix": prefix,
"userid": "",
"passwd": "",
"title": "Login to FastAPI on IBM i",
"message": "Please type your username and password" if msg == None else msg
}
@router.post("/dologin")
def dologin(request: Request, username: Optional[str] = Form(...), password: Optional[str] = Form(...)):
success, errId, errText = authUser(username, password)
if not success:
response = RedirectResponse(url=f"/auth/login?msg={errText}")
return response
else:
id: str = uuid.uuid4().hex
sessions[id] = {"Username": username}
host: str = request.headers.get('host')
hostname, _ = host.split(':')
response = RedirectResponse(url="/")
response.set_cookie(
"id",
value=id,
domain=hostname,
httponly=True,
max_age=1800,
expires=1800,
)
return response
from config import DB2_HOST, DB2_USER, DB2_PASS
import pyodbc
driver = '{IBM i Access ODBC Driver}'
__internalConn = pyodbc.connect(
DRIVER=driver,
SYSTEM=DB2_HOST,
UID=DB2_USER,
PWD=DB2_PASS
)
def authUser(username: str, password: str):
"""
Check the user profile and password
"""
if not username or username.isspace():
return False, None, 'Username and password are required'
if not password or password.isspace():
return False, None, 'Username and password are required'
c1 = __internalConn.cursor()
c1.execute(f"VALUES (QUSRSYS.LOGON('{username.upper()}', '{password}'))")
result = c1.fetchone()[0]
c1.close()
if not (result != None and result and not result.isspace()):
return True, None, None
else:
msg: str = result.strip()
id = msg[0:7]
data = msg[7:]
return False, id, data
def __AuthUser():
"""REMEMBER TO SET AUTHORITY TO THIS OBJ, *PUBLIC *EXCLUDE !!!
If permitted for {INTERNAL_DB2_USER}, this creates /QSYS.LIB/QUSRSYS.LIB/LOGON.SRVPGM to validate username and password using QSYGETPH
"""
sqlStmt001 = """
call qsys2.ifs_write(PATH_NAME => '/tmp/main.c', OVERWRITE => 'REPLACE', LINE => '
{
#include "QSYSINC/H/QSYGETPH"
QSYGETPH (
MAIN.USR_ID
, MAIN.USR_PASSWORD
, MAIN.HAND
, MAIN.ERR
, MAIN.USR_PASSWORD_LEN
, MAIN.USR_CCSID
);
}
')
"""
sqlStmt002 = """
create or replace function qusrsys.logon (
user_id char(10),
user_password varchar(128) ccsid 1208
)
returns varchar (256)
set option output=*print, commit=*none, dbgview = *source --list
main:begin
declare usr_id char(10);
declare usr_password_len int;
declare usr_password char(128) ccsid 1208;
declare usr_ccsid int;
declare err char(256);
declare hand char(12);
set err = x'000000ff00000000';
set usr_id = user_id;
set usr_password_len = length(user_password);
set usr_password = user_password;
set usr_ccsid = 1208;
include '/tmp/main.c';
return substring( err , 9);
end
"""
c1 = __internalConn.cursor()
c1.execute(sqlStmt001)
c1.execute(sqlStmt002)
if __name__ == '__main__':
__AuthUser()
\ No newline at end of file
......@@ -7,6 +7,7 @@ from time import time
# import our new api router
from api_router import router as apis
from auth_router import router as auth
# Declare the main:app entrypoint
......@@ -18,6 +19,11 @@ app.include_router(
prefix="/api/v1",
)
app.include_router(
auth,
prefix="/auth",
)
# Instruct the templating system, where it should look for template files.
global_init('templates')
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment