Logout features

This commit is contained in:
Dita Aji Pratama 2024-06-19 04:36:26 +07:00
parent 8d7eefb2e2
commit 0edb5cabb5
3 changed files with 155 additions and 5 deletions

View File

@ -5,7 +5,7 @@
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
# You should have received a copy of the GNU General Public License along with this program. If not, see https://www.gnu.org/licenses/. # You should have received a copy of the GNU General Public License along with this program. If not, see https://www.gnu.org/licenses/.
from bottle import Bottle, route, request, response from bottle import Bottle, route, request, response, redirect
import json import json
from config import directory from config import directory
@ -69,6 +69,26 @@ def index():
} }
return public_login.login().html(params) return public_login.login().html(params)
@app.route('/logout')
def index():
beaker_session = request.environ.get('beaker.session')
if "token" in beaker_session:
params = {
"jwt" : beaker_session["token"],
"type" : "out"
}
response_session = api_auth.auth().session(params)
response_logout = api_auth.auth().logout(params)
if response_session['status'] == 'success' and response_logout['status'] == 'success' :
redirect('/?message=logout success')
else:
print('logout failed')
print(f"response session: {response_session['status']}")
print(f"response logout: {response_logout['status']}")
redirect('/?message=logout failed')
else:
redirect('/')
@app.route('/api/auth/registration/register/<roles>', method='POST') @app.route('/api/auth/registration/register/<roles>', method='POST')
def index(roles): def index(roles):
try: try:
@ -144,3 +164,13 @@ def index(type):
except Exception as e: except Exception as e:
print(str(e)) print(str(e))
return json.dumps({}, indent = 2).encode() return json.dumps({}, indent = 2).encode()
@app.route('/api/auth/logout', method='POST')
def index():
try:
params = request.json
response.content_type = 'application/json'
return json.dumps(api_auth.auth().logout(params), indent = 2).encode()
except Exception as e:
print(str(e))
return json.dumps({}, indent = 2).encode()

View File

@ -1,30 +1,50 @@
import mysql.connector as mariadb import mysql.connector as mariadb
from mako.template import Template from mako.template import Template
from config import globalvar, database from config import globalvar, database
from bottle import request
import procedure.session as procedure_session
class home: class home:
def __init__(self): def __init__(self):
self.db_main = mariadb.connect(**database.db_main) self.db_main = mariadb.connect(**database.db_main)
self.cursor = self.db_main.cursor(dictionary=True) self.cursor = self.db_main.cursor(dictionary=True)
self.user_roles = [0] # Cari user roles disini self.user = {
"data":{
"profile":{
"username":None,
"email":None,
"phone":None,
"roles":[0]
}
}
}
def html(self, params): def html(self, params):
active_page = "Home" active_page = "Home"
allowed_roles = [0,1,2,3]
beaker_session = request.environ.get('beaker.session')
jwt = beaker_session["token"] if "token" in beaker_session else None
if jwt is not None:
self.user = procedure_session.session().user(jwt, allowed_roles)
user = self.user['data']
return Template(params["mako"]["website"]['index']).render( return Template(params["mako"]["website"]['index']).render(
title = globalvar.title, title = globalvar.title,
header = globalvar.header, header = globalvar.header,
navbar = Template(params["mako"]["website"]['navbar']).render( navbar = Template(params["mako"]["website"]['navbar']).render(
menu = globalvar.menu['public']['navbar'], menu = globalvar.menu['public']['navbar'],
user_roles = self.user_roles, user_roles = user['profile']['roles'],
active_page = active_page active_page = active_page
), ),
footer = Template(params["mako"]["website"]['footer']).render( footer = Template(params["mako"]["website"]['footer']).render(
copyright = globalvar.copyright, copyright = globalvar.copyright,
), ),
container = Template(params["mako"]["website"]['container']).render( container = Template(params["mako"]["website"]['container']).render(
greeting = f"Welcome to your new web application! This placeholder page is here to let you know that your web framework is successfully set up and ready to go. Now, it's time to start building your project. Dive into the documentation to explore the features and capabilities at your disposal." greeting = f"Welcome to your new web application! This placeholder page is here to let you know that your web framework is successfully set up and ready to go. Now, it's time to start building your project. Dive into the documentation to explore the features and capabilities at your disposal.",
user = user
) )
) )

