Ejemplo n.º 1
0
 public Neo4jHandler(string uri, string user, string password)
 {
     //建立基礎連線
     _driver = GraphDatabase.Driver(uri, AuthTokens.Basic(user, password));
 }
Ejemplo n.º 2
0
 public IDriver CreateDriverWithCustomizedConnectionTimeout(string uri, string user, string password)
 {
     return(GraphDatabase.Driver(uri, AuthTokens.Basic(user, password),
                                 o => o.WithConnectionTimeout(TimeSpan.FromSeconds(15))));
 }
Ejemplo n.º 3
0
 public IDriver CreateDriverWithCustomizedTrustStrategy(string uri, string user, string password)
 {
     return(GraphDatabase.Driver(uri, AuthTokens.Basic(user, password),
                                 o => o.WithTrustManager(TrustManager.CreateInsecure())));
 }
Ejemplo n.º 4
0
 public Neo4jRelationshipApiService(string serveruri, string username, string password)
 {
     driver = GraphDatabase.Driver(serveruri, AuthTokens.Basic(username, password));
 }
Ejemplo n.º 5
0
        public async Task Should_only_remove_one_node()
        {
            var builder = new WebHostBuilder().UseStartup(typeof(Startup));

            var server = new TestServer(builder);

            var client = server.CreateClient();

            using (var driver = GraphDatabase.Driver("bolt://hobby-ilkndjgcjildgbkeejcngapl.dbs.graphenedb.com:24786", AuthTokens.Basic("neo4j", "b.jSzmmKQQak2w.adk8es1bWYoBSXUt")))
                using (var session = driver.Session())
                {
                    var beforeCountResult = session.Run(
                        @"
                        MATCH (n)
                        RETURN count(n) as count
                    ");
                    var beforeCount = beforeCountResult.First()["count"].As <int>();

                    var result = await client.PostAsync("/api/remove", new StringContent(""));

                    var afterCountResult = session.Run(
                        @"
                        MATCH (n)
                        RETURN count(n) as count
                    ");
                    var afterCount = afterCountResult.First()["count"].As <int>();

                    afterCount.ShouldBe(beforeCount - 1);
                }
        }
Ejemplo n.º 6
0
 public DriverLifecycleExample(string uri, string user, string password)
 {
     Driver = GraphDatabase.Driver(uri, AuthTokens.Basic(user, password));
 }
Ejemplo n.º 7
0
 private static IAuthToken GetAuthToken(string username, string password, string realm)
 {
     return(string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password)
         ? AuthTokens.None
         : AuthTokens.Basic(username, password, realm));
 }
Ejemplo n.º 8
0
 public Neo4JConnector(string uri, string user, string password)
 {
     dbDriver = GraphDatabase.Driver(uri, AuthTokens.Basic(user, password));
 }
Ejemplo n.º 9
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var connectionURI = Configuration["DatabaseConfigurations:BoltURI"];
            var username      = Configuration["DatabaseConfigurations:User"];
            var password      = Configuration["DatabaseConfigurations:Password"];

            services.AddSingleton <IDriver>(provider => GraphDatabase.Driver(connectionURI, AuthTokens.Basic(username, password)));
            services.AddScoped <IStudentRepository, StudentRepository>();
            services.AddScoped <ISubjectRepository, SubjectRepository>();
            services.AddScoped <ICourseRepository, CourseRepository>();
            services.AddScoped <ITeacherRepository, TeacherRepository>();
            services.AddScoped <IUserRepository, UserRepository>();

            services.AddTransient <IUserService, UserService>();
            services.AddTransient <IStudentService, StudentService>();
            services.AddTransient <ISubjectService, SubjectService>();
            services.AddTransient <IAuthenticationService, AuthenticationService>();
            services.AddTransient <ICourseService, CourseService>();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version     = "v1",
                    Title       = "Study Groups API",
                    Description = " - "
                });
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
                c.DescribeAllEnumsAsStrings();
            });

            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                                  builder => builder.
                                  //WithOrigins(Configuration["CORSConfigurations:AllowedOrigin"])
                                  AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  .AllowCredentials());
            });

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(opt =>
            {
                opt.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = Configuration["ValidClientURI"],
                    ValidAudience    = Configuration["ValidClientURI"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWTSecretKey"]))
                };
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
Ejemplo n.º 10
0
 public static IDriver MakeDriver(string url)
 {
     return(GraphDatabase.Driver(url, AuthTokens.Basic("app", "app")));
 }
Ejemplo n.º 11
0
        public List <Route> getRoutes(List <Connections> connections, string selectedTravelDay, string selectedTravelTime)
        {
            selectedTravelDay = validateWeekDay(selectedTravelDay);

            using (var driver = GraphDatabase.Driver("bolt://localhost:7687", AuthTokens.Basic("neo4j", "password")))
                using (var session = driver.Session())
                {
                    //list of shortest routes (least bus changes)
                    List <Route> routes = new List <Route>();

                    foreach (var connection in connections)
                    {
                        //Neo4j query - receive all possible routes between bus stop A to bus stop B
                        var result = session.Run("MATCH p=shortestPath((a:BusStop {refNo:\"" + connection.busStopA + "\"})-[r:RELATION*]->(b:BusStop {refNo:\"" + connection.busStopB + "\"})) return extract(n in nodes(p)" +
                                                 " | n) AS nodes, EXTRACT (rel in rels(p) | rel) AS relations");

                        //all bus stops names within route
                        List <string> busStopsName = new List <string>();
                        //all bus stops refs within route
                        List <string> busStopsRef = new List <string>();
                        //cities where the bus stops are
                        List <string> busStopCity = new List <string>();
                        //all possible relations
                        List <Relation> relations = new List <Relation>();

                        //extracts data from Neo4j query result, that is relations, bus name, bus ref and bus city
                        extractRelations(result, relations, busStopsName, busStopsRef, busStopCity);

                        if (!busStopsRef.Any())
                        {
                            continue;
                        }

                        List <List <string> > allPaths = new List <List <string> >();

                        //create all posible paths
                        getAllPaths(allPaths, relations);


                        //* the purpose of the below code is to select the shortest path (one with least bus change)
                        //calculating shortes connection from all available
                        List <int> changes = new List <int>();
                        calculateLeastChangePath(changes, allPaths);

                        //selecting route with least changes
                        int shortestPath = changes.IndexOf(changes.Min());

                        //get arrival time for each stop
                        bool isValidRoute = true;
                        getBusArrivalTimes(shortestPath, ref isValidRoute, allPaths, selectedTravelDay, selectedTravelTime, busStopsRef);

                        //adding shortest route to list i
                        if (isValidRoute)
                        {
                            var coordinates = getBusStopsCoordinates(busStopsRef, busStopCity);
                            if (coordinates.Count != busStopsName.Count)
                            {
                                continue;
                            }

                            routes.Add(new Route
                            {
                                busChanges      = changes.Min(),
                                busNumber       = new List <string>(allPaths[shortestPath]),
                                busStopNameList = new List <string>(busStopsName),
                                busStopCity     = new List <string>(busStopCity),
                                busStopRefList  = new List <string>(busStopsRef),
                                coordinates     = new List <string>(coordinates),
                                arrivalTime     = new List <string>(arrivalTimeList)
                            });
                        }
                    }
                    return(routes);
                }
        }
 public SymBotRSAAuth(SymConfig config)
 {
     this.symConfig  = config;
     this.authTokens = new AuthTokens();
 }
Ejemplo n.º 13
0
 public GraphAdapter(string uri, string user, string password)
 {
     _driver = GraphDatabase.Driver(uri, AuthTokens.Basic(user, password));
 }
Ejemplo n.º 14
0
 private neo4jManager(string uri, string user, string password)
 {
     _driver = GraphDatabase.Driver(uri, AuthTokens.Basic(user, password));
 }
 public DriverIntroductionExample(string uri, string user, string password)
 {
     _driver = GraphDatabase.Driver(uri, AuthTokens.Basic(user, password));
 }
Ejemplo n.º 16
0
        public static Task CreateCFDActionTask(
            AuthTokens tokens,
            string url,
            string path,
            string parentId,
            CFDMesh meshData,
            CFDSolution solution,
            int geometryFileSize,
            Dictionary <string, object> overrides,
            bool create
            )
        {
            if (overrides != null && overrides.ContainsKey("keep_mesh") && (bool)overrides["keep_mesh"])
            {
                create = false;
            }

            var actionTask = new GenericViewSet <Task>(
                tokens,
                url,
                path
                ).GetOrCreate(
                new Dictionary <string, object>
            {
                { "name", "Actions" },
                { "parent", parentId }
            },
                new Dictionary <string, object>
            {
                {
                    "config", new Dictionary <string, object>
                    {
                        { "task_type", "magpy" },
                        { "cmd", "cfd.io.tasks.write_mesh" },
                        { "base_mesh", meshData.BaseMesh },
                        { "snappyhex_mesh", meshData.SnappyHexMesh.ToDict() },
                    }
                }
            },
                create
                );

            // Then Action Task to create CFD files
            if (create)
            {
                if (solution != null && geometryFileSize > 0)
                {
                    new GenericViewSet <Task>(
                        tokens,
                        url,
                        path
                        ).Update(
                        actionTask.UID,
                        new Dictionary <string, object>
                    {
                        { "name", "Actions" },
                        { "status", "pending" },
                        {
                            "config", new Dictionary <string, object>
                            {
                                { "task_type", "magpy" },
                                { "cmd", "cfd.io.tasks.write_solution" },
                                { "solution", solution }
                            }
                        }
                    }
                        );
                }
                else
                {
                    // TODO - We need to handle if there is no solution given. Then we need to create the controlDict so people can do the meshing.
                }
            }

            return(actionTask);
        }
Ejemplo n.º 17
0
        public void GivenADriverIsConfiguredWithAuthEnabledAndTheWrongPasswordIsProvided()
        {
            var driverWithIncorrectPassword = GraphDatabase.Driver(TckHooks.Uri, AuthTokens.Basic("neo4j", "lala"));

            ScenarioContext.Current.Set(driverWithIncorrectPassword);
        }
Ejemplo n.º 18
0
        public void TestInitialize()
        {
            // load graph definition and connect to the servers
            _graphDef = new JSONGraphSQLSchema(@"./TestData/MovieGraph.json");

            // setup neo4j and sql drivers
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("./appsettings.json", optional: false, reloadOnChange: true)
                          .AddJsonFile("./appsettings.private.json", optional: true, reloadOnChange: true);
            IConfigurationRoot configuration = builder.Build();

            var useDocker = bool.Parse(configuration
                                       .GetSection("appSettings")
                                       .GetSection("createLocalDockerImages").Value);
            var neo4jHost = configuration
                            .GetSection("appSettings")
                            .GetSection("neo4jHost").Value;
            var neo4jPort = int.Parse(configuration
                                      .GetSection("appSettings")
                                      .GetSection("neo4jPort").Value);
            var neo4jUser = configuration
                            .GetSection("appSettings")
                            .GetSection("neo4jUser").Value;
            var neo4jPassword = configuration
                                .GetSection("appSettings")
                                .GetSection("neo4jPassword").Value;
            var sqlHost = configuration
                          .GetSection("appSettings")
                          .GetSection("sqlHost").Value;
            var sqlPort = int.Parse(configuration
                                    .GetSection("appSettings")
                                    .GetSection("sqlPort").Value);
            var sqlPassword = configuration
                              .GetSection("appSettings")
                              .GetSection("sqlPassword").Value;
            var skipInitialization = string.Compare(configuration
                                                    .GetSection("appSettings")
                                                    .GetSection("skipInitialization").Value, "true", true) == 0;

            var neo4jBoltUrl   = $"bolt://{neo4jHost}:{neo4jPort}";
            var sqlConnStrInit = $"Data Source={sqlHost},{sqlPort};User id=SA;Password={sqlPassword};";
            var sqlConnStr     = $"Data Source={sqlHost},{sqlPort};Initial Catalog=octestdb;User id=SA;Password={sqlPassword};";

            _driver    = GraphDatabase.Driver(neo4jBoltUrl, AuthTokens.Basic(neo4jUser, neo4jPassword));
            _conn      = () => new SqlConnection(sqlConnStr);
            _conn_init = () => new SqlConnection(sqlConnStrInit);

            // initialize test harness
            if (!File.Exists("./TestInitDone.tmp") || !skipInitialization)
            {
                if (useDocker)
                {
                    // create and start test harness containers containers
                    CreateTestHarnessContainers(
                        neo4jUser,
                        neo4jPassword,
                        neo4jPort,
                        sqlHost,
                        sqlPort,
                        sqlPassword
                        ).ConfigureAwait(false).GetAwaiter().GetResult();
                }

                // initialize neo4j db
                InitializeNeo4jDB();

                // initialize sql db
                InitializeSQLDB();

                Console.WriteLine("Test Initialization completed.");
                File.WriteAllText("./TestInitDone.tmp", DateTime.UtcNow.ToString());
            }
            else
            {
                // Depending the cached the initialization state to speed up unit test
                Console.WriteLine("Test Initialization skipped. To redo test initialization, remove './TestInitDone.tmp'.");
            }
        }
Ejemplo n.º 19
0
 public HelloWorldExample(string uri, string user, string password)
 {
     _driver = GraphDatabase.Driver(uri, AuthTokens.Basic(user, password));
 }
Ejemplo n.º 20
0
        public void Connect()
        {
            if (IsConnected)
            {
                return;
            }

            Driver = GraphDatabase.Driver(
                URI,
                (string.IsNullOrWhiteSpace(UserName) || string.IsNullOrWhiteSpace(Password)) ? null : AuthTokens.Basic(UserName, Password),
                this.Config);
        }
Ejemplo n.º 21
0
 public Social()
 {
     _driver = GraphDatabase.Driver(new Uri("bolt://localhost:7687"), AuthTokens.Basic("neo4j", "neo4j"));
 }
Ejemplo n.º 22
0
 // tag::kerberos-auth[]
 public IDriver CreateDriverWithKerberosAuth(string uri, string ticket)
 {
     return(GraphDatabase.Driver(uri, AuthTokens.Kerberos(ticket),
                                 o => o.WithEncryptionLevel(EncryptionLevel.None)));
 }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            var neo4JConnectionConfiguration = Configuration.FromSection <Neo4JConnectionConfiguration>("neo4JConnectionConfiguration");

            services.AddSingleton(s => GraphDatabase.Driver(neo4JConnectionConfiguration.ConnectionString,
                                                            AuthTokens.Basic(neo4JConnectionConfiguration.UserName, neo4JConnectionConfiguration.Password)));
            services.AddScoped(s => s.GetService <IDriver>().Session());
            services.AddNeo4jClientStore <ApplicationUser>();

            services.AddIdentity <ApplicationUser, Neo4jIdentityRole>()
            .AddNeo4jDataStores()
            .AddNeo4jMultiFactorStore <ApplicationFactor>()
            .AddDefaultTokenProviders();

            services.AddDetection();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddTransient <IEmailSender, EmailSender>();



            // configure identity server with in-memory stores, keys, clients and scopes
            var identityServerBuilder = services.AddIdentityServer(options =>
            {
                options.UserInteraction.LoginUrl              = "/identity/account/login";
                options.UserInteraction.LogoutUrl             = "/identity/account/logout";
                options.UserInteraction.ConsentUrl            = "/identity/consent";
                options.Authentication.CheckSessionCookieName = $".idsrv.session.{Configuration["appName"]}";
            })
                                        .AddDeveloperSigningCredential()
                                        .AddInMemoryPersistedGrants()
                                        .AddInMemoryIdentityResources(Config.GetIdentityResources())
                                        .AddInMemoryApiResources(Config.GetApiResources())
                                        .AddInMemoryClients(Config.GetClients())
                                        .AddAspNetIdentity <ApplicationUser>();

            // My Overrides.
            identityServerBuilder.ReplaceRedirectUriValidator <StrictRemoteRedirectUriValidator>();


            var authenticationBuilder = services.AddAuthentication();
            var googleClientId        = Configuration["Google-ClientId"];
            var googleClientSecret    = Configuration["Google-ClientSecret"];

            if (!string.IsNullOrEmpty(googleClientId) && !string.IsNullOrEmpty(googleClientSecret))
            {
                authenticationBuilder.AddGoogle(options =>
                {
                    options.ClientId               = googleClientId;
                    options.ClientSecret           = googleClientSecret;
                    options.Events.OnRemoteFailure = context =>
                    {
                        context.Response.Redirect("/");
                        context.HandleResponse();
                        return(Task.CompletedTask);
                    };
                });
            }

            var section             = Configuration.GetSection("oauth2");
            var oAuth2SchemeRecords = new List <OAuth2SchemeRecord>();

            section.Bind(oAuth2SchemeRecords);
            foreach (var record in oAuth2SchemeRecords)
            {
                var scheme = record.Scheme;
                authenticationBuilder.P7AddOpenIdConnect(scheme, scheme, options =>
                {
                    options.Authority            = record.Authority;
                    options.CallbackPath         = record.CallbackPath;
                    options.RequireHttpsMetadata = false;

                    options.ClientId   = record.ClientId;
                    options.SaveTokens = true;

                    options.Events.OnRedirectToIdentityProvider = context =>
                    {
                        if (context.ProtocolMessage.RequestType == OpenIdConnectRequestType.Authentication)
                        {
                            context.ProtocolMessage.AcrValues = "some-acr=some-value";
                        }
                        return(Task.CompletedTask);
                    };
                    options.Events.OnRemoteFailure = context =>
                    {
                        context.Response.Redirect("/");
                        context.HandleResponse();
                        return(Task.CompletedTask);
                    };
                });
            }
        }
Ejemplo n.º 24
0
 public Neo4jBase(IOptions <Neo4jConfig> config)
 {
     _config        = config.Value;
     _graphDatabase = GraphDatabase.Driver($"bolt://{_config.Host}:{_config.Port}", AuthTokens.Basic(_config.UserName, _config.Password));
 }
Ejemplo n.º 25
0
 public IDriver CreateDriverWithBasicAuth(string uri, string user, string password)
 {
     return(GraphDatabase.Driver(uri, AuthTokens.Basic(user, password)));
 }
Ejemplo n.º 26
0
 public IDriver CreateDriverWithBasicAuth(string uri, string Person, string password)
 {
     return(GraphDatabase.Driver(new Uri(uri), AuthTokens.Basic(Person, password)));
 }
Ejemplo n.º 27
0
 public IDriver CreateDriverWithCustomizedMaxRetryTime(string uri, string user, string password)
 {
     return(GraphDatabase.Driver(uri, AuthTokens.Basic(user, password),
                                 o => o.WithMaxTransactionRetryTime(TimeSpan.FromSeconds(15))));
 }
Ejemplo n.º 28
0
 public void RemoveToken(string loginProvider, string name)
 {
     AuthTokens = AuthTokens.Except(AuthTokens.Where(t => t.LoginProvider == loginProvider && t.Name == name));
 }
Ejemplo n.º 29
0
 public IDriver CreateDriverWithCustomizedSecurityStrategy(string uri, string user, string password)
 {
     return(GraphDatabase.Driver(uri, AuthTokens.Basic(user, password),
                                 o => o.WithEncryptionLevel(EncryptionLevel.None)));
 }
 public DriverIntroductionExample(string uri, string user, string password)
 {
     _driver = GraphDatabase.Driver(uri, AuthTokens.Basic(user, password),
                                    configBuilder => configBuilder.WithLogger(new SimpleLogger()));
 }