def register_user(): # get post data post_data = request.get_json() response_object = {"status": "fail", "message": "Invalid payload."} if not post_data: return jsonify(response_object), 400 username = post_data.get("username") email = post_data.get("email") password = post_data.get("password") try: # check for existing user user = User.query.filter( or_(User.username == username, User.email == email) ).first() if not user: # add new user to db user = User(username=username, email=email, password=password) db.session.add(user) db.session.commit() # generate auth token auth_token = user.encode_auth_token(user.id) response_object["status"] = "success" response_object["message"] = "Successfully registered." response_object["auth_token"] = auth_token.decode() return jsonify(response_object), 201 else: response_object["message"] = "Sorry. That user already exists." return jsonify(response_object), 400 # handler errors except (exc.IntegrityError, ValueError): db.session.rollback() return jsonify(response_object), 400
def register_user(): post_data = request.get_json() res = {"status": "fail", "message": "Invalid payload."} if not post_data: return jsonify(res), 400 username = post_data.get("username") email = post_data.get("email") password = post_data.get("password") if not username or not email or not password: return jsonify(res), 400 try: user = User.query.filter( or_(User.username == username, User.email == email) ).first() if user: res["message"] = "Sorry, that user already exists." return jsonify(res), 400 else: new_user = User(username=username, email=email, password=password) db.session.add(new_user) db.session.commit() auth_token = new_user.encode_auth_token(new_user.id) current_app.logger.debug(f"Auth Token: {auth_token}, {type(auth_token)}") current_app.logger.debug(f"Auth Token Decode: {auth_token.decode()}") res["status"] = "success" res["message"] = "Successfully registered." res["auth_token"] = auth_token.decode() return jsonify(res), 201 except (exc.IntegrityError, ValueError): db.session.rollback() return jsonify(res), 400