Changeset 13f1472 for resTools_backend/backend
- Timestamp:
- 09/18/22 18:09:53 (2 years ago)
- Branches:
- master
- Parents:
- 49b0bbd
- Location:
- resTools_backend/backend
- Files:
-
- 7 added
- 19 edited
Legend:
- Unmodified
- Added
- Removed
-
resTools_backend/backend/Controllers/MenuController.cs
r49b0bbd r13f1472 35 35 return Ok(); 36 36 } 37 38 [HttpPost("{id}/upload")] 39 public async Task<IActionResult> UploadImage(int id, [FromForm] IFormFile file) 40 { 41 await _menuService.UploadImage(id, file); 42 return Ok(); 43 } 37 44 } -
resTools_backend/backend/Controllers/ReviewsController.cs
r49b0bbd r13f1472 12 12 { 13 13 private readonly IReviewService _reviewService = null; 14 private readonly IUserService _userService = null; 14 15 15 public ReviewsController(IReviewService reviewService )16 public ReviewsController(IReviewService reviewService, IUserService userService) 16 17 { 17 18 _reviewService = reviewService; 19 _userService = userService; 18 20 } 19 21 … … 39 41 userId = (int)this.HttpContext.Items["User"]; 40 42 } 41 catch (Exception ex) { return null; } 43 catch (Exception ex) { 44 var user = await _userService.GetByEmail((string)this.HttpContext.Items["User"]); 45 if (user == null) 46 { 47 return null; 48 } 49 userId = user.Id; 50 } 42 51 await _reviewService.AddReview(req, userId); 43 52 return Ok(); -
resTools_backend/backend/Controllers/UsersController.cs
r49b0bbd r13f1472 39 39 { 40 40 userId = (int)this.HttpContext.Items["User"]; 41 }catch (Exception ex){ return null; } 41 } 42 catch (Exception ex) 43 { 44 var usr = await _userService.GetByEmail((string)this.HttpContext.Items["User"]); 45 if(usr == null) 46 { 47 return null; 48 } 49 userId = usr.Id; 50 } 42 51 User user = await _userService.GetById(userId); 43 return new AuthenticateResponse() { Email=user.Email, Id = user.Id, IsAdmin = user.IsAdmin, IsConfirmed = user.IsConfirmed };52 return new AuthenticateResponse() { Email=user.Email, Id = user.Id, IsAdmin = user.IsAdmin, IsConfirmed = user.IsConfirmed, isVip = user.IsVip}; 44 53 } 45 54 … … 93 102 return response; 94 103 } 104 105 [Authorize] 106 [HttpGet()] 107 public async Task<List<UserResponse>> GetUsers() 108 { 109 return await _userService.GetUsers(); 110 } 111 112 [Authorize] 113 [HttpPost("{id}/vip")] 114 public async Task UpdateVip(int id, bool newStatus) 115 { 116 await _userService.UpdateVipStatus(id,newStatus); 117 } 95 118 } -
resTools_backend/backend/DTOs/AuthenticateResponse.cs
r49b0bbd r13f1472 17 17 [JsonProperty] 18 18 public bool IsConfirmed { get; set; } 19 [JsonProperty] 20 public bool isVip { get; set; } 19 21 } -
resTools_backend/backend/DTOs/CreateMenuItemRequest.cs
r49b0bbd r13f1472 11 11 [JsonProperty] 12 12 public int Price { get; set; } 13 [JsonProperty] 14 public bool IsVipOnly { get; set; } 15 [JsonProperty] 16 public string Alergens { get; set; } 13 17 } 14 18 } -
resTools_backend/backend/DTOs/CreateUserRequest.cs
r49b0bbd r13f1472 10 10 [JsonProperty] 11 11 public string Password { get; set; } 12 13 [JsonProperty] 14 public bool IsConfirmed { get; set; } 12 15 } 13 16 } -
resTools_backend/backend/DTOs/MenuItemResponse.cs
r49b0bbd r13f1472 13 13 [JsonProperty] 14 14 public int Price { get; set; } 15 [JsonProperty] 16 public bool IsVipOnly { get; set; } 17 [JsonProperty] 18 public string Alergens { get; set; } 19 [JsonProperty] 20 public string Image { get; set; } 15 21 } 16 22 } -
resTools_backend/backend/Data/DataContext.cs
r49b0bbd r13f1472 94 94 } 95 95 96 private DbSet<QueueItem> queueItems; 97 public DbSet<QueueItem> QueueItems 98 { 99 get 100 { 101 if (queueItems == null) 102 { 103 queueItems = Set<QueueItem>(); 104 } 105 106 return queueItems; 107 } 108 } 109 96 110 97 111 protected override void OnModelCreating(ModelBuilder modelBuilder) … … 152 166 modelBuilder.Entity<ToDoItem>() 153 167 .HasOne(p => p.LinkedReview); 168 169 modelBuilder.Entity<QueueItem>().Property(x => x.Id).IsRequired().ValueGeneratedOnAdd(); 154 170 } 155 171 } -
resTools_backend/backend/Email/EmailSender.cs
r49b0bbd r13f1472 1 using SendGrid; 1 using backend.Data; 2 using backend.Entities; 3 using SendGrid; 2 4 using SendGrid.Helpers.Mail; 3 5 … … 9 11 public class EmailSender : IEmailSender 10 12 { 13 14 private readonly DataContext _context = null; 15 public EmailSender(DataContext context) 16 { 17 _context = context; 18 } 19 11 20 public async Task SendEmailAsync(string subject, string message, string toEmail) 12 21 { 13 var client = new SendGridClient("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"); 14 var msg = new SendGridMessage()22 23 _context.QueueItems.Add(new QueueItem() 15 24 { 16 From = new EmailAddress("danilo.najkov@students.finki.ukim.mk", "Danilo"),17 25 Subject = subject, 18 PlainTextContent= message,19 HtmlContent = message20 };21 msg.AddTo(new EmailAddress(toEmail));22 msg.SetClickTracking(false, false);23 var response = await client.SendEmailAsync(msg);26 Message = message, 27 Reciptient = toEmail, 28 CreatedAt = DateTime.UtcNow, 29 Retries = 0 30 }); 31 await _context.SaveChangesAsync(); 24 32 } 25 33 } -
resTools_backend/backend/Entities/MenuItem.cs
r49b0bbd r13f1472 7 7 public string Description { get; set; } 8 8 public int Price { get; set; } 9 public byte[] Image { get; set; } 10 public bool IsVipOnly { get; set; } 11 public string Alergens { get; set; } 9 12 public virtual Restaurant Restaurant { get; set; } 10 13 } -
resTools_backend/backend/Entities/User.cs
r49b0bbd r13f1472 10 10 public bool IsAdmin { get; set; } 11 11 public bool IsConfirmed { get; set; } 12 public bool IsVip { get; set; } 12 13 public string? ConfirmationURL { get; set; } 13 14 public DateTime? ConfirmationValidTo { get; set; } -
resTools_backend/backend/Helpers/JwtMiddleware.cs
r49b0bbd r13f1472 6 6 using backend.Services; 7 7 using backend.Helpers; 8 using Google.Apis.Auth; 9 using System.Text.Json; 10 using Newtonsoft.Json; 8 11 9 12 public class JwtMiddleware … … 11 14 private readonly RequestDelegate _next; 12 15 private readonly AppSettings _appSettings; 16 private static readonly HttpClient client = new HttpClient(); 17 13 18 14 19 public JwtMiddleware(RequestDelegate next, IOptions<AppSettings> appSettings) … … 22 27 var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last(); 23 28 24 if (token != null )25 a ttachUserToContext(context, userService, token);29 if (token != null && token != "null") 30 await attachUserToContext(context, userService, token); 26 31 27 32 await _next(context); 28 33 } 29 34 30 private voidattachUserToContext(HttpContext context, IUserService userService, string token)35 private async Task attachUserToContext(HttpContext context, IUserService userService, string token) 31 36 { 32 37 try 33 38 { 39 var fbResult = await this.ValidateFacebookToken(token); 40 if (fbResult != null) 41 { 42 context.Items["User"] = fbResult; 43 return; 44 } 45 34 46 var tokenHandler = new JwtSecurityTokenHandler(); 35 47 var key = System.Text.Encoding.ASCII.GetBytes(_appSettings.Secret); … … 47 59 48 60 context.Items["User"] = userId; 61 49 62 } 50 63 catch 51 64 { 52 // do nothing if jwt validation fails 65 try 66 { 67 var result = await GoogleJsonWebSignature.ValidateAsync(token); 68 context.Items["User"] = result.Email; 69 } 70 catch 71 { 72 // do nothing 73 } 53 74 } 54 75 } 76 77 private async Task<string> ValidateFacebookToken(string token) 78 { 79 try 80 { 81 var stringTask = await client.GetStringAsync("https://graph.facebook.com/me?fields=email&access_token=" + token); 82 var obj = JsonConvert.DeserializeObject<FacebookResult>(stringTask); 83 return obj.email; 84 } 85 catch 86 { 87 return null; 88 } 89 } 90 91 internal class FacebookResult 92 { 93 public string email { get; set; } 94 public string id { get; set; } 95 } 55 96 } -
resTools_backend/backend/Migrations/DataContextModelSnapshot.cs
r49b0bbd r13f1472 31 31 NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id")); 32 32 33 b.Property<string>("Alergens") 34 .IsRequired() 35 .HasColumnType("text"); 36 33 37 b.Property<string>("Description") 34 38 .IsRequired() 35 39 .HasColumnType("text"); 36 40 41 b.Property<byte[]>("Image") 42 .IsRequired() 43 .HasColumnType("bytea"); 44 45 b.Property<bool>("IsVipOnly") 46 .HasColumnType("boolean"); 47 37 48 b.Property<int>("Price") 38 49 .HasColumnType("integer"); … … 50 61 51 62 b.ToTable("MenuItems"); 63 }); 64 65 modelBuilder.Entity("backend.Entities.QueueItem", b => 66 { 67 b.Property<int>("Id") 68 .ValueGeneratedOnAdd() 69 .HasColumnType("integer"); 70 71 NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id")); 72 73 b.Property<DateTime>("CreatedAt") 74 .HasColumnType("timestamp with time zone"); 75 76 b.Property<string>("Message") 77 .IsRequired() 78 .HasColumnType("text"); 79 80 b.Property<string>("Reciptient") 81 .IsRequired() 82 .HasColumnType("text"); 83 84 b.Property<int>("Retries") 85 .HasColumnType("integer"); 86 87 b.Property<string>("Subject") 88 .IsRequired() 89 .HasColumnType("text"); 90 91 b.HasKey("Id"); 92 93 b.ToTable("QueueItems"); 52 94 }); 53 95 … … 225 267 226 268 b.Property<bool>("IsConfirmed") 269 .HasColumnType("boolean"); 270 271 b.Property<bool>("IsVip") 227 272 .HasColumnType("boolean"); 228 273 -
resTools_backend/backend/Program.cs
r49b0bbd r13f1472 2 2 using backend.Email; 3 3 using backend.Helpers; 4 using backend.Jobs; 4 5 using backend.Services; 5 6 using Microsoft.EntityFrameworkCore; 6 7 using Microsoft.OpenApi.Models; 8 using Quartz; 7 9 using WebApi.Helpers; 8 10 … … 56 58 builder.Services.AddDbContext<DataContext>(p => p.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection"))); 57 59 60 builder.Services.AddQuartz(q => 61 { 62 q.UseMicrosoftDependencyInjectionScopedJobFactory(); 63 var jobKey = new JobKey("QueueJob"); 64 q.AddJob<QueueJob>(opts => opts.WithIdentity(jobKey)); 65 66 q.AddTrigger(opts => opts 67 .ForJob(jobKey) 68 .WithIdentity("QueueJob-trigger") 69 .WithCronSchedule("0 0/1 * * * ?")); 70 71 }); 72 73 IServiceCollection serviceCollection = builder.Services.AddQuartzHostedService(q => q.WaitForJobsToComplete = true); 74 58 75 var app = builder.Build(); 59 76 -
resTools_backend/backend/Services/MenuService.cs
r49b0bbd r13f1472 10 10 public Task AddMenu(CreateMenuItemRequest menu); 11 11 public Task RemoveMenu(int id); 12 public Task UploadImage(int id, IFormFile file); 12 13 } 13 14 public class MenuService : IMenuService … … 29 30 Title = menu.Title, 30 31 Description = menu.Description, 31 Price = menu.Price 32 }); 32 Price = menu.Price, 33 Alergens = menu.Alergens, 34 IsVipOnly = menu.IsVipOnly, 35 Image = Array.Empty<byte>() 36 }) ; 33 37 _context.Restoraunts.Update(res); 34 38 await _context.SaveChangesAsync(); … … 42 46 await _context.SaveChangesAsync(); 43 47 } 48 49 public async Task UploadImage(int id, IFormFile file) 50 { 51 using (var memoryStream = new MemoryStream()) 52 { 53 await file.CopyToAsync(memoryStream); 54 var menuItem = await _context.MenuItems.FindAsync(id); 55 menuItem.Image = memoryStream.ToArray(); 56 _context.MenuItems.Update(menuItem); 57 _context.SaveChanges(); 58 } 59 } 44 60 } 45 61 } -
resTools_backend/backend/Services/RestaurantService.cs
r49b0bbd r13f1472 45 45 Title = x.Title, 46 46 Description = x.Description, 47 Price = x.Price 47 Price = x.Price, 48 Alergens = x.Alergens, 49 Image = String.Format("data:image/png;base64,{0}", Convert.ToBase64String(x.Image)), 50 IsVipOnly = x.IsVipOnly 48 51 }).ToList(), 49 52 Reviews = x.Reviews.Select(x => new ReviewResponse() … … 55 58 Title = x.Title, 56 59 Username = x.User == null ? "Anonymous" : x.User.Email 57 }).ToList(), 58 AverageReview = x.Reviews.Count>0 ? x.Reviews.Select(x => x.Stars).Average() : 0 60 }).ToList() 59 61 }) 60 62 .FirstOrDefaultAsync(); 63 var reviews = await _context.Reviews.ToListAsync(); 64 res.AverageReview = reviews.Select(x => x.Stars).Sum(); 61 65 return res; 62 66 } -
resTools_backend/backend/Services/ReviewService.cs
r49b0bbd r13f1472 1 1 using backend.Data; 2 2 using backend.DTOs; 3 using backend.Email; 3 4 using backend.Entities; 4 5 using Microsoft.EntityFrameworkCore; … … 15 16 { 16 17 private readonly DataContext _context = null; 18 private readonly IEmailSender _emailSender; 17 19 18 public ReviewService(DataContext context )20 public ReviewService(DataContext context, IEmailSender emailSender) 19 21 { 20 22 _context = context; 23 _emailSender = emailSender; 24 21 25 } 22 26 … … 39 43 _context.Restoraunts.Update(res); 40 44 await _context.SaveChangesAsync(); 45 46 if (review.Stars < 3) 47 { 48 var adminUser = await _context.Users.FirstOrDefaultAsync(x => x.IsAdmin); 49 await _emailSender.SendEmailAsync("Добивте лоша оценка", $"<html><h1>{review.Title}</h1><p>{review.Description}</p></html>", adminUser.Email); 50 } 41 51 } 42 52 -
resTools_backend/backend/Services/UserService.cs
r49b0bbd r13f1472 20 20 Task<AuthenticateResponse> Register(CreateUserRequest req, bool isFirst); 21 21 Task<User> GetById(int id); 22 Task<User> GetByEmail(string email); 22 23 Task SendEmailConfirmation(string email); 23 24 Task SendPasswordReset(string email); 24 25 Task ConfirmEmail(User user, string checkValid); 25 26 Task ResetPassword(string checkValid, string password); 27 Task<List<UserResponse>> GetUsers(); 28 Task UpdateVipStatus(int id, bool isVip); 29 26 30 } 27 31 … … 39 43 } 40 44 45 public async Task<User> GetByEmail(string email) 46 { 47 return await _context.Users.FirstOrDefaultAsync(x => x.Email == email); 48 } 49 41 50 public async Task<AuthenticateResponse> Authenticate(AuthenticateRequest model) 42 51 { … … 49 58 var token = generateJwtToken(user); 50 59 51 return new AuthenticateResponse { Email = user.Email, Id = user.Id, Token = token, IsAdmin = user.IsAdmin, IsConfirmed = user.IsConfirmed };60 return new AuthenticateResponse { Email = user.Email, Id = user.Id, Token = token, IsAdmin = user.IsAdmin, IsConfirmed = user.IsConfirmed, isVip = user.IsVip}; 52 61 } 53 62 … … 75 84 public async Task<AuthenticateResponse> Register(CreateUserRequest req, bool isFirst) 76 85 { 77 User user = new User() { Email = req.Email, Password = req.Password, IsAdmin = isFirst, IsConfirmed = false }; 86 var exists = await _context.Users.FirstOrDefaultAsync(x => x.Email == req.Email); 87 if(exists != null && req.IsConfirmed) 88 { 89 return new AuthenticateResponse { Email = exists.Email, Id = exists.Id, IsAdmin = exists.IsAdmin, IsConfirmed = true }; 90 } 91 User user = new User() { Email = req.Email, Password = req.Password, IsAdmin = isFirst, IsConfirmed = req.IsConfirmed, IsVip = false }; 78 92 await _context.Users.AddAsync(user); 79 93 await _context.SaveChangesAsync(); 80 94 var token = generateJwtToken(user); 81 return new AuthenticateResponse { Email = user.Email, Id = user.Id, Token = token, IsAdmin = user.IsAdmin, IsConfirmed = false};95 return new AuthenticateResponse { Email = user.Email, Id = user.Id, Token = token, IsAdmin = user.IsAdmin, IsConfirmed = req.IsConfirmed, isVip = user.IsVip }; 82 96 } 83 97 … … 125 139 } 126 140 141 public async Task<List<UserResponse>> GetUsers() 142 { 143 return await _context.Users.Select(x => new UserResponse() 144 { 145 Email = x.Email, 146 Id = x.Id, 147 IsVip = x.IsVip 148 }).OrderBy(x => x.Id).ToListAsync(); 149 } 150 151 public async Task UpdateVipStatus(int id, bool isVip) 152 { 153 var user = await _context.Users.FindAsync(id); 154 user.IsVip = isVip; 155 _context.Users.Update(user); 156 await _context.SaveChangesAsync(); 157 } 158 127 159 private string generateJwtToken(User user) 128 160 { -
resTools_backend/backend/backend.csproj
r49b0bbd r13f1472 12 12 13 13 <ItemGroup> 14 <PackageReference Include="Google.Apis.Auth" Version="1.57.0" /> 15 <PackageReference Include="Microsoft.AspNetCore.Authentication.Google" Version="6.0.9" /> 14 16 <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.3" /> 15 17 <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="6.0.3" /> … … 22 24 <PackageReference Include="Npgsql" Version="6.0.3" /> 23 25 <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="6.0.3" /> 26 <PackageReference Include="Quartz" Version="3.4.0" /> 27 <PackageReference Include="Quartz.Extensions.Hosting" Version="3.4.0" /> 24 28 <PackageReference Include="SendGrid" Version="9.28.0" /> 25 29 <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
Note:
See TracChangeset
for help on using the changeset viewer.