예제 #1
0
def refresh():
  current_user = get_jwt_identity()

  try:
    return makeResponse(payload={'access_token': create_access_token(identity=current_user)})
  except Exception as e:
    return makeResponse(error=e)
예제 #2
0
 def post(self):
     """Refresh access token"""
     email = get_jwt_identity()
     try:
         user = User.objects.get(email=email)
     except User.DoesNotExist:
         abort(403, 'No such user, or wrong password')
     if not user.active:
         abort(403, 'No such user, or wrong password')
     access_expire = current_app.config['JWT_ACCESS_TOKEN_EXPIRES']
     access_token = create_access_token(identity=user.email)
     refresh_expire_date = datetime.strptime(
         request.cookies['refreshExpire'],
         '%Y-%m-%d %H:%M:%S.%f'
     )
     refresh_delta = refresh_expire_date - datetime.now()
     resp = jsonify(
         {
             'access': access_token,
             'accessExpire': int(access_expire.total_seconds()),
             'refreshExpire': int(refresh_delta.total_seconds()),
         }
     )
     set_access_cookies(resp, access_token)
     return resp
예제 #3
0
def change_password():
    '''Route to change password'''
    current_user = get_jwt_identity()
    data = request.get_json()
    old_password = data.get('old_password')
    new_password = data.get('new_password')
    dict_data = {'old_password': old_password, 'new_password': new_password}
    if validate.val_none(**dict_data):
        result = validate.val_none(**dict_data)
        return jsonify(result), 406
    if validate.empty(**dict_data):
        result = validate.empty(**dict_data)
        return jsonify(result), 406
    val_length = validate.pass_length(dict_data['new_password'])
    if val_length:
        return jsonify(
            {'message':
                'Password is weak! Must have atleast 8 characters'}), 406
    person = User.users.items()
    existing_username = {
        k: v for k, v in person if current_user == v['username']}
    valid_user = [v for v in existing_username.values()
                  if check_password_hash(v['password'], old_password)]
    if valid_user:
        User.change_password(current_user, data)
        return jsonify({'message': 'Reset successful'}), 200
    else:
        return jsonify(
            {'message':
                'Wrong Password. Cannot reset. Forgotten password?'}), 401
예제 #4
0
 def refresh(self):
     """
         Security endpoint for the refresh token, so we can obtain a new
         token without forcing the user to login again
     ---
     post:
       responses:
         200:
           description: Refresh Successful
           content:
             application/json:
               schema:
                 type: object
                 properties:
                   refresh_token:
                     type: string
         401:
           $ref: '#/components/responses/401'
         500:
           $ref: '#/components/responses/500'
     """
     resp = {
         API_SECURITY_REFRESH_TOKEN_KEY: create_access_token(
             identity=get_jwt_identity(), fresh=False
         )
     }
     return self.response(200, **resp)
예제 #5
0
def set_profile():
    current_user = get_jwt_identity()

    if not request.is_json:
        return jsonify({"msg": "Missing JSON in request"}), 400

    uphill_max = request.json.get("uphill_max", None)
    if uphill_max is None:
        return jsonify({"msg": "Missing uphill_max"}), 400

    downhill_max = request.json.get("downhill_max", None)
    if downhill_max is None:
        return jsonify({"msg": "Missing downhill_max"}), 400

    avoid_curbs = request.json.get("avoid_curbs", None)
    if avoid_curbs is None:
        return jsonify({"msg": "Missing avoid_curbs"}), 400

    Profile.save(
        user_id=current_user,
        uphill_max=uphill_max,
        downhill_max=downhill_max,
        avoid_curbs=avoid_curbs
    )

    return jsonify({"msg": "Successfully added/updated profile"}), 200
예제 #6
0
def refresh():
    current_user = get_jwt_identity()
    access_token = create_access_token(identity=current_user)
    ret = {
        'access_token': access_token
    }
    add_token_to_database(access_token, app.config['JWT_IDENTITY_CLAIM'])
    return jsonify(ret), 200
예제 #7
0
def deleteType(repo_id, type_id):
    current_user = get_jwt_identity()
    if PeopleManager.checkRepoPermissions(current_user, repo_id) == False:
        return makeResponse(status=401, message="You do not have permissions to access this repository!")
    try:
        return makeResponse(payload=SchemaManager.deleteType(repo_id, type_id), message="Deleted type")
    except Exception as e:
        return makeResponse(error=e)
예제 #8
0
def import_user():
    try:
        from flask_jwt_extended import get_jwt_identity
        current_identity = User.query.get(int(get_jwt_identity()))
        return current_identity
    except ImportError:
        raise ImportError(
            'User argument not passed')
예제 #9
0
파일: v1.py 프로젝트: PrahlM93/ADReset2
def get_answers():
    """
    List all the answers associated with the user.

    :rtype: flask.Response
    """
    user_ad_guid = get_jwt_identity()['guid']
    user_id = db.session.query(User.id).filter_by(ad_guid=user_ad_guid).scalar()
    return Answer.query.filter_by(user_id=user_id)
