Skip to content

Commit

Permalink
Adding wrapped function protector
Browse files Browse the repository at this point in the history
New function is declared that wraps called function. This way we make sure the predefined function will be called at each protected route we want.
  • Loading branch information
vexy committed Feb 29, 2020
1 parent 32f48d7 commit e269f84
Showing 1 changed file with 20 additions and 2 deletions.
22 changes: 20 additions & 2 deletions auth-module.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,39 @@
from flask import Flask, jsonify, request, make_response
import jwt
import datetime
from functools import wraps

# initialize main Flask object
if __name__ == '__main__':
app = Flask(__name__)

app.config['SECRET_KEY'] = 'some_secret_key'

def token_required(f):
@wraps(f)
def decorated(*args, **kwargs):
token = request.args.get('token') #get token from URL

if not token:
return jsonify({'message': 'Token is missing!'}), 403

try:
data = jwt.decode(token, app.config['SECRET_KEY'])
except:
return jsonify({'message': 'Invalid token supplied!'}), 403
return f(*args, **kwargs)

return decorated

# ROUTES DEFINITION:
@app.route('/unprotected')
def unprotected():
return 'This is unprotected area'
return jsonify({'message': 'Anyone can view this!'})

@app.route('/protected')
@token_required
def protected():
return 'This is protected area'
return jsonify({'message': 'Protected area'})

@app.route('/login')
def login():
Expand Down

0 comments on commit e269f84

Please sign in to comment.