コード例 #1
0
def add_user():
    # check if the data is json
    if request.is_json:
        data = request.get_json(force=True)
        username = data['username']
        email = data['email']
        password = data['password']

        # hashing the password
        harshed_password = bcrypt.generate_password_hash(password).decode(
            'utf-8')

        #check if user exist
        if User.check_username(username):
            return jsonify({'message': 'Username already exists'}), 409
        if User.check_email(email):
            return jsonify({'message': 'Email already exists'}), 409

        addUser = User(username=username,
                       email=email,
                       password=harshed_password)

        try:
            record = addUser.insert_record()
            # creating an acess token to enable a user access a resource
            access_token = create_access_token(identity=record.id)
            # to renew an access token
            refresh_token = create_refresh_token(identity=record.id)

            return jsonify({
                'acess_token': access_token,
                "refresh_token": refresh_token
            }), 200

            # return user_schema.jsonify(record),200
        except Exception as e:
            return jsonify({'message': 'Error adding user'}), 500

    else:
        jsonify({'message': 'JSON request expected'}), 400
コード例 #2
0
def login_user():
    # check if the data is json
    if request.is_json:
        data = request.get_json(force=True)
        username = data['username']
        password = data['password']

        # first chech if the user exist || if true check if the password check is correct
        if User.check_username(username=username):
            if User.check_password(username, password):

                user = User.fetch_by_username(username=username)
                access = create_access_token(identity=user.id)
                refresh_token = create_refresh_token(identity=user.id)

                return jsonify({
                    'acess_token': access,
                    "refresh_token": refresh_token
                })
            else:
                return jsonify({'message': 'Invalid password'}), 401
        else:
            return jsonify({'message': 'User not recognised'}), 401