Example #1
0
def user(user_id):
    '''
    For GET requests, return the given user.
    For DELETE requests, delete the given user.
    '''

    user = User.query.filter_by(id=user_id).first()
    if user is None:
        return 'user does not exist', 404

    # request is a GET
    if request.method == 'GET':
        schema = UserSchema(strict=True)
        user_data = schema.dump(user)
        return jsonify(user_data)

    # request is a DELETE
    elif request.method == 'DELETE':
        if current_user == user:
            return json.dumps({'success': False}), 200, {
                'ContentType': 'application/json'
            }
        db.session.delete(user)
        db.session.commit()
        return json.dumps({'success': True}), 200, {
            'ContentType': 'application/json'
        }
Example #2
0
def read_all(active_only=False):
    query = User.query
    if active_only:
        query = query.filter(User.is_active == True)
    users = query.all()
    user_schema = UserSchema(many=True)
    return user_schema.dump(users)
Example #3
0
def profiles():
    '''render webpage profiles'''
    users = db.session.query(User).all()
    if request.method == "POST":
        serializer = UserSchema(many=True)
        result = serializer.dump(users)
        return jsonify({'Users': result.data})
    return render_template('profile.html', users=users)
Example #4
0
 def on_get(self, req, res):
     session = req.context['session']
     users = session.query(User).all()
     schema = UserSchema()
     out = []
     for u in users:
         out.append(schema.dump(u).data)
     res.status = falcon.HTTP_200
     res.body = self.to_json(out)
Example #5
0
 def post(self):
     """创建 Redis 实例
     """
     data = request.get_json()
     user, errors = UserSchema().load(data)
     if errors:
         return errors, 400
     user.save()
     return {'ok': True}, 201
Example #6
0
def GetUser(request):
    print(current_user.get_id())
    userdetails = User.query.filter_by(id=current_user.get_id()).first()
    schema = UserSchema()
    pprint(schema.dump(userdetails).data)
    user_details = schema.dump(userdetails).data
    if request == None:
        return user_details
    return jsonify(user_details)
Example #7
0
 def put(self, object_id):
     """更新服务器
     """
     schema = UserSchema(context={'instance': g.instance})
     data = request.get_json()
     server, errors = schema.load(data, partial=True)
     if errors:
         return errors, 400
     server.save()
     return {'ok': True}
Example #8
0
def create(user, cleartext_password):
    schema = UserSchema()
    user["email"] = sanitize_email(user["email"])
    new_user = schema.load(user, session=db.session)

    new_user.set_password(cleartext_password)

    db.session.add(new_user)
    db.session.commit()

    return new_user
Example #9
0
    def decorated_view(*args, **kwargs):

        data = request.get_json()
        schema = UserSchema()
        validate = schema.validate({
            'email': data['email'],
            'password': data['password']
        })
        for key in validate:
            if key:
                return json.dumps({'message': validate[key][0]}), 400

        return func(*args, **kwargs)
Example #10
0
 def post(self):
     message = {'errors': {}}
     data = request.get_json()
     email = data.get('email')
     username = data.get('username')
     password = data.get('password')
     username_valid = False if UserModel.find_by_username(
         username) else True
     email_valid = False if UserModel.find_by_email(email) else True
     email_exists = True if validate_email(email, check_mx=True) else False
     if not username_valid:
         message['errors'][
             'UsernameExistsError'] = 'UserModel with such username already exists'
     if not email_valid:
         message['errors'][
             'UserWithSuchEmailExists'] = 'UserModel with such email already exists'
     if not email_exists:
         message['errors'][
             'EmailDoesNotExistError'] = 'Entered email does not exist'
     try:
         UserSchema().load(data)
     except ValidationError as vall_err:
         message['errors']['ValidationError'] = vall_err.messages
         return make_response(jsonify(message), 400)
     else:
         if message['errors']:
             return make_response(jsonify(message), 400)
         user = UserModel(username=username, email=email)
         user.set_password(password)
         user.save_to_db()
         return message, 201
Example #11
0
def CreateUser(request):
    print("Request is : ", request.json)
    if not request.json:
        return jsonify({'message': 'No input data provided '}), 400
    content = request.get_json()
    schema = UserSchema()
    userData = schema.load(content)
    newAsset = userData.data
    a = User(**newAsset)
    db.session.add(a)
    try:
        db.session.commit()
        return jsonify({"sucess": True})
    except IntegrityError:
        return jsonify({"sucess": False})
        db.session.rollback()
