browser-go-api/auth/auth.py

73 lines
2.4 KiB
Python
Raw Permalink Normal View History

2019-10-05 06:25:01 +00:00
from flask import Blueprint, request, jsonify, session
from database import db
from models.User import User
2019-10-05 06:25:01 +00:00
auth = Blueprint('auth', __name__, url_prefix='/auth')
2019-10-05 06:29:43 +00:00
@auth.route('/signup', methods=['POST'])
2019-10-05 06:25:01 +00:00
def auth_signup():
data = request.get_json()
user = User.query.filter_by(email=data.get('email')).first()
if not user:
2019-10-06 20:44:38 +00:00
user = User.query.filter_by(username=data.get('username')).first()
if not user:
try:
user = User(
username = data['username'],
email = data['email'],
password = data['password'],
)
db.session.add(user)
db.session.commit()
auth_token = user.encode_auth_token(user.id)
response = {
'status': 'success',
'message': 'Succesfully registered.',
2019-10-07 05:51:36 +00:00
'token': auth_token.decode()
2019-10-06 20:44:38 +00:00
}
return jsonify(response), 201
except Exception as e:
print(e.__dict__)
response = {
'status': 'fail',
'message': 'There was an error. Please try again.'
}
return jsonify(response), 401
else: # username is taken
response = {
'status': 'fail',
2019-10-06 20:44:38 +00:00
'message': 'User already exists. Please login.'
}
2019-10-06 20:44:38 +00:00
else: # email is taken
response = {
'status': 'fail',
'message': 'User already exists. Please login.'
}
return jsonify(response), 202
2019-10-05 06:25:01 +00:00
2019-10-05 06:29:43 +00:00
@auth.route('/login', methods=['POST'])
2019-10-05 06:25:01 +00:00
def auth_login():
2019-10-06 22:39:22 +00:00
# get the post data
data = request.get_json()
try:
# fetch the user data
print('getting here')
2019-10-09 07:08:37 +00:00
print(data)
2019-10-06 22:39:22 +00:00
user = User.query.filter_by(email=data['email']).first()
print(user.username)
auth_token = user.encode_auth_token(user.id)
print(auth_token)
if auth_token:
response = {
'status': 'success',
'message': 'Successfully logged in.',
2019-10-07 05:51:36 +00:00
'token': auth_token.decode()
2019-10-06 22:39:22 +00:00
}
return jsonify(response), 200
except Exception as e:
print(e)
response = {
'status': 'fail',
'message': 'Try again'
}
return jsonify(response), 500