예제 #10
0
 def delete(self, name):
     current_user = get_jwt_identity()
     new_app = AppModel.query.filter_by(name=name, user_id=current_user).first()
     if new_app:
         rm_config_files(new_app)
         new_app.delete()
         return {'status': 'success'}, 200
     else:
         return {'status': 'failed'}, 404
예제 #11
0
 def get(self):
     """List blog"""
     email = get_jwt_identity()
     print(email)
     if email is None:
         query = Blog.select().where(Blog.published == True)  # noqa: E712
     else:
         query = Blog.select()
     return paginate(query, BlogSchema())
예제 #12
0
 def get(self):
     user_id = get_jwt_identity()
     items = [item.json() for item in ItemModel.find_all()]
     if user_id:
         return {'items': items}, 200
     return {
         'items': [item['name'] for item in items],
         'message': 'More data available if you log in.'
     }, 200
예제 #13
0
def user_profile():
    current_user = get_jwt_identity()
    user = User.query.get(current_user)
    osm_token = OpenStreetMapToken.query.filter_by(
        user_id=user.user_id
    ).first()

    return jsonify(
        user_id=user.user_id,
        display_name=osm_token.display_name
    )
예제 #14
0
def addType(repo_id):
    name = request.form.get('name')
    code = request.form.get('code')
    description = request.form.get('description')
    current_user = get_jwt_identity()
    if PeopleManager.checkRepoPermissions(current_user, repo_id) == False:
        return makeResponse(status=401, message="You do not have permissions to access this repository!")
    try:
        return makeResponse(message="Added type", payload=SchemaManager.addType(repo_id, name, code, description, extractRepeatingParameterBlocksFromRequest(request, 'fields')))
    except Exception as e:
        return makeResponse(error=e)
예제 #15
0
def addField(repo_id, typecode):
    name = request.form.get('name')
    code = request.form.get('code')
    fieldtype = request.form.get('type')
    description = request.form.get('description')
    current_user = get_jwt_identity()
    if PeopleManager.checkRepoPermissions(current_user, repo_id) == False:
        return makeResponse(status=401, message="You do not have permissions to access this repository!")
    try:
        return makeResponse(payload=SchemaManager.addField(repo_id, typecode, name, code, fieldtype, description), message="Added field")
    except Exception as e:
        return makeResponse(error=e)
예제 #16
0
파일: me.py 프로젝트: mekanix/tilda.center
 def get(self):
     """Get my details"""
     email = get_jwt_identity()
     try:
         user = User.get(email=email)
     except User.DoesNotExist:
         abort(404, 'User not found')
     schema = UserSchema()
     response, errors = schema.dump(user)
     if errors:
         abort(409, errors)
     return response
예제 #17
0
def addData(repo_id, typecode):
    data = request.form.get('data')
    current_user = get_jwt_identity()
    if PeopleManager.checkRepoPermissions(current_user, repo_id) == False:
        return makeResponse(status=401, message="You do not have permissions to access this repository!")
    try:
        if SchemaManager.addDataToRepo(repo_id, typecode, json.loads(data)):
            return makeResponse(payload={"msg": "Added data to repository"})
        else:
            return makeResponse(payload={"msg": "No data to add"})
    except Exception as e:
        return makeResponse(error=e)
    def post(self):
        """
        Get a new access token without requiring username and password—only the 'refresh token'
        provided in the /login endpoint.

        Note that refreshed access tokens have a `fresh=False`, which means that the user may have not
        given us their username and password for potentially a long time (if the token has been
        refreshed many times over).
        """
        current_user = get_jwt_identity()
        new_token = create_access_token(identity=current_user, fresh=False)
        return {'access_token': new_token}, 200
예제 #19
0
파일: auth.py 프로젝트: iadgov/WALKOFF
def refresh(body=None, token_info=None, user=None):
    current_user_id = get_jwt_identity()
    user = User.query.filter(User.id == current_user_id).first()
    if user is None:
        revoke_token(get_raw_jwt())
        return Problem(
            UNAUTHORIZED_ERROR,
            'Could not grant access token.',
            'User {} from refresh JWT identity could not be found.'.format(current_user_id))
    if user.active:
        return {'access_token': create_access_token(identity=current_user_id, fresh=False)}, OBJECT_CREATED
    else:
        return user_deactivated_problem
예제 #20
0
파일: v1.py 프로젝트: PrahlM93/ADReset2
def delete_answers():
    """
    Delete the user's configured answers.

    :rtype: flask.Response
    """
    user_ad_guid = get_jwt_identity()['guid']
    user_id = db.session.query(User.id).filter_by(ad_guid=user_ad_guid).scalar()
    answers = Answer.query.filter_by(user_id=user_id).all()
    for answer in answers:
        db.session.delete(answer)
    db.session.commit()
    return jsonify({}), 204