Example #12
0
 def delete(self):
     # 新增数据
     data = request.get_json()
     userschema = user_schema.load(data)
     app = UserSchema(**userschema)
     db.session.add(app)
     db.session.commit()
     return normal_request("create app success")
Example #13
0
def get_one_user(public_id):
    """
    This route gets a single user from the database
    and returns it as a json object.

    Args {string} public_id

    Returns {Object<json>} 200
            success: {string}
            user: {Object<json>}

    Throws {Exception{Object<json>}}
            error: NoResultFound 404
                   SQLAlchemyError 400
                   NotAuthorized 401
    """
    # Get the user's id from access token
    uid = get_jwt_identity()

    # If user's public_id doesn't equal public id in url, return error
    if user.public_id != public_id:
        return jsonify({'error': 'Not authorized!'}), 401

    # Try to get user from database
    query = User.query.filter_by(public_id=uid)

    try:
        user = query.one()

    # If no result found, return error
    except NoResultFound:
        return jsonify({'error': 'No result found!'}), 404

    # If some other sqlalchemy error is thrown, return error
    except SQLAlchemyError:
        return jsonify({'error': 'Some problem occurred!'}), 400

    # Serialze the user object and return json response
    user_schema = UserSchema()
    output = user_schema.dump(user).data

    return jsonify({
        'success': 'Successfully retrieved user.',
        'user': output
    }), 200
Example #14
0
def get_all_users():
    """
    This route gets all users from the database and returns
    the array as a json object.

    Returns {Object<json>} 200
            num_results: {string}
            success: {string}
            users: {Object<json>}

    Throws {Exception{Object<json>}}
            error: NoResultFound 404
                   SQLAlchemyError 400
    """
    # Try to get all users from database
    query = User.query

    try:
        users = query.all()

        # If query returns no users, return erorr
        if len(users) == 0:
            return jsonify({'error': 'No results found!'}), 404

    # If no result found, return error
    except NoResultFound:
        return jsonify({'error': 'No result found!'}), 404

    # If some other sqlalchemy error is thrown, return error
    except SQLAlchemyError:
        return jsonify({'error': 'Some problem occurred!'}), 400

    # Serialize array of users
    user_schema = UserSchema(many=True)
    output = user_schema.dump(users).data

    # Return json response
    return jsonify({
        'num_results': str(len(output)),
        'success': 'Successfully retrieved users!',
        'users': output,
    }), 200
class UserController(MethodView):

  def __init__(self):
    self.service = UserService()
    self.schema = UserSchema()
    self.many_schema = UserSchema(many=True)
  
  def get(self, user_id):
    res = None
    serialized = None
    if user_id is None:
      res = self.service.get_all_users()
      serialized = self.many_schema.dump(res)
    else:
      res = self.service.get_user_by_id(user_id)
      serialized = self.schema.dump(res)
    return jsonify({'user': serialized}), 200
  
  def post(self):
    password = request.json['password']
    
    encrypted_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
    
    user = User(
      email=request.json['email'], 
      password=encrypted_password)
    self.service.save_user(user)
    
    serialized = self.schema.dump(user)
    
    return jsonify({'user': serialized}), 201
  
  def put(self, user_id):
    user = self.service.update_user_by_id(user_id, request.json['user'])
    serialized = self.schema.dump(user)
    return jsonify({'user': serialized}), 200
  
  def delete(self, user_id):
    self.service.delete_user_by_id(user_id)
    return jsonify({}), 204
Example #16
0
def users():
    '''
    For GET requests, return all users.
    For POST requests, add a new user.
    '''
    if request.method == 'GET':
        all_users = User.query.all()
        schema = UserSchema(many=True, strict=True)
        users = schema.dump(all_users)
        return jsonify(users[0])
    # request is a POST
    else:
        username = request.form.get('Username')
        role = request.form.get('Role')
        role = Role.query.filter_by(name=role).first()
        user = User.query.filter_by(username=username).first()

        if user is not None:
            return json.dumps({'success': False}), 200, {
                'ContentType': 'application/json'
            }
        elif role is None:
            return 'failed to enter into database - role doesnt exist', 400

        user = User(username=username, role_id=role.id)
        user.set_password(request.form.get('Password'))
        db.session.add(user)
        db.session.commit()
        schema = UserSchema(strict=True)
        user_data = schema.dump(user)
        return jsonify(user_data[0]), 201
