session and logout features with sending the token inside the body
This commit is contained in:
		
							parent
							
								
									cb257cb443
								
							
						
					
					
						commit
						c85c2ac8ff
					
				
							
								
								
									
										24
									
								
								handler.py
									
									
									
									
									
								
							
							
						
						
									
										24
									
								
								handler.py
									
									
									
									
									
								
							@ -89,6 +89,26 @@ def index():
 | 
				
			|||||||
    }
 | 
					    }
 | 
				
			||||||
    return public_reset.reset().html(params)
 | 
					    return public_reset.reset().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/register/<roles>', method=['OPTIONS', 'POST'])
 | 
					@app.route('/api/auth/register/<roles>', method=['OPTIONS', 'POST'])
 | 
				
			||||||
def index(roles):
 | 
					def index(roles):
 | 
				
			||||||
    try:
 | 
					    try:
 | 
				
			||||||
@ -208,7 +228,7 @@ def index(type):
 | 
				
			|||||||
            return None
 | 
					            return None
 | 
				
			||||||
        else:
 | 
					        else:
 | 
				
			||||||
            response.content_type = 'application/json'
 | 
					            response.content_type = 'application/json'
 | 
				
			||||||
            params = {}
 | 
					            params = request.json
 | 
				
			||||||
            params["type"   ] = type
 | 
					            params["type"   ] = type
 | 
				
			||||||
            return json.dumps(api_auth.auth().session(params), indent = 2).encode()
 | 
					            return json.dumps(api_auth.auth().session(params), indent = 2).encode()
 | 
				
			||||||
    except Exception as e:
 | 
					    except Exception as e:
 | 
				
			||||||
@ -221,7 +241,7 @@ def index():
 | 
				
			|||||||
        if request.method == 'OPTIONS':
 | 
					        if request.method == 'OPTIONS':
 | 
				
			||||||
            return None
 | 
					            return None
 | 
				
			||||||
        else:
 | 
					        else:
 | 
				
			||||||
            params = {}
 | 
					            params = request.json
 | 
				
			||||||
            return json.dumps(api_auth.auth().logout(params), indent = 2).encode()
 | 
					            return json.dumps(api_auth.auth().logout(params), indent = 2).encode()
 | 
				
			||||||
    except Exception as e:
 | 
					    except Exception as e:
 | 
				
			||||||
        print(str(e),flush=True)
 | 
					        print(str(e),flush=True)
 | 
				
			||||||
 | 
				
			|||||||
@ -297,21 +297,24 @@ class auth:
 | 
				
			|||||||
                loggorilla.prcss(APIADDR, "Get the token from params")
 | 
					                loggorilla.prcss(APIADDR, "Get the token from params")
 | 
				
			||||||
                jwt         = params["jwt"  ]
 | 
					                jwt         = params["jwt"  ]
 | 
				
			||||||
            else:
 | 
					            else:
 | 
				
			||||||
                loggorilla.fyinf(APIADDR, "type is not 'set': get the jwt from Header")
 | 
					                jwt         = params["jwt"  ]
 | 
				
			||||||
                loggorilla.prcss(APIADDR, "Extract the token from Header")
 | 
					                #loggorilla.fyinf(APIADDR, "type is not 'set': get the jwt from Header")
 | 
				
			||||||
                auth_header = request.get_header('Authorization')
 | 
					                #loggorilla.prcss(APIADDR, "Extract the token from Header")
 | 
				
			||||||
                loggorilla.prcss(APIADDR, "Check the bearer")
 | 
					                #auth_header = request.get_header('Authorization')
 | 
				
			||||||
                if auth_header.split(' ')[0] == 'Bearer':
 | 
					                #loggorilla.prcss(APIADDR, "Check the bearer")
 | 
				
			||||||
                    loggorilla.fyinf(APIADDR, "Use bearer")
 | 
					                #if auth_header.split(' ')[0] == 'Bearer':
 | 
				
			||||||
                    jwt 	    = auth_header.split(' ')[1]
 | 
					                #    loggorilla.fyinf(APIADDR, "Use bearer")
 | 
				
			||||||
                else:
 | 
					                #    jwt 	    = auth_header.split(' ')[1]
 | 
				
			||||||
                    loggorilla.fyinf(APIADDR, "Not use bearer")
 | 
					                #else:
 | 
				
			||||||
                    jwt = None
 | 
					                #    loggorilla.fyinf(APIADDR, "Not use bearer")
 | 
				
			||||||
 | 
					                #    jwt = None
 | 
				
			||||||
            payload     	= tokenguard.decode(jwt, globalvar.ssh['key']['public'])
 | 
					            payload     	= tokenguard.decode(jwt, globalvar.ssh['key']['public'])
 | 
				
			||||||
            session_id  	= payload["session"]["id"]
 | 
					            session_id  	= payload["session"]["id"]
 | 
				
			||||||
 | 
					            session_beaker	= request.environ.get('beaker.session')
 | 
				
			||||||
            if type == 'set':
 | 
					            if type == 'set':
 | 
				
			||||||
                loggorilla.prcss(APIADDR, "Set authorization on header")
 | 
					                loggorilla.prcss(APIADDR, "Set session")
 | 
				
			||||||
                bottle_response.set_header("Authorization", f"Bearer {jwt}")
 | 
					                session_beaker["token"] = jwt
 | 
				
			||||||
 | 
					                session_beaker.save()
 | 
				
			||||||
                response["status"   ] = "success"
 | 
					                response["status"   ] = "success"
 | 
				
			||||||
                response["desc"     ] = "Session set"
 | 
					                response["desc"     ] = "Session set"
 | 
				
			||||||
            elif type == 'check':
 | 
					            elif type == 'check':
 | 
				
			||||||