예제 #21
0
 def post(self):
     schema = BlogSchema()
     blog, errors = schema.load(current_app.api.payload)
     if errors:
         return errors, 409
     email = get_jwt_identity()
     try:
         user = User.get(email=email)
     except User.DoesNotExist:
         return {'message': 'User not found'}, 404
     blog.author = user
     blog.save()
     return schema.dump(blog)
예제 #22
0
 def get(self):
     """Get my details"""
     email = get_jwt_identity()
     try:
         user = User.objects.get(email=email)
     except User.DoesNotExist:
         abort(403, 'No such user, or wrong password')
     if not user.active:
         abort(403, 'No such user, or wrong password')
     schema = UserSchema()
     response, errors = schema.dump(user)
     if errors:
         abort(409, errors)
     return response
예제 #23
0
def get_profile():
    """Get user routing profiles. Note that while only one is currently
    stored/retrieved, this function has been written in anticipation of storing
    multiple profiles."""
    current_user = get_jwt_identity()
    profile = Profile.query.filter_by(user_id=current_user).first()
    if profile is None:
        profiles = []
    else:
        profiles = [{
            "uphill_max": profile.uphill_max,
            "downhill_max": profile.downhill_max,
            "avoid_curbs": profile.avoid_curbs
        }]
    return jsonify({"profiles": profiles}), 200
예제 #24
0
 def put(self, name):
     current_user = get_jwt_identity()
     uploaded_file = request.files['config']
     cluster_name = request.form.get('cluster')
     cluster = Cluster.query.filter_by(name=cluster_name, user_id=current_user).first()
     if not cluster:
         abort(400, "Cluster Not Found")
     try:
         create_application(name, current_user, uploaded_file, cluster)
     except ruamel.yaml.YAMLError:
         current_app.logger.error("Invalid yaml file")
         abort(400, "Invalid YAML file")
     except UnknownFormatError:
         current_app.logger.error("Invalid configuration file")
         abort(400, "Invalid YAML file")
     return {'status': 'success'}, 200
예제 #25
0
파일: v1.py 프로젝트: PrahlM93/ADReset2
def get_answer(answer_id):
    """
    List a specific answer.

    :rtype: flask.Response
    """
    user_ad_guid = get_jwt_identity()['guid']
    user_id = db.session.query(User.id).filter_by(ad_guid=user_ad_guid).scalar()
    answer = Answer.query.get(answer_id)
    if answer:
        if answer.user_id == user_id:
            return jsonify(answer.to_json(include_url=False))
        else:
            raise Unauthorized('This answer is not associated with your account')
    else:
        raise NotFound('The answer was not found')
예제 #26
0
 def post(self):
     """Create service"""
     email = get_jwt_identity()
     user = User.objects.get(email=email)
     schema = ServiceSchema()
     service, errors = schema.load(current_app.api.payload)
     if errors:
         return errors, 409
     service.user = user.pk
     try:
         service.save()
     except NotUniqueError:
         abort(409, error='Service with that name already exists')
     response, errors = schema.dump(service)
     if errors:
         return errors, 409
     return response
    def get(self):
        """
        Here we get the JWT identity, and then if the user is logged in (we were able to get an identity)
        we return the entire item list.

        Otherwise we just return the item names.

        This could be done with e.g. see orders that have been placed, but not see details about the orders
        unless the user has logged in.
        """
        user_id = get_jwt_identity()
        items = [item.json() for item in ItemModel.find_all()]
        if user_id:
            return {'items': items}, 200
        return {
            'items': [item['name'] for item in items],
            'message': 'More data available if you log in.'
        }, 200
예제 #28
0
파일: auth.py 프로젝트: iadgov/WALKOFF
 def __func():
     data = request.get_json()
     refresh_token = data.get('refresh_token', None) if data else None
     if refresh_token is None:
         return Problem(BAD_REQUEST, 'Could not logout.', 'A refresh token is required to logout.')
     decoded_refresh_token = decode_token(refresh_token)
     refresh_token_identity = decoded_refresh_token[current_app.config['JWT_IDENTITY_CLAIM']]
     user_id = get_jwt_identity()
     if user_id == refresh_token_identity:
         user = User.query.filter(User.id == user_id).first()
         if user is not None:
             user.logout()
         revoke_token(decode_token(refresh_token))
         return None, NO_CONTENT
     else:
         return Problem(
             BAD_REQUEST,
             'Could not logout.',
             'The identity of the refresh token does not match the identity of the authentication token.')