Example #17
0
 def on_post(self, req, res):
     """
     Create a new user. Will test the data passed to the resource.
     """
     session = req.context['session']
     data = json.loads(req.bounded_stream.read().decode())
     result = UserSchema().load(data)
     if result.errors:
         res.status = falcon.HTTP_BAD_REQUEST
         res.body = self.to_json({'errors': result.errors})
     else:
         roles = get_roles()
         user = User(email=data['email'],
                     fn=data['fn'],
                     ln=data['ln'],
                     password=hash_password(data['password']),
                     role=roles['member'])
         session.add(user)
         session.flush()
         schema = UserSchema()
         res.status = falcon.HTTP_200
         res.body = self.to_json(schema.dump(user).data)
Example #18
0
from app import app, db
from flask import Flask, request, jsonify
from app.models import User, Flight, UserSchema, FlightSchema
from flask_cors import CORS
CORS(app)

# initialize schema
user_schema = UserSchema(strict=True)
users_schema = UserSchema(many=True, strict=True)

flight_schema = FlightSchema(strict=True)
flights_schema = FlightSchema(many=True, strict=True)


@app.route('/registro-usuario', methods=['POST'])
def add_user():
    name = request.json['name']
    email = request.json['email']
    user_type = request.json['user_type']
    cpf = request.json['cpf']
    phone_number = request.json['phone_number']
    birthday = request.json['birthday']
    matricula = request.json['cpf']

    new_user = User(matricula, name, email, user_type, cpf, phone_number,
                    birthday)
    new_user.persist()

    return user_schema.jsonify(new_user)

Example #19
0
import math
from datetime import datetime

from flask import flash, redirect, render_template, request, url_for
from flask_login import current_user, login_required

from app import db
from app.main import bp
from app.main.forms import (AddCategoryForm, AddTaskForm, AddUserCategoryForm,
                            EditProfileForm, NewSessionAddTaskForm,
                            RunSessionForm)
from app.models import (Category, Session, Task, TaskSchema, User,
                        UserCategory, UserSchema)

USER_SCHEMA = UserSchema(exclude=("last_seen", ))
TASKS_SCHEMA = TaskSchema(many=True, exclude=("timestamp", ))
DEBUG = False


@bp.before_request
def before_request():
    if current_user.is_authenticated:
        current_user.last_seen = datetime.utcnow()
        db.session.commit()


@bp.route('/')
@bp.route('/index', methods=['GET'])
@login_required
def index():
    user = User.query.filter_by(username=current_user.username).first_or_404()
 def __init__(self):
   self.service = UserService()
   self.schema = UserSchema()
   self.many_schema = UserSchema(many=True)
Example #21
0
 def get(self):
     """获取 Redis 列表
     """
     servers = User.query.all()
     return UserSchema().dump(servers, many=True).data
Example #22
0
from flask import jsonify
from flask import request
from sqlalchemy.exc import IntegrityError

from app import app
from app import db
from app.models import User, Restaurant, Rating, Address
from app.models import UserSchema, RestaurantSchema, AddressSchema, RatingSchema, RatingSchemaUpdate

from marshmallow import ValidationError

from datetime import datetime, timedelta
from sqlalchemy import func
from sqlalchemy.sql import label

users_schema = UserSchema(many=True)
user_schema = UserSchema()

restaurants_schema = RestaurantSchema(many=True)
restaurant_schema = RestaurantSchema()

address_schema = AddressSchema()

rating_schema = RatingSchema()
ratingupdate_schema = RatingSchemaUpdate()
ratings_schema = RatingSchema(many=True)

import pdb


#function to add object to database
Example #23
0
def get_user(id):
    user_schema = UserSchema()
    user = UserModel.query.filter_by(id=id).first_or_404()
    dump_data = user_schema.dump(user)
    return dump_data
