diff options
Diffstat (limited to 'backend/api')
27 files changed, 918 insertions, 156 deletions
diff --git a/backend/api/api/Controllers/AuthController.cs b/backend/api/api/Controllers/AuthController.cs index 6dfe483a..7167d1bf 100644 --- a/backend/api/api/Controllers/AuthController.cs +++ b/backend/api/api/Controllers/AuthController.cs @@ -49,8 +49,6 @@ namespace api.Controllers return Ok(newToken); - - } diff --git a/backend/api/api/Controllers/DatasetController.cs b/backend/api/api/Controllers/DatasetController.cs index d022d6d2..c0ba0039 100644 --- a/backend/api/api/Controllers/DatasetController.cs +++ b/backend/api/api/Controllers/DatasetController.cs @@ -1,6 +1,9 @@ using api.Models; using api.Services; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; +using Microsoft.Net.Http.Headers; +using System.Net.Http.Headers; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 @@ -11,39 +14,96 @@ namespace api.Controllers public class DatasetController : ControllerBase { private readonly IDatasetService _datasetService; + private JwtToken jwtToken; - public DatasetController(IDatasetService datasetService) + public DatasetController(IDatasetService datasetService, IConfiguration configuration) { _datasetService = datasetService; + jwtToken = new JwtToken(configuration); } - // GET: api/<DatasetController>/{id}/datasets - [HttpGet("{id}/datasets")] - public ActionResult<List<Dataset>> Get(string id) + // GET: api/<DatasetController>/mydatasets + [HttpGet("/mydatasets")] + [Authorize(Roles = "User")] + public ActionResult<List<Dataset>> Get() { - return _datasetService.GetAllDatesets(id); + string username; + var header = Request.Headers[HeaderNames.Authorization]; + if (AuthenticationHeaderValue.TryParse(header, out var headerValue)) + { + var scheme = headerValue.Scheme; + var parameter = headerValue.Parameter; + username = jwtToken.TokenToUsername(parameter); + if (username == null) + return null; + } + else + return BadRequest(); + + //ako bude trebao ID, samo iz baze uzeti + + return _datasetService.GetMyDatesets(username); + } + + // GET: api/<DatasetController>/publicdatasets + [HttpGet("/datasets")] + public ActionResult<List<Dataset>> GetPublicDS() + { + return _datasetService.GetPublicDatesets(); + } + + // GET api/<DatasetController>/{name} + //get odredjeni dataset + [HttpGet("/{name}")] + [Authorize(Roles = "User")] + public ActionResult<Dataset> Get(string name) + { + string username; + var header = Request.Headers[HeaderNames.Authorization]; + if (AuthenticationHeaderValue.TryParse(header, out var headerValue)) + { + var scheme = headerValue.Scheme; + var parameter = headerValue.Parameter; + username = jwtToken.TokenToUsername(parameter); + if (username == null) + return null; + } + else + return BadRequest(); + + var dataset = _datasetService.GetOneDataset(username, name); + + if (dataset == null) + return NotFound($"Dataset with name = {name} or user with username = {username} not found"); + + return dataset; } - // GET api/<DatasetController>/{id}/{name} - [HttpGet("{id}/{name}")] - public ActionResult<Dataset> Get(string id, string name) + /*za pretragu vratiti dataset koji je public + public ActionResult<Dataset> Get(string name) { - var dataset = _datasetService.GetOneDataset(id, name); + + + var dataset = _datasetService.GetOneDataset(username, name); if (dataset == null) - return NotFound($"Dataset with name = {name} not found"); + return NotFound($"Dataset with name = {name} or user with username = {username} not found"); return dataset; } + */ - // POST api/<DatasetController> - [HttpPost("post")] + // POST api/<DatasetController>/add + [HttpPost("add")] + [Authorize(Roles = "User")] public ActionResult<Dataset> Post([FromBody] Dataset dataset) { - var existingUser = _datasetService.GetOneDataset(dataset.uploaderId,dataset.name); + //da li ce preko tokena da se ubaci username ili front salje + //dataset.username = usernameToken; + var existingDataset = _datasetService.GetOneDataset(dataset.username, dataset.name); - if (existingUser != null) + if (existingDataset != null) return NotFound($"Dateset with name = {dataset.name} exisits"); else { @@ -53,30 +113,59 @@ namespace api.Controllers } } - // PUT api/<DatasetController>/5 - [HttpPut("{id}/{name}")] - public ActionResult Put(string id, string name, [FromBody] Dataset dataset) + // PUT api/<DatasetController>/{name} + [HttpPut("/{name}")] + [Authorize(Roles = "User")] + public ActionResult Put(string name, [FromBody] Dataset dataset) { - var existingDataset = _datasetService.GetOneDataset(id, name); + string username; + var header = Request.Headers[HeaderNames.Authorization]; + if (AuthenticationHeaderValue.TryParse(header, out var headerValue)) + { + var scheme = headerValue.Scheme; + var parameter = headerValue.Parameter; + username = jwtToken.TokenToUsername(parameter); + if (username == null) + return null; + } + else + return BadRequest(); + + var existingDataset = _datasetService.GetOneDataset(username, name); //ne mora da se proverava if (existingDataset == null) - return NotFound($"Dataset with name = {name} not found"); + return NotFound($"Dataset with name = {name} or user with username = {username} not found"); + + _datasetService.Update(username, name, dataset); - _datasetService.Update(id, name, dataset); - return NoContent(); + return Ok($"Dataset with name = {name} updated"); } - // DELETE api/<DatasetController>/5 - [HttpDelete("{id}")] - public ActionResult Delete(string id, string name) + // DELETE api/<DatasetController>/name + [HttpDelete("/{name}")] + [Authorize(Roles = "User")] + public ActionResult Delete(string name) { - var dataset = _datasetService.GetOneDataset(id, name); + string username; + var header = Request.Headers[HeaderNames.Authorization]; + if (AuthenticationHeaderValue.TryParse(header, out var headerValue)) + { + var scheme = headerValue.Scheme; + var parameter = headerValue.Parameter; + username = jwtToken.TokenToUsername(parameter); + if (username == null) + return null; + } + else + return BadRequest(); + + var dataset = _datasetService.GetOneDataset(username, name); if (dataset == null) - return NotFound($"Dataset with name = {name} not found"); + return NotFound($"Dataset with name = {name} or user with username = {username} not found"); - _datasetService.Delete(dataset.uploaderId,dataset.name); + _datasetService.Delete(dataset.username, dataset.name); return Ok($"Dataset with name = {name} deleted"); @@ -86,27 +175,15 @@ namespace api.Controllers /* { - "_id": "", - "uploaderId" : "uploaderId", - "name" : "name", - "description" : "description", - "dateCreated" : "dateCreated", - "inputColumns" : [2,3,4], - "columnToPredict" : 1, - "randomTestSet" : true, - "randomTestSetDistribution" : 1, - "type" : "type", - "encoding" : "encoding", - "optimizer" : "optimizer", - "lossFunction" : "lossFunction", - "inputNeurons" : 2, - "hiddenLayerNeurons" : 3, - "hiddenLayers" : 8, - "batchSize" : 6, - "inputLayerActivationFunction" : "inputLayerActivationFunction", - "hiddenLayerActivationFunction" : "hiddenLayerActivationFunction", - "outputLayerActivationFunction" : "outputLayerActivationFunction", - "extension" : "extension" - + "_id": "", + "name": "name", + "description": "description", + "header" : ["ag","rt"], + "fileId" : "652", + "extension": "csb", + "isPublic" : true, + "accessibleByLink": true, + "dateCreated": "dateCreated", + "lastUpdated" : "proba12" } */
\ No newline at end of file diff --git a/backend/api/api/Controllers/FileController.cs b/backend/api/api/Controllers/FileController.cs new file mode 100644 index 00000000..3bfdad93 --- /dev/null +++ b/backend/api/api/Controllers/FileController.cs @@ -0,0 +1,112 @@ +using System.Net.Http.Headers; +using api.Models; +using api.Services; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Net.Http.Headers; +namespace api.Controllers +{ + [Route("api/[controller]")] + [ApiController] + public class FileController : ControllerBase + { + private string[] permittedExtensions = { ".csv" }; + private readonly IConfiguration _configuration; + private JwtToken _token; + private IFileService _fileservice; + public FileController(IConfiguration configuration,IFileService fileService) + { + _configuration = configuration; + _token = new JwtToken(configuration); + _fileservice = fileService; + + } + + + [HttpPost("Csv")] + [Authorize(Roles = "User")] + public async Task<ActionResult<string>> CsvUpload([FromForm]IFormFile file) + { + + //get username from jwtToken + string username; + var header = Request.Headers[HeaderNames.Authorization]; + if (AuthenticationHeaderValue.TryParse(header, out var headerValue)) + { + + var scheme = headerValue.Scheme; + var parameter = headerValue.Parameter; + username = _token.TokenToUsername(parameter); + if (username == null) + return null; + }else + return BadRequest(); + + + //Check filetype + var filename=file.FileName; + var ext=Path.GetExtension(filename).ToLowerInvariant(); + var name = Path.GetFileNameWithoutExtension(filename).ToLowerInvariant(); + if (string.IsNullOrEmpty(ext) || ! permittedExtensions.Contains(ext)) { + return BadRequest("Wrong file type"); + } + var folderPath=Path.Combine(Directory.GetCurrentDirectory(),"UploadedFiles",username); + //Check Directory + if (!Directory.Exists(folderPath)) + { + Directory.CreateDirectory(folderPath); + } + //Index file if same filename + var fullPath = Path.Combine(folderPath, filename); + int i=0; + + while (System.IO.File.Exists(fullPath)) { + i++; + fullPath = Path.Combine(folderPath,name+i.ToString()+ext); + } + + + //Write file + using (var stream=new FileStream(fullPath, FileMode.Create)) + { + await file.CopyToAsync(stream); + } + FileModel fileModel= new FileModel(); + fileModel.path=fullPath; + fileModel.username=username; + fileModel=_fileservice.Create(fileModel); + + return Ok(fileModel); + } + + [HttpGet("Download")] + [Authorize(Roles = "User")] + public async Task<ActionResult> DownloadFile(string id) + { + //Get Username + string username; + var header = Request.Headers[HeaderNames.Authorization]; + if (AuthenticationHeaderValue.TryParse(header, out var headerValue)) + { + + var scheme = headerValue.Scheme; + var parameter = headerValue.Parameter; + username = _token.TokenToUsername(parameter); + if (username == null) + return null; + } + else + return BadRequest(); + + string filePath = _fileservice.GetFilePath(id, username); + if (filePath == null) + return BadRequest(); + + return File(System.IO.File.ReadAllBytes(filePath),"application/octet-stream", Path.GetFileName(filePath)); + + } + + + + } +} diff --git a/backend/api/api/Controllers/FileUploadController.cs b/backend/api/api/Controllers/FileUploadController.cs deleted file mode 100644 index 46e7f4f9..00000000 --- a/backend/api/api/Controllers/FileUploadController.cs +++ /dev/null @@ -1,47 +0,0 @@ -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -namespace api.Controllers -{ - [Route("api/[controller]")] - [ApiController] - public class FileUploadController : ControllerBase - { - private string[] permittedExtensions = { ".csv" }; - - - [HttpPost("Csv")] - [Authorize(Roles = "User")] - public async Task<ActionResult<string>> CsvUpload([FromForm]IFormFile file,[FromForm]string username)//???Umesto username poslati jwt odakle se moze preuzeti username radi sigurnosti - { - var filename=file.FileName; - var ext=Path.GetExtension(filename).ToLowerInvariant(); - var name = Path.GetFileNameWithoutExtension(filename).ToLowerInvariant(); - if (string.IsNullOrEmpty(ext) || ! permittedExtensions.Contains(ext)) { - return BadRequest("Wrong file type"); - } - var folderPath=Path.Combine(Directory.GetCurrentDirectory(),"UploadedFiles",username); - if (!Directory.Exists(folderPath)) - { - Directory.CreateDirectory(folderPath); - } - - var fullPath = Path.Combine(folderPath, filename); - int i=0; - - while (System.IO.File.Exists(fullPath)) { - i++; - fullPath = Path.Combine(folderPath,name+i.ToString()+ext); - } - - - - using (var stream=new FileStream(fullPath, FileMode.Create)) - { - await file.CopyToAsync(stream); - } - - return Ok(); - } - } -} diff --git a/backend/api/api/Controllers/ModelController.cs b/backend/api/api/Controllers/ModelController.cs new file mode 100644 index 00000000..1d03d924 --- /dev/null +++ b/backend/api/api/Controllers/ModelController.cs @@ -0,0 +1,159 @@ +using api.Models; +using api.Services; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Net.Http.Headers; +using System.Net.Http.Headers; + +namespace api.Controllers +{ + [Route("api/[controller]")] + [ApiController] + public class ModelController : ControllerBase + { + + private IMlConnectionService _mlService; + private readonly IModelService _modelService; + private JwtToken jwtToken; + + + public ModelController(IMlConnectionService mlService, IModelService modelService, IConfiguration configuration) + { + _mlService = mlService; + _modelService = modelService; + jwtToken = new JwtToken(configuration); + } + + [HttpPost("sendModel")] + [Authorize(Roles = "User")] + public async Task<ActionResult<string>> Test([FromBody] object model) + { + var result = await _mlService.SendModelAsync(model); + return Ok(result); + } + + // GET: api/<ModelController>/mymodels + [HttpGet("/mymodels")] + [Authorize(Roles = "User")] + public ActionResult<List<Model>> Get() + { + string username; + var header = Request.Headers[HeaderNames.Authorization]; + if (AuthenticationHeaderValue.TryParse(header, out var headerValue)) + { + var scheme = headerValue.Scheme; + var parameter = headerValue.Parameter; + username = jwtToken.TokenToUsername(parameter); + if (username == null) + return null; + } + else + return BadRequest(); + + return _modelService.GetMyModels(username); + } + + // name modela + // GET api/<ModelController>/{name} + [HttpGet("/{name}")] + [Authorize(Roles = "User")] + public ActionResult<Model> Get(string name) + { + string username; + var header = Request.Headers[HeaderNames.Authorization]; + if (AuthenticationHeaderValue.TryParse(header, out var headerValue)) + { + var scheme = headerValue.Scheme; + var parameter = headerValue.Parameter; + username = jwtToken.TokenToUsername(parameter); + if (username == null) + return null; + } + else + return BadRequest(); + + var model = _modelService.GetOneModel(username, name); + + if (model == null) + return NotFound($"Model with name = {name} or user with username = {username} not found"); + + return model; + } + + // POST api/<ModelController>/add + [HttpPost("add")] + [Authorize(Roles = "User")] + public ActionResult<Model> Post([FromBody] Model model) + { + var existingModel = _modelService.GetOneModel(model.username, model.name); + + if (existingModel != null) + return NotFound($"Model with name = {model.name} exisits"); + else + { + _modelService.Create(model); + + return CreatedAtAction(nameof(Get), new { id = model._id }, model); + } + } + + // PUT api/<ModelController>/{username}/{name} + [HttpPut("{name}")] + [Authorize(Roles = "User")] + public ActionResult Put(string name, [FromBody] Model model) + { + string username; + var header = Request.Headers[HeaderNames.Authorization]; + if (AuthenticationHeaderValue.TryParse(header, out var headerValue)) + { + var scheme = headerValue.Scheme; + var parameter = headerValue.Parameter; + username = jwtToken.TokenToUsername(parameter); + if (username == null) + return null; + } + else + return BadRequest(); + + + var existingModel = _modelService.GetOneModel(username, name); + + if (existingModel == null) + return NotFound($"Model with name = {name} or user with username = {username} not found"); + + _modelService.Update(username, name, model); + return NoContent(); + } + + // DELETE api/<ModelController>/username + [HttpDelete("{name}")] + [Authorize(Roles = "User")] + public ActionResult Delete(string name) + { + string username; + var header = Request.Headers[HeaderNames.Authorization]; + if (AuthenticationHeaderValue.TryParse(header, out var headerValue)) + { + var scheme = headerValue.Scheme; + var parameter = headerValue.Parameter; + username = jwtToken.TokenToUsername(parameter); + if (username == null) + return null; + } + else + return BadRequest(); + + var model = _modelService.GetOneModel(username, name); + + if (model == null) + return NotFound($"Model with name = {name} or user with username = {username} not found"); + + _modelService.Delete(model.username, model.name); + + return Ok($"Model with name = {name} deleted"); + + } + + } +} diff --git a/backend/api/api/Controllers/PredictorController.cs b/backend/api/api/Controllers/PredictorController.cs new file mode 100644 index 00000000..d5a55b3c --- /dev/null +++ b/backend/api/api/Controllers/PredictorController.cs @@ -0,0 +1,159 @@ +using api.Models; +using api.Services; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Net.Http.Headers; +using System.Net.Http.Headers; + +namespace api.Controllers +{ + [Route("api/[controller]")] + [ApiController] + public class PredictorController : Controller + { + private readonly IPredictorService _predictorService; + private JwtToken jwtToken; + + public PredictorController(IPredictorService predictorService, IConfiguration configuration) + { + _predictorService = predictorService; + jwtToken = new JwtToken(configuration); + } + + // GET: api/<PredictorController>/mypredictors + [HttpGet("mypredictors")] + [Authorize(Roles = "User")] + public ActionResult<List<Predictor>> Get() + { + string username; + var header = Request.Headers[HeaderNames.Authorization]; + if (AuthenticationHeaderValue.TryParse(header, out var headerValue)) + { + var scheme = headerValue.Scheme; + var parameter = headerValue.Parameter; + username = jwtToken.TokenToUsername(parameter); + if (username == null) + return null; + } + else + return BadRequest(); + + return _predictorService.GetMyPredictors(username); + } + // GET: api/<PredictorController>/publicpredictors + [HttpGet("publicpredictors")] + public ActionResult<List<Predictor>> GetPublicPredictors() + { + return _predictorService.GetPublicPredictors(); + } + + // GET api/<PredictorController>/{name} + [HttpGet("/{name}")] + [Authorize(Roles = "User")] + public ActionResult<Predictor> Get(string name) + { + string username; + var header = Request.Headers[HeaderNames.Authorization]; + if (AuthenticationHeaderValue.TryParse(header, out var headerValue)) + { + var scheme = headerValue.Scheme; + var parameter = headerValue.Parameter; + username = jwtToken.TokenToUsername(parameter); + if (username == null) + return null; + } + else + return BadRequest(); + + var predictor = _predictorService.GetOnePredictor(username, name); + + if (predictor == null) + return NotFound($"Predictor with name = {name} or user with username = {username} not found"); + + return predictor; + } + + // POST api/<PredictorController>/add + [HttpPost("add")] + [Authorize(Roles = "User")] + public ActionResult<Predictor> Post([FromBody] Predictor predictor) + { + var existingModel = _predictorService.GetOnePredictor(predictor.username, predictor.name); + + if (existingModel != null) + return NotFound($"Predictor with name = {predictor.name} exisits"); + else + { + _predictorService.Create(predictor); + + return CreatedAtAction(nameof(Get), new { id = predictor._id }, predictor); + } + } + + + + // PUT api/<PredictorController>/{name} + [HttpPut("/{name}")] + [Authorize(Roles = "User")] + public ActionResult Put(string name, [FromBody] Predictor predictor) + { + string username; + var header = Request.Headers[HeaderNames.Authorization]; + if (AuthenticationHeaderValue.TryParse(header, out var headerValue)) + { + var scheme = headerValue.Scheme; + var parameter = headerValue.Parameter; + username = jwtToken.TokenToUsername(parameter); + if (username == null) + return null; + } + else + return BadRequest(); + + var existingDataset = _predictorService.GetOnePredictor(username, name); + + //ne mora da se proverava + if (existingDataset == null) + return NotFound($"Predictor with name = {name} or user with username = {username} not found"); + + _predictorService.Update(username, name, predictor); + + return Ok($"Predictor with name = {name} updated"); + } + + + // DELETE api/<PredictorController>/name + [HttpDelete("/{name}")] + [Authorize(Roles = "User")] + public ActionResult Delete(string name) + { + string username; + var header = Request.Headers[HeaderNames.Authorization]; + if (AuthenticationHeaderValue.TryParse(header, out var headerValue)) + { + var scheme = headerValue.Scheme; + var parameter = headerValue.Parameter; + username = jwtToken.TokenToUsername(parameter); + if (username == null) + return null; + } + else + return BadRequest(); + + var predictor = _predictorService.GetOnePredictor(username, name); + + if (predictor == null) + return NotFound($"Predictor with name = {name} or user with username = {username} not found"); + + _predictorService.Delete(predictor.username, predictor.name); + + return Ok($"Predictor with name = {name} deleted"); + + } + + + + + } +} diff --git a/backend/api/api/Controllers/UserController.cs b/backend/api/api/Controllers/UserController.cs index d41a42e3..58121656 100644 --- a/backend/api/api/Controllers/UserController.cs +++ b/backend/api/api/Controllers/UserController.cs @@ -1,5 +1,6 @@ using api.Models; using api.Services; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System.Diagnostics; @@ -72,6 +73,7 @@ namespace api.Controllers // PUT api/<UserController>/5 [HttpPut("{id}")] + [Authorize(Roles = "User")] public ActionResult Put(string id, [FromBody] User user) { var existingUser = userService.Get(id); @@ -86,6 +88,7 @@ namespace api.Controllers // DELETE api/<UserController>/5 [HttpDelete("{id}")] + [Authorize(Roles = "User")] public ActionResult Delete(string id) { var user = userService.Get(id); diff --git a/backend/api/api/Data/UserStoreDatabaseSettings.cs b/backend/api/api/Data/UserStoreDatabaseSettings.cs index 0d923fc7..e83d2b54 100644 --- a/backend/api/api/Data/UserStoreDatabaseSettings.cs +++ b/backend/api/api/Data/UserStoreDatabaseSettings.cs @@ -10,5 +10,8 @@ namespace api.Data public string DatabaseName { get; set; } = String.Empty; public string CollectionName { get; set; } = String.Empty; public string DatasetCollectionName { get; set; } = String.Empty; + public string PredictorCollectionName { get; set; } = String.Empty; + public string ModelCollectionName { get; set; } = String.Empty; + public string FilesCollectionName { get; set; } = String.Empty; } } diff --git a/backend/api/api/Interfaces/IUserStoreDatabaseSettings.cs b/backend/api/api/Interfaces/IUserStoreDatabaseSettings.cs index 8d2a175f..a5b5f5eb 100644 --- a/backend/api/api/Interfaces/IUserStoreDatabaseSettings.cs +++ b/backend/api/api/Interfaces/IUserStoreDatabaseSettings.cs @@ -6,5 +6,8 @@ string DatabaseName { get; set; } string CollectionName { get; set; } string DatasetCollectionName { get; set; } + string PredictorCollectionName { get; set; } + string ModelCollectionName { get; set; } + string FilesCollectionName { get; set; } } } diff --git a/backend/api/api/Models/Dataset.cs b/backend/api/api/Models/Dataset.cs index 0dc87f40..d4649c17 100644 --- a/backend/api/api/Models/Dataset.cs +++ b/backend/api/api/Models/Dataset.cs @@ -1,46 +1,25 @@ -using MongoDB.Bson; +using System; +using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; namespace api.Models { - public class Dataset - { - internal string uploaderId; + public class Dataset + { + public string username { get; set; } [BsonId] [BsonRepresentation(BsonType.ObjectId)]//mongo data type to .net public string _id { get; set; } - [BsonElement("uploaderId")] - public string UploaderId { get; set; } - [BsonElement("name")] public string name { get; set; } - public string description { get; set; } - //datetime - public string dateCreated { get; set; } - - public int[] inputColumns { get; set; } - public int columnToPredict { get; set; } - public bool randomTestSet { get; set; } - public int randomTestSetDistribution { get; set; } - - - public string type { get; set; } - public string encoding { get; set; } - public string optimizer { get; set; } - public string lossFunction { get; set; } - public int inputNeurons { get; set; } - public int hiddenLayerNeurons { get; set; } - public int hiddenLayers { get; set; } - public int batchSize { get; set; } - public string inputLayerActivationFunction { get; set; } - public string hiddenLayerActivationFunction { get; set; } - public string outputLayerActivationFunction { get; set; } - - - [BsonElement("extension")] + public string[] header { get; set; } + public string fileId { get; set; } public string extension { get; set; } - - + public bool isPublic { get; set; } + public bool accessibleByLink { get; set; } + public string dateCreated { get; set; } + public string lastUpdated { get; set; } } } + diff --git a/backend/api/api/Models/FileModel.cs b/backend/api/api/Models/FileModel.cs new file mode 100644 index 00000000..9e7c8b5d --- /dev/null +++ b/backend/api/api/Models/FileModel.cs @@ -0,0 +1,14 @@ +using MongoDB.Bson; +using MongoDB.Bson.Serialization.Attributes; + +namespace api.Models +{ + public class FileModel + { + [BsonId] + [BsonRepresentation(BsonType.ObjectId)] + public string _id { get; set; } + public string username { get; set; } + public string path { get; set; } + } +} diff --git a/backend/api/api/Models/JwtToken.cs b/backend/api/api/Models/JwtToken.cs index 3ecbf92d..a98d1967 100644 --- a/backend/api/api/Models/JwtToken.cs +++ b/backend/api/api/Models/JwtToken.cs @@ -23,7 +23,7 @@ namespace api.Models { Subject = new ClaimsIdentity(new[] { new Claim("name", user.UserName), new Claim("role", "User")}), - Expires = DateTime.UtcNow.AddDays(1), + Expires = DateTime.UtcNow.AddMinutes(20), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); @@ -33,13 +33,25 @@ namespace api.Models public string RenewToken(string existingToken) { - if (existingToken == null) + var userName = TokenToUsername(existingToken); + if (userName == null) + return null; + var authUser = new AuthRequest(); + authUser.UserName = userName; + + return GenToken(authUser); + + } + + public string TokenToUsername(string token) + { + if (token == null) return null; var tokenHandler = new JwtSecurityTokenHandler(); - var key= Encoding.ASCII.GetBytes(_configuration.GetSection("AppSettings:JwtToken").Value); + var key = Encoding.ASCII.GetBytes(_configuration.GetSection("AppSettings:JwtToken").Value); try { - tokenHandler.ValidateToken(existingToken, new TokenValidationParameters + tokenHandler.ValidateToken(token, new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), @@ -48,11 +60,7 @@ namespace api.Models }, out SecurityToken validatedToken); var jwtToken = (JwtSecurityToken)validatedToken; - var userName =jwtToken.Claims.First(x => x.Type == "name").Value; - var authUser = new AuthRequest(); - authUser.UserName = userName; - - return GenToken(authUser); + return jwtToken.Claims.First(x => x.Type == "name").Value; } catch { diff --git a/backend/api/api/Models/Model.cs b/backend/api/api/Models/Model.cs new file mode 100644 index 00000000..dfc4336a --- /dev/null +++ b/backend/api/api/Models/Model.cs @@ -0,0 +1,45 @@ +using MongoDB.Bson; +using MongoDB.Bson.Serialization.Attributes; + +namespace api.Models +{ + public class Model + { + + [BsonId] + [BsonRepresentation(BsonType.ObjectId)]//mongo data type to .net + public string _id { get; set; } + public string username { get; set; } + + + public string name { get; set; } + public string description { get; set; } + //datetime + public string dateCreated { get; set; } + public string lastUpdated { get; set; } + //proveriti id + public string datasetId { get; set; } + + //Test set settings + public string[] inputColumns { get; set; } + public string columnToPredict { get; set; } + public bool randomOrder {get;set;} + public bool randomTestSet { get; set; } + public float randomTestSetDistribution { get; set; } + + //Neural net training + public string type { get; set; } + public string encoding { get; set; } + public string optimizer { get; set; } + public string lossFunction { get; set; } + public int inputNeurons { get; set; } + public int hiddenLayerNeurons { get; set; } + public int hiddenLayers { get; set; } + public int batchSize { get; set; } + public string inputLayerActivationFunction { get; set; } + public string hiddenLayerActivationFunction { get; set; } + public string outputLayerActivationFunction { get; set; } + + + } +} diff --git a/backend/api/api/Models/Predictor.cs b/backend/api/api/Models/Predictor.cs new file mode 100644 index 00000000..cd2f4557 --- /dev/null +++ b/backend/api/api/Models/Predictor.cs @@ -0,0 +1,22 @@ +using System; +using MongoDB.Bson; +using MongoDB.Bson.Serialization.Attributes; + +namespace api.Models +{ + public class Predictor + { + [BsonId] + [BsonRepresentation(BsonType.ObjectId)]//mongo data type to .net + public string _id { get; set; } + public string username { get; set; } + public string name { get; set; } + public string description { get; set; } + public string[] inputs { get; set; } + public string output { get; set; } + public bool isPublic { get; set; } + public bool accessibleByLink { get; set; } + public string dateCreated { get; set; } + } +} + diff --git a/backend/api/api/Program.cs b/backend/api/api/Program.cs index 2c569daf..65399bdf 100644 --- a/backend/api/api/Program.cs +++ b/backend/api/api/Program.cs @@ -28,6 +28,11 @@ builder.Services.AddSingleton<IMongoClient>(s => builder.Services.AddScoped<IDatasetService, DatasetService>(); builder.Services.AddScoped<IUserService, UserService>(); builder.Services.AddScoped<IAuthService, AuthService>(); +builder.Services.AddScoped<IMlConnectionService, MlConnectionService>(); +builder.Services.AddScoped<IModelService, ModelService>(); +builder.Services.AddScoped<IPredictorService, PredictorService>(); +builder.Services.AddScoped<IFileService, FileService>(); + //Add Authentication builder.Services.AddAuthentication( diff --git a/backend/api/api/Services/DatasetService.cs b/backend/api/api/Services/DatasetService.cs index 1b6d22be..27a8b3ee 100644 --- a/backend/api/api/Services/DatasetService.cs +++ b/backend/api/api/Services/DatasetService.cs @@ -21,23 +21,30 @@ namespace api.Services } //brisanje odredjenog name-a - public void Delete(string uploaderId, string name) + public void Delete(string username, string name) { - _dataset.DeleteOne(dataset => (dataset.UploaderId == uploaderId && dataset.name == name)); + _dataset.DeleteOne(dataset => (dataset.username == username && dataset.name == name)); } - public List<Dataset> GetAllDatesets(string uploaderId) + + public List<Dataset> GetMyDatesets(string username) + { + return _dataset.Find(dataset => dataset.username == username).ToList(); + } + public List<Dataset> GetPublicDatesets() { - return _dataset.Find(dataset => dataset.uploaderId == uploaderId).ToList(); + return _dataset.Find(dataset => dataset.isPublic == true).ToList(); } - public Dataset GetOneDataset(string uploaderId, string name) + + public Dataset GetOneDataset(string username, string name) { - return _dataset.Find(dataset => dataset.UploaderId == uploaderId && dataset.name == name).FirstOrDefault(); + return _dataset.Find(dataset => dataset.username == username && dataset.name == name).FirstOrDefault(); } + //odraditi za pretragu getOne //ako je potrebno da se zameni name ili ekstenzija - public void Update(string uploaderId, string name, Dataset dataset) + public void Update(string username, string name, Dataset dataset) { - _dataset.ReplaceOne(dataset => dataset.UploaderId == uploaderId && dataset.name == name, dataset); + _dataset.ReplaceOne(dataset => dataset.username == username && dataset.name == name, dataset); } } } diff --git a/backend/api/api/Services/FileService.cs b/backend/api/api/Services/FileService.cs new file mode 100644 index 00000000..e68a0fe3 --- /dev/null +++ b/backend/api/api/Services/FileService.cs @@ -0,0 +1,34 @@ +using api.Interfaces; +using api.Models; +using MongoDB.Driver; + +namespace api.Services +{ + public class FileService : IFileService + { + + private readonly IMongoCollection<FileModel> _file; + + public FileService(IUserStoreDatabaseSettings settings, IMongoClient mongoClient) + { + var database = mongoClient.GetDatabase(settings.DatabaseName); + _file = database.GetCollection<FileModel>(settings.FilesCollectionName); + } + + public FileModel Create(FileModel file) + { + if (file == null) + return null; + _file.InsertOne(file); + return file; + + } + public string GetFilePath(string id, string username) + { + FileModel file = _file.Find(x => x._id == id && x.username == username).FirstOrDefault(); + if (file == null) + return null; + return file.path; + } + } +} diff --git a/backend/api/api/Services/IDatasetService.cs b/backend/api/api/Services/IDatasetService.cs index 9cf8c3cb..61a04b94 100644 --- a/backend/api/api/Services/IDatasetService.cs +++ b/backend/api/api/Services/IDatasetService.cs @@ -5,10 +5,11 @@ namespace api.Services { public interface IDatasetService { - Dataset GetOneDataset(string uploaderId, string name); - List<Dataset> GetAllDatesets(string uploaderId); + Dataset GetOneDataset(string username, string name); + List<Dataset> GetMyDatesets(string username); + List<Dataset> GetPublicDatesets(); Dataset Create(Dataset dataset); - void Update(string uploaderId, string name, Dataset dataset); - void Delete(string uploaderId, string name); + void Update(string username, string name, Dataset dataset); + void Delete(string username, string name); } } diff --git a/backend/api/api/Services/IFileService.cs b/backend/api/api/Services/IFileService.cs new file mode 100644 index 00000000..7446e283 --- /dev/null +++ b/backend/api/api/Services/IFileService.cs @@ -0,0 +1,10 @@ +using api.Models; + +namespace api.Services +{ + public interface IFileService + { + FileModel Create(FileModel file); + string GetFilePath(string id, string username); + } +}
\ No newline at end of file diff --git a/backend/api/api/Services/IMlConnectionService.cs b/backend/api/api/Services/IMlConnectionService.cs new file mode 100644 index 00000000..f38fb50a --- /dev/null +++ b/backend/api/api/Services/IMlConnectionService.cs @@ -0,0 +1,8 @@ + +namespace api.Services +{ + public interface IMlConnectionService + { + Task<string> SendModelAsync(object model); + } +}
\ No newline at end of file diff --git a/backend/api/api/Services/IModelService.cs b/backend/api/api/Services/IModelService.cs new file mode 100644 index 00000000..c1931ffa --- /dev/null +++ b/backend/api/api/Services/IModelService.cs @@ -0,0 +1,16 @@ +using System; +using api.Models; + +namespace api.Services +{ + public interface IModelService + { + Model GetOneModel(string username, string name); + List<Model> GetMyModels(string username); + //List<Model> GetPublicModels(); + Model Create(Model model); + void Update(string username, string name, Model model); + void Delete(string username, string name); + } +} + diff --git a/backend/api/api/Services/IPredictorService.cs b/backend/api/api/Services/IPredictorService.cs new file mode 100644 index 00000000..594b233b --- /dev/null +++ b/backend/api/api/Services/IPredictorService.cs @@ -0,0 +1,16 @@ +using System; +using api.Models; + +namespace api.Services +{ + public interface IPredictorService + { + Predictor GetOnePredictor(string username, string name); + List<Predictor> GetMyPredictors(string username); + List<Predictor> GetPublicPredictors(); + Predictor Create(Predictor predictor); + void Update(string username, string name, Predictor predictor); + void Delete(string username, string name); + } +} + diff --git a/backend/api/api/Services/MlConnectionService.cs b/backend/api/api/Services/MlConnectionService.cs new file mode 100644 index 00000000..7adade0c --- /dev/null +++ b/backend/api/api/Services/MlConnectionService.cs @@ -0,0 +1,17 @@ +using RestSharp; + +namespace api.Services +{ + public class MlConnectionService : IMlConnectionService + { + public async Task<string> SendModelAsync(object model) + { + RestClient client = new RestClient("http://localhost:5000"); + var request = new RestRequest("data", Method.Post); + request.AddJsonBody(model); + var result = await client.ExecuteAsync(request); + return result.Content;//Response od ML microservisa + + } + } +} diff --git a/backend/api/api/Services/ModelService.cs b/backend/api/api/Services/ModelService.cs new file mode 100644 index 00000000..2ba3c54d --- /dev/null +++ b/backend/api/api/Services/ModelService.cs @@ -0,0 +1,52 @@ +using System; +using api.Interfaces; +using api.Models; +using MongoDB.Driver; + +namespace api.Services +{ + public class ModelService : IModelService + { + + private readonly IMongoCollection<Model> _model; + + public ModelService(IUserStoreDatabaseSettings settings, IMongoClient mongoClient) + { + var database = mongoClient.GetDatabase(settings.DatabaseName); + _model = database.GetCollection<Model>(settings.ModelCollectionName); + } + + public Model Create(Model model) + { + _model.InsertOne(model); + return model; + } + + public void Delete(string username, string name) + { + _model.DeleteOne(model => (model.username == username && model.name == name)); + } + + public List<Model> GetMyModels(string username) + { + return _model.Find(model => model.username == username).ToList(); + } + /* + public List<Model> GetPublicModels() + { + return _model.Find(model => model.isPublic == true).ToList(); + } + */ + public Model GetOneModel(string username, string name) + { + return _model.Find(model => model.username == username && model.name == name).FirstOrDefault(); + } + + public void Update(string username, string name, Model model) + { + _model.ReplaceOne(model => model.username == username && model.name == name, model); + } + + } +} + diff --git a/backend/api/api/Services/PredictorService.cs b/backend/api/api/Services/PredictorService.cs new file mode 100644 index 00000000..69fb25c9 --- /dev/null +++ b/backend/api/api/Services/PredictorService.cs @@ -0,0 +1,50 @@ +using api.Interfaces; +using api.Models; +using MongoDB.Driver; + +namespace api.Services +{ + public class PredictorService : IPredictorService + { + private readonly IMongoCollection<Predictor> _predictor; + + public PredictorService(IUserStoreDatabaseSettings settings, IMongoClient mongoClient) + { + var database = mongoClient.GetDatabase(settings.DatabaseName); + _predictor = database.GetCollection<Predictor>(settings.PredictorCollectionName); + } + + public Predictor Create(Predictor predictor) + { + _predictor.InsertOne(predictor); + return predictor; + } + + public void Delete(string username, string name) + { + _predictor.DeleteOne(predictor => (predictor.username == username && predictor.name == name)); + } + + public List<Predictor> GetMyPredictors(string username) + { + return _predictor.Find(predictor => predictor.username == username).ToList(); + } + + public Predictor GetOnePredictor(string username, string name) + { + return _predictor.Find(predictor => predictor.username == username && predictor.name == name).FirstOrDefault(); + + } + + public List<Predictor> GetPublicPredictors() + { + return _predictor.Find(predictor => predictor.isPublic == true).ToList(); + } + + public void Update(string username, string name, Predictor predictor) + { + _predictor.ReplaceOne(predictor => predictor.username == username && predictor.name == name, predictor); + + } + } +} diff --git a/backend/api/api/api.csproj b/backend/api/api/api.csproj index 46842c3e..f63407ca 100644 --- a/backend/api/api/api.csproj +++ b/backend/api/api/api.csproj @@ -10,6 +10,8 @@ <PackageReference Include="BCrypt.Net-Next" Version="4.0.3" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.3" /> <PackageReference Include="Microsoft.IdentityModel.Tokens" Version="6.16.0" /> + <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> + <PackageReference Include="RestSharp" Version="107.3.0" /> <PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.16.0" /> </ItemGroup> @@ -20,6 +22,7 @@ <ItemGroup> <Folder Include="UploadedFiles\" /> + <Folder Include="UploadedFiles\tester1\" /> </ItemGroup> </Project> diff --git a/backend/api/api/appsettings.json b/backend/api/api/appsettings.json index 3661f171..fdccfb07 100644 --- a/backend/api/api/appsettings.json +++ b/backend/api/api/appsettings.json @@ -11,13 +11,21 @@ "AllowedHosts": "*", "UserStoreDatabaseSettings": { /* LocalHost + */ "ConnectionString": "mongodb://127.0.0.1:27017/", "DatabaseName": "si_project", - "CollectionName": "User" - */ + "CollectionName": "users", + "DatasetCollectionName": "Dataset", + "ModelCollectionName": "Model", + "PredictorCollectionName": "Predictor", + "FilesCollectionName": "Files" + /* "ConnectionString": "mongodb+srv://si_user:si_user@sidatabase.twtfm.mongodb.net/myFirstDatabase?retryWrites=true&w=majority", "DatabaseName": "si_db", "CollectionName": "users", - "DatasetCollectionName" : "Dataset" + "DatasetCollectionName": "Dataset", + "ModelCollectionName": "Model", + "PredictorCollectionName": "Predictor", + "FilesCollectionName": "Files"*/ } -} +}
\ No newline at end of file |