Changeset 057037b for backend


Ignore:
Timestamp:
04/11/22 15:29:19 (3 years ago)
Author:
Danilo <danilo.najkov@…>
Branches:
master
Children:
7a983b0
Parents:
b66b3ac
Message:

backend full

Location:
backend
Files:
13 added
12 edited

Legend:

Unmodified
Added
Removed
  • backend/Controllers/UsersController.cs

    rb66b3ac r057037b  
    11namespace backend.Controllers;
    22
     3using backend.DTOs;
    34using backend.Helpers;
    45using backend.Models;
     
    1011public class UsersController : ControllerBase
    1112{
    12     private IUserService _userService;
     13    private readonly IUserService _userService = null;
    1314
    1415    public UsersController(IUserService userService)
     
    1718    }
    1819
    19     [HttpPost("authenticate")]
    20     public IActionResult Authenticate(AuthenticateRequest model)
     20    [HttpPost("login")]
     21    public async Task<AuthenticateResponse> Authenticate(AuthenticateRequest model)
    2122    {
    22         var response = _userService.Authenticate(model);
     23        var response = await _userService.Authenticate(model);
    2324
    2425        if (response == null)
    25             return BadRequest(new { message = "Username or password is incorrect" });
     26            throw new Exception("Email or password is incorrect");
    2627
    27         return Ok(response);
     28        return response;
    2829    }
    2930
    30     [Authorize]
    31     [HttpGet]
    32     public IActionResult GetUserById(int id)
     31    [HttpPost("register")]
     32    public async Task<AuthenticateResponse> Register(CreateUserRequest req)
    3333    {
    34         var users = _userService.GetById(id);
    35         return Ok(users);
     34        var response = await _userService.Register(req);
     35        return response;
    3636    }
    3737}
  • backend/DTOs/AuthenticateRequest.cs

    rb66b3ac r057037b  
    66{
    77    [Required]
    8     public string Username { get; set; }
     8    public string Email { get; set; }
    99
    1010    [Required]
  • backend/DTOs/AuthenticateResponse.cs

    rb66b3ac r057037b  
    11using backend.Entities;
     2using Newtonsoft.Json;
    23
    34namespace backend.Models;
     
    67public class AuthenticateResponse
    78{
     9    [JsonProperty]
    810    public int Id { get; set; }
    9     public string Username { get; set; }
     11    [JsonProperty]
     12    public string Email { get; set; }
     13    [JsonProperty]
    1014    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     }
    1915}
  • backend/Entities/Reservation.cs

    rb66b3ac r057037b  
    1 namespace backend.Entities
     1using Newtonsoft.Json;
     2
     3namespace backend.Entities
    24{
    35    public class Reservation
     
    57        public int Id { get; set; }
    68        public DateTime StartDate { get; set; }
     9        public int Persons { get; set; }
    710        public virtual Restaurant Restaurant { get; set; }
    811        public ReservationPlace ReservationPlace { get; set; }
  • backend/Entities/Restaurant.cs

    rb66b3ac r057037b  
    1 namespace backend.Entities
     1using Newtonsoft.Json;
     2
     3namespace backend.Entities
    24{
    35    public class Restaurant
  • backend/Entities/User.cs

    rb66b3ac r057037b  
     1using Newtonsoft.Json;
     2
    13namespace backend.Entities;
    24
     
    46{
    57    public int Id { get; set; }
    6     public string Username { get; set; }
     8    public string Email { get; set; }
    79    public string Password { get; set; }
     10    [JsonIgnore]
    811    public virtual Restaurant Restaurant { get; set; }
    912}
  • backend/Helpers/AuthorizeAttribute.cs

    rb66b3ac r057037b  
    1010    public void OnAuthorization(AuthorizationFilterContext context)
    1111    {
    12         var user = (User)context.HttpContext.Items["User"];
     12        var user = context.HttpContext.Items["User"];
    1313        if (user == null)
    1414        {
  • backend/Helpers/JwtMiddleware.cs

    rb66b3ac r057037b  
    44using Microsoft.IdentityModel.Tokens;
    55using System.IdentityModel.Tokens.Jwt;
    6 using System.Text;
    76using backend.Services;
    87using backend.Helpers;
     
    3433        {
    3534            var tokenHandler = new JwtSecurityTokenHandler();
    36             var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
     35            var key = System.Text.Encoding.ASCII.GetBytes(_appSettings.Secret);
    3736            tokenHandler.ValidateToken(token, new TokenValidationParameters
    3837            {
     
    4746            var userId = int.Parse(jwtToken.Claims.First(x => x.Type == "id").Value);
    4847
    49             context.Items["User"] = userService.GetById(userId);
     48            context.Items["User"] = userId;
    5049        }
    5150        catch
  • backend/Migrations/DataContextModelSnapshot.cs

    rb66b3ac r057037b  
    3838                        .IsRequired()
    3939                        .HasColumnType("text");
     40
     41                    b.Property<int>("Persons")
     42                        .HasColumnType("integer");
    4043
    4144                    b.Property<int>("ReservationPlace")
     
    9295                    NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
    9396
    94                     b.Property<string>("Password")
     97                    b.Property<string>("Email")
    9598                        .IsRequired()
    9699                        .HasColumnType("text");
    97100
    98                     b.Property<string>("Username")
     101                    b.Property<string>("Password")
    99102                        .IsRequired()
    100103                        .HasColumnType("text");
  • backend/Program.cs

    rb66b3ac r057037b  
    44using Microsoft.EntityFrameworkCore;
    55using Microsoft.OpenApi.Models;
    6 using Swashbuckle.AspNetCore.Swagger;
    76using WebApi.Helpers;
    87
     
    1110// Add services to the container.
    1211builder.Services.Configure<AppSettings>(builder.Configuration.GetSection("AppSettings"));
    13 builder.Services.AddControllers();
     12builder.Services.AddControllers().AddNewtonsoftJson();
    1413// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
    1514builder.Services.AddEndpointsApiExplorer();
     
    4544});
    4645builder.Services.AddScoped<IUserService, UserService>();
     46builder.Services.AddScoped<IRestaurantService, RestaurantService>();
     47builder.Services.AddScoped<IReservationService, ReservationService>();
     48builder.Services.AddScoped<ISmsService, SmsService>();
    4749
    4850builder.Services.AddDbContext<DataContext>(p => p.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")));
  • backend/Services/UserService.cs

    rb66b3ac r057037b  
    11namespace backend.Services;
    22
     3using backend.Data;
     4using backend.DTOs;
    35using backend.Entities;
    46using backend.Helpers;
    57using backend.Models;
     8using Microsoft.EntityFrameworkCore;
    69using Microsoft.Extensions.Options;
    710using Microsoft.IdentityModel.Tokens;
    811using System.IdentityModel.Tokens.Jwt;
    912using System.Security.Claims;
    10 using System.Text;
    1113
    1214public interface IUserService
    1315{
    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);
    1619}
    1720
    1821public class UserService : IUserService
    1922{
    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;
    2525
    26     private readonly AppSettings _appSettings;
    27 
    28     public UserService(IOptions<AppSettings> appSettings)
     26    public UserService(IOptions<AppSettings> appSettings, DataContext context)
    2927    {
    3028        _appSettings = appSettings.Value;
     29        _context = context;
    3130    }
    3231
    33     public AuthenticateResponse Authenticate(AuthenticateRequest model)
     32    public async Task<AuthenticateResponse> Authenticate(AuthenticateRequest model)
    3433    {
    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);
    3635
    3736        // return null if user not found
     
    4140        var token = generateJwtToken(user);
    4241
    43         return new AuthenticateResponse(user, token);
     42        return new AuthenticateResponse { Email = user.Email, Id = user.Id, Token = token};
    4443    }
    4544
    46     public User GetById(int id)
     45    public async Task<User> GetById(int id)
    4746    {
    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 };
    4957    }
    5058
     
    5361        // generate token that is valid for 7 days
    5462        var tokenHandler = new JwtSecurityTokenHandler();
    55         var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
     63        var key = System.Text.Encoding.ASCII.GetBytes(_appSettings.Secret);
    5664        var tokenDescriptor = new SecurityTokenDescriptor
    5765        {
  • backend/backend.csproj

    rb66b3ac r057037b  
    88
    99  <ItemGroup>
     10    <None Include="..\.editorconfig" Link=".editorconfig" />
     11  </ItemGroup>
     12
     13  <ItemGroup>
    1014    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.3" />
     15    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="6.0.3" />
    1116    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.3" />
    1217    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.3">
Note: See TracChangeset for help on using the changeset viewer.