Example #24
0
def bot():
    incoming_msg = request.values.get('Body', '').lower()
    resp = MessagingResponse()
    msg = resp.message()
    sender_number = request.values.get('From')
    print("IN BOT")
    print(incoming_msg)
    responded = False
    if 'add state' in incoming_msg:
        state_name = incoming_msg.split("add state", 1)[1]

        search_term = state_name.strip()
        search_term = f"%{search_term}%"

        state = State.query.filter((State.State.like(search_term))).first()
        stateSchema = StateSchema()
        state = stateSchema.dump(state)
        state_id = state["Id"]
        state_cured = state["Cured"]
        state_dead = state["Dead"]
        state_confirmed = state["Confirmed"]
        state_name = state["State"]

        check_user_state_exist = User.query.filter_by(
            MobileNo=sender_number, State_Id=state['Id']).first()

        if not check_user_state_exist:
            user_new = User(State_Id=state_id, MobileNo=sender_number)
            db.session.add(user_new)
            db.session.commit()

            msg.body(f"{state_name} added for COVID-19 tracking.")

        else:
            msg.body(f"{state_name} already added for tracking.")

        msg.body(
            f"Currently in {state_name}, there are \n {state_confirmed} cases confirmed \n {state_cured} cases "
            f"cured \n {state_dead} deaths ")

        responded = True

    if 'all states' in incoming_msg:
        user_list = User.query.filter_by(MobileNo=sender_number).all()
        userSchema = UserSchema(many=True)
        user_list = userSchema.dump(user_list)

        print(user_list)
        if not user_list:
            msg.body(
                f"No states added currently add it like *add state Gujarat*")
        for user_detail in user_list:
            state_id = user_detail["states"]

            state = State.query.filter_by(Id=state_id).first()
            stateSchema = StateSchema()
            state = stateSchema.dump(state)
            state_id = state["Id"]
            state_cured = state["Cured"]
            state_dead = state["Dead"]
            state_confirmed = state["Confirmed"]
            state_name = state["State"]

            empty = "‎‎ ‎"  # invisible character, to get new line hack
            msg.body(empty)
            msg.body(
                f" Currently in \n *{state_name}*, there are \n {state_confirmed} cases confirmed \n {state_cured} cases "
                f"cured \n {state_dead} deaths. \n {empty}\n")

        responded = True
    if 'remove state' in incoming_msg:
        state_name = incoming_msg.split("remove state", 1)[1]
        search_term = state_name.strip()
        search_term = f"%{search_term}%"

        user_list = User.query.filter_by(MobileNo=sender_number).all()
        userSchema = UserSchema(many=True)
        user_list = userSchema.dump(user_list)

        print(user_list)
        if not user_list:
            msg.body(
                f"No states to remove currently add it like *add state Gujarat*"
            )

        if user_list:
            state = State.query.filter((State.State.like(search_term))).first()
            stateSchema = StateSchema()
            state = stateSchema.dump(state)
            state_id = state["Id"]
            state_name = state["State"]

            User.query.filter_by(MobileNo=sender_number,
                                 State_Id=state_id).delete()
            db.session.commit()
            msg.body(f"{state_name} removed from tracking")

        responded = True

    if 'get news' in incoming_msg:

        all_news = News.query.all()
        news_schema = NewsSchema(many=True)
        all_news = news_schema.dump(all_news)

        for news in all_news:
            title = news["Title"]

            empty = "‎‎ ‎"  # invisible character, to get new line hack
            msg.body(f" \n *Title* :  {title} \n {empty}\n ")

        responded = True

    if "what is covid 19" in incoming_msg:
        msg.body(
            "COVID-19 is a disease caused by a new strain of coronavirus. ‘CO’ stands for corona, ‘VI’ for virus, and ‘D’ for disease. Formerly, this disease was referred to as ‘2019 novel coronavirus’ or ‘2019-nCoV.’ The COVID-19 virus is a new virus linked to the same family of viruses as Severe Acute Respiratory Syndrome (SARS) and some types of common cold"
        )

        responded = True
    if "symptoms of covid 19" in incoming_msg:
        msg.body(
            "Symptoms can include fever, cough and shortness of breath. In more severe cases, infection can cause pneumonia or breathing difficulties. More rarely, the disease can be fatal. These symptoms are similar to the flu (influenza) or the common cold, which are a lot more common than COVID-19. This is why testing is required to confirm if someone has COVID-19."
        )

        responded = True

    if "how to be safe" in incoming_msg:
        msg.body('''✓ staying home when sick
✓ covering mouth and nose with flexed elbow or tissue when coughing or sneezing. Dispose ofused tissue immediately;
✓ washing hands often with soap and water; and
✓ cleaning frequently touched surfaces and objects
        ''')
        responded = True

    if "help" in incoming_msg:
        msg.body('''You can give me the following commands
👉 add state {state name}
👉 all states
👉 remove state {state name}
👉 get news
👉 what is covid 19
👉 symptoms of covid 19
👉 how to be safe
👉 help
''')
        responded = True
    if not responded:
        chatter_resp = chat_bot.get_response(incoming_msg)
        # print(chatter_resp)
        # print(chatter_resp.serialize())
        serialize_resp = chatter_resp.serialize()
        res_text = serialize_resp["text"]
        # print(res_text)

        empty = "‎‎ ‎"  # invisible character, to get new line hack
        msg.body(f"{res_text}")
        msg.body(f"{empty} \n you can type *help* for menu")
    return str(resp)
