Skip to content

Instantly share code, notes, and snippets.

@Sanket758
Created January 23, 2021 10:25
Show Gist options
  • Save Sanket758/ec25ae28bf4b805e7d690d9aab7f8eb2 to your computer and use it in GitHub Desktop.
Save Sanket758/ec25ae28bf4b805e7d690d9aab7f8eb2 to your computer and use it in GitHub Desktop.
Flask API to handle Login and Registration.
from flask import Flask, jsonify, request, json
from flask_pymongo import PyMongo
from bson.objectid import ObjectId
from datetime import datetime
from flask_bcrypt import Bcrypt
# from flask_cors import CORS
# from flask_jwt_extended import JWTManager
app = Flask(__name__)
app.config['MONGO_DBNAME'] = 'demo'
app.config['MONGO_URI'] = 'mongodb://localhost:27017/demo'
mongo = PyMongo(app)
bcrypt = Bcrypt(app)
@app.route('/register', methods=["POST"])
def register():
users = mongo.db.users
first_name = request.get_json()['first_name']
last_name = request.get_json()['last_name']
username = request.get_json()['username']
password = bcrypt.generate_password_hash(request.get_json()['password']).decode('utf-8')
created = datetime.utcnow()
inserted_id = users.insert_one({
'first_name': first_name,
'last_name': last_name,
'username': username,
'password': password,
'created': created
}).inserted_id
new_user = users.find_one({'_id': ObjectId(inserted_id)})
result = {'Username': new_user['username'] + ' registered'}
return jsonify({'result': result})
@app.route('/login', methods=['POST'])
def login():
users = mongo.db.users
username = request.get_json()['username']
password = request.get_json()['password']
response = users.find_one({'username': username})
if response:
if bcrypt.check_password_hash(response['password'], password):
result = jsonify({'status': 'logged in successfully'})
else:
result = jsonify({"error": "Invalid username and password"})
else:
result = jsonify({"result": "No results found"})
return result
@app.route('/login', methods=['POST'])
def login():
users = mongo.db.users
username = request.get_json()['username']
password = request.get_json()['password']
response = users.find_one({'username': username})
if response:
if bcrypt.check_password_hash(response['password'], password):
result = jsonify({'status': 'logged in successfully'})
else:
result = jsonify({"error": "Invalid username and password"})
else:
result = jsonify({"result": "No results found"})
return result
if __name__ == '__main__':
app.run(debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment