Module src.auth
Expand source code
import jwt
from flask_restful import Resource
import globals
import datetime
import bcrypt
from webargs.flaskparser import use_args, parser, abort
from webargs import fields
userDB = globals.userDB
def verify(token):
"""
It tries to decode the token using the secret key, and if it fails, it returns false
:param token: The token to be verified
:return: The token is being decoded and returned.
"""
try:
return jwt.decode(token, globals.JWT_SECRET, "HS256")
except:
return False
# The class takes in a username and password, checks if the username exists in the database, if it
# does, it checks if the password is correct, if it is, it creates a JWT token and returns it to the
# user
class Login(Resource):
login_args = {"username": fields.Str(
required=True), "password": fields.Str(required=True)}
@use_args(login_args)
def post(self, args):
"""
If the username and password are correct, return a token, otherwise return an error
:param args: {'username': 'test', 'password': 'test'}
:return: The token is being returned.
"""
try:
user = userDB.find_one({"userName": args["username"]})
if user:
passW = user["password"].encode()
if bcrypt.checkpw(args["password"].encode(), passW):
jwToken = jwt.encode({
"exp": datetime.datetime.now().astimezone() + datetime.timedelta(hours=12),
"id": str(user.get("_id"))},
globals.JWT_SECRET)
return {"Token": jwToken}, 200
else:
return str("Username/password Invalid"), 401
else:
return str("Username/password Invalid"), 401
except:
return "There was an error", 404
# This error handler is necessary for usage with Flask-RESTful
@parser.error_handler
def handle_request_parsing_error(err, req, schema, *, error_status_code, error_headers):
"""webargs error handler that uses Flask-RESTful's abort function to return
a JSON error response to the client.
"""
if not error_status_code:
abort(400, errors=err.messages)
else:
abort(error_status_code, errors=err.messages)
Functions
def handle_request_parsing_error(err, req, schema, *, error_status_code, error_headers)-
webargs error handler that uses Flask-RESTful's abort function to return a JSON error response to the client.
Expand source code
@parser.error_handler def handle_request_parsing_error(err, req, schema, *, error_status_code, error_headers): """webargs error handler that uses Flask-RESTful's abort function to return a JSON error response to the client. """ if not error_status_code: abort(400, errors=err.messages) else: abort(error_status_code, errors=err.messages) def verify(token)-
It tries to decode the token using the secret key, and if it fails, it returns false
:param token: The token to be verified :return: The token is being decoded and returned.
Expand source code
def verify(token): """ It tries to decode the token using the secret key, and if it fails, it returns false :param token: The token to be verified :return: The token is being decoded and returned. """ try: return jwt.decode(token, globals.JWT_SECRET, "HS256") except: return False
Classes
class Login-
Represents an abstract RESTful resource. Concrete resources should extend from this class and expose methods for each supported HTTP method. If a resource is invoked with an unsupported HTTP method, the API will return a response with status 405 Method Not Allowed. Otherwise the appropriate method is called and passed all arguments from the url rule used when adding the resource to an Api instance. See :meth:
~flask_restful.Api.add_resourcefor details.Expand source code
class Login(Resource): login_args = {"username": fields.Str( required=True), "password": fields.Str(required=True)} @use_args(login_args) def post(self, args): """ If the username and password are correct, return a token, otherwise return an error :param args: {'username': 'test', 'password': 'test'} :return: The token is being returned. """ try: user = userDB.find_one({"userName": args["username"]}) if user: passW = user["password"].encode() if bcrypt.checkpw(args["password"].encode(), passW): jwToken = jwt.encode({ "exp": datetime.datetime.now().astimezone() + datetime.timedelta(hours=12), "id": str(user.get("_id"))}, globals.JWT_SECRET) return {"Token": jwToken}, 200 else: return str("Username/password Invalid"), 401 else: return str("Username/password Invalid"), 401 except: return "There was an error", 404Ancestors
- flask_restful.Resource
- flask.views.MethodView
- flask.views.View
Class variables
var login_argsvar methods : Optional[List[str]]
Methods
def post(self, args)-
If the username and password are correct, return a token, otherwise return an error
:param args: {'username': 'test', 'password': 'test'} :return: The token is being returned.
Expand source code
@use_args(login_args) def post(self, args): """ If the username and password are correct, return a token, otherwise return an error :param args: {'username': 'test', 'password': 'test'} :return: The token is being returned. """ try: user = userDB.find_one({"userName": args["username"]}) if user: passW = user["password"].encode() if bcrypt.checkpw(args["password"].encode(), passW): jwToken = jwt.encode({ "exp": datetime.datetime.now().astimezone() + datetime.timedelta(hours=12), "id": str(user.get("_id"))}, globals.JWT_SECRET) return {"Token": jwToken}, 200 else: return str("Username/password Invalid"), 401 else: return str("Username/password Invalid"), 401 except: return "There was an error", 404