Example #25
0
def create_bracket():
    """
    This route adds a new bracket to the database and
    returns a success message as a json object.

    Returns {Object<json>} 200
            success: {string}
            bracket: {Object<json>}

    Throws {Exception{Object<json>}}
            error: NotAuthorized 401
                   NoResultFound 404
                   SQLAlchemyError 400
    """
    # Get the user's id from access token
    uid = get_jwt_identity()

    # If no user id, return error
    if not uid:
        return make_response(
            jsonify({'error': 'Could not verify!'}), 401,
            {'WWW-Authentication': 'Basic realm="Login required!"'})

    # Try to get user from database
    query = User.query.filter_by(public_id=uid)

    try:
        user = query.one()

    # If no result found, return error
    except NoResultFound:
        return jsonify({'error': 'No result found!'}), 401

    # If some other sqlalchemy error is thrown, return error
    except SQLAlchemyError:
        return jsonify({'error': 'Some problem occurred!'}), 400

    # Get bracket data from request
    data = request.get_json()

    # Verify that all required bracket data was sent
    bracket_columns = [
        'grp_a_1', 'grp_a_2', 'grp_b_1', 'grp_b_2', 'grp_c_1', 'grp_c_2',
        'grp_d_1', 'grp_d_2', 'grp_e_1', 'grp_e_2', 'grp_f_1', 'grp_f_2',
        'grp_g_1', 'grp_g_2', 'grp_h_1', 'grp_h_2'
    ]
    if not any(key in data for key in bracket_columns):
        return make_response(jsonify({'error': 'Missing data!'}), 400)

    # Create bracket object
    bracket = Bracket(uid=user.public_id,
                      grp_a_1=data['grp_a_1'],
                      grp_a_2=data['grp_a_2'],
                      grp_b_1=data['grp_b_1'],
                      grp_b_2=data['grp_b_2'],
                      grp_c_1=data['grp_c_1'],
                      grp_c_2=data['grp_c_2'],
                      grp_d_1=data['grp_d_1'],
                      grp_d_2=data['grp_d_2'],
                      grp_e_1=data['grp_e_1'],
                      grp_e_2=data['grp_e_2'],
                      grp_f_1=data['grp_f_1'],
                      grp_f_2=data['grp_f_2'],
                      grp_g_1=data['grp_g_1'],
                      grp_g_2=data['grp_g_2'],
                      grp_h_1=data['grp_h_1'],
                      grp_h_2=data['grp_h_2'])

    # Try to add bracket to database
    try:
        db.session.add(bracket)
        db.session.commit()

    # If bracket name already in database, return error
    except IntegrityError:
        return jsonify({'error':
                        'User with name or email already exists'}), 400

    # If some other sqlalchemy error is thrown, return error
    except SQLAlchemyError:
        return jsonify({'error': 'Some problem occurred!'}), 400

    # Add the bracket to the user object
    user.bracket = bracket

    # Serialze the bracket and user objects and return json response
    bracket_schema = BracketSchema()
    b_output = bracket_schema.dump(bracket).data
    user_schema = UserSchema()
    u_output = user_schema.dump(user).data

    return jsonify({
        'success': 'Successfully retrieved bracket.',
        'bracket': b_output,
        'user': u_output,
    }), 200
Example #26
0
from app import db
from flask_restplus import Namespace, Resource, fields
from app.models import User, UserSchema, Post, Company, PostSchema
from flask import jsonify, request
from .dto import userDTO, postDTO

api = Namespace('users', description='Users api')

user_schema = UserSchema()
user_schema_list = UserSchema(many=True)

post_schema = PostSchema()
post_schema_list = PostSchema(many=True)

@api.route('/')
class UsersResourceList(Resource):
    @api.marshal_with(userDTO, code=201)
    @api.expect(userDTO)
    def post(self):
        users = User.query.all()
        return user_schema_list.jsonify(users)

@api.route('/<int:id>')
class UsersResource(Resource):
    def get(self, id):
        user = User.query.get_or_404(id)
        return user_schema.jsonify(user)

@api.route('/<int:id>/posts')
class UsersResourcePosts(Resource):
    def get(self, id):