예제 #29
0
def load_data():
    '''

    This method returns the computed data, resulting from one of the following
    implemented session:

        - data_new
        - data_append
        - model_predict
        - model_generate

    Note: more information on flask-jwt partially protecting routes:

        http://flask-jwt-extended.readthedocs.io/en/latest/optional_endpoints.html

    '''

    if request.method == 'POST':
        current_user = get_jwt_identity()

        # programmatic-interface
        if request.get_json():
            # send data to brain
            loader = Load_Data(request.get_json(), current_user)
            if loader.get_session_type()['session_type']:
                session_type = loader.get_session_type()['session_type']

                if session_type == 'data_new':
                    response = loader.load_data_new()
                elif session_type == 'data_append':
                    response = loader.load_data_append()
                elif session_type == 'model_generate':
                    response = loader.load_model_generate()
                elif session_type == 'model_predict':
                    response = loader.load_model_predict()
                else:
                    response = loader.get_errors()

            else:
                response = loader.get_errors()

            # return response
            return response
예제 #30
0
def boot():
    current_user = get_jwt_identity()
    repo_id = request.form.get('repo_id')

    try:
        repo_id = int(repo_id)
    except:
        repo_id = None

    payload = {'repos': PeopleManager.getReposForPerson(current_user)}

    try:
        # Try to get first repo_id
        if repo_id is None or repo_id == 0:
            repo_id = payload['repos']['repos'][0]['id']

        payload['schema'] = {'types': SchemaManager.getTypes(repo_id)}
    except:
        pass

    try:
        return makeResponse(payload=payload)
    except Exception as e:
        return makeResponse(error=e)
def handler_user_load_error(e):
    identity = get_jwt_identity().get('id')
    return {'message': "Error loading the user {}".format(identity)}, 401
예제 #32
0
 def post(self):
     id_user = get_jwt_identity()
     requests = json.loads(request.data)
     code_activation = requests['code_activation']
     return UserModel.activation_user(id_user, code_activation)
def get_review(id: int):
    review: Review = Review.query.get(id)
    return flask.jsonify({
        "result": True,
        "data": review.to_json(with_user=get_jwt_identity())
    })
예제 #34
0
def get_projects():
    name = get_jwt_identity()
    ch = Project.query.all()
    return jsonify([p.serialize for p in ch]), 200
예제 #35
0
def get_by_id_Network(db: Graph):
    current_user = get_jwt_identity()
    result = Network.fetch_by_id(db, current_user, request.args.get("id"))

    return jsonify(result)
예제 #36
0
def execute_pipeline(project_name):
    print(project_name, flush=True)
    json_data = json.loads(str(request.data, encoding='utf-8'))
    print(json_data, type(json_data))
    content = json_data
    json_data = content["data"]
    print(json_data)

    cursor = collection.find({
        'project_name': project_name,
        'users': get_jwt_identity()
    })
    run_number = 0
    for project in cursor:
        status = "pending"
        run_number = len(project["results"]) + 1
        project["results"][str(run_number)] = {
            "result":
            "Pipeline is still running. Results will be available after execution.",
            "run_status": status,
            "scheduled_time": datetime.datetime.now(),
            "time_exection": "not available",
            "pipeline_json": json_data
        }
        collection.update({"_id": project["_id"]}, {
            "$set": {
                "results": project["results"]
            },
            "$currentDate": {
                "lastModified": True
            }
        })

    result = run_pipeline.delay(json_data)
    output = result.get(propagate=False)
    cursor = collection.find({
        'project_name': project_name,
        'users': get_jwt_identity()
    })

    for project in cursor:
        status = "success"
        project["results"][str(run_number)]["result"] = output
        project["results"][str(run_number)]["run_status"] = status

        collection.update({"_id": project["_id"]}, {
            "$set": {
                "results": project["results"]
            },
            "$currentDate": {
                "lastModified": True
            }
        })

    status = "200"
    response_output = "Pipeline scheduled successfully"
    response = flask.Response(
        json.dumps({
            "data": response_output,
            "status": status_codes[status]
        },
                   default=json_util.default))

    return response
예제 #37
0
 def post(cls):
     current_user = get_jwt_identity()
     new_token = create_access_token(identity=current_user, fresh=False)
     return {"access_token": new_token}, 200
예제 #38
0
 def post(cls):
     jti = get_raw_jwt()[
         "jti"]  # jti is "JWT ID", a unique identifier for a JWT.
     user_id = get_jwt_identity()
     BLACKLIST.add(jti)
     return {"message": USER_LOGGED_OUT.format(user_id)}, 200
예제 #39
0
def protected():
    username = get_jwt_identity()
    return jsonify({'hello': 'from {}'.format(username)}), 200
예제 #40
0
def refresh():
    current_user = get_jwt_identity()
    ret = {'access_token': create_access_token(identity=current_user)}
    return ret
예제 #41
0
def get_user(name):
    current_user = get_jwt_identity()
    user = mongo.db.users.find_one({'name': name})
    del user["_id"]
    del user["password"]
    return user
예제 #42
0
def refresh():
    current_user = get_jwt_identity()
    new_token = create_access_token(identity=current_user)
    return send_json({'token': new_token}, 200)
예제 #43
0
def _stories():
    '''
    Returns a list of stories depending on the query parameters.
    - from/to query parameters: the user specifies from which time frame he/she
        wants the stories;
    - theme query parameter: the user specifies the theme of the dice set used in the
        stories;
    - q parameters: the user specifies a word that must be present in the stories.
    - user_id: id of the owner of the stories
    Raises:
        ValueError: the date format is not valid
    Returns:
        200 -> the list of the stories in the chosen time frame
        400 -> invalid parameters
        404 -> no stories are present
    '''
    stories = Story.query.filter_by(deleted=False)

    user_id = request.args.get('user_id')
    if user_id is not None:
        current_user = jwt.get_jwt_identity()
        if current_user and current_user['id'] == int(user_id):
            stories = stories.filter_by(author_id=user_id)
        else:
            stories = stories.filter_by(is_draft=False, author_id=user_id)
    else:
        stories = stories.filter_by(is_draft=False)

    stories = stories.order_by(Story.date.desc())

    if stories.count() == 0:
        return errors.response('211')
    else:
        # check for query parameters
        if len(request.args) != 0:

            #becomes true only if at least one correct query param is found
            flag = False

            from_date = request.args.get('from')
            to_date = request.args.get('to')
            theme = request.args.get('theme')
            text = request.args.get('text')

            # check if the query parameters from_date exists
            if from_date is not None:
                if to_date is None:
                    to_date = str((dt.datetime.now() + dt.timedelta(days=1)).date())

                flag = True

                #datetime values
                from_dt = None
                to_dt = None

                # check if the values are valid
                try:
                    from_dt = dt.datetime.strptime(from_date, '%Y-%m-%d')
                    to_dt = dt.datetime.strptime(to_date, '%Y-%m-%d')

                except ValueError:
                    return errors.response('212')
                else:  # successful try!
                    # checks for edge cases
                    if from_dt == to_dt:
                        to_dt = from_dt + dt.timedelta(days=1)

                    if from_dt > to_dt:
                        return errors.response('213')
                    else:
                        # query the database with the given values
                        stories = stories.group_by(Story.date) \
                            .having(Story.date >= from_dt) \
                            .having(Story.date <= to_dt)
                        if stories.count() == 0:
                            return errors.response('214')

            #check for theme query param
            if theme is not None:
                flag = True

                t_delta = dt.datetime.now() - dt.timedelta(days=5)
                stories = stories.filter(Story.date >= t_delta)
                stories = stories.filter(Story.theme == theme)

            #check for text query param
            if text is not None:
                flag = True

                words = text.split(' ')
                for word in words:
                    # search for single words, case insensitive
                    stories = stories.filter(Story.text.ilike(f'%{word}%'))

            #check for user_id param
            if user_id is not None:
                flag = True


            if not flag:
                return errors.response('235')

            #check if the sum of all the filtering is not zero
            if stories.count() == 0 or not flag:
                return errors.response('215')

    return make_response(jsonify([s.serialize() for s in stories.all()]), 200)
예제 #44
0
 def get(self):
     print(request.headers)
     username = get_jwt_identity()
     return UserModel.get_one_user(str(username))
예제 #45
0
def upload_file(project_name):
    print(request.data)
    print(request.files)
    print(request.method)
    if request.method == 'OPTIONS' or request.method == 'POST':

        if len(request.files) > 0:
            file = request.files['file']
            filename = secure_filename(file.filename)

            project_path = os.path.join(app.config['UPLOAD_FOLDER'],
                                        project_name)
            file_path = os.path.join(app.config['UPLOAD_FOLDER'], project_name,
                                     filename)

            if (os.path.isdir(project_path)):
                file.save(file_path)
            else:
                os.makedirs(project_path)
                file.save(file_path)

            cursor = collection.find({
                'project_name': project_name,
                'users': get_jwt_identity()
            })

            for project in cursor:
                print(project)
                status = "400"
                if (filename in project["files"]):
                    status = "200"
                    response = flask.Response(
                        json.dumps(
                            {
                                "data": "File with same name already exists",
                                "status": status_codes[status]
                            },
                            default=json_util.default))

                    return response
                else:

                    # if(file_extension in IMAGE_EXTENSIONS):
                    #     project["files"]["images"][filename] = {
                    #                     "file_name": filename,
                    #                     "file_path": file_path
                    #                 }
                    # elif(file_extension in DOCUMENT_EXTENSIONS):
                    #     project["files"]["documents"][filename] = {
                    #                     "file_name": filename,
                    #                     "file_path": file_path
                    #                 }
                    # else:
                    #     status = "400"
                    #     response = flask.Response(json.dumps({"data":"Invalid File Type",
                    #         "status": status_codes[status]},
                    #         default=json_util.default))
                    #
                    #     return response
                    project["files"][filename] = {
                        "file_name": filename,
                        "file_path": file_path
                    }

                    collection.update({"_id": project["_id"]}, {
                        "$set": {
                            "files": project["files"]
                        },
                        "$currentDate": {
                            "lastModified": True
                        }
                    })
                    status = "200"
            response = flask.Response(
                json.dumps(
                    {
                        "data": os.path.join(app.config['UPLOAD_FOLDER'],
                                             filename),
                        "status": status_codes[status]
                    },
                    default=json_util.default))

            return response
    return "Nothing happend"
예제 #46
0
def get_refreshtoken():
    uuid = get_jwt_identity()
    user = User.query.filter_by(uuid=uuid).first()
    access_token = create_access_token(identity=user, fresh=False)
    return jsonify(token=access_token, user=user.to_dict())
예제 #47
0
def protected():
    data = request.json.get('data', None)
    # Access the identity of the current user with get_jwt_identity
    current_user = get_jwt_identity()
    print(current_user, flush=True)
    return jsonify(data=data, logged_in_as=current_user), 200
예제 #48
0
    def post(self):
        if not WhiteTokenModel.is_jti_whitelisted(get_raw_jwt()["jti"]):
            return {'message': 'Not logged in'}, 205

        current_user = get_jwt_identity()
        data = friend_edit_parser.parse_args()

        if not data["friend_name"]:
            return {'message': 'Friend name is required'}, 203

        friend_user = User.find_by_username(data["friend_name"])
        if friend_user == None:
            return {"message": "Friends user object not found"}, 204

        if not data["status"]:
            return {'message': 'Status is required'}, 203

        try:
            if data["status"] == "send":
                friend_object = Friends.find_by_uid_and_fid(
                    current_user, friend_user.user_id)
                if friend_object != None:
                    return {"message": "Error: Already on list"}, 203
                friends_friend_object = Friends.find_by_uid_and_fid(
                    friend_user.user_id, current_user)
                if friends_friend_object != None:
                    return {"message": "Error: Already on friends list"}, 203

                if friend_user.user_id == current_user:
                    return {
                        "message": "Error: Can't send a request to yourself"
                    }, 203

                own_friend_entry = Friends(user_id=current_user,
                                           friend_id=friend_user.user_id,
                                           friend_status="sent")
                friends_friend_entry = Friends(user_id=friend_user.user_id,
                                               friend_id=current_user,
                                               friend_status="received")
                own_friend_entry.save_to_db()
                friends_friend_entry.save_to_db()
                return {'message': "Friend request sent."}, 201

            if data["status"] == "accept":
                friend_object = Friends.find_by_uid_and_fid(
                    current_user, friend_user.user_id)
                if friend_object == None:
                    return {"message": "Friend object not found"}, 204
                friends_friend_object = Friends.find_by_uid_and_fid(
                    friend_user.user_id, current_user)
                if friends_friend_object == None:
                    return {"message": "Friends friend object not found"}, 204

                if friend_object.friend_status != "received" or friends_friend_object.friend_status != "sent":
                    return {
                        "message": "Can't accept because there is no request."
                    }, 203

                friend_object.friend_status = "accepted"
                friends_friend_object.friend_status = "accepted"

                friend_object.commit()
                friends_friend_object.commit()

                return {'message': "Friend request accepted."}, 201

            if data["status"] == "delete":
                friend_object = Friends.find_by_uid_and_fid(
                    current_user, friend_user.user_id)
                if friend_object == None:
                    return {"message": "Friend object not found"}, 204
                friends_friend_object = Friends.find_by_uid_and_fid(
                    friend_user.user_id, current_user)
                if friends_friend_object == None:
                    return {"message": "Friends friend object not found"}, 204

                friend_object.delete_from_db()
                friends_friend_object.delete_from_db()

                return {
                    'message':
                    'Friend entry for friend {} was deleted'.format(
                        friend_user.user_name),
                }, 201

            return {'message': "Invalid status."}, 201
        except Exception as err:
            return {'message': 'Something went wrong', "error": str(err)}, 500
예제 #49
0
def protected():
    claims = get_jwt_identity()
    print(claims)
    return {"ok": 1}
예제 #50
0
 def wrap(*args, **kwargs):
     current_user = get_jwt_identity()
     if kwargs['username'] != current_user:
         return send_json({'error': 'Unauthorized access1'}, 400)
     return f(*args, **kwargs)
예제 #51
0
def delete_course(db: Graph):
    dataDict = json.loads(request.data)
    current_user = get_jwt_identity()
    Course.delete_by_user(db, current_user, dataDict["id"])
    return jsonify({"sucess": True, "message": "Rede removida."}), 202
