From 3577d7df8233a2d4205918f01cc245a1226ce456 Mon Sep 17 00:00:00 2001 From: "DESKTOP-S0O2C44\\ROG" Date: Sat, 5 Mar 2022 22:47:46 +0100 Subject: Dodat model korisnika i kreirane klase za konekciju sa bazom. --- backend/api/api/Data/MongoDbSettings.cs | 17 +++++++++++++++++ backend/api/api/Models/User.cs | 18 ++++++++++++++++++ backend/api/api/Services/MongoDbService.cs | 11 +++++++++++ backend/api/api/api.csproj | 5 +++++ backend/api/api/appsettings.json | 10 +++++++++- 5 files changed, 60 insertions(+), 1 deletion(-) create mode 100644 backend/api/api/Data/MongoDbSettings.cs create mode 100644 backend/api/api/Models/User.cs create mode 100644 backend/api/api/Services/MongoDbService.cs (limited to 'backend/api') diff --git a/backend/api/api/Data/MongoDbSettings.cs b/backend/api/api/Data/MongoDbSettings.cs new file mode 100644 index 00000000..8b42a02c --- /dev/null +++ b/backend/api/api/Data/MongoDbSettings.cs @@ -0,0 +1,17 @@ +using Microsoft.EntityFrameworkCore; +using MongoDB.Driver; + +namespace api.Data +{ + public class MongoDbSettings + { + public string? ConnectionURI { get; set; } = null; + public string? DatabaseName { get; set; } = null; + public string? CollectionName { get; set; } = null; + + + + + + } +} diff --git a/backend/api/api/Models/User.cs b/backend/api/api/Models/User.cs new file mode 100644 index 00000000..d0f2bc0f --- /dev/null +++ b/backend/api/api/Models/User.cs @@ -0,0 +1,18 @@ +using System.ComponentModel.DataAnnotations; + +namespace api.Models +{ + public class User + { + [Key] + public Guid userId { get; set; } + public string username { get; set; } + public string email { get; set; } + public string password { get; set; } + + + public string firstName { get; set; } + public int lastName { get; set; } + + } +} diff --git a/backend/api/api/Services/MongoDbService.cs b/backend/api/api/Services/MongoDbService.cs new file mode 100644 index 00000000..f8b37536 --- /dev/null +++ b/backend/api/api/Services/MongoDbService.cs @@ -0,0 +1,11 @@ + + + +namespace api.Services +{ + public class MongoDbService + { + + + } +} diff --git a/backend/api/api/api.csproj b/backend/api/api/api.csproj index f278c90a..d4cc5552 100644 --- a/backend/api/api/api.csproj +++ b/backend/api/api/api.csproj @@ -10,4 +10,9 @@ + + + + + diff --git a/backend/api/api/appsettings.json b/backend/api/api/appsettings.json index 10f68b8c..7a5b7f7a 100644 --- a/backend/api/api/appsettings.json +++ b/backend/api/api/appsettings.json @@ -5,5 +5,13 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "*" + "AllowedHosts": "*", + + "MongoDb": { + "ConnectionURI": "mongodb+srv://LINKIKKKKKKK" + "DatabaseName": "" + "CollectionName": "" + + } + } -- cgit v1.2.3 From a86d5871e6e1270f9863efe3642a7a1f645c980c Mon Sep 17 00:00:00 2001 From: Ognjen Cirkovic Date: Sun, 6 Mar 2022 02:09:55 +0100 Subject: Dodata klasa za hashovanje sifri. --- backend/api/api/Models/PasswordCrypt.cs | 27 +++++++++++++++++++++++++++ backend/api/api/api.csproj | 4 ++-- 2 files changed, 29 insertions(+), 2 deletions(-) create mode 100644 backend/api/api/Models/PasswordCrypt.cs (limited to 'backend/api') diff --git a/backend/api/api/Models/PasswordCrypt.cs b/backend/api/api/Models/PasswordCrypt.cs new file mode 100644 index 00000000..016fde51 --- /dev/null +++ b/backend/api/api/Models/PasswordCrypt.cs @@ -0,0 +1,27 @@ +namespace api.Models +{ + public class PasswordCrypt + { + private static int difficulty = 10; + + public static String hashPassword(String password) + { + String salt = BCrypt.Net.BCrypt.GenerateSalt(difficulty); + String passwordHash = BCrypt.Net.BCrypt.HashPassword(password, salt); + + return passwordHash; + } + public static Boolean checkPassword(String plainText,String hash) + { + Boolean verified = false; + + if (hash == null || !hash.StartsWith("$2a$")) + throw new ArgumentException("invalid hash"); + + verified=BCrypt.Net.BCrypt.Verify(plainText, hash); + + return verified; + + } + } +} diff --git a/backend/api/api/api.csproj b/backend/api/api/api.csproj index f278c90a..97b88d00 100644 --- a/backend/api/api/api.csproj +++ b/backend/api/api/api.csproj @@ -1,4 +1,4 @@ - + net6.0 @@ -7,7 +7,7 @@ - + -- cgit v1.2.3 From 716754330e70a61ed0cb119d24a54e7bc7b4736b Mon Sep 17 00:00:00 2001 From: Ognjen Cirkovic Date: Mon, 7 Mar 2022 00:44:07 +0100 Subject: Napravljene klase za token i zahteve za logovanje i registrovanje.Napravljen kontroler i servis za prijavljivanje i registrovanje. --- backend/api/api/Controllers/AuthController.cs | 34 +++++++++++++++++++++++ backend/api/api/Models/JwtToken.cs | 37 +++++++++++++++++++++++++ backend/api/api/Models/Users/AuthRequest.cs | 13 +++++++++ backend/api/api/Models/Users/RegisterRequest.cs | 23 +++++++++++++++ backend/api/api/Services/AuthService.cs | 36 ++++++++++++++++++++++++ backend/api/api/api.csproj | 2 ++ backend/api/api/appsettings.json | 17 +++++++----- 7 files changed, 155 insertions(+), 7 deletions(-) create mode 100644 backend/api/api/Controllers/AuthController.cs create mode 100644 backend/api/api/Models/JwtToken.cs create mode 100644 backend/api/api/Models/Users/AuthRequest.cs create mode 100644 backend/api/api/Models/Users/RegisterRequest.cs create mode 100644 backend/api/api/Services/AuthService.cs (limited to 'backend/api') diff --git a/backend/api/api/Controllers/AuthController.cs b/backend/api/api/Controllers/AuthController.cs new file mode 100644 index 00000000..1f47067f --- /dev/null +++ b/backend/api/api/Controllers/AuthController.cs @@ -0,0 +1,34 @@ +using api.Models.Users; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using api.Services; + +namespace api.Controllers +{ + [Route("api/[controller]")] + [ApiController] + public class AuthController : ControllerBase + { + private AuthService _auth; + public AuthController(IConfiguration configuration) + { + _auth=new AuthService(configuration); + } + + [HttpPost("register")] + public async Task> Register(RegisterRequest user) + { + + return Ok(_auth.Register(user)); + } + + [HttpPost("login")] + public async Task> Login(AuthRequest user) + { + + return Ok(_auth.Login(user)); + } + + + } +} diff --git a/backend/api/api/Models/JwtToken.cs b/backend/api/api/Models/JwtToken.cs new file mode 100644 index 00000000..23307185 --- /dev/null +++ b/backend/api/api/Models/JwtToken.cs @@ -0,0 +1,37 @@ +using System.IdentityModel.Tokens.Jwt; +using System.Security.Claims; +using System.Text; +using api.Models.Users; +using Microsoft.IdentityModel.Tokens; + +namespace api.Models +{ + public class JwtToken + { + private readonly IConfiguration _configuration; + + public JwtToken(IConfiguration configuration) + { + _configuration = configuration; + } + + public string GenToken(AuthRequest user) + { + var tokenHandler = new JwtSecurityTokenHandler(); + var key = Encoding.ASCII.GetBytes(_configuration.GetSection("AppSettings:JwtToken").Value); + var tokenDescriptor = new SecurityTokenDescriptor + { + Subject = new ClaimsIdentity(new[] { new Claim("name", user.UserName), + new Claim("role", "User")}), + Expires = DateTime.UtcNow.AddDays(1), + SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) + }; + var token = tokenHandler.CreateToken(tokenDescriptor); + return tokenHandler.WriteToken(token); + + } + + + + } +} diff --git a/backend/api/api/Models/Users/AuthRequest.cs b/backend/api/api/Models/Users/AuthRequest.cs new file mode 100644 index 00000000..fbf2412d --- /dev/null +++ b/backend/api/api/Models/Users/AuthRequest.cs @@ -0,0 +1,13 @@ +using System.ComponentModel.DataAnnotations; + +namespace api.Models.Users +{ + public class AuthRequest + { + [Required] + public string UserName { get; set; } + [Required] + public string Password { get; set; } + + } +} diff --git a/backend/api/api/Models/Users/RegisterRequest.cs b/backend/api/api/Models/Users/RegisterRequest.cs new file mode 100644 index 00000000..675d571d --- /dev/null +++ b/backend/api/api/Models/Users/RegisterRequest.cs @@ -0,0 +1,23 @@ +using System.ComponentModel.DataAnnotations; + +namespace api.Models.Users +{ + public class RegisterRequest + { + [Required] + public string firstName { get; set; } + + [Required] + public string lastName { get; set; } + + [Required] + public string username { get; set; } + + [Required] + public string email { get; set; } + + [Required] + public string password { get; set; } + + } +} diff --git a/backend/api/api/Services/AuthService.cs b/backend/api/api/Services/AuthService.cs new file mode 100644 index 00000000..1a901cb8 --- /dev/null +++ b/backend/api/api/Services/AuthService.cs @@ -0,0 +1,36 @@ +using api.Models; +using api.Models.Users; + +namespace api.Services +{ + public class AuthService + { + private JwtToken _jwt; + private readonly IConfiguration _configuration; + public AuthService(IConfiguration configuration) + { + _configuration = configuration; + _jwt = new JwtToken(_configuration); + } + public string Login(AuthRequest user) + { + //Check username in DB + + //Verify password + + //gen token + + return _jwt.GenToken(user); + + } + public RegisterRequest Register(RegisterRequest user) + { + //check for existing email and username + user.password = PasswordCrypt.hashPassword(user.password); + //Add to DB. TO DO + return user; + } + + + } +} diff --git a/backend/api/api/api.csproj b/backend/api/api/api.csproj index 97b88d00..d2a5dd9d 100644 --- a/backend/api/api/api.csproj +++ b/backend/api/api/api.csproj @@ -8,6 +8,8 @@ + + diff --git a/backend/api/api/appsettings.json b/backend/api/api/appsettings.json index 10f68b8c..5d8e7156 100644 --- a/backend/api/api/appsettings.json +++ b/backend/api/api/appsettings.json @@ -1,9 +1,12 @@ { - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - }, - "AllowedHosts": "*" + "AppSettings": { + "JwtToken": "2mnttqPtRb4GIWHFtagm" + }, + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" } -- cgit v1.2.3 From 2e8e7bad8f7cf0c5c333ac4bf95381defbdf4ae0 Mon Sep 17 00:00:00 2001 From: Ognjen Cirkovic Date: Mon, 7 Mar 2022 19:56:52 +0100 Subject: Dodat Cors. --- backend/api/api/Program.cs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) (limited to 'backend/api') diff --git a/backend/api/api/Program.cs b/backend/api/api/Program.cs index 478b7052..84514972 100644 --- a/backend/api/api/Program.cs +++ b/backend/api/api/Program.cs @@ -1,11 +1,22 @@ var builder = WebApplication.CreateBuilder(args); -// Add services to the container. +//Add Cors +builder.Services.AddCors(); + +// Add services to the container builder.Services.AddControllers(); var app = builder.Build(); + +//Add Cors +app.UseCors( + x=>x.AllowAnyOrigin() + .AllowAnyMethod() + .AllowAnyHeader() + ); + // Configure the HTTP request pipeline. app.UseAuthorization(); -- cgit v1.2.3 From 158c874a459b41cfacbd0238230dc5f48f481d44 Mon Sep 17 00:00:00 2001 From: "DESKTOP-S0O2C44\\ROG" Date: Tue, 8 Mar 2022 17:19:37 +0100 Subject: Odradjena konekcija sa bazom. Odradjen kontroler za korisnika(get,post, put, delete). --- backend/api/api/Controllers/UserController.cs | 91 ++++++++++++++++++++++ backend/api/api/Data/MongoDbSettings.cs | 17 ---- backend/api/api/Data/UserStoreDatabaseSettings.cs | 13 ++++ .../api/Interfaces/IUserStoreDatabaseSettings.cs | 9 +++ backend/api/api/Models/User.cs | 24 ++++-- backend/api/api/Program.cs | 19 +++++ backend/api/api/Services/IUserService.cs | 13 ++++ backend/api/api/Services/MongoDbService.cs | 11 --- backend/api/api/Services/UserService.cs | 54 +++++++++++++ backend/api/api/appsettings.json | 9 +-- 10 files changed, 220 insertions(+), 40 deletions(-) create mode 100644 backend/api/api/Controllers/UserController.cs delete mode 100644 backend/api/api/Data/MongoDbSettings.cs create mode 100644 backend/api/api/Data/UserStoreDatabaseSettings.cs create mode 100644 backend/api/api/Interfaces/IUserStoreDatabaseSettings.cs create mode 100644 backend/api/api/Services/IUserService.cs delete mode 100644 backend/api/api/Services/MongoDbService.cs create mode 100644 backend/api/api/Services/UserService.cs (limited to 'backend/api') diff --git a/backend/api/api/Controllers/UserController.cs b/backend/api/api/Controllers/UserController.cs new file mode 100644 index 00000000..b1544477 --- /dev/null +++ b/backend/api/api/Controllers/UserController.cs @@ -0,0 +1,91 @@ +using api.Models; +using api.Services; +using Microsoft.AspNetCore.Mvc; +using System.Diagnostics; + +// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 +//dovrsi kontroler +namespace api.Controllers +{ + [Route("api/[controller]")] + [ApiController] + public class UserController : ControllerBase + { + private readonly IUserService userService; + + public UserController(IUserService userService) + { + this.userService = userService; + } + + // GET: api/ + [HttpGet] + public ActionResult> Get() + { + return userService.Get(); + } + + // GET api//5 + //potrebno za profile page + [HttpGet("{id}")] + public ActionResult Get(string id) + { + var user = userService.Get(id); + + if (user == null) + return NotFound($"User with Id = {id} not found"); + + return user; + } + + // POST api/ + [HttpPost] + public ActionResult Post([FromBody] User user) + { + userService.Create(user); + + //Debug.WriteLine("\nTest.\n"); + + return CreatedAtAction(nameof(Get), new { id = user._id }, user); + + } + + // PUT api//5 + [HttpPut("{id}")] + public ActionResult Put(string id, [FromBody] User user) + { + var existingUser = userService.Get(id); + + if(existingUser == null) + return NotFound($"User with Id = {id} not found"); + + userService.Update(id, existingUser); + return NoContent(); + } + + // DELETE api//5 + [HttpDelete("{id}")] + public ActionResult Delete(string id) + { + var user = userService.Get(id); + + if (user == null) + return NotFound($"User with Id = {id} not found"); + + userService.Delete(user._id); + return Ok($"Student with Id = {id} deleted"); + } + } +} +/* +{ + "userId": { + "$oid": "62276146c4a20eabc664abc3" + }, + "username" : "ivan996sk", + "email" : "ivan996sk@gmail.com", + "password" : "proba", + "firstName" : "Ivan", + "lastName" : "Ljubisavljevic" +} +*/ \ No newline at end of file diff --git a/backend/api/api/Data/MongoDbSettings.cs b/backend/api/api/Data/MongoDbSettings.cs deleted file mode 100644 index 8b42a02c..00000000 --- a/backend/api/api/Data/MongoDbSettings.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using MongoDB.Driver; - -namespace api.Data -{ - public class MongoDbSettings - { - public string? ConnectionURI { get; set; } = null; - public string? DatabaseName { get; set; } = null; - public string? CollectionName { get; set; } = null; - - - - - - } -} diff --git a/backend/api/api/Data/UserStoreDatabaseSettings.cs b/backend/api/api/Data/UserStoreDatabaseSettings.cs new file mode 100644 index 00000000..0efd2895 --- /dev/null +++ b/backend/api/api/Data/UserStoreDatabaseSettings.cs @@ -0,0 +1,13 @@ +using Microsoft.EntityFrameworkCore; +using MongoDB.Driver; +using api.Interfaces; + +namespace api.Data +{ + public class UserStoreDatabaseSettings : IUserStoreDatabaseSettings + { + public string ConnectionString { get; set; } = String.Empty; + public string DatabaseName { get; set; } = String.Empty; + public string CollectionName { get; set; } = String.Empty; + } +} diff --git a/backend/api/api/Interfaces/IUserStoreDatabaseSettings.cs b/backend/api/api/Interfaces/IUserStoreDatabaseSettings.cs new file mode 100644 index 00000000..43fe9b3a --- /dev/null +++ b/backend/api/api/Interfaces/IUserStoreDatabaseSettings.cs @@ -0,0 +1,9 @@ +namespace api.Interfaces +{ + public interface IUserStoreDatabaseSettings + { + string ConnectionString { get; set; } + string DatabaseName { get; set; } + string CollectionName { get; set; } + } +} diff --git a/backend/api/api/Models/User.cs b/backend/api/api/Models/User.cs index d0f2bc0f..46db50ab 100644 --- a/backend/api/api/Models/User.cs +++ b/backend/api/api/Models/User.cs @@ -1,18 +1,28 @@ using System.ComponentModel.DataAnnotations; +using MongoDB.Bson; +using MongoDB.Bson.Serialization.Attributes; + namespace api.Models { + [BsonIgnoreExtraElements]//ignorise visak elemenata iz baze --moze da se obrise jer nemamo viska public class User { - [Key] - public Guid userId { get; set; } - public string username { get; set; } - public string email { get; set; } - public string password { get; set; } + [BsonId] + [BsonRepresentation(BsonType.ObjectId)]//mongo data type to .net + public string _id { get; set; } + [BsonElement("username")] + public string Username { get; set; } + [BsonElement("email")] + public string Email { get; set; } + [BsonElement("password")] + public string Password { get; set; } - public string firstName { get; set; } - public int lastName { get; set; } + [BsonElement("firstName")] + public string FirstName { get; set; } + [BsonElement("lastName")] + public string LastName { get; set; } } } diff --git a/backend/api/api/Program.cs b/backend/api/api/Program.cs index 84514972..c54b1b3e 100644 --- a/backend/api/api/Program.cs +++ b/backend/api/api/Program.cs @@ -1,9 +1,28 @@ +using api.Data; +using api.Interfaces; +using api.Services; +using Microsoft.Extensions.Options; +using MongoDB.Driver; + var builder = WebApplication.CreateBuilder(args); //Add Cors builder.Services.AddCors(); // Add services to the container +//dodajemo dep inj + +builder.Services.Configure( + builder.Configuration.GetSection(nameof(UserStoreDatabaseSettings))); + +builder.Services.AddSingleton(sp => + sp.GetRequiredService>().Value); + +builder.Services.AddSingleton(s => + new MongoClient(builder.Configuration.GetValue("UserStoreDatabaseSettings:ConnectionString"))); + +builder.Services.AddScoped(); + builder.Services.AddControllers(); diff --git a/backend/api/api/Services/IUserService.cs b/backend/api/api/Services/IUserService.cs new file mode 100644 index 00000000..e9f14c8b --- /dev/null +++ b/backend/api/api/Services/IUserService.cs @@ -0,0 +1,13 @@ +using api.Models; + +namespace api.Services +{ + public interface IUserService + { + List Get();// daje sve korisnike + User Get(string id); //daje korisnika po id-u + User Create(User user); // kreira korisnika + void Update(string id, User user); //apdejruje korisnika po idu + void Delete(string id);//brise korisnika + } +} diff --git a/backend/api/api/Services/MongoDbService.cs b/backend/api/api/Services/MongoDbService.cs deleted file mode 100644 index f8b37536..00000000 --- a/backend/api/api/Services/MongoDbService.cs +++ /dev/null @@ -1,11 +0,0 @@ - - - -namespace api.Services -{ - public class MongoDbService - { - - - } -} diff --git a/backend/api/api/Services/UserService.cs b/backend/api/api/Services/UserService.cs new file mode 100644 index 00000000..e5d1bb32 --- /dev/null +++ b/backend/api/api/Services/UserService.cs @@ -0,0 +1,54 @@ +using api.Interfaces; +using api.Models; +using MongoDB.Driver; + +namespace api.Services +{ + public class UserService : IUserService + { + private readonly IMongoCollection _users; + + public UserService(IUserStoreDatabaseSettings settings, IMongoClient mongoClient) + { + var database = mongoClient.GetDatabase(settings.DatabaseName); + _users = database.GetCollection(settings.CollectionName); + } + public User Create(User user) + { + _users.InsertOne(user); + return user; + } + + + + public List Get() + { + return _users.Find(user => true).ToList(); + } + + public User Get(string id) + { + return _users.Find(user => user._id == id).FirstOrDefault(); + } + + public void Delete(string id) + { + _users.DeleteOne(user => user._id == id); + + } + public void Update(string id, User user) + { + _users.ReplaceOne(user => user._id == id, user); + } + } +} +/* + { + "_id": "", + "username" : "ivan996sk", + "email" : "ivan996sk@gmail.com", + "password" : "proba", + "firstName" : "Ivan", + "lastName" : "Ljubisavljevic" +} + */ \ No newline at end of file diff --git a/backend/api/api/appsettings.json b/backend/api/api/appsettings.json index b9144d93..d2c95254 100644 --- a/backend/api/api/appsettings.json +++ b/backend/api/api/appsettings.json @@ -9,10 +9,9 @@ } }, "AllowedHosts": "*", - "MongoDb": { - "ConnectionURI": "mongodb+srv://LINKIKKKKKKK", - "DatabaseName": "", - "CollectionName": "" - + "UserStoreDatabaseSettings": { + "ConnectionString": "mongodb://127.0.0.1:27017/", + "DatabaseName": "si_project", + "CollectionName": "User" } } -- cgit v1.2.3 From 52dec403d19a732591f9ce27ec802e3f8c480a9a Mon Sep 17 00:00:00 2001 From: Ognjen Cirkovic Date: Tue, 8 Mar 2022 18:28:18 +0100 Subject: Dodat dependency injection. Auth Servis povezan sa bazom --- backend/api/api/Controllers/AuthController.cs | 6 ++-- backend/api/api/Program.cs | 3 +- backend/api/api/Services/AuthService.cs | 41 ++++++++++++++++++--------- backend/api/api/Services/IAuthService.cs | 10 +++++++ 4 files changed, 42 insertions(+), 18 deletions(-) create mode 100644 backend/api/api/Services/IAuthService.cs (limited to 'backend/api') diff --git a/backend/api/api/Controllers/AuthController.cs b/backend/api/api/Controllers/AuthController.cs index 1f47067f..100ab3ca 100644 --- a/backend/api/api/Controllers/AuthController.cs +++ b/backend/api/api/Controllers/AuthController.cs @@ -9,10 +9,10 @@ namespace api.Controllers [ApiController] public class AuthController : ControllerBase { - private AuthService _auth; - public AuthController(IConfiguration configuration) + private IAuthService _auth; + public AuthController(IAuthService auth) { - _auth=new AuthService(configuration); + _auth = auth; } [HttpPost("register")] diff --git a/backend/api/api/Program.cs b/backend/api/api/Program.cs index c54b1b3e..4c2d1b9f 100644 --- a/backend/api/api/Program.cs +++ b/backend/api/api/Program.cs @@ -22,7 +22,8 @@ builder.Services.AddSingleton(s => new MongoClient(builder.Configuration.GetValue("UserStoreDatabaseSettings:ConnectionString"))); builder.Services.AddScoped(); - +builder.Services.AddScoped(); + builder.Services.AddControllers(); diff --git a/backend/api/api/Services/AuthService.cs b/backend/api/api/Services/AuthService.cs index 1a901cb8..015fdac7 100644 --- a/backend/api/api/Services/AuthService.cs +++ b/backend/api/api/Services/AuthService.cs @@ -1,34 +1,47 @@ -using api.Models; +using api.Interfaces; +using api.Models; using api.Models.Users; +using MongoDB.Driver; namespace api.Services { - public class AuthService + public class AuthService : IAuthService { private JwtToken _jwt; private readonly IConfiguration _configuration; - public AuthService(IConfiguration configuration) + private readonly IMongoCollection _users; + public AuthService(IConfiguration configuration, IUserStoreDatabaseSettings settings, IMongoClient mongoClient) { _configuration = configuration; _jwt = new JwtToken(_configuration); + var database = mongoClient.GetDatabase(settings.DatabaseName); + _users = database.GetCollection(settings.CollectionName); } public string Login(AuthRequest user) { - //Check username in DB - - //Verify password - - //gen token - + User u = _users.Find(x => x.Username == user.UserName).FirstOrDefault(); + if (u == null) + return "Username doesn't exist"; + if (!PasswordCrypt.checkPassword(user.Password, u.Password)) + return "Wrong password"; return _jwt.GenToken(user); } - public RegisterRequest Register(RegisterRequest user) + public string Register(RegisterRequest user) { - //check for existing email and username - user.password = PasswordCrypt.hashPassword(user.password); - //Add to DB. TO DO - return user; + User u = new User(); + u.Username = user.username; + u.Email = user.email; + u.Password = PasswordCrypt.hashPassword(user.password); + u.FirstName = user.firstName; + u.LastName = user.lastName; + if (_users.Find(user => user.Username == u.Username).FirstOrDefault() != null) + return "Username Already Exists"; + if (_users.Find(user => user.Email == u.Email).FirstOrDefault() != null) + return "Email Already Exists"; + + _users.InsertOne(u); + return "User added"; } diff --git a/backend/api/api/Services/IAuthService.cs b/backend/api/api/Services/IAuthService.cs new file mode 100644 index 00000000..79085f8c --- /dev/null +++ b/backend/api/api/Services/IAuthService.cs @@ -0,0 +1,10 @@ +using api.Models.Users; + +namespace api.Services +{ + public interface IAuthService + { + string Login(AuthRequest user); + string Register(RegisterRequest user); + } +} \ No newline at end of file -- cgit v1.2.3 From 0240854fb119a1bbbf799daa11c978783331ecd4 Mon Sep 17 00:00:00 2001 From: Ognjen Cirkovic Date: Tue, 8 Mar 2022 18:58:09 +0100 Subject: Dodata autorizacija sa test zahtevom. --- backend/api/api/Controllers/AuthController.cs | 8 ++++++++ backend/api/api/Program.cs | 20 ++++++++++++++++++++ backend/api/api/api.csproj | 1 + 3 files changed, 29 insertions(+) (limited to 'backend/api') diff --git a/backend/api/api/Controllers/AuthController.cs b/backend/api/api/Controllers/AuthController.cs index 100ab3ca..c74c579d 100644 --- a/backend/api/api/Controllers/AuthController.cs +++ b/backend/api/api/Controllers/AuthController.cs @@ -2,6 +2,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using api.Services; +using Microsoft.AspNetCore.Authorization; namespace api.Controllers { @@ -29,6 +30,13 @@ namespace api.Controllers return Ok(_auth.Login(user)); } + [HttpGet("Auth")] + [Authorize(Roles ="User")] + public async Task> TestAuth() + { + return Ok("works"); + } + } } diff --git a/backend/api/api/Program.cs b/backend/api/api/Program.cs index 4c2d1b9f..550f6ce1 100644 --- a/backend/api/api/Program.cs +++ b/backend/api/api/Program.cs @@ -1,7 +1,10 @@ +using System.Text; using api.Data; using api.Interfaces; using api.Services; +using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.Extensions.Options; +using Microsoft.IdentityModel.Tokens; using MongoDB.Driver; var builder = WebApplication.CreateBuilder(args); @@ -21,9 +24,23 @@ builder.Services.AddSingleton(sp => builder.Services.AddSingleton(s => new MongoClient(builder.Configuration.GetValue("UserStoreDatabaseSettings:ConnectionString"))); +//Inject Dependencies builder.Services.AddScoped(); builder.Services.AddScoped(); +//Add Authentication +builder.Services.AddAuthentication( + JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options => { + options.TokenValidationParameters = new TokenValidationParameters + { + ValidateIssuerSigningKey = true, + IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(builder.Configuration.GetSection("AppSettings:JwtToken").Value)), + ValidateIssuer=false, + ValidateAudience=false + }; + + }); + builder.Services.AddControllers(); @@ -39,6 +56,9 @@ app.UseCors( // Configure the HTTP request pipeline. +//Add Authentication +app.UseAuthentication(); + app.UseAuthorization(); app.MapControllers(); diff --git a/backend/api/api/api.csproj b/backend/api/api/api.csproj index 1451fa77..6081cd21 100644 --- a/backend/api/api/api.csproj +++ b/backend/api/api/api.csproj @@ -8,6 +8,7 @@ + -- cgit v1.2.3 From 3f967d3aefd019f18dc7f464e77c889270dd7d18 Mon Sep 17 00:00:00 2001 From: Ognjen Cirkovic Date: Wed, 9 Mar 2022 00:20:46 +0100 Subject: Dodat kontroler za ucitavanje datoteka. Izbrisan auth test. --- backend/api/api/.gitignore | 3 ++ backend/api/api/Controllers/AuthController.cs | 6 --- .../api/api/Controllers/FileUploadController.cs | 47 ++++++++++++++++++++++ backend/api/api/api.csproj | 4 ++ 4 files changed, 54 insertions(+), 6 deletions(-) create mode 100644 backend/api/api/Controllers/FileUploadController.cs (limited to 'backend/api') diff --git a/backend/api/api/.gitignore b/backend/api/api/.gitignore index 8afdcb63..242abea5 100644 --- a/backend/api/api/.gitignore +++ b/backend/api/api/.gitignore @@ -3,6 +3,9 @@ ## ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore +##Ignore contents for UploadedFiles Folder +UploadedFiles/* + # User-specific files *.rsuser *.suo diff --git a/backend/api/api/Controllers/AuthController.cs b/backend/api/api/Controllers/AuthController.cs index c74c579d..01354f87 100644 --- a/backend/api/api/Controllers/AuthController.cs +++ b/backend/api/api/Controllers/AuthController.cs @@ -30,12 +30,6 @@ namespace api.Controllers return Ok(_auth.Login(user)); } - [HttpGet("Auth")] - [Authorize(Roles ="User")] - public async Task> TestAuth() - { - return Ok("works"); - } } diff --git a/backend/api/api/Controllers/FileUploadController.cs b/backend/api/api/Controllers/FileUploadController.cs new file mode 100644 index 00000000..46e7f4f9 --- /dev/null +++ b/backend/api/api/Controllers/FileUploadController.cs @@ -0,0 +1,47 @@ +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> 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/api.csproj b/backend/api/api/api.csproj index 6081cd21..46842c3e 100644 --- a/backend/api/api/api.csproj +++ b/backend/api/api/api.csproj @@ -18,4 +18,8 @@ + + + + -- cgit v1.2.3 From 191d14be7be275e1f5de58c2cbf83fec9d27cf52 Mon Sep 17 00:00:00 2001 From: "DESKTOP-S0O2C44\\ROG" Date: Wed, 9 Mar 2022 19:59:05 +0100 Subject: Ipravljen update korisnika #24 --- backend/api/api/Controllers/UserController.cs | 7 +++---- backend/api/api/appsettings.json | 4 ++++ 2 files changed, 7 insertions(+), 4 deletions(-) (limited to 'backend/api') diff --git a/backend/api/api/Controllers/UserController.cs b/backend/api/api/Controllers/UserController.cs index b1544477..a106880e 100644 --- a/backend/api/api/Controllers/UserController.cs +++ b/backend/api/api/Controllers/UserController.cs @@ -56,10 +56,11 @@ namespace api.Controllers { var existingUser = userService.Get(id); + //ne mora da se proverava if(existingUser == null) return NotFound($"User with Id = {id} not found"); - userService.Update(id, existingUser); + userService.Update(id, user); return NoContent(); } @@ -79,9 +80,7 @@ namespace api.Controllers } /* { - "userId": { - "$oid": "62276146c4a20eabc664abc3" - }, + "_id": "", "username" : "ivan996sk", "email" : "ivan996sk@gmail.com", "password" : "proba", diff --git a/backend/api/api/appsettings.json b/backend/api/api/appsettings.json index d2c95254..257c2f45 100644 --- a/backend/api/api/appsettings.json +++ b/backend/api/api/appsettings.json @@ -13,5 +13,9 @@ "ConnectionString": "mongodb://127.0.0.1:27017/", "DatabaseName": "si_project", "CollectionName": "User" + /* "ConnectionString": "mongodb+srv://SIDatabase:SIDatabase@sidatabase.twtfm.mongodb.net/myFirstDatabase?retryWrites=true&w=majority", + "DatabaseName": "si_db", + "CollectionName": "users" + */ } } -- cgit v1.2.3 From a95a921478435cc6400236d291281c3d0156a7e1 Mon Sep 17 00:00:00 2001 From: "DESKTOP-S0O2C44\\ROG" Date: Wed, 9 Mar 2022 20:42:27 +0100 Subject: Odradjena konekcija sa klasterom. Zabranjeno kreiranje korisnika sa istim imenom. #24 --- backend/api/api/Controllers/UserController.cs | 24 +++++++++++++++++++++--- backend/api/api/Services/IUserService.cs | 1 + backend/api/api/Services/UserService.cs | 6 ++++-- backend/api/api/appsettings.json | 7 +++++-- 4 files changed, 31 insertions(+), 7 deletions(-) (limited to 'backend/api') diff --git a/backend/api/api/Controllers/UserController.cs b/backend/api/api/Controllers/UserController.cs index a106880e..85f8218d 100644 --- a/backend/api/api/Controllers/UserController.cs +++ b/backend/api/api/Controllers/UserController.cs @@ -37,17 +37,35 @@ namespace api.Controllers return user; } + // GET api//5 + //potrebno za profile page + [HttpGet("{id}")] + public ActionResult GetUserUsername(string username) + { + var user = userService.GetUserUsername(username); + if (user == null) + return NotFound($"User with Id = {username} not found"); + + return user; + } // POST api/ [HttpPost] public ActionResult Post([FromBody] User user) { - userService.Create(user); + + var existingUser = userService.GetUserUsername(user.Username); - //Debug.WriteLine("\nTest.\n"); + if (existingUser != null) + return NotFound($"User with username = {user.Username} exisits"); + else + { + userService.Create(user); - return CreatedAtAction(nameof(Get), new { id = user._id }, user); + //Debug.WriteLine("\nTest.\n"); + return CreatedAtAction(nameof(Get), new { id = user._id }, user); + } } // PUT api//5 diff --git a/backend/api/api/Services/IUserService.cs b/backend/api/api/Services/IUserService.cs index e9f14c8b..b6725694 100644 --- a/backend/api/api/Services/IUserService.cs +++ b/backend/api/api/Services/IUserService.cs @@ -6,6 +6,7 @@ namespace api.Services { List Get();// daje sve korisnike User Get(string id); //daje korisnika po id-u + User GetUserUsername(string username); //daje korisnika po korisnickom imenu User Create(User user); // kreira korisnika void Update(string id, User user); //apdejruje korisnika po idu void Delete(string id);//brise korisnika diff --git a/backend/api/api/Services/UserService.cs b/backend/api/api/Services/UserService.cs index e5d1bb32..e1d1e8b7 100644 --- a/backend/api/api/Services/UserService.cs +++ b/backend/api/api/Services/UserService.cs @@ -19,12 +19,14 @@ namespace api.Services return user; } - - public List Get() { return _users.Find(user => true).ToList(); } + public User GetUserUsername(string username) + { + return _users.Find(user => user.Username == username).FirstOrDefault(); + } public User Get(string id) { diff --git a/backend/api/api/appsettings.json b/backend/api/api/appsettings.json index 257c2f45..204eba33 100644 --- a/backend/api/api/appsettings.json +++ b/backend/api/api/appsettings.json @@ -10,12 +10,15 @@ }, "AllowedHosts": "*", "UserStoreDatabaseSettings": { + /* LocalHost "ConnectionString": "mongodb://127.0.0.1:27017/", "DatabaseName": "si_project", "CollectionName": "User" - /* "ConnectionString": "mongodb+srv://SIDatabase:SIDatabase@sidatabase.twtfm.mongodb.net/myFirstDatabase?retryWrites=true&w=majority", + + */ + "ConnectionString": "mongodb+srv://si_user:si_user@sidatabase.twtfm.mongodb.net/myFirstDatabase?retryWrites=true&w=majority", "DatabaseName": "si_db", "CollectionName": "users" - */ + } } -- cgit v1.2.3