Example #27
0
def create_user():
    """
    This route adds a new user to the database, sends a
    confirmation link to the user's email and returns a
    success message aa a json object.

    Returns {Object<json>} 200
            success: {string}

    Throws {Exception{Object<json>}}
            error: NotAuthorized 401
                   NoResultFound 404
                   SQLAlchemyError 400
    """
    # Get user's authorization credentials
    auth = request.authorization

    # If no authorization credentials, return error
    if not auth or not auth.username or not auth.password:
        return make_response(
            jsonify({'error': 'Could not verify!'}), 401,
            {'WWW-Authentication': 'Basic realm="Login required!"'})

    # Get user data from request
    data = request.get_json()

    # If name or email is missing, return error
    if not data['name'] or not data['email']:
        return make_response(jsonify({'error': 'Missing data!'}), 400)

    # Create a salted password
    random_bytes = urandom(24)
    salt = b64encode(random_bytes).decode('utf-8')
    salted_password = auth['password'] + salt

    # Hash the salted password
    hashed_password = generate_password_hash(salted_password,
                                             method='pbkdf2:sha512:80000',
                                             salt_length=20)

    # Create user object
    user = User(name=data['name'],
                email=data['email'],
                username=auth['username'],
                password=hashed_password,
                salt=salt,
                created_at=datetime.utcnow())

    user.generate_public_id()

    # Try to add user to database
    try:
        db.session.add(user)
        db.session.commit()

    # If username already in database, return error
    except IntegrityError:
        return jsonify({'error':
                        'User with name or email already exists'}), 400

    # If some other sqlalchemy error is thrown, return error
    except SQLAlchemyError:
        return jsonify({'error': 'Some problem occurred!'}), 400

    # Serialize the user object
    user_schema = UserSchema()
    output = user_schema.dump(user).data

    # Create the tokens to be sent to the user
    expires = timedelta(seconds=1800)
    access_token = create_access_token(identity=user.public_id,
                                       expires_delta=expires)
    refresh_token = create_refresh_token(identity=user.public_id)

    # Get the csrf tokens so they can be set as headers in response
    csrf_access_token = get_csrf_token(access_token)
    csrf_refresh_token = get_csrf_token(refresh_token)

    # Create json response
    response = make_response(
        jsonify({
            'user': output,
            'success': 'Login successful!'
        }), 200)

    # Set JWT cookies and headers and return response
    set_access_cookies(response, access_token)
    set_refresh_cookies(response, refresh_token)
    response.set_cookie('public_id', user.public_id)
    response.headers['access'] = csrf_access_token
    response.headers['refresh'] = csrf_refresh_token

    return response
Example #28
0
def login():
    """
    This route authenticates the user by checking the username and
    password if it exists or by decoding the jwt token if it exists.
    Each time a user logs in new jwt tokens cookies will be set in
    the response.

    Returns {Object<json>} 200
            success: {string}
            user: {Object<json>}

    Throws {Exception{Object<json}}:
            error: NoResultFound 401
                   SQLAlchemyError 400
                   InactiveUser 400
    """

    # If authorization header is present, try to authenticate the user
    if request.authorization:
        auth = request.authorization

        # If not username and password, return error
        if not auth.username or not auth.password:
            return not_authorized_error('Basic')

        # Find the user by username
        query = User.query.filter_by(username=auth.username)

        try:
            user = query.one()

        # If no user found, try by email or return error
        except NoResultFound:

            # Try to find the user by email
            query = User.query.filter_by(email=auth.username)

            try:
                user = query.one()

            # If no user found, try by email or return error
            except NoResultFound:
                return make_response(
                    jsonify({
                        'error': ('Sorry, your username or password was '
                                  'incorrect. Please try again.')
                    }), 401,
                    {'WWW-Authentication': 'Basic realm="Login required!"'})
            # If some other sqlalchemy error is thrown, return error
            except SQLAlchemyError:
                return jsonify({'error': 'Some problem occurred!'}), 400

        # If some other sqlalchemy error is thrown, return error
        except SQLAlchemyError:
            return jsonify({'error': 'Some problem occurred!'}), 400

        # If provided password does not match user password, return error
        if not check_password_hash(user.password, auth.password + user.salt):
            return make_response(
                jsonify({
                    'error': ('Sorry, your username or password was '
                              'incorrect. Please try again.')
                }), 401,
                {'WWW-Authentication': 'Basic realm="Login required!"'})

        # Serialize the user object
        user_schema = UserSchema()
        output = user_schema.dump(user).data

        # Create the tokens to be sent to the user
        expires = timedelta(seconds=1800)
        access_token = create_access_token(identity=user.public_id,
                                           expires_delta=expires)
        refresh_token = create_refresh_token(identity=user.public_id)

        # Get the csrf tokens so they can be set as headers in response
        csrf_access_token = get_csrf_token(access_token)
        csrf_refresh_token = get_csrf_token(refresh_token)

        # Create json response
        response = make_response(
            jsonify({
                'user': output,
                'success': 'Login successful!'
            }), 200)

        # Set JWT cookies and headers and return response
        set_access_cookies(response, access_token)
        set_refresh_cookies(response, refresh_token)
        response.set_cookie('public_id', user.public_id)
        response.headers['access'] = csrf_access_token
        response.headers['refresh'] = csrf_refresh_token

        return response

    # If no authorization header present, check for jwt token cookies
    else:
        public_id = get_jwt_identity()

        # If there isn't a valid jwt token, return error
        if not public_id:
            return not_authorized_error('Cookie')

        # Find the user
        query = User.query.filter_by(public_id=public_id)

        try:
            user = query.first()

        # If no user found, return error
        except NoResultFound:
            return not_authorized_error('Cookie')

        # If some other sqlalchemy error is thrown, return error
        except SQLAlchemyError:
            return jsonify({'error': 'Some problem occurred!'}), 400

        # Serialize the user object
        user_schema = UserSchema()
        output = user_schema.dump(user).data

        # Create the tokens to be sent to the user
        expires = timedelta(seconds=1800)
        access_token = create_access_token(identity=user.public_id,
                                           expires_delta=expires)
        refresh_token = create_refresh_token(identity=user.public_id)

        # Get the csrf tokens so they can be set as headers in response
        csrf_access_token = get_csrf_token(access_token)
        csrf_refresh_token = get_csrf_token(refresh_token)

        # Create json response
        response = make_response(
            jsonify({
                'user': output,
                'success': 'Login successful!'
            }), 200)

        # Set JWT cookies and headers and return response
        set_access_cookies(response, access_token)
        set_refresh_cookies(response, refresh_token)
        response.set_cookie('public_id', user.public_id)
        response.headers['access'] = csrf_access_token
        response.headers['refresh'] = csrf_refresh_token

        return response
