def create_user():
    """
    Requires either a CSRF token shared between the UI and the Services OR an
    authenticated request from a valid user.
    """
    csrf_token = request.headers.get("X-Csrf-Token")
    if not csrf_token or csrf_token != current_app.config["UI_API_KEY"]:
        auth = False
        if request.authorization:
            auth = verify_auth(request.authorization["username"], request.authorization["password"])
        if not auth:
            return jsonify(error="Invalid Authentication"), 401
    data = json.loads(request.data)
    # add user to db
    role_mapping = {
        1: ["annotate", "asset_manager", "user_admin", "redmine"],  # Administrator
        2: ["annotate", "asset_manager"],  # Marine Operator
        3: [],  # Science User
    }
    role_scopes = role_mapping[data["role_id"]]
    valid_scopes = UserScope.query.filter(UserScope.scope_name.in_(role_scopes)).all()

    try:
        new_user = User.from_json(data)
        new_user.scopes = valid_scopes
        new_user.active = True
        db.session.add(new_user)
        db.session.commit()
    except Exception as e:
        return jsonify(error=e.message), 409

    try:
        redmine = redmine_login()
        organization = new_user.organization.organization_name
        tmp = dt.datetime.now() + dt.timedelta(days=1)
        due_date = dt.datetime.strftime(tmp, "%Y-%m-%d")
        issue = redmine.issue.new()
        issue.project_id = current_app.config["REDMINE_PROJECT_ID"]
        issue.subject = "New User Registration for OOI UI: %s, %s" % (new_user.first_name, new_user.last_name)
        issue.description = (
            "A new user has requested access to the OOI User Interface. Please review the application for %s, their role in the organization %s is %s and email address is %s"
            % (new_user.first_name, organization, new_user.role, new_user.email)
        )
        issue.priority_id = 1
        issue.due_date = due_date
        # Get the list of ticker Trackers
        trackers = list(redmine.tracker.all())
        # Find the REDMINE_TRACKER (like 'Support') and get the id
        # This make a difference for field validation and proper tracker assignment
        config_redmine_tracker = current_app.config["REDMINE_TRACKER"]
        tracker_id = [tracker.id for tracker in trackers if tracker.name == config_redmine_tracker][0]
        issue.tracker_id = tracker_id
        issue.save()
    except Exception as e:
        current_app.logger.exception("Failed to generate redmine issue for new user")
        return jsonify(error=e.message), 409

    return jsonify(new_user.to_json()), 201
Beispiel #2
0
def create_user():
    '''
    Requires either a CSRF token shared between the UI and the Services OR an
    authenticated request from a valid user.
    '''
    csrf_token = request.headers.get('X-Csrf-Token')
    if not csrf_token or csrf_token != current_app.config['UI_API_KEY']:
        auth = False
        if request.authorization:
            auth = verify_auth(request.authorization['username'],
                               request.authorization['password'])
        if not auth:
            return jsonify(error="Invalid Authentication"), 401
    data = json.loads(request.data)
    #add user to db
    try:
        new_user = User.from_json(data)
        db.session.add(new_user)
        db.session.commit()
    except ValidationError as e:
        return jsonify(error=e.message), 409

    #add redmine ticket
    key = current_app.config['REDMINE_KEY']
    redmine = Redmine(current_app.config['REDMINE_URL'],
                      key=key,
                      requests={'verify': False})
    issue = redmine.issue.new()
    issue.project_id = 'ooi-ui-api-testing'
    issue.subject = new_user.first_name + ' ' + new_user.last_name + ' is requesting access to Redmine.'
    issue.description = 'The user email is ' + new_user.email + '.  The new request is for the role ' + new_user.role + ' and for the ' + data[
        'organization'] + ' organization.  Please enable this OOI account.'
    issue.priority_id = 1
    issue.save()

    # rm = requests.post('/redmine/ticket',
    #     headers={
    #         'Authorization': 'Basic ' + b64encode(('admin:test').encode('utf-8')).decode('utf-8'),
    #         'Accept': 'application/json',
    #         'Content-Type': 'application/json'
    #     },
    #     data=json.dumps({'project_id': 'ooi-ui-api-testing',
    #                'subject': new_user.first_name+' ' + new_user.last_name + ' is requesting access to Redmine.',
    #                'description': 'The user email is '+ new_user.email + '.  The new request is for the role '+new_user.role +' and for the '+data['organization'] +' organization.',
    #                'priority_id': 1}))
    #                # 'assigned_to_id': 1}))
    # response_rm = rm.status_code

    #except:
    #   return "Redmine Error", 409

    return jsonify(new_user.to_json()), 201