예제 #52
0
파일: device.py 프로젝트: katsel/cnaas-nms
    def post(self):
        """ Start sync of device(s) """
        json_data = request.get_json()
        # default args
        kwargs: dict = {
            'dry_run': True,
            'auto_push': False,
            'force': False,
            'resync': False
        }

        if 'dry_run' in json_data and isinstance(json_data['dry_run'], bool) \
                and not json_data['dry_run']:
            kwargs['dry_run'] = False
        if 'force' in json_data and isinstance(json_data['force'], bool):
            kwargs['force'] = json_data['force']
        if 'auto_push' in json_data and isinstance(json_data['auto_push'], bool):
            kwargs['auto_push'] = json_data['auto_push']
        if 'resync' in json_data and isinstance(json_data['resync'], bool):
            kwargs['resync'] = json_data['resync']
        if 'comment' in json_data and isinstance(json_data['comment'], str):
            kwargs['job_comment'] = json_data['comment']
        if 'ticket_ref' in json_data and isinstance(json_data['ticket_ref'], str):
            kwargs['job_ticket_ref'] = json_data['ticket_ref']

        total_count: Optional[int] = None
        nr = cnaas_init()

        if 'hostname' in json_data:
            hostname = str(json_data['hostname'])
            if not Device.valid_hostname(hostname):
                return empty_result(
                    status='error',
                    data=f"Hostname '{hostname}' is not a valid hostname"
                ), 400
            _, total_count, _ = inventory_selector(nr, hostname=hostname)
            if total_count != 1:
                return empty_result(
                    status='error',
                    data=f"Hostname '{hostname}' not found or is not a managed device"
                ), 400
            kwargs['hostname'] = hostname
            what = hostname
        elif 'device_type' in json_data:
            devtype_str = str(json_data['device_type']).upper()
            if DeviceType.has_name(devtype_str):
                kwargs['device_type'] = devtype_str
            else:
                return empty_result(
                    status='error',
                    data=f"Invalid device type '{json_data['device_type']}' specified"
                ), 400
            what = f"{json_data['device_type']} devices"
            _, total_count, _ = inventory_selector(nr, resync=kwargs['resync'],
                                                   device_type=devtype_str)
        elif 'group' in json_data:
            group_name = str(json_data['group'])
            if group_name not in get_groups():
                return empty_result(status='error', data='Could not find a group with name {}'.format(group_name))
            kwargs['group'] = group_name
            what = 'group {}'.format(group_name)
            _, total_count, _ = inventory_selector(nr, resync=kwargs['resync'],
                                                   group=group_name)
        elif 'all' in json_data and isinstance(json_data['all'], bool) and json_data['all']:
            what = "all devices"
            _, total_count, _ = inventory_selector(nr, resync=kwargs['resync'])
        else:
            return empty_result(
                status='error',
                data=f"No devices to synchronize was specified"
            ), 400

        scheduler = Scheduler()
        job_id = scheduler.add_onetime_job(
            'cnaas_nms.confpush.sync_devices:sync_devices',
            when=1,
            scheduled_by=get_jwt_identity(),
            kwargs=kwargs)

        res = empty_result(data=f"Scheduled job to synchronize {what}")
        res['job_id'] = job_id

        resp = make_response(json.dumps(res), 200)
        if total_count:
            resp.headers['X-Total-Count'] = total_count
        resp.headers['Content-Type'] = "application/json"
        return resp
예제 #53
0
def add_project_user(id):
    # Fetch form data
    projectDetails = request.get_json()
    user = projectDetails.get('user')
    role = projectDetails.get('role')

    # Check if all data is supplied
    if user is None:
        return jsonify({"error": "Project user not specified"}), 400
    if role is None:
        return jsonify({"error": "Project user role not specified"}), 400
    if role not in allowed_projectUser_states:
        return jsonify({"error": "Project user role not a legal value"}), 400

    # Check if project actually exists
    project = database.getProjectByID(id)
    if project is None:
        return jsonify({"error": "Specified project does not exist"})

    # Check if you have permission to add a user to this project
    projectVisibility = project['projectVisibility']
    userRole = function.getProjectUserRole(get_jwt_identity(), id)
    validTarget = function.getProjectUserRole(role, id)
    print(type(user))
    print(type(str(get_jwt_identity())))
    print(user)
    print(get_jwt_identity())
    if validTarget is None:
        if projectVisibility == 'PUBLIC':
            if role not in ['INVITED', 'USER']:
                return jsonify(
                    {"error": "May only invite or add user on public project"})
        elif projectVisibility == 'RESTRICTED':
            if role == 'INVITED':
                if not function.isProjectAdmin(userRole):
                    return jsonify({
                        "error":
                        "Only admins can invite users on restricted projects"
                    })
            elif role == 'PENDING':
                if user != str(get_jwt_identity()):
                    return jsonify({
                        "error":
                        "Only a user can request membership for himself"
                    })
            else:
                return jsonify({
                    "error":
                    "May only invite or request user on restricted project"
                })
        elif projectVisibility == 'PRIVATE':
            if role == 'INVITED':
                if not function.isProjectAdmin(userRole):
                    return jsonify({
                        "error":
                        "Only admins can invite users on private projects"
                    })
            else:
                return jsonify({
                    "error":
                    "You may only invite users for private projects"
                })
    else:
        return jsonify({"error": "User already has a project role"})

    projectUser = database.addProjectUser(user, id, role)
    return jsonify(projectUser), 201
