university-final-iot-backend/app/accounts/controllers.py

65 lines
2.2 KiB
Python
Raw Normal View History

2018-05-06 19:42:21 +00:00
from app import bcrypt, status
from flask import request
2018-05-04 13:44:17 +00:00
from .models import Account
2018-05-03 14:40:30 +00:00
def initialize_routes(accounts):
2018-05-06 19:42:21 +00:00
@accounts.route("", methods=['POST'])
2018-05-04 13:44:17 +00:00
def create_account():
print(request.data)
user = request.data.get('user')
if not Account.exists_with_any_of(
username=user.get('username'), email=user.get('email')):
password_hash = bcrypt.generate_password_hash(
user.get('password')
).decode('utf-8')
acct = Account(user.get('username'),
password_hash,
user.get('email'))
acct.save()
2018-05-06 19:42:21 +00:00
response = {
2018-05-04 13:44:17 +00:00
'status': 'success',
'message': 'Success!'
2018-05-06 19:42:21 +00:00
}
return response, status.HTTP_200_OK
2018-05-04 13:44:17 +00:00
else:
2018-05-06 19:42:21 +00:00
response = {
2018-05-04 13:44:17 +00:00
'status': 'error',
'message': 'User already exists!'
2018-05-06 19:42:21 +00:00
}
return response, status.HTTP_422_UNPROCESSABLE_ENTITY
2018-05-04 13:44:17 +00:00
@accounts.route("/token", methods=['POST'])
def create_token():
2018-05-03 15:01:32 +00:00
print(request.data)
user = request.data.get('user')
2018-05-04 13:44:17 +00:00
if not user:
2018-05-06 19:42:21 +00:00
response = {
2018-05-04 13:44:17 +00:00
'status': 'error',
'message': 'Invalid request'
2018-05-06 19:42:21 +00:00
}
return response, status.HTTP_400_BAD_REQUEST
2018-05-04 13:44:17 +00:00
if not Account.exists(username=user.get('username')):
2018-05-06 19:42:21 +00:00
response = {
2018-05-04 13:44:17 +00:00
'status': 'error',
'message': 'Invalid credentials'
2018-05-06 19:42:21 +00:00
}
return response, status.HTTP_401_UNAUTHORIZED
2018-05-04 13:44:17 +00:00
account = Account.get(username=user.get('username'))
if not bcrypt.check_password_hash(
account.password, user.get('password')):
2018-05-06 19:42:21 +00:00
response = {
2018-05-04 13:44:17 +00:00
'status': 'error',
'message': 'Invalid credentials'
2018-05-06 19:42:21 +00:00
}
return response, status.HTTP_401_UNAUTHORIZED
2018-05-04 13:44:17 +00:00
2018-05-06 19:42:21 +00:00
response = {
2018-05-04 13:44:17 +00:00
'status': 'success',
'message': 'Successfully logged in',
'token': account.create_auth_token()
2018-05-06 19:42:21 +00:00
}
return response, status.HTTP_200_OK