100
app/procedure/session.py Normal file
View File

@ -0,0 +1,100 @@
import mysql.connector as mariadb
import datetime
import config.database as database
import config.globalvar as globalvar
import scripts.loggorilla as loggorilla
import scripts.tokenguard as tokenguard
class session():
def __init__(self):
self.db_main = mariadb.connect(**database.db_main)
self.cursor = self.db_main.cursor(dictionary=True)
def user(self, jwt, allowed_roles):
APIADDR = "procedure.validation"
response = {}
try:
loggorilla.prcss(APIADDR, "Define parameters")
payload = tokenguard.decode(jwt, globalvar.ssh['key']['public'])
loggorilla.prcss(APIADDR, "Get dependency data")
self.cursor.execute(f"SELECT * FROM auth_session WHERE id = %s ; ", (payload["session"]["id"],) )
r_session = self.cursor.fetchone()
self.cursor.execute(f"SELECT COUNT(*) AS `count`, auth_profile.* FROM auth_profile_verification LEFT JOIN auth_profile ON auth_profile.id = auth_profile_verification.auth_profile WHERE auth_profile.token = %s AND auth_profile_verification.type = 'email' AND auth_profile_verification.verified = 1 ; ", (r_session['token'],) )
r_profile = self.cursor.fetchone()
self.cursor.execute(f"SELECT auth_roles FROM auth_profile_roles WHERE auth_profile = %s ; ", (r_profile['id'],) )
r_roles = self.cursor.fetchall()
r_profile['roles'] = [0]
for row in r_roles:
r_profile['roles'].remove(0)
r_profile['roles'].append(row['auth_roles'])
loggorilla.prcss(APIADDR, "Validation")
if datetime.datetime.now() > r_session['end']:
loggorilla.prcss(APIADDR, "Deleting")
self.cursor.execute("DELETE FROM auth_session WHERE id = %s ; ", (r_session['id'],) )
loggorilla.prcss(APIADDR, "Giving response")
loggorilla.accss(APIADDR, "Expired. Your session removed." )
response["status" ] = "failed"
response["desc" ] = "Expired. Your session removed."
response["data" ] = {
"valid" :{
"status" : 0,
"desc" : "expired"
},
"session" : r_session,
"profile" : r_profile
}
elif r_profile["count"] == 0:
loggorilla.prcss(APIADDR, "Giving response")
loggorilla.accss(APIADDR, "No active account for this" )
response["status" ] = "failed"
response["desc" ] = "No active account for this"
response["data" ] = {
"message" : "Please contact us if you still had a problem",
"valid" :{
"status" : 0,
"desc" : "forbidden"
},
"session" : r_session,
"profile" : r_profile
}
elif any(role in allowed_roles for role in r_profile['roles']):
loggorilla.prcss(APIADDR, "Giving response")
response["status" ] = "success"
response["desc" ] = "User roles authorized"
response["data" ] = {
"valid" :{
"status" : 1,
"desc" : "authorized"
},
"session" : r_session,
"profile" : r_profile
}
else:
loggorilla.prcss(APIADDR, "Giving response")
loggorilla.accss(APIADDR, "User roles unauthorized" )
response["status" ] = "failed"
response["desc" ] = "User roles unauthorized"
response["data" ] = {
"valid" :{
"status" : 0,
"desc" : "unauthorized"
},
"session" : r_session,
"profile" : r_profile
}
except Exception as e:
loggorilla.error(APIADDR, str(e) )
response["status" ] = "failed"
response["desc" ] = "Internal Server Error. Please contact us if you still have an error. for detail"
finally:
self.cursor.close()
self.db_main.close()
return response