예제 #54
0
파일: device.py 프로젝트: katsel/cnaas-nms
    def post(self, device_id: int):
        """ Init a device """
        if not isinstance(device_id, int):
            return empty_result(status='error', data="'device_id' must be an integer"), 400

        json_data = request.get_json()

        if 'hostname' not in json_data:
            return empty_result(status='error', data="POST data must include new 'hostname'"), 400
        else:
            if not Device.valid_hostname(json_data['hostname']):
                return empty_result(
                    status='error',
                    data='Provided hostname is not valid'), 400
            else:
                new_hostname = json_data['hostname']

        if 'device_type' not in json_data:
            return empty_result(status='error', data="POST data must include 'device_type'"), 400
        else:
            try:
                device_type = str(json_data['device_type']).upper()
            except Exception:
                return empty_result(status='error', data="'device_type' must be a string"), 400

            if not DeviceType.has_name(device_type):
                return empty_result(status='error', data="Invalid 'device_type' provided"), 400

        job_kwargs = {
            'device_id': device_id,
            'new_hostname': new_hostname
        }

        if 'mlag_peer_id' in json_data or 'mlag_peer_hostname' in json_data:
            if 'mlag_peer_id' not in json_data or 'mlag_peer_hostname' not in json_data:
                return empty_result(
                    status='error',
                    data="Both 'mlag_peer_id' and 'mlag_peer_hostname' must be specified"), 400
            if not isinstance(json_data['mlag_peer_id'], int):
                return empty_result(status='error', data="'mlag_peer_id' must be an integer"), 400
            if not Device.valid_hostname(json_data['mlag_peer_hostname']):
                return empty_result(
                    status='error',
                    data="Provided 'mlag_peer_hostname' is not valid"), 400
            job_kwargs['mlag_peer_id'] = json_data['mlag_peer_id']
            job_kwargs['mlag_peer_new_hostname'] = json_data['mlag_peer_hostname']

        if device_type == DeviceType.ACCESS.name:
            scheduler = Scheduler()
            job_id = scheduler.add_onetime_job(
                'cnaas_nms.confpush.init_device:init_access_device_step1',
                when=1,
                scheduled_by=get_jwt_identity(),
                kwargs=job_kwargs)
        else:
            return empty_result(status='error', data="Unsupported 'device_type' provided"), 400

        res = empty_result(data=f"Scheduled job to initialize device_id { device_id }")
        res['job_id'] = job_id

        return res
예제 #55
0
 def get(self):
     id_user = get_jwt_identity()
     return UserModel.Getuser(id_user)
예제 #56
0
 def post(self):
     verify_jwt_in_request()
     claims = get_jwt_claims()
     claims = marshal(claims, Seller.jwt_claim_fields)
     identity = get_jwt_identity()
     return {'claims': claims, 'identity': identity}, 200
예제 #57
0
 def post(self):
     id_user = get_jwt_identity()
     get_number = request.form['number']
     return UserModel.OTPuser(get_number, id_user)
예제 #58
0
def protected():
    # Access the identity of the current user with get_jwt_identity
    current_user = get_jwt_identity()
    return jsonify(logged_in_as=current_user), 200
예제 #59
0
 def post(self):
     current_user = get_jwt_identity()
     access_token = create_access_token(current_user)
     return {'access_token': access_token}
예제 #60
0
def _validate_draft_story(storyid):
    '''
    Validate a draft story, given the new text.
    If the story is already completed, this call does nothing.
    Otherwise it checks if the story satisfies all the requirements.

    Returns:
        200 -> story validated and committed to the database
        400 -> story already valid or failed validation
        403 -> the story doesn't belong to the current user
        404 -> story not found
        410 -> story deleted
        500 -> db commit failed
    '''

    #check if the new text is provided
    data = json.loads(str(request.data, 'utf8'))
    if 'text' not in data:
        return errors.response('243')

    s = Story.query.get(storyid)

    if s is None:
        return errors.response('232')

    if s.deleted:
        return errors.response('233')

    current_user = jwt.get_jwt_identity()
    if s.author_id != current_user['id']:
        return errors.response('245') #unauthorized request


    draft = data.get('draft')
    if draft is None:
        draft = False
    else:
        if draft == '1' or draft == 'True':
            draft = True
        elif draft == '0' or draft == 'False':
            draft = False
        else:
            return errors.response('231')

    #if the story is a draft, check if it is valid
    if s.is_draft:
        try:
            #modify story body
            s.text = data['text']

            #validate
            if not draft:
                _check_story(s.dice_set, s.text)
                s.is_draft = False

            db.session.commit()

            #telegram
            # celery.send_task('tasks.task_request_telegram', args=[s.serialize()])

            return jsonify({'code': 200, 'message': f'Story {storyid} has been succesfully edited'}), 200
        except NotValidStoryError:
            db.session.rollback()
            return errors.response('242')
        except SQLAlchemyError as e:
            print(e)
            db.session.rollback()
            return errors.response('246')
    else:
        return errors.response('241')