Changeset 057037b
- Timestamp:
- 04/11/22 15:29:19 (3 years ago)
- Branches:
- master
- Children:
- 7a983b0
- Parents:
- b66b3ac
- Files:
-
- 14 added
- 13 edited
Legend:
- Unmodified
- Added
- Removed
-
backend/Controllers/UsersController.cs
rb66b3ac r057037b 1 1 namespace backend.Controllers; 2 2 3 using backend.DTOs; 3 4 using backend.Helpers; 4 5 using backend.Models; … … 10 11 public class UsersController : ControllerBase 11 12 { 12 private IUserService _userService;13 private readonly IUserService _userService = null; 13 14 14 15 public UsersController(IUserService userService) … … 17 18 } 18 19 19 [HttpPost(" authenticate")]20 public IActionResultAuthenticate(AuthenticateRequest model)20 [HttpPost("login")] 21 public async Task<AuthenticateResponse> Authenticate(AuthenticateRequest model) 21 22 { 22 var response = _userService.Authenticate(model);23 var response = await _userService.Authenticate(model); 23 24 24 25 if (response == null) 25 return BadRequest(new { message = "Username or password is incorrect" });26 throw new Exception("Email or password is incorrect"); 26 27 27 return Ok(response);28 return response; 28 29 } 29 30 30 [Authorize] 31 [HttpGet] 32 public IActionResult GetUserById(int id) 31 [HttpPost("register")] 32 public async Task<AuthenticateResponse> Register(CreateUserRequest req) 33 33 { 34 var users = _userService.GetById(id);35 return Ok(users);34 var response = await _userService.Register(req); 35 return response; 36 36 } 37 37 } -
backend/DTOs/AuthenticateRequest.cs
rb66b3ac r057037b 6 6 { 7 7 [Required] 8 public string Username{ get; set; }8 public string Email { get; set; } 9 9 10 10 [Required] -
backend/DTOs/AuthenticateResponse.cs
rb66b3ac r057037b 1 1 using backend.Entities; 2 using Newtonsoft.Json; 2 3 3 4 namespace backend.Models; … … 6 7 public class AuthenticateResponse 7 8 { 9 [JsonProperty] 8 10 public int Id { get; set; } 9 public string Username { get; set; } 11 [JsonProperty] 12 public string Email { get; set; } 13 [JsonProperty] 10 14 public string Token { get; set; } 11 12 13 public AuthenticateResponse(User user, string token)14 {15 Id = user.Id;16 Username = user.Username;17 Token = token;18 }19 15 } -
backend/Entities/Reservation.cs
rb66b3ac r057037b 1 namespace backend.Entities 1 using Newtonsoft.Json; 2 3 namespace backend.Entities 2 4 { 3 5 public class Reservation … … 5 7 public int Id { get; set; } 6 8 public DateTime StartDate { get; set; } 9 public int Persons { get; set; } 7 10 public virtual Restaurant Restaurant { get; set; } 8 11 public ReservationPlace ReservationPlace { get; set; } -
backend/Entities/Restaurant.cs
rb66b3ac r057037b 1 namespace backend.Entities 1 using Newtonsoft.Json; 2 3 namespace backend.Entities 2 4 { 3 5 public class Restaurant -
backend/Entities/User.cs
rb66b3ac r057037b 1 using Newtonsoft.Json; 2 1 3 namespace backend.Entities; 2 4 … … 4 6 { 5 7 public int Id { get; set; } 6 public string Username{ get; set; }8 public string Email { get; set; } 7 9 public string Password { get; set; } 10 [JsonIgnore] 8 11 public virtual Restaurant Restaurant { get; set; } 9 12 } -
backend/Helpers/AuthorizeAttribute.cs
rb66b3ac r057037b 10 10 public void OnAuthorization(AuthorizationFilterContext context) 11 11 { 12 var user = (User)context.HttpContext.Items["User"];12 var user = context.HttpContext.Items["User"]; 13 13 if (user == null) 14 14 { -
backend/Helpers/JwtMiddleware.cs
rb66b3ac r057037b 4 4 using Microsoft.IdentityModel.Tokens; 5 5 using System.IdentityModel.Tokens.Jwt; 6 using System.Text;7 6 using backend.Services; 8 7 using backend.Helpers; … … 34 33 { 35 34 var tokenHandler = new JwtSecurityTokenHandler(); 36 var key = Encoding.ASCII.GetBytes(_appSettings.Secret);35 var key = System.Text.Encoding.ASCII.GetBytes(_appSettings.Secret); 37 36 tokenHandler.ValidateToken(token, new TokenValidationParameters 38 37 { … … 47 46 var userId = int.Parse(jwtToken.Claims.First(x => x.Type == "id").Value); 48 47 49 context.Items["User"] = user Service.GetById(userId);48 context.Items["User"] = userId; 50 49 } 51 50 catch -
backend/Migrations/DataContextModelSnapshot.cs
rb66b3ac r057037b 38 38 .IsRequired() 39 39 .HasColumnType("text"); 40 41 b.Property<int>("Persons") 42 .HasColumnType("integer"); 40 43 41 44 b.Property<int>("ReservationPlace") … … 92 95 NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id")); 93 96 94 b.Property<string>(" Password")97 b.Property<string>("Email") 95 98 .IsRequired() 96 99 .HasColumnType("text"); 97 100 98 b.Property<string>(" Username")101 b.Property<string>("Password") 99 102 .IsRequired() 100 103 .HasColumnType("text"); -
backend/Program.cs
rb66b3ac r057037b 4 4 using Microsoft.EntityFrameworkCore; 5 5 using Microsoft.OpenApi.Models; 6 using Swashbuckle.AspNetCore.Swagger;7 6 using WebApi.Helpers; 8 7 … … 11 10 // Add services to the container. 12 11 builder.Services.Configure<AppSettings>(builder.Configuration.GetSection("AppSettings")); 13 builder.Services.AddControllers() ;12 builder.Services.AddControllers().AddNewtonsoftJson(); 14 13 // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle 15 14 builder.Services.AddEndpointsApiExplorer(); … … 45 44 }); 46 45 builder.Services.AddScoped<IUserService, UserService>(); 46 builder.Services.AddScoped<IRestaurantService, RestaurantService>(); 47 builder.Services.AddScoped<IReservationService, ReservationService>(); 48 builder.Services.AddScoped<ISmsService, SmsService>(); 47 49 48 50 builder.Services.AddDbContext<DataContext>(p => p.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection"))); -
backend/Services/UserService.cs
rb66b3ac r057037b 1 1 namespace backend.Services; 2 2 3 using backend.Data; 4 using backend.DTOs; 3 5 using backend.Entities; 4 6 using backend.Helpers; 5 7 using backend.Models; 8 using Microsoft.EntityFrameworkCore; 6 9 using Microsoft.Extensions.Options; 7 10 using Microsoft.IdentityModel.Tokens; 8 11 using System.IdentityModel.Tokens.Jwt; 9 12 using System.Security.Claims; 10 using System.Text;11 13 12 14 public interface IUserService 13 15 { 14 AuthenticateResponse Authenticate(AuthenticateRequest model); 15 User GetById(int id); 16 Task<AuthenticateResponse> Authenticate(AuthenticateRequest model); 17 Task<AuthenticateResponse> Register(CreateUserRequest req); 18 Task<User> GetById(int id); 16 19 } 17 20 18 21 public class UserService : IUserService 19 22 { 20 // users hardcoded for simplicity, store in a db with hashed passwords in production applications 21 private List<User> _users = new List<User> 22 { 23 new User { Id = 1, Username = "test", Password = "test" } 24 }; 23 private readonly AppSettings _appSettings; 24 private readonly DataContext _context = null; 25 25 26 private readonly AppSettings _appSettings; 27 28 public UserService(IOptions<AppSettings> appSettings) 26 public UserService(IOptions<AppSettings> appSettings, DataContext context) 29 27 { 30 28 _appSettings = appSettings.Value; 29 _context = context; 31 30 } 32 31 33 public AuthenticateResponseAuthenticate(AuthenticateRequest model)32 public async Task<AuthenticateResponse> Authenticate(AuthenticateRequest model) 34 33 { 35 var user = _users.SingleOrDefault(x => x.Username == model.Username&& x.Password == model.Password);34 User user = await _context.Users.FirstOrDefaultAsync(x => x.Email == model.Email && x.Password == model.Password); 36 35 37 36 // return null if user not found … … 41 40 var token = generateJwtToken(user); 42 41 43 return new AuthenticateResponse (user, token);42 return new AuthenticateResponse { Email = user.Email, Id = user.Id, Token = token}; 44 43 } 45 44 46 public UserGetById(int id)45 public async Task<User> GetById(int id) 47 46 { 48 return _users.FirstOrDefault(x => x.Id == id); 47 return await _context.Users.FindAsync(id); 48 } 49 50 public async Task<AuthenticateResponse> Register(CreateUserRequest req) 51 { 52 User user = new User() { Email = req.Email, Password = req.Password }; 53 await _context.Users.AddAsync(user); 54 await _context.SaveChangesAsync(); 55 var token = generateJwtToken(user); 56 return new AuthenticateResponse { Email = user.Email, Id = user.Id, Token = token }; 49 57 } 50 58 … … 53 61 // generate token that is valid for 7 days 54 62 var tokenHandler = new JwtSecurityTokenHandler(); 55 var key = Encoding.ASCII.GetBytes(_appSettings.Secret);63 var key = System.Text.Encoding.ASCII.GetBytes(_appSettings.Secret); 56 64 var tokenDescriptor = new SecurityTokenDescriptor 57 65 { -
backend/backend.csproj
rb66b3ac r057037b 8 8 9 9 <ItemGroup> 10 <None Include="..\.editorconfig" Link=".editorconfig" /> 11 </ItemGroup> 12 13 <ItemGroup> 10 14 <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.3" /> 15 <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="6.0.3" /> 11 16 <PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.3" /> 12 17 <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.3"> -
resTools_backend.sln
rb66b3ac r057037b 4 4 VisualStudioVersion = 17.0.31912.275 5 5 MinimumVisualStudioVersion = 10.0.40219.1 6 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "backend", "backend\backend.csproj", "{69386AEC-421E-4DB5-8A83-E9DBD9AACD49}" 6 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "backend", "backend\backend.csproj", "{69386AEC-421E-4DB5-8A83-E9DBD9AACD49}" 7 EndProject 8 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{1369BF0A-CBA9-4788-8EB8-4E0AC8EA65B0}" 9 ProjectSection(SolutionItems) = preProject 10 .editorconfig = .editorconfig 11 EndProjectSection 7 12 EndProject 8 13 Global
Note:
See TracChangeset
for help on using the changeset viewer.