-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
126 lines (100 loc) · 3.98 KB
/
app.py
File metadata and controls
126 lines (100 loc) · 3.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
import uuid
from werkzeug.security import generate_password_hash, check_password_hash
import jwt
import datetime
from functools import wraps
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///DATABASE.db"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = 'My secret key' #please change this
app.config['JSON_SORT_KEYS'] = False
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
public_id = db.Column(db.String(50), unique=True)
name = db.Column(db.String)
email = db.Column(db.String)
password = db.Column(db.String)
def token_required(f):
@wraps(f)
def decorated(*args, **kwargs):
token = None
# jwt is passed in the request header
if 'x-access-token' in request.headers:
token = request.headers['x-access-token']
# return 401 if token is not passed
if not token:
return jsonify({
'response' : 'Token is missing !!',
'message' : 'If you are having any problem tweet me @lifeofdekisugi'
}), 401
try:
# decoding the payload to fetch the stored details
data = jwt.decode(token, app.config['SECRET_KEY'])
current_user = User.query.filter_by(public_id = data['public_id']).first()
except:
return jsonify({'response' : 'Token is invalid !!'}), 401
# returns the current logged in users contex to the routes
return f(current_user, *args, **kwargs)
return decorated
@app.route('/')
def hello_world():
return ({
'response' : 'working !!',
'author' : 'Shahir Islam',
'repo-link' : 'https://github.com/lifeofdekisugi/flask-startup-kit',
'more-links' : '/sign-up , /login, /home (you need to use JWT token)'
})
@app.route('/sign-up', methods=['POST'])
def sign_up():
try:
signUpData = request.form
name = signUpData['name']
email = signUpData['email']
hashed_password = generate_password_hash(signUpData['password'] , method='sha256')
new_user = User(public_id=str(uuid.uuid4()),name=name, email=email, password=hashed_password)
db.session.add(new_user)
db.session.commit()
return jsonify({
'response ' : 'success',
'next-step' : '/login'
})
except Exception:
return jsonify({
'response ' : 'error',
'next-step' : 'Please Try Again'
})
@app.route('/login', methods=['POST'])
def login():
auth = request.form
email = auth['email']
password = auth['password']
if not auth or not email or not password:
#return make_response('Could not Verify', 401, {'WWW-Authenticate' : 'Basic realm="Login Required"'})
return jsonify({'response' : 'Login Failed'})
user = User.query.filter_by(email=email).first()
if not user:
#return make_response('Could not Verify', 401, {'WWW-Authenticate' : 'Basic realm="Login Required"'})
return jsonify({'response' : 'Email not found :('})
if check_password_hash(user.password, password):
token = jwt.encode({'public_id' : user.public_id, 'exp' : datetime.datetime.utcnow() + datetime.timedelta(minutes=60)}, app.config['SECRET_KEY'])
return jsonify({
'response' : 'success',
'token' : token.decode('UTF-8'),
})
@app.route('/home')
@token_required
def app_home(current_user):
if not current_user:
return jsonify({
'response' : 'error',
'message' : 'You are not authenticated. \n Please Login and try again.'
})
return jsonify({
'response' : 'success',
'message' : 'You did it mate.'
})
if __name__ == "__main__":
app.run(debug=True) #before deploy change debug to False