Beispiel #3
0
def create_user():
    '''
    Requires either a CSRF token shared between the UI and the Services OR an
    authenticated request from a valid user.
    '''
    csrf_token = request.headers.get('X-Csrf-Token')
    if not csrf_token or csrf_token != current_app.config['UI_API_KEY']:
        auth = False
        if request.authorization:
            auth = verify_auth(request.authorization['username'],
                               request.authorization['password'])
        if not auth:
            return jsonify(error="Invalid Authentication"), 401
    data = json.loads(request.data)
    #add user to db
    role_mapping = {
        1: ['annotate', 'asset_manager', 'user_admin',
            'redmine'],  # Administrator
        2: ['annotate', 'asset_manager'],  # Marine Operator
        3: []  # Science User
    }
    role_scopes = role_mapping[data['role_id']]
    valid_scopes = UserScope.query.filter(
        UserScope.scope_name.in_(role_scopes)).all()

    try:
        new_user = User.from_json(data)
        new_user.scopes = valid_scopes
        db.session.add(new_user)
        db.session.commit()
    except Exception as e:
        return jsonify(error=e.message), 409

    try:
        redmine = redmine_login()
        organization = new_user.organization.organization_name
        issue = redmine.issue.new()
        issue.project_id = current_app.config['REDMINE_PROJECT_ID']
        issue.subject = 'New User Registration for OOI UI: %s, %s' % (
            new_user.first_name, new_user.last_name)
        issue.description = 'A new user has requested access to the OOI User Interface. Please review the application for %s, their role in the organization %s is %s and email address is %s' % (
            new_user.first_name, organization, new_user.role, new_user.email)
        issue.priority_id = 1
        issue.save()
    except:
        current_app.logger.exception(
            "Failed to generate redmine issue for new user")

    return jsonify(new_user.to_json()), 201
Beispiel #4
0
def create_user():
    '''
    Requires either a CSRF token shared between the UI and the Services OR an
    authenticated request from a valid user.
    '''
    csrf_token = request.headers.get('X-Csrf-Token')
    if not csrf_token or csrf_token != current_app.config['UI_API_KEY']:
        auth = False
        if request.authorization:
            auth = verify_auth(request.authorization['username'], request.authorization['password'])
        if not auth:
            return jsonify(error="Invalid Authentication"), 401
    data = json.loads(request.data)
    #add user to db
    role_mapping = {
        1: ['annotate', 'asset_manager', 'user_admin', 'redmine'], # Administrator
        2: ['annotate', 'asset_manager'],                          # Marine Operator
        3: []                                                      # Science User
    }
    role_scopes = role_mapping[data['role_id']]
    valid_scopes = UserScope.query.filter(UserScope.scope_name.in_(role_scopes)).all()

    try:
        new_user = User.from_json(data)
        new_user.scopes = valid_scopes
        db.session.add(new_user)
        db.session.commit()
    except Exception as e:
        return jsonify(error=e.message), 409

    try:
        redmine = redmine_login()
        organization = new_user.organization.organization_name
        issue = redmine.issue.new()
        issue.project_id = current_app.config['REDMINE_PROJECT_ID']
        issue.subject = 'New User Registration for OOI UI: %s, %s' % (new_user.first_name, new_user.last_name)
        issue.description = 'A new user has requested access to the OOI User Interface. Please review the application for %s, their role in the organization %s is %s and email address is %s' % (new_user.first_name, organization, new_user.role, new_user.email)
        issue.priority_id = 1
        issue.save()
    except:
        current_app.logger.exception("Failed to generate redmine issue for new user")

    return jsonify(new_user.to_json()), 201