Example #29
0
def oauth(provider):
    """
    This route authenticates the user by receiving a provider
    and oauth token and verifying a user exists. When a user logs
    in new jwt tokens cookies will be set in the response.

    Args {string} provider - facebook or google

    Returns {Object<json>} 200
            success: {string}
            user: {Object<json>}

    Throws {Exception{Object<json}}:
            error: Authorization 401
                   NoResultFound 401
                   SQLAlchemyError 400
                   MissingUser 400
                   InactiveUser 400
    """
    # If no authorization header, return error
    if not request.headers.get('Authorization'):
        return jsonify({'error': 'Not a valid request'}), 401

    # Get the token from authorization header and convert to dictionary
    token = request.headers.get('Authorization').split('Bearer ')[1]
    token = json.loads(token)

    # Try to find oauth user in database
    query = OAuth.query.filter_by(
        provider=provider,
        provider_uid=token['userID'],
    )

    try:
        oauth = query.first()

    # If no result found, return error
    except NoResultFound:
        return jsonify(
            {'error':
             "The user doesn't exist. Sign up to create an account"}), 404

    # If some other sqlalchemy error is thrown, return error
    except SQLAlchemyError:
        return jsonify({'error': 'Some problem occurred!'}), 400

    # If not oauth create a new user
    if not oauth:

        # Get user data from request
        data = request.get_json()

        # If name or email is missing, return error
        if not (data['name'] or not data['email'] or not data['picture']
                or not data['provider_user_id']):
            return make_response(jsonify({'error': 'Missing data!'}), 400)

        # Create user object
        user = User(name=data['name'],
                    email=data['email'],
                    picture=data['picture'],
                    created_at=datetime.utcnow())

        user.generate_public_id()

        # Try to add user to database
        try:
            db.session.add(user)
            db.session.commit()

        # If username already in database, return error
        except IntegrityError:
            return jsonify({'error':
                            'User with name or email already exists'}), 400

        # If some other sqlalchemy error is thrown, return error
        except SQLAlchemyError:
            return jsonify({'error': 'Some problem occurred!'}), 400

        # Create new oauth token account for user
        oauth = OAuth(
            provider=provider,
            provider_uid=data['provider_user_id'],
            token=token,
        )

        # Associate the new local user account with the OAuth token
        oauth.user = user

        # Save and commit database models
        db.session.add(oauth)
        db.session.commit()

    # If there is no user relation, return error
    if not oauth.user:
        return jsonify({'error': 'Some problem occurred!'}), 400

    user = oauth.user

    # Serialze the user object
    user_schema = UserSchema()
    output = user_schema.dump(user).data

    # Create the tokens to be sent to the user
    expires = timedelta(seconds=1800)
    access_token = create_access_token(identity=user.public_id,
                                       expires_delta=expires)
    refresh_token = create_refresh_token(identity=user.public_id)

    # Get the csrf tokens so they can be set as headers in response
    csrf_access_token = get_csrf_token(access_token)
    csrf_refresh_token = get_csrf_token(refresh_token)

    # Create json response
    response = make_response(
        jsonify({
            'user': output,
            'success': 'Login successful!'
        }), 200)

    # Set JWT cookies and headers and return response
    set_access_cookies(response, access_token)
    set_refresh_cookies(response, refresh_token)
    response.set_cookie('public_id', user.public_id)
    response.headers['access'] = csrf_access_token
    response.headers['refresh'] = csrf_refresh_token

    return response