@ -332,8 +335,8 @@ class auth:
 | 
				
			|||||||
                        "status":"active"
 | 
					                        "status":"active"
 | 
				
			||||||
                    }
 | 
					                    }
 | 
				
			||||||
            elif type == 'out':
 | 
					            elif type == 'out':
 | 
				
			||||||
                loggorilla.prcss(APIADDR, "Remove Authorization header")
 | 
					                loggorilla.prcss(APIADDR, "Out session")
 | 
				
			||||||
                bottle_response.set_header("Authorization", "")
 | 
					                session_beaker.delete()
 | 
				
			||||||
                response["status"   ] = "success"
 | 
					                response["status"   ] = "success"
 | 
				
			||||||
                response["desc"     ] = "Session out"
 | 
					                response["desc"     ] = "Session out"
 | 
				
			||||||
            else:
 | 
					            else:
 | 
				
			||||||
@ -452,36 +455,28 @@ class auth:
 | 
				
			|||||||
        return response
 | 
					        return response
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    def logout(self, params):
 | 
					    def logout(self, params):
 | 
				
			||||||
        APIADDR     = "/api/auth/logout"
 | 
					        APIADDR     = "/logout"
 | 
				
			||||||
        loggorilla.prcss(APIADDR, "Define parameters")
 | 
					        loggorilla.prcss(APIADDR, "Define parameters")
 | 
				
			||||||
        response    = {}
 | 
					        response    = {}
 | 
				
			||||||
        loggorilla.prcss(APIADDR, "Extract the token from Header")
 | 
					        jwt         = params["jwt"  ]
 | 
				
			||||||
        auth_header = request.get_header('Authorization')
 | 
					 | 
				
			||||||
        loggorilla.prcss(APIADDR, "Check the bearer")
 | 
					 | 
				
			||||||
        if auth_header.split(' ')[0] == 'Bearer':
 | 
					 | 
				
			||||||
            loggorilla.fyinf(APIADDR, "Use bearer")
 | 
					 | 
				
			||||||
            jwt 	    = auth_header.split(' ')[1]
 | 
					 | 
				
			||||||
        else:
 | 
					 | 
				
			||||||
            loggorilla.fyinf(APIADDR, "Not use bearer")
 | 
					 | 
				
			||||||
            jwt = None
 | 
					 | 
				
			||||||
        payload     = tokenguard.decode(jwt, globalvar.ssh['key']['public'])
 | 
					        payload     = tokenguard.decode(jwt, globalvar.ssh['key']['public'])
 | 
				
			||||||
        session_id  = payload["session"]["id"]
 | 
					        session_id  = payload["session"]["id"]
 | 
				
			||||||
        self.cursor.execute("BEGIN;")
 | 
					        self.cursor.execute("BEGIN;")
 | 
				
			||||||
        try:
 | 
					        try:
 | 
				
			||||||
            loggorilla.prcss(APIADDR, "Deleting")
 | 
					            loggorilla.prcss(APIADDR, "Deleting")
 | 
				
			||||||
            self.cursor.execute("DELETE FROM auth_session WHERE id = %s ; ", (session_id,) )
 | 
					            self.cursor.execute("DELETE FROM auth_session WHERE id = %s ; ", (session_id,) )
 | 
				
			||||||
            loggorilla.prcss(APIADDR, "Giving response")
 | 
					 | 
				
			||||||
            loggorilla.fyinf(APIADDR, f"Session {session_id} removed.")
 | 
					            loggorilla.fyinf(APIADDR, f"Session {session_id} removed.")
 | 
				
			||||||
 | 
					            loggorilla.prcss(APIADDR, "Giving response")
 | 
				
			||||||
            response["status"	] = "success"
 | 
					            response["status"	] = "success"
 | 
				
			||||||
            response["desc"	] = f"Your session removed."
 | 
					            response["desc"		] = f"Session ({session_id}) removed."
 | 
				
			||||||
        except Exception as e:
 | 
					        except Exception as e:
 | 
				
			||||||
 | 
					            loggorilla.prcss(APIADDR, "Rollback")
 | 
				
			||||||
            self.cursor.execute("ROLLBACK;")
 | 
					            self.cursor.execute("ROLLBACK;")
 | 
				
			||||||
            loggorilla.error(APIADDR, str(e) )
 | 
					            loggorilla.error(APIADDR, str(e) )
 | 
				
			||||||
            response["status"	] = "failed"
 | 
					            response["status"	] = "failed"
 | 
				
			||||||
            response["desc"	] = "Internal Server Error. Please contact us if you still have an error. for detail"
 | 
					            response["desc"		] = "Internal Server Error. Please contact us if you still have an error. for detail"
 | 
				
			||||||
        finally:
 | 
					        finally:
 | 
				
			||||||
            self.cursor.execute("COMMIT;")
 | 
					            self.cursor.execute("COMMIT;")
 | 
				
			||||||
            self.cursor.close()
 | 
					            self.cursor.close()
 | 
				
			||||||
            self.db_main.close()
 | 
					            self.db_main.close()
 | 
				
			||||||
        return response
 | 
					        return response
 | 
				
			||||||
 | 
					 | 
				
			||||||
 | 
				
			|||||||
		Loading…
	
		Reference in New Issue
	
	Block a user