Example #30
0
def edit_user(id):
    """
    This route edits a user in the database and
    returns the updated user aa a json object.

    Returns {Object<json>} 200
            success: {string}
            user: {Object<json>}

    Throws {Exception{Object<json>}}
            error: NotAuthorized 401
                   ExpiredSignatureError 400
                   DecodeJWTError 400
                   NoResultFound 404
                   SQLAlchemyError 400
    """
    auth = {}

    # Get the user data from the request
    data = request.get_json()

    # If there is no authorization header, get
    # the user's id from the access token cookie
    if not request.headers.get('Authorization'):
        public_id = get_jwt_identity()

        # If user's id doesn't match url id, return error
        if public_id != id:
            return jsonify({'error': 'Not authorized!'}), 401

    # If basic authorization, get the user's
    # id from the authorization username
    elif request.authorization:

        auth = request.authorization

        # If authorization credentials missing, return error
        if not auth or not auth.username or not auth.password:
            return make_response(
                jsonify({'error': 'Could not verify'}), 401,
                {'WWW-Authentication': 'Basic realm="Login required!"'})

        public_id = auth.username

        # If the user's public id doesn't match url id, return error
        if public_id != id:
            return jsonify({'error': 'Not authorized!'}), 401

    else:
        # Get the user's token from the authorization header
        token = request.headers.get('Authorization').split(' ')[1]

        # If there is no token, return error
        if not token:
            return jsonify({'error': 'Missing token!'}), 401

        token = token.encode("utf-8")

        # Decode the jwt token
        try:
            jwt_data = jwt.decode(token,
                                  app.config.get('SECRET_KEY'),
                                  algorithm='HS256')

        # If the token has expired, return error
        except jwt.ExpiredSignatureError:
            # Signature has expired
            return jsonify(
                {'error': 'Reset token is expired. Please try again.'}), 400

        # If failed to decode jwt, return error
        if not jwt_data:
            return jsonify({'error': 'Failed to decode jwt token.'}), 400

        # Get the user's id from the decoded jwt
        public_id = jwt_data['public_id']

        # If the user's id doesn't match the url id, return error
        if public_id != id:
            return jsonify({'error': 'Not authorized!'}), 401

    # Try to get the user from the database
    query = User.query.filter_by(public_id=public_id)

    try:
        user = query.one()

    # If no result found, return error
    except NoResultFound:
        return jsonify({'error': 'No result found!'}), 404

    # If some other sqlalchemy error is thrown, return error
    except SQLAlchemyError:
        return jsonify({'error': 'Some problem occurred!'}), 400

    # If password provided but can't be verified, return error
    if 'password' in auth:

        if not check_password_hash(user.password, auth.password + user.salt):
            return jsonify({
                'error': ('The password you provided could '
                          'not be found for this user.')
            }), 401

    # If new password provided, create salt and hash it
    if 'password' in data:
        random_bytes = urandom(24)
        salt = b64encode(random_bytes).decode('utf-8')
        salted_password = data['password'] + salt

        hashed_password = generate_password_hash(salted_password,
                                                 method='pbkdf2:sha512:80000',
                                                 salt_length=20)
        user.password = hashed_password
        user.salt = salt

    # If other user attributes provided, add
    # them to user and save in database
    if 'name' in data:
        user.name = data['name']

    if 'username' in data:
        user.username = data['username']

    if 'email' in data:
        user.email = data['email']

    if 'picture' in data:
        user.picture = data['picture']

    db.session.commit()

    # Serialize user
    user_schema = UserSchema()
    output = user_schema.dump(user).data

    # Create json and return response
    return jsonify({'success': 'The user has been updated', 'user': output})