├── .gitignore ├── .vscode ├── launch.json └── tasks.json ├── API ├── API.csproj ├── Controllers │ ├── AccountController.cs │ ├── AdminController.cs │ ├── BaseApiController.cs │ ├── BuggyController.cs │ ├── FallbackController.cs │ ├── LikesController.cs │ ├── MessagesController.cs │ ├── UsersController.cs │ └── WeatherForecastController.cs ├── DTOs │ ├── CreateMessageDto.cs │ ├── LikeDto.cs │ ├── LoginDto.cs │ ├── MemberDto.cs │ ├── MemberUpdateDto.cs │ ├── MessageDto.cs │ ├── PhotoDto.cs │ ├── RegisterDto.cs │ └── UserDto.cs ├── Data │ ├── DataContext.cs │ ├── LikesRepository.cs │ ├── MessageRepository.cs │ ├── Migrations │ │ ├── 20200920093441_PostgresInitial.Designer.cs │ │ ├── 20200920093441_PostgresInitial.cs │ │ └── DataContextModelSnapshot.cs │ ├── Seed.cs │ ├── UnitOfWork.cs │ ├── UserRepository.cs │ └── UserSeedData.json ├── Entities │ ├── AppRole.cs │ ├── AppUser.cs │ ├── AppUserRole.cs │ ├── Connection.cs │ ├── Group.cs │ ├── Message.cs │ ├── Photo.cs │ └── UserLike.cs ├── Errors │ └── ApiException.cs ├── Extensions │ ├── ApplicationServiceExtensions.cs │ ├── ClaimsPrincipleExtensions.cs │ ├── DateTimeExtensions.cs │ ├── HttpExtensions.cs │ ├── IdentityServiceExtensions.cs │ └── QueryableExtensions.cs ├── GlobalUsings.cs ├── Helpers │ ├── AutoMapperProfiles.cs │ ├── CloudinarySettings.cs │ ├── LikesParams.cs │ ├── LogUserActivity.cs │ ├── MessageParams.cs │ ├── PagedList.cs │ ├── PaginationHeader.cs │ ├── PaginationParams.cs │ └── UserParams.cs ├── Interfaces │ ├── ILikesRepository.cs │ ├── IMessageRepository.cs │ ├── IPhotoService.cs │ ├── ITokenService.cs │ ├── IUnitOfWork.cs │ └── IUserRepository.cs ├── Middleware │ └── ExceptionMiddleware.cs ├── Program.cs ├── Properties │ └── launchSettings.json ├── Services │ ├── PhotoService.cs │ └── TokenService.cs ├── SignalR │ ├── MessageHub.cs │ ├── PresenceHub.cs │ └── PresenceTracker.cs ├── WeatherForecast.cs ├── appsettings.Development.json └── wwwroot │ ├── 3rdpartylicenses.txt │ ├── assets │ ├── icons │ │ ├── icon-128x128.png │ │ ├── icon-144x144.png │ │ ├── icon-152x152.png │ │ ├── icon-192x192.png │ │ ├── icon-384x384.png │ │ ├── icon-512x512.png │ │ ├── icon-72x72.png │ │ └── icon-96x96.png │ └── user.png │ ├── favicon.ico │ ├── fontawesome-webfont.1e59d2330b4c6deb84b3.ttf │ ├── fontawesome-webfont.20fd1704ea223900efa9.woff2 │ ├── fontawesome-webfont.8b43027f47b20503057d.eot │ ├── fontawesome-webfont.c1e38fd9e0e74ba58f7a.svg │ ├── fontawesome-webfont.f691f37e57f04c152e23.woff │ ├── index.html │ ├── main.caefe71cdf94de206389.js │ ├── manifest.webmanifest │ ├── polyfills.08cdd93a9921fbb99ed7.js │ ├── runtime.f9956ac3c2762746a398.js │ └── styles.6e0c830e7e8106445402.css ├── DatingApp.sln └── client ├── .browserslistrc ├── .editorconfig ├── .gitignore ├── README.md ├── angular.json ├── e2e ├── protractor.conf.js ├── src │ ├── app.e2e-spec.ts │ └── app.po.ts └── tsconfig.json ├── karma.conf.js ├── ngsw-config.json ├── package-lock.json ├── package.json ├── src ├── app │ ├── _directives │ │ └── has-role.directive.ts │ ├── _forms │ │ ├── date-input │ │ │ ├── date-input.component.css │ │ │ ├── date-input.component.html │ │ │ └── date-input.component.ts │ │ └── text-input │ │ │ ├── text-input.component.css │ │ │ ├── text-input.component.html │ │ │ └── text-input.component.ts │ ├── _guards │ │ ├── admin.guard.ts │ │ ├── auth.guard.ts │ │ └── prevent-unsaved-changes.guard.ts │ ├── _interceptors │ │ ├── error.interceptor.ts │ │ ├── jwt.interceptor.ts │ │ └── loading.interceptor.ts │ ├── _models │ │ ├── group.ts │ │ ├── member.ts │ │ ├── message.ts │ │ ├── pagination.ts │ │ ├── photo.ts │ │ ├── user.ts │ │ └── userParams.ts │ ├── _modules │ │ └── shared.module.ts │ ├── _resolvers │ │ └── member-detailed.resolver.ts │ ├── _services │ │ ├── account.service.ts │ │ ├── admin.service.ts │ │ ├── busy.service.ts │ │ ├── confirm.service.ts │ │ ├── members.service.ts │ │ ├── message.service.ts │ │ ├── paginationHelper.ts │ │ └── presence.service.ts │ ├── admin │ │ ├── admin-panel │ │ │ ├── admin-panel.component.css │ │ │ ├── admin-panel.component.html │ │ │ └── admin-panel.component.ts │ │ ├── photo-management │ │ │ ├── photo-management.component.css │ │ │ ├── photo-management.component.html │ │ │ └── photo-management.component.ts │ │ └── user-management │ │ │ ├── user-management.component.css │ │ │ ├── user-management.component.html │ │ │ └── user-management.component.ts │ ├── app-routing.module.ts │ ├── app.component.css │ ├── app.component.html │ ├── app.component.spec.ts │ ├── app.component.ts │ ├── app.module.ts │ ├── errors │ │ ├── not-found │ │ │ ├── not-found.component.css │ │ │ ├── not-found.component.html │ │ │ └── not-found.component.ts │ │ ├── server-error │ │ │ ├── server-error.component.css │ │ │ ├── server-error.component.html │ │ │ └── server-error.component.ts │ │ └── test-errors │ │ │ ├── test-errors.component.css │ │ │ ├── test-errors.component.html │ │ │ └── test-errors.component.ts │ ├── home │ │ ├── home.component.css │ │ ├── home.component.html │ │ └── home.component.ts │ ├── lists │ │ ├── lists.component.css │ │ ├── lists.component.html │ │ └── lists.component.ts │ ├── members │ │ ├── member-card │ │ │ ├── member-card.component.css │ │ │ ├── member-card.component.html │ │ │ └── member-card.component.ts │ │ ├── member-detail │ │ │ ├── member-detail.component.css │ │ │ ├── member-detail.component.html │ │ │ └── member-detail.component.ts │ │ ├── member-edit │ │ │ ├── member-edit.component.css │ │ │ ├── member-edit.component.html │ │ │ └── member-edit.component.ts │ │ ├── member-list │ │ │ ├── member-list.component.css │ │ │ ├── member-list.component.html │ │ │ └── member-list.component.ts │ │ ├── member-messages │ │ │ ├── member-messages.component.css │ │ │ ├── member-messages.component.html │ │ │ └── member-messages.component.ts │ │ └── photo-editor │ │ │ ├── photo-editor.component.css │ │ │ ├── photo-editor.component.html │ │ │ └── photo-editor.component.ts │ ├── messages │ │ ├── messages.component.css │ │ ├── messages.component.html │ │ └── messages.component.ts │ ├── modals │ │ ├── confirm-dialog │ │ │ ├── confirm-dialog.component.css │ │ │ ├── confirm-dialog.component.html │ │ │ └── confirm-dialog.component.ts │ │ └── roles-modal │ │ │ ├── roles-modal.component.css │ │ │ ├── roles-modal.component.html │ │ │ └── roles-modal.component.ts │ ├── nav │ │ ├── nav.component.css │ │ ├── nav.component.html │ │ └── nav.component.ts │ └── register │ │ ├── register.component.css │ │ ├── register.component.html │ │ └── register.component.ts ├── assets │ ├── .gitkeep │ ├── icons │ │ ├── icon-128x128.png │ │ ├── icon-144x144.png │ │ ├── icon-152x152.png │ │ ├── icon-192x192.png │ │ ├── icon-384x384.png │ │ ├── icon-512x512.png │ │ ├── icon-72x72.png │ │ └── icon-96x96.png │ └── user.png ├── environments │ ├── environment.prod.ts │ └── environment.ts ├── favicon.ico ├── index.html ├── main.ts ├── manifest.webmanifest ├── polyfills.ts ├── styles.css └── test.ts ├── tsconfig.app.json ├── tsconfig.json ├── tsconfig.spec.json └── tslint.json /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to find out which attributes exist for C# debugging 3 | // Use hover for the description of the existing attributes 4 | // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": ".NET Core Launch (web)", 9 | "type": "coreclr", 10 | "request": "launch", 11 | "preLaunchTask": "build", 12 | // If you have changed target frameworks, make sure to update the program path. 13 | "program": "${workspaceFolder}/API/bin/Debug/net5.0/API.dll", 14 | "args": [], 15 | "cwd": "${workspaceFolder}/API", 16 | "stopAtEntry": false, 17 | // Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser 18 | "serverReadyAction": { 19 | "action": "openExternally", 20 | "pattern": "\\bNow listening on:\\s+(https?://\\S+)" 21 | }, 22 | "env": { 23 | "ASPNETCORE_ENVIRONMENT": "Development" 24 | }, 25 | "sourceFileMap": { 26 | "/Views": "${workspaceFolder}/Views" 27 | } 28 | }, 29 | { 30 | "name": ".NET Core Attach", 31 | "type": "coreclr", 32 | "request": "attach", 33 | "processId": "${command:pickProcess}" 34 | } 35 | ] 36 | } -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "label": "build", 6 | "command": "dotnet", 7 | "type": "process", 8 | "args": [ 9 | "build", 10 | "${workspaceFolder}/API/API.csproj", 11 | "/property:GenerateFullPaths=true", 12 | "/consoleloggerparameters:NoSummary" 13 | ], 14 | "problemMatcher": "$msCompile" 15 | }, 16 | { 17 | "label": "publish", 18 | "command": "dotnet", 19 | "type": "process", 20 | "args": [ 21 | "publish", 22 | "${workspaceFolder}/API/API.csproj", 23 | "/property:GenerateFullPaths=true", 24 | "/consoleloggerparameters:NoSummary" 25 | ], 26 | "problemMatcher": "$msCompile" 27 | }, 28 | { 29 | "label": "watch", 30 | "command": "dotnet", 31 | "type": "process", 32 | "args": [ 33 | "watch", 34 | "run", 35 | "${workspaceFolder}/API/API.csproj", 36 | "/property:GenerateFullPaths=true", 37 | "/consoleloggerparameters:NoSummary" 38 | ], 39 | "problemMatcher": "$msCompile" 40 | } 41 | ] 42 | } -------------------------------------------------------------------------------- /API/API.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | runtime; build; native; contentfiles; analyzers; buildtransitive 14 | all 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /API/Controllers/AccountController.cs: -------------------------------------------------------------------------------- 1 | namespace API.Controllers; 2 | 3 | public class AccountController : BaseApiController 4 | { 5 | private readonly ITokenService _tokenService; 6 | private readonly IMapper _mapper; 7 | private readonly UserManager _userManager; 8 | private readonly SignInManager _signInManager; 9 | public AccountController(UserManager userManager, SignInManager signInManager, ITokenService tokenService, IMapper mapper) 10 | { 11 | _signInManager = signInManager; 12 | _userManager = userManager; 13 | _mapper = mapper; 14 | _tokenService = tokenService; 15 | } 16 | 17 | [HttpPost("register")] 18 | public async Task> Register(RegisterDto registerDto) 19 | { 20 | if (await UserExists(registerDto.Username)) return BadRequest("Username is taken"); 21 | 22 | var user = _mapper.Map(registerDto); 23 | 24 | user.UserName = registerDto.Username.ToLower(); 25 | 26 | var result = await _userManager.CreateAsync(user, registerDto.Password); 27 | 28 | if (!result.Succeeded) return BadRequest(result.Errors); 29 | 30 | var roleResult = await _userManager.AddToRoleAsync(user, "Member"); 31 | 32 | if (!roleResult.Succeeded) return BadRequest(result.Errors); 33 | 34 | return new UserDto 35 | { 36 | Username = user.UserName, 37 | Token = await _tokenService.CreateToken(user), 38 | KnownAs = user.KnownAs, 39 | Gender = user.Gender 40 | }; 41 | } 42 | 43 | [HttpPost("login")] 44 | public async Task> Login(LoginDto loginDto) 45 | { 46 | var user = await _userManager.Users 47 | .Include(p => p.Photos) 48 | .SingleOrDefaultAsync(x => x.UserName == loginDto.Username.ToLower()); 49 | 50 | if (user == null) return Unauthorized("Invalid username"); 51 | 52 | var result = await _signInManager 53 | .CheckPasswordSignInAsync(user, loginDto.Password, false); 54 | 55 | if (!result.Succeeded) return Unauthorized(); 56 | 57 | return new UserDto 58 | { 59 | Username = user.UserName, 60 | Token = await _tokenService.CreateToken(user), 61 | PhotoUrl = user.Photos.FirstOrDefault(x => x.IsMain)?.Url, 62 | KnownAs = user.KnownAs, 63 | Gender = user.Gender 64 | }; 65 | } 66 | 67 | private async Task UserExists(string username) 68 | { 69 | return await _userManager.Users.AnyAsync(x => x.UserName == username.ToLower()); 70 | } 71 | } -------------------------------------------------------------------------------- /API/Controllers/AdminController.cs: -------------------------------------------------------------------------------- 1 | namespace API.Controllers 2 | { 3 | public class AdminController : BaseApiController 4 | { 5 | private readonly UserManager _userManager; 6 | public AdminController(UserManager userManager) 7 | { 8 | _userManager = userManager; 9 | } 10 | 11 | [Authorize(Policy = "RequireAdminRole")] 12 | [HttpGet("users-with-roles")] 13 | public async Task GetUsersWithRoles() 14 | { 15 | var users = await _userManager.Users 16 | .Include(r => r.UserRoles) 17 | .ThenInclude(r => r.Role) 18 | .OrderBy(u => u.UserName) 19 | .Select(u => new 20 | { 21 | u.Id, 22 | Username = u.UserName, 23 | Roles = u.UserRoles.Select(r => r.Role.Name).ToList() 24 | }) 25 | .ToListAsync(); 26 | 27 | return Ok(users); 28 | } 29 | 30 | [Authorize(Policy = "RequireAdminRole")] 31 | [HttpPost("edit-roles/{username}")] 32 | public async Task EditRoles(string username, [FromQuery] string roles) 33 | { 34 | var selectedRoles = roles.Split(",").ToArray(); 35 | 36 | var user = await _userManager.FindByNameAsync(username); 37 | 38 | if (user == null) return NotFound("Could not find user"); 39 | 40 | var userRoles = await _userManager.GetRolesAsync(user); 41 | 42 | var result = await _userManager.AddToRolesAsync(user, selectedRoles.Except(userRoles)); 43 | 44 | if (!result.Succeeded) return BadRequest("Failed to add to roles"); 45 | 46 | result = await _userManager.RemoveFromRolesAsync(user, userRoles.Except(selectedRoles)); 47 | 48 | if (!result.Succeeded) return BadRequest("Failed to remove from roles"); 49 | 50 | return Ok(await _userManager.GetRolesAsync(user)); 51 | } 52 | 53 | [Authorize(Policy = "ModeratePhotoRole")] 54 | [HttpGet("photos-to-moderate")] 55 | public ActionResult GetPhotosForModeration() 56 | { 57 | return Ok("Admins or moderators can see this"); 58 | } 59 | } 60 | } -------------------------------------------------------------------------------- /API/Controllers/BaseApiController.cs: -------------------------------------------------------------------------------- 1 | using API.Helpers; 2 | using Microsoft.AspNetCore.Mvc; 3 | 4 | namespace API.Controllers 5 | { 6 | [ServiceFilter(typeof(LogUserActivity))] 7 | [ApiController] 8 | [Route("api/[controller]")] 9 | public class BaseApiController : ControllerBase 10 | { 11 | 12 | } 13 | } -------------------------------------------------------------------------------- /API/Controllers/BuggyController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using API.Data; 3 | using API.Entities; 4 | using Microsoft.AspNetCore.Authorization; 5 | using Microsoft.AspNetCore.Mvc; 6 | 7 | namespace API.Controllers 8 | { 9 | public class BuggyController : BaseApiController 10 | { 11 | private readonly DataContext _context; 12 | public BuggyController(DataContext context) 13 | { 14 | _context = context; 15 | } 16 | 17 | [Authorize] 18 | [HttpGet("auth")] 19 | public ActionResult GetSecret() 20 | { 21 | return "secret text"; 22 | } 23 | 24 | [HttpGet("not-found")] 25 | public ActionResult GetNotFound() 26 | { 27 | var thing = _context.Users.Find(-1); 28 | 29 | if (thing == null) return NotFound(); 30 | 31 | return Ok(thing); 32 | } 33 | 34 | [HttpGet("server-error")] 35 | public ActionResult GetServerError() 36 | { 37 | var thing = _context.Users.Find(-1); 38 | 39 | var thingToReturn = thing.ToString(); 40 | 41 | return thingToReturn; 42 | } 43 | 44 | [HttpGet("bad-request")] 45 | public ActionResult GetBadRequest() 46 | { 47 | return BadRequest(); 48 | } 49 | } 50 | } -------------------------------------------------------------------------------- /API/Controllers/FallbackController.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using Microsoft.AspNetCore.Mvc; 3 | 4 | namespace API.Controllers 5 | { 6 | public class FallbackController : Controller 7 | { 8 | public ActionResult Index() 9 | { 10 | return PhysicalFile(Path.Combine(Directory.GetCurrentDirectory(), 11 | "wwwroot", "index.html"), "text/HTML"); 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /API/Controllers/LikesController.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading.Tasks; 3 | using API.DTOs; 4 | using API.Entities; 5 | using API.Extensions; 6 | using API.Helpers; 7 | using API.Interfaces; 8 | using Microsoft.AspNetCore.Authorization; 9 | using Microsoft.AspNetCore.Mvc; 10 | 11 | namespace API.Controllers 12 | { 13 | [Authorize] 14 | public class LikesController : BaseApiController 15 | { 16 | private readonly IUnitOfWork _unitOfWork; 17 | public LikesController(IUnitOfWork unitOfWork) 18 | { 19 | _unitOfWork = unitOfWork; 20 | } 21 | 22 | [HttpPost("{username}")] 23 | public async Task AddLike(string username) 24 | { 25 | var sourceUserId = User.GetUserId(); 26 | var likedUser = await _unitOfWork.UserRepository.GetUserByUsernameAsync(username); 27 | var sourceUser = await _unitOfWork.LikesRepository.GetUserWithLikes(sourceUserId); 28 | 29 | if (likedUser == null) return NotFound(); 30 | 31 | if (sourceUser.UserName == username) return BadRequest("You cannot like yourself"); 32 | 33 | var userLike = await _unitOfWork.LikesRepository.GetUserLike(sourceUserId, likedUser.Id); 34 | 35 | if (userLike != null) return BadRequest("You already like this user"); 36 | 37 | userLike = new UserLike 38 | { 39 | SourceUserId = sourceUserId, 40 | LikedUserId = likedUser.Id 41 | }; 42 | 43 | sourceUser.LikedUsers.Add(userLike); 44 | 45 | if (await _unitOfWork.Complete()) return Ok(); 46 | 47 | return BadRequest("Failed to like user"); 48 | } 49 | 50 | [HttpGet] 51 | public async Task>> GetUserLikes([FromQuery] LikesParams likesParams) 52 | { 53 | likesParams.UserId = User.GetUserId(); 54 | var users = await _unitOfWork.LikesRepository.GetUserLikes(likesParams); 55 | 56 | Response.AddPaginationHeader(users.CurrentPage, 57 | users.PageSize, users.TotalCount, users.TotalPages); 58 | 59 | return Ok(users); 60 | } 61 | } 62 | } -------------------------------------------------------------------------------- /API/Controllers/MessagesController.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading.Tasks; 3 | using API.DTOs; 4 | using API.Entities; 5 | using API.Extensions; 6 | using API.Helpers; 7 | using API.Interfaces; 8 | using AutoMapper; 9 | using Microsoft.AspNetCore.Authorization; 10 | using Microsoft.AspNetCore.Mvc; 11 | 12 | namespace API.Controllers 13 | { 14 | [Authorize] 15 | public class MessagesController : BaseApiController 16 | { 17 | private readonly IMapper _mapper; 18 | private readonly IUnitOfWork _unitOfWork; 19 | public MessagesController(IMapper mapper, IUnitOfWork unitOfWork) 20 | { 21 | _unitOfWork = unitOfWork; 22 | _mapper = mapper; 23 | } 24 | 25 | [HttpGet] 26 | public async Task>> GetMessagesForUser([FromQuery] 27 | MessageParams messageParams) 28 | { 29 | messageParams.Username = User.GetUsername(); 30 | 31 | var messages = await _unitOfWork.MessageRepository.GetMessagesForUser(messageParams); 32 | 33 | Response.AddPaginationHeader(messages.CurrentPage, messages.PageSize, 34 | messages.TotalCount, messages.TotalPages); 35 | 36 | return messages; 37 | } 38 | 39 | [HttpDelete("{id}")] 40 | public async Task DeleteMessage(int id) 41 | { 42 | var username = User.GetUsername(); 43 | 44 | var message = await _unitOfWork.MessageRepository.GetMessage(id); 45 | 46 | if (message.Sender.UserName != username && message.Recipient.UserName != username) 47 | return Unauthorized(); 48 | 49 | if (message.Sender.UserName == username) message.SenderDeleted = true; 50 | 51 | if (message.Recipient.UserName == username) message.RecipientDeleted = true; 52 | 53 | if (message.SenderDeleted && message.RecipientDeleted) 54 | _unitOfWork.MessageRepository.DeleteMessage(message); 55 | 56 | if (await _unitOfWork.Complete()) return Ok(); 57 | 58 | return BadRequest("Problem deleting the message"); 59 | } 60 | } 61 | } -------------------------------------------------------------------------------- /API/Controllers/WeatherForecastController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Mvc; 6 | using Microsoft.Extensions.Logging; 7 | 8 | namespace API.Controllers 9 | { 10 | [ApiController] 11 | [Route("[controller]")] 12 | public class WeatherForecastController : ControllerBase 13 | { 14 | private static readonly string[] Summaries = new[] 15 | { 16 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" 17 | }; 18 | 19 | private readonly ILogger _logger; 20 | 21 | // The Web API will only accept tokens 1) for users, and 2) having the access_as_user scope for this API 22 | static readonly string[] scopeRequiredByApi = new string[] { "access_as_user" }; 23 | 24 | public WeatherForecastController(ILogger logger) 25 | { 26 | _logger = logger; 27 | } 28 | 29 | [HttpGet] 30 | public IEnumerable Get() 31 | { 32 | var rng = new Random(); 33 | return Enumerable.Range(1, 5).Select(index => new WeatherForecast 34 | { 35 | Date = DateTime.Now.AddDays(index), 36 | TemperatureC = rng.Next(-20, 55), 37 | Summary = Summaries[rng.Next(Summaries.Length)] 38 | }) 39 | .ToArray(); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /API/DTOs/CreateMessageDto.cs: -------------------------------------------------------------------------------- 1 | namespace API.DTOs 2 | { 3 | public class CreateMessageDto 4 | { 5 | public string RecipientUsername { get; set; } 6 | public string Content { get; set; } 7 | } 8 | } -------------------------------------------------------------------------------- /API/DTOs/LikeDto.cs: -------------------------------------------------------------------------------- 1 | namespace API.DTOs 2 | { 3 | public class LikeDto 4 | { 5 | public int Id { get; set; } 6 | public string Username { get; set; } 7 | public int Age { get; set; } 8 | public string KnownAs { get; set; } 9 | public string PhotoUrl { get; set; } 10 | public string City { get; set; } 11 | } 12 | } -------------------------------------------------------------------------------- /API/DTOs/LoginDto.cs: -------------------------------------------------------------------------------- 1 | namespace API.DTOs 2 | { 3 | public class LoginDto 4 | { 5 | public string Username { get; set; } 6 | public string Password { get; set; } 7 | } 8 | } -------------------------------------------------------------------------------- /API/DTOs/MemberDto.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace API.DTOs 5 | { 6 | public class MemberDto 7 | { 8 | public int Id { get; set; } 9 | public string Username { get; set; } 10 | public string PhotoUrl { get; set; } 11 | public int Age { get; set; } 12 | public string KnownAs { get; set; } 13 | public DateTime Created { get; set; } 14 | public DateTime LastActive { get; set; } 15 | public string Gender { get; set; } 16 | public string Introduction { get; set; } 17 | public string LookingFor { get; set; } 18 | public string Interests { get; set; } 19 | public string City { get; set; } 20 | public string Country { get; set; } 21 | public ICollection Photos { get; set; } 22 | } 23 | } -------------------------------------------------------------------------------- /API/DTOs/MemberUpdateDto.cs: -------------------------------------------------------------------------------- 1 | namespace API.DTOs 2 | { 3 | public class MemberUpdateDto 4 | { 5 | public string Introduction { get; set; } 6 | public string LookingFor { get; set; } 7 | public string Interests { get; set; } 8 | public string City { get; set; } 9 | public string Country { get; set; } 10 | } 11 | } -------------------------------------------------------------------------------- /API/DTOs/MessageDto.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text.Json.Serialization; 3 | 4 | namespace API.DTOs 5 | { 6 | public class MessageDto 7 | { 8 | public int Id { get; set; } 9 | public int SenderId { get; set; } 10 | public string SenderUsername { get; set; } 11 | public string SenderPhotoUrl { get; set; } 12 | public int RecipientId { get; set; } 13 | public string RecipientUsername { get; set; } 14 | public string RecipientPhotoUrl { get; set; } 15 | public string Content { get; set; } 16 | public DateTime? DateRead { get; set; } 17 | public DateTime MessageSent { get; set; } 18 | 19 | [JsonIgnore] 20 | public bool SenderDeleted { get; set; } 21 | 22 | [JsonIgnore] 23 | public bool RecipientDeleted { get; set; } 24 | } 25 | } -------------------------------------------------------------------------------- /API/DTOs/PhotoDto.cs: -------------------------------------------------------------------------------- 1 | namespace API.DTOs 2 | { 3 | public class PhotoDto 4 | { 5 | public int Id { get; set; } 6 | public string Url { get; set; } 7 | public bool IsMain { get; set; } 8 | } 9 | } -------------------------------------------------------------------------------- /API/DTOs/RegisterDto.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel.DataAnnotations; 3 | 4 | namespace API.DTOs 5 | { 6 | public class RegisterDto 7 | { 8 | [Required] public string Username { get; set; } 9 | [Required] public string KnownAs { get; set; } 10 | [Required] public string Gender { get; set; } 11 | [Required] public DateTime DateOfBirth { get; set; } 12 | [Required] public string City { get; set; } 13 | [Required] public string Country { get; set; } 14 | 15 | [Required] 16 | [StringLength(8, MinimumLength = 4)] 17 | public string Password { get; set; } 18 | } 19 | } -------------------------------------------------------------------------------- /API/DTOs/UserDto.cs: -------------------------------------------------------------------------------- 1 | namespace API.DTOs 2 | { 3 | public class UserDto 4 | { 5 | public string Username { get; set; } 6 | public string Token { get; set; } 7 | public string PhotoUrl { get; set; } 8 | public string KnownAs { get; set; } 9 | public string Gender { get; set; } 10 | } 11 | } -------------------------------------------------------------------------------- /API/Data/LikesRepository.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using System.Threading.Tasks; 4 | using API.DTOs; 5 | using API.Entities; 6 | using API.Extensions; 7 | using API.Helpers; 8 | using API.Interfaces; 9 | using Microsoft.EntityFrameworkCore; 10 | 11 | namespace API.Data 12 | { 13 | public class LikesRepository : ILikesRepository 14 | { 15 | private readonly DataContext _context; 16 | public LikesRepository(DataContext context) 17 | { 18 | _context = context; 19 | } 20 | 21 | public async Task GetUserLike(int sourceUserId, int likedUserId) 22 | { 23 | return await _context.Likes.FindAsync(sourceUserId, likedUserId); 24 | } 25 | 26 | public async Task> GetUserLikes(LikesParams likesParams) 27 | { 28 | var users = _context.Users.OrderBy(u => u.UserName).AsQueryable(); 29 | var likes = _context.Likes.AsQueryable(); 30 | 31 | if (likesParams.Predicate == "liked") 32 | { 33 | likes = likes.Where(like => like.SourceUserId == likesParams.UserId); 34 | users = likes.Select(like => like.LikedUser); 35 | } 36 | 37 | if (likesParams.Predicate == "likedBy") 38 | { 39 | likes = likes.Where(like => like.LikedUserId == likesParams.UserId); 40 | users = likes.Select(like => like.SourceUser); 41 | } 42 | 43 | var likedUsers = users.Select(user => new LikeDto 44 | { 45 | Username = user.UserName, 46 | KnownAs = user.KnownAs, 47 | Age = user.DateOfBirth.CalculateAge(), 48 | PhotoUrl = user.Photos.FirstOrDefault(p => p.IsMain).Url, 49 | City = user.City, 50 | Id = user.Id 51 | }); 52 | 53 | return await PagedList.CreateAsync(likedUsers, 54 | likesParams.PageNumber, likesParams.PageSize); 55 | } 56 | 57 | public async Task GetUserWithLikes(int userId) 58 | { 59 | return await _context.Users 60 | .Include(x => x.LikedUsers) 61 | .FirstOrDefaultAsync(x => x.Id == userId); 62 | } 63 | } 64 | } -------------------------------------------------------------------------------- /API/Data/MessageRepository.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using API.DTOs; 6 | using API.Entities; 7 | using API.Extensions; 8 | using API.Helpers; 9 | using API.Interfaces; 10 | using AutoMapper; 11 | using AutoMapper.QueryableExtensions; 12 | using Microsoft.EntityFrameworkCore; 13 | 14 | namespace API.Data 15 | { 16 | public class MessageRepository : IMessageRepository 17 | { 18 | private readonly DataContext _context; 19 | private readonly IMapper _mapper; 20 | public MessageRepository(DataContext context, IMapper mapper) 21 | { 22 | _mapper = mapper; 23 | _context = context; 24 | } 25 | 26 | public void AddGroup(Group group) 27 | { 28 | _context.Groups.Add(group); 29 | } 30 | 31 | public void AddMessage(Message message) 32 | { 33 | _context.Messages.Add(message); 34 | } 35 | 36 | public void DeleteMessage(Message message) 37 | { 38 | _context.Messages.Remove(message); 39 | } 40 | 41 | public async Task GetConnection(string connectionId) 42 | { 43 | return await _context.Connections.FindAsync(connectionId); 44 | } 45 | 46 | public async Task GetGroupForConnection(string connectionId) 47 | { 48 | return await _context.Groups 49 | .Include(c => c.Connections) 50 | .Where(c => c.Connections.Any(x => x.ConnectionId == connectionId)) 51 | .FirstOrDefaultAsync(); 52 | } 53 | 54 | public async Task GetMessage(int id) 55 | { 56 | return await _context.Messages 57 | .Include(u => u.Sender) 58 | .Include(u => u.Recipient) 59 | .SingleOrDefaultAsync(x => x.Id == id); 60 | } 61 | 62 | public async Task GetMessageGroup(string groupName) 63 | { 64 | return await _context.Groups 65 | .Include(x => x.Connections) 66 | .FirstOrDefaultAsync(x => x.Name == groupName); 67 | } 68 | 69 | public async Task> GetMessagesForUser(MessageParams messageParams) 70 | { 71 | var query = _context.Messages 72 | .OrderByDescending(m => m.MessageSent) 73 | .ProjectTo(_mapper.ConfigurationProvider) 74 | .AsQueryable(); 75 | 76 | query = messageParams.Container switch 77 | { 78 | "Inbox" => query.Where(u => u.RecipientUsername == messageParams.Username 79 | && u.RecipientDeleted == false), 80 | "Outbox" => query.Where(u => u.SenderUsername == messageParams.Username 81 | && u.SenderDeleted == false), 82 | _ => query.Where(u => u.RecipientUsername == 83 | messageParams.Username && u.RecipientDeleted == false && u.DateRead == null) 84 | }; 85 | 86 | return await PagedList.CreateAsync(query, messageParams.PageNumber, messageParams.PageSize); 87 | 88 | } 89 | 90 | public async Task> GetMessageThread(string currentUsername, 91 | string recipientUsername) 92 | { 93 | var messages = await _context.Messages 94 | .Where(m => m.Recipient.UserName == currentUsername && m.RecipientDeleted == false 95 | && m.Sender.UserName == recipientUsername 96 | || m.Recipient.UserName == recipientUsername 97 | && m.Sender.UserName == currentUsername && m.SenderDeleted == false 98 | ) 99 | .MarkUnreadAsRead(currentUsername) 100 | .OrderBy(m => m.MessageSent) 101 | .ProjectTo(_mapper.ConfigurationProvider) 102 | .ToListAsync(); 103 | 104 | return messages; 105 | } 106 | 107 | public void RemoveConnection(Connection connection) 108 | { 109 | _context.Connections.Remove(connection); 110 | } 111 | } 112 | } -------------------------------------------------------------------------------- /API/Data/Seed.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Text.Json; 3 | using System.Threading.Tasks; 4 | using API.Entities; 5 | using Microsoft.AspNetCore.Identity; 6 | using Microsoft.EntityFrameworkCore; 7 | 8 | namespace API.Data 9 | { 10 | public class Seed 11 | { 12 | public static async Task SeedUsers(UserManager userManager, 13 | RoleManager roleManager) 14 | { 15 | if (await userManager.Users.AnyAsync()) return; 16 | 17 | var userData = await System.IO.File.ReadAllTextAsync("Data/UserSeedData.json"); 18 | var users = JsonSerializer.Deserialize>(userData); 19 | if (users == null) return; 20 | 21 | var roles = new List 22 | { 23 | new AppRole{Name = "Member"}, 24 | new AppRole{Name = "Admin"}, 25 | new AppRole{Name = "Moderator"}, 26 | }; 27 | 28 | foreach (var role in roles) 29 | { 30 | await roleManager.CreateAsync(role); 31 | } 32 | 33 | foreach (var user in users) 34 | { 35 | user.UserName = user.UserName.ToLower(); 36 | await userManager.CreateAsync(user, "Pa$$w0rd"); 37 | await userManager.AddToRoleAsync(user, "Member"); 38 | } 39 | 40 | var admin = new AppUser 41 | { 42 | UserName = "admin" 43 | }; 44 | 45 | await userManager.CreateAsync(admin, "Pa$$w0rd"); 46 | await userManager.AddToRolesAsync(admin, new[] {"Admin", "Moderator"}); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /API/Data/UnitOfWork.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using API.Interfaces; 3 | using AutoMapper; 4 | 5 | namespace API.Data 6 | { 7 | public class UnitOfWork : IUnitOfWork 8 | { 9 | private readonly IMapper _mapper; 10 | private readonly DataContext _context; 11 | public UnitOfWork(DataContext context, IMapper mapper) 12 | { 13 | _context = context; 14 | _mapper = mapper; 15 | } 16 | 17 | public IUserRepository UserRepository => new UserRepository(_context, _mapper); 18 | 19 | public IMessageRepository MessageRepository => new MessageRepository(_context, _mapper); 20 | 21 | public ILikesRepository LikesRepository => new LikesRepository(_context); 22 | 23 | public async Task Complete() 24 | { 25 | return await _context.SaveChangesAsync() > 0; 26 | } 27 | 28 | public bool HasChanges() 29 | { 30 | _context.ChangeTracker.DetectChanges(); 31 | var changes = _context.ChangeTracker.HasChanges(); 32 | 33 | return changes; 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /API/Data/UserRepository.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using API.DTOs; 6 | using API.Entities; 7 | using API.Helpers; 8 | using API.Interfaces; 9 | using AutoMapper; 10 | using AutoMapper.QueryableExtensions; 11 | using Microsoft.EntityFrameworkCore; 12 | 13 | namespace API.Data 14 | { 15 | public class UserRepository : IUserRepository 16 | { 17 | private readonly DataContext _context; 18 | private readonly IMapper _mapper; 19 | public UserRepository(DataContext context, IMapper mapper) 20 | { 21 | _mapper = mapper; 22 | _context = context; 23 | } 24 | 25 | public async Task GetMemberAsync(string username) 26 | { 27 | return await _context.Users 28 | .Where(x => x.UserName == username) 29 | .ProjectTo(_mapper.ConfigurationProvider) 30 | .SingleOrDefaultAsync(); 31 | } 32 | 33 | public async Task> GetMembersAsync(UserParams userParams) 34 | { 35 | var query = _context.Users.AsQueryable(); 36 | 37 | query = query.Where(u => u.UserName != userParams.CurrentUsername); 38 | query = query.Where(u => u.Gender == userParams.Gender); 39 | 40 | var minDob = DateTime.Today.AddYears(-userParams.MaxAge - 1); 41 | var maxDob = DateTime.Today.AddYears(-userParams.MinAge); 42 | 43 | query = query.Where(u => u.DateOfBirth >= minDob && u.DateOfBirth <= maxDob); 44 | 45 | query = userParams.OrderBy switch 46 | { 47 | "created" => query.OrderByDescending(u => u.Created), 48 | _ => query.OrderByDescending(u => u.LastActive) 49 | }; 50 | 51 | return await PagedList.CreateAsync(query.ProjectTo(_mapper 52 | .ConfigurationProvider).AsNoTracking(), 53 | userParams.PageNumber, userParams.PageSize); 54 | } 55 | 56 | public async Task GetUserByIdAsync(int id) 57 | { 58 | return await _context.Users.FindAsync(id); 59 | } 60 | 61 | public async Task GetUserByUsernameAsync(string username) 62 | { 63 | return await _context.Users 64 | .Include(p => p.Photos) 65 | .SingleOrDefaultAsync(x => x.UserName == username); 66 | } 67 | 68 | public async Task GetUserGender(string username) 69 | { 70 | return await _context.Users 71 | .Where(x => x.UserName == username) 72 | .Select(x => x.Gender).FirstOrDefaultAsync(); 73 | } 74 | 75 | public async Task> GetUsersAsync() 76 | { 77 | return await _context.Users 78 | .Include(p => p.Photos) 79 | .ToListAsync(); 80 | } 81 | 82 | public void Update(AppUser user) 83 | { 84 | _context.Entry(user).State = EntityState.Modified; 85 | } 86 | } 87 | } -------------------------------------------------------------------------------- /API/Entities/AppRole.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using Microsoft.AspNetCore.Identity; 3 | 4 | namespace API.Entities 5 | { 6 | public class AppRole : IdentityRole 7 | { 8 | public ICollection UserRoles { get; set; } 9 | } 10 | } -------------------------------------------------------------------------------- /API/Entities/AppUser.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using Microsoft.AspNetCore.Identity; 4 | 5 | namespace API.Entities 6 | { 7 | public class AppUser : IdentityUser 8 | { 9 | public DateTime DateOfBirth { get; set; } 10 | public string KnownAs { get; set; } 11 | public DateTime Created { get; set; } = DateTime.Now; 12 | public DateTime LastActive { get; set; } = DateTime.Now; 13 | public string Gender { get; set; } 14 | public string Introduction { get; set; } 15 | public string LookingFor { get; set; } 16 | public string Interests { get; set; } 17 | public string City { get; set; } 18 | public string Country { get; set; } 19 | public ICollection Photos { get; set; } 20 | 21 | public ICollection LikedByUsers { get; set; } 22 | public ICollection LikedUsers { get; set; } 23 | 24 | public ICollection MessagesSent { get; set; } 25 | public ICollection MessagesReceived { get; set; } 26 | public ICollection UserRoles { get; set; } 27 | 28 | } 29 | } -------------------------------------------------------------------------------- /API/Entities/AppUserRole.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Identity; 2 | 3 | namespace API.Entities 4 | { 5 | public class AppUserRole : IdentityUserRole 6 | { 7 | public AppUser User { get; set; } 8 | public AppRole Role { get; set; } 9 | } 10 | } -------------------------------------------------------------------------------- /API/Entities/Connection.cs: -------------------------------------------------------------------------------- 1 | namespace API.Entities 2 | { 3 | public class Connection 4 | { 5 | public Connection() 6 | { 7 | } 8 | 9 | public Connection(string connectionId, string username) 10 | { 11 | ConnectionId = connectionId; 12 | Username = username; 13 | } 14 | 15 | public string ConnectionId { get; set; } 16 | public string Username { get; set; } 17 | } 18 | } -------------------------------------------------------------------------------- /API/Entities/Group.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.ComponentModel.DataAnnotations; 3 | 4 | namespace API.Entities 5 | { 6 | public class Group 7 | { 8 | public Group() 9 | { 10 | } 11 | 12 | public Group(string name) 13 | { 14 | Name = name; 15 | } 16 | 17 | [Key] 18 | public string Name { get; set; } 19 | public ICollection Connections { get; set; } = new List(); 20 | } 21 | } -------------------------------------------------------------------------------- /API/Entities/Message.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace API.Entities 4 | { 5 | public class Message 6 | { 7 | public int Id { get; set; } 8 | public int SenderId { get; set; } 9 | public string SenderUsername { get; set; } 10 | public AppUser Sender { get; set; } 11 | public int RecipientId { get; set; } 12 | public string RecipientUsername { get; set; } 13 | public AppUser Recipient { get; set; } 14 | public string Content { get; set; } 15 | public DateTime? DateRead { get; set; } 16 | public DateTime MessageSent { get; set; } = DateTime.UtcNow; 17 | public bool SenderDeleted { get; set; } 18 | public bool RecipientDeleted { get; set; } 19 | } 20 | } -------------------------------------------------------------------------------- /API/Entities/Photo.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations.Schema; 2 | 3 | namespace API.Entities 4 | { 5 | [Table("Photos")] 6 | public class Photo 7 | { 8 | public int Id { get; set; } 9 | public string Url { get; set; } 10 | public bool IsMain { get; set; } 11 | public string PublicId { get; set; } 12 | public AppUser AppUser { get; set; } 13 | public int AppUserId { get; set; } 14 | } 15 | } -------------------------------------------------------------------------------- /API/Entities/UserLike.cs: -------------------------------------------------------------------------------- 1 | namespace API.Entities 2 | { 3 | public class UserLike 4 | { 5 | public AppUser SourceUser { get; set; } 6 | public int SourceUserId { get; set; } 7 | 8 | public AppUser LikedUser { get; set; } 9 | public int LikedUserId { get; set; } 10 | } 11 | } -------------------------------------------------------------------------------- /API/Errors/ApiException.cs: -------------------------------------------------------------------------------- 1 | namespace API.Errors 2 | { 3 | public class ApiException 4 | { 5 | public ApiException(int statusCode, string message = null, string details = null) 6 | { 7 | StatusCode = statusCode; 8 | Message = message; 9 | Details = details; 10 | } 11 | 12 | public int StatusCode { get; set; } 13 | public string Message { get; set; } 14 | public string Details { get; set; } 15 | } 16 | } -------------------------------------------------------------------------------- /API/Extensions/ApplicationServiceExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using API.Data; 3 | using API.Helpers; 4 | using API.Interfaces; 5 | using API.Services; 6 | using API.SignalR; 7 | using AutoMapper; 8 | using Microsoft.EntityFrameworkCore; 9 | using Microsoft.Extensions.Configuration; 10 | using Microsoft.Extensions.DependencyInjection; 11 | 12 | namespace API.Extensions 13 | { 14 | public static class ApplicationServiceExtensions 15 | { 16 | public static IServiceCollection AddApplicationServices(this IServiceCollection services, IConfiguration config) 17 | { 18 | services.AddSingleton(); 19 | services.Configure(config.GetSection("CloudinarySettings")); 20 | services.AddScoped(); 21 | services.AddScoped(); 22 | services.AddScoped(); 23 | services.AddScoped(); 24 | services.AddAutoMapper(typeof(AutoMapperProfiles).Assembly); 25 | services.AddDbContext(options => 26 | { 27 | var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); 28 | 29 | string connStr; 30 | 31 | // Depending on if in development or production, use either Heroku-provided 32 | // connection string, or development connection string from env var. 33 | if (env == "Development") 34 | { 35 | // Use connection string from file. 36 | connStr = config.GetConnectionString("DefaultConnection"); 37 | } 38 | else 39 | { 40 | // Use connection string provided at runtime by Heroku. 41 | var connUrl = Environment.GetEnvironmentVariable("DATABASE_URL"); 42 | 43 | // Parse connection URL to connection string for Npgsql 44 | connUrl = connUrl.Replace("postgres://", string.Empty); 45 | var pgUserPass = connUrl.Split("@")[0]; 46 | var pgHostPortDb = connUrl.Split("@")[1]; 47 | var pgHostPort = pgHostPortDb.Split("/")[0]; 48 | var pgDb = pgHostPortDb.Split("/")[1]; 49 | var pgUser = pgUserPass.Split(":")[0]; 50 | var pgPass = pgUserPass.Split(":")[1]; 51 | var pgHost = pgHostPort.Split(":")[0]; 52 | var pgPort = pgHostPort.Split(":")[1]; 53 | 54 | connStr = $"Server={pgHost};Port={pgPort};User Id={pgUser};Password={pgPass};Database={pgDb}; SSL Mode=Require; Trust Server Certificate=true"; 55 | } 56 | 57 | // Whether the connection string came from the local development configuration file 58 | // or from the environment variable from Heroku, use it to set up your DbContext. 59 | options.UseNpgsql(connStr); 60 | }); 61 | 62 | return services; 63 | } 64 | } 65 | } -------------------------------------------------------------------------------- /API/Extensions/ClaimsPrincipleExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.Security.Claims; 2 | 3 | namespace API.Extensions 4 | { 5 | public static class ClaimsPrincipleExtensions 6 | { 7 | public static string GetUsername(this ClaimsPrincipal user) 8 | { 9 | return user.FindFirst(ClaimTypes.Name)?.Value; 10 | } 11 | 12 | public static int GetUserId(this ClaimsPrincipal user) 13 | { 14 | return int.Parse(user.FindFirst(ClaimTypes.NameIdentifier)?.Value); 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /API/Extensions/DateTimeExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace API.Extensions 4 | { 5 | public static class DateTimeExtensions 6 | { 7 | public static int CalculateAge(this DateTime dob) 8 | { 9 | var today = DateTime.Today; 10 | var age = today.Year - dob.Year; 11 | if (dob.Date > today.AddYears(-age)) age--; 12 | return age; 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /API/Extensions/HttpExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json; 2 | using API.Helpers; 3 | using Microsoft.AspNetCore.Http; 4 | 5 | namespace API.Extensions 6 | { 7 | public static class HttpExtensions 8 | { 9 | public static void AddPaginationHeader(this HttpResponse response, int currentPage, 10 | int itemsPerPage, int totalItems, int totalPages) 11 | { 12 | var paginationHeader = new PaginationHeader(currentPage, itemsPerPage, totalItems, totalPages); 13 | 14 | var options = new JsonSerializerOptions 15 | { 16 | PropertyNamingPolicy = JsonNamingPolicy.CamelCase 17 | }; 18 | 19 | response.Headers.Add("Pagination", JsonSerializer.Serialize(paginationHeader, options)); 20 | response.Headers.Add("Access-Control-Expose-Headers", "Pagination"); 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /API/Extensions/IdentityServiceExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.Text; 2 | using System.Threading.Tasks; 3 | using API.Data; 4 | using API.Entities; 5 | using Microsoft.AspNetCore.Authentication.JwtBearer; 6 | using Microsoft.AspNetCore.Identity; 7 | using Microsoft.Extensions.Configuration; 8 | using Microsoft.Extensions.DependencyInjection; 9 | using Microsoft.IdentityModel.Tokens; 10 | 11 | namespace API.Extensions 12 | { 13 | public static class IdentityServiceExtensions 14 | { 15 | public static IServiceCollection AddIdentityServices(this IServiceCollection services, 16 | IConfiguration config) 17 | { 18 | services.AddIdentityCore(opt => 19 | { 20 | opt.Password.RequireNonAlphanumeric = false; 21 | }) 22 | .AddRoles() 23 | .AddRoleManager>() 24 | .AddSignInManager>() 25 | .AddRoleValidator>() 26 | .AddEntityFrameworkStores(); 27 | 28 | services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) 29 | .AddJwtBearer(options => 30 | { 31 | options.TokenValidationParameters = new TokenValidationParameters 32 | { 33 | ValidateIssuerSigningKey = true, 34 | IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["TokenKey"])), 35 | ValidateIssuer = false, 36 | ValidateAudience = false, 37 | }; 38 | 39 | options.Events = new JwtBearerEvents 40 | { 41 | OnMessageReceived = context => 42 | { 43 | var accessToken = context.Request.Query["access_token"]; 44 | 45 | var path = context.HttpContext.Request.Path; 46 | if (!string.IsNullOrEmpty(accessToken) && 47 | path.StartsWithSegments("/hubs")) 48 | { 49 | context.Token = accessToken; 50 | } 51 | 52 | return Task.CompletedTask; 53 | } 54 | }; 55 | }); 56 | 57 | services.AddAuthorization(opt => 58 | { 59 | opt.AddPolicy("RequireAdminRole", policy => policy.RequireRole("Admin")); 60 | opt.AddPolicy("ModeratePhotoRole", policy => policy.RequireRole("Admin", "Moderator")); 61 | }); 62 | 63 | return services; 64 | } 65 | } 66 | } -------------------------------------------------------------------------------- /API/Extensions/QueryableExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using API.Entities; 4 | 5 | namespace API.Extensions 6 | { 7 | public static class QueryableExtensions 8 | { 9 | public static IQueryable MarkUnreadAsRead(this IQueryable query, string currentUsername) 10 | { 11 | var unreadMessages = query.Where(m => m.DateRead == null 12 | && m.RecipientUsername == currentUsername); 13 | 14 | if (unreadMessages.Any()) 15 | { 16 | foreach (var message in unreadMessages) 17 | { 18 | message.DateRead = DateTime.UtcNow; 19 | } 20 | } 21 | 22 | return query; 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /API/GlobalUsings.cs: -------------------------------------------------------------------------------- 1 | global using System; 2 | global using System.Collections.Generic; 3 | global using System.Linq; 4 | global using System.Threading.Tasks; 5 | global using API.Data; 6 | global using API.Entities; 7 | global using API.Extensions; 8 | global using API.Middleware; 9 | global using API.SignalR; 10 | global using Microsoft.AspNetCore.Builder; 11 | global using Microsoft.AspNetCore.Hosting; 12 | global using Microsoft.AspNetCore.Identity; 13 | global using Microsoft.EntityFrameworkCore; 14 | global using Microsoft.Extensions.Configuration; 15 | global using Microsoft.Extensions.DependencyInjection; 16 | global using Microsoft.Extensions.Hosting; 17 | global using Microsoft.Extensions.Logging; 18 | global using API.DTOs; 19 | global using API.Interfaces; 20 | global using AutoMapper; 21 | global using Microsoft.AspNetCore.Mvc; 22 | global using Microsoft.AspNetCore.Authorization; -------------------------------------------------------------------------------- /API/Helpers/AutoMapperProfiles.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using API.DTOs; 4 | using API.Entities; 5 | using API.Extensions; 6 | using AutoMapper; 7 | 8 | namespace API.Helpers 9 | { 10 | public class AutoMapperProfiles : Profile 11 | { 12 | public AutoMapperProfiles() 13 | { 14 | CreateMap() 15 | .ForMember(dest => dest.PhotoUrl, opt => opt.MapFrom(src => 16 | src.Photos.FirstOrDefault(x => x.IsMain).Url)) 17 | .ForMember(dest => dest.Age, opt => opt.MapFrom(src => src.DateOfBirth.CalculateAge())); 18 | CreateMap(); 19 | CreateMap(); 20 | CreateMap(); 21 | CreateMap() 22 | .ForMember(dest => dest.SenderPhotoUrl, opt => opt.MapFrom(src => 23 | src.Sender.Photos.FirstOrDefault(x => x.IsMain).Url)) 24 | .ForMember(dest => dest.RecipientPhotoUrl, opt => opt.MapFrom(src => 25 | src.Recipient.Photos.FirstOrDefault(x => x.IsMain).Url)); 26 | CreateMap(); 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /API/Helpers/CloudinarySettings.cs: -------------------------------------------------------------------------------- 1 | namespace API.Helpers 2 | { 3 | public class CloudinarySettings 4 | { 5 | public string CloudName { get; set; } 6 | public string ApiKey { get; set; } 7 | public string ApiSecret { get; set; } 8 | } 9 | } -------------------------------------------------------------------------------- /API/Helpers/LikesParams.cs: -------------------------------------------------------------------------------- 1 | namespace API.Helpers 2 | { 3 | public class LikesParams : PaginationParams 4 | { 5 | public int UserId { get; set; } 6 | public string Predicate { get; set; } 7 | } 8 | } -------------------------------------------------------------------------------- /API/Helpers/LogUserActivity.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading.Tasks; 3 | using API.Extensions; 4 | using API.Interfaces; 5 | using Microsoft.AspNetCore.Mvc.Filters; 6 | using Microsoft.Extensions.DependencyInjection; 7 | 8 | namespace API.Helpers 9 | { 10 | public class LogUserActivity : IAsyncActionFilter 11 | { 12 | public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) 13 | { 14 | var resultContext = await next(); 15 | 16 | if (!resultContext.HttpContext.User.Identity.IsAuthenticated) return; 17 | 18 | var userId = resultContext.HttpContext.User.GetUserId(); 19 | var uow = resultContext.HttpContext.RequestServices.GetService(); 20 | var user = await uow.UserRepository.GetUserByIdAsync(userId); 21 | user.LastActive = DateTime.UtcNow; 22 | await uow.Complete(); 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /API/Helpers/MessageParams.cs: -------------------------------------------------------------------------------- 1 | namespace API.Helpers 2 | { 3 | public class MessageParams : PaginationParams 4 | { 5 | public string Username { get; set; } 6 | public string Container { get; set; } = "Unread"; 7 | } 8 | } -------------------------------------------------------------------------------- /API/Helpers/PagedList.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.EntityFrameworkCore; 6 | 7 | namespace API.Helpers 8 | { 9 | public class PagedList : List 10 | { 11 | public PagedList(IEnumerable items, int count, int pageNumber, int pageSize) 12 | { 13 | CurrentPage = pageNumber; 14 | TotalPages = (int) Math.Ceiling(count / (double) pageSize); 15 | PageSize = pageSize; 16 | TotalCount = count; 17 | AddRange(items); 18 | } 19 | 20 | public int CurrentPage { get; set; } 21 | public int TotalPages { get; set; } 22 | public int PageSize { get; set; } 23 | public int TotalCount { get; set; } 24 | 25 | public static async Task> CreateAsync(IQueryable source, int pageNumber, 26 | int pageSize) 27 | { 28 | var count = await source.CountAsync(); 29 | var items = await source.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToListAsync(); 30 | return new PagedList(items, count, pageNumber, pageSize); 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /API/Helpers/PaginationHeader.cs: -------------------------------------------------------------------------------- 1 | namespace API.Helpers 2 | { 3 | public class PaginationHeader 4 | { 5 | public PaginationHeader(int currentPage, int itemsPerPage, int totalItems, int totalPages) 6 | { 7 | CurrentPage = currentPage; 8 | ItemsPerPage = itemsPerPage; 9 | TotalItems = totalItems; 10 | TotalPages = totalPages; 11 | } 12 | 13 | public int CurrentPage { get; set; } 14 | public int ItemsPerPage { get; set; } 15 | public int TotalItems { get; set; } 16 | public int TotalPages { get; set; } 17 | } 18 | } -------------------------------------------------------------------------------- /API/Helpers/PaginationParams.cs: -------------------------------------------------------------------------------- 1 | namespace API.Helpers 2 | { 3 | public class PaginationParams 4 | { 5 | private const int MaxPageSize = 50; 6 | public int PageNumber { get; set; } = 1; 7 | private int _pageSize = 10; 8 | 9 | public int PageSize 10 | { 11 | get => _pageSize; 12 | set => _pageSize = (value > MaxPageSize) ? MaxPageSize : value; 13 | } 14 | 15 | } 16 | } -------------------------------------------------------------------------------- /API/Helpers/UserParams.cs: -------------------------------------------------------------------------------- 1 | namespace API.Helpers 2 | { 3 | public class UserParams : PaginationParams 4 | { 5 | public string CurrentUsername { get; set; } 6 | public string Gender { get; set; } 7 | public int MinAge { get; set; } = 18; 8 | public int MaxAge { get; set; } = 150; 9 | public string OrderBy { get; set; } = "lastActive"; 10 | } 11 | } -------------------------------------------------------------------------------- /API/Interfaces/ILikesRepository.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading.Tasks; 3 | using API.DTOs; 4 | using API.Entities; 5 | using API.Helpers; 6 | 7 | namespace API.Interfaces 8 | { 9 | public interface ILikesRepository 10 | { 11 | Task GetUserLike(int sourceUserId, int likedUserId); 12 | Task GetUserWithLikes(int userId); 13 | Task> GetUserLikes(LikesParams likesParams); 14 | } 15 | } -------------------------------------------------------------------------------- /API/Interfaces/IMessageRepository.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading.Tasks; 3 | using API.DTOs; 4 | using API.Entities; 5 | using API.Helpers; 6 | 7 | namespace API.Interfaces 8 | { 9 | public interface IMessageRepository 10 | { 11 | void AddGroup(Group group); 12 | void RemoveConnection(Connection connection); 13 | Task GetConnection(string connectionId); 14 | Task GetMessageGroup(string groupName); 15 | Task GetGroupForConnection(string connectionId); 16 | void AddMessage(Message message); 17 | void DeleteMessage(Message message); 18 | Task GetMessage(int id); 19 | Task> GetMessagesForUser(MessageParams messageParams); 20 | Task> GetMessageThread(string currentUsername, string recipientUsername); 21 | } 22 | } -------------------------------------------------------------------------------- /API/Interfaces/IPhotoService.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using CloudinaryDotNet.Actions; 3 | using Microsoft.AspNetCore.Http; 4 | 5 | namespace API.Interfaces 6 | { 7 | public interface IPhotoService 8 | { 9 | Task AddPhotoAsync(IFormFile file); 10 | Task DeletePhotoAsync(string publicId); 11 | } 12 | } -------------------------------------------------------------------------------- /API/Interfaces/ITokenService.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using API.Entities; 3 | 4 | namespace API.Interfaces 5 | { 6 | public interface ITokenService 7 | { 8 | Task CreateToken(AppUser user); 9 | } 10 | } -------------------------------------------------------------------------------- /API/Interfaces/IUnitOfWork.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | 3 | namespace API.Interfaces 4 | { 5 | public interface IUnitOfWork 6 | { 7 | IUserRepository UserRepository {get; } 8 | IMessageRepository MessageRepository {get;} 9 | ILikesRepository LikesRepository {get; } 10 | Task Complete(); 11 | bool HasChanges(); 12 | } 13 | } -------------------------------------------------------------------------------- /API/Interfaces/IUserRepository.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading.Tasks; 3 | using API.DTOs; 4 | using API.Entities; 5 | using API.Helpers; 6 | 7 | namespace API.Interfaces 8 | { 9 | public interface IUserRepository 10 | { 11 | void Update(AppUser user); 12 | Task> GetUsersAsync(); 13 | Task GetUserByIdAsync(int id); 14 | Task GetUserByUsernameAsync(string username); 15 | Task> GetMembersAsync(UserParams userParams); 16 | Task GetMemberAsync(string username); 17 | Task GetUserGender(string username); 18 | } 19 | } -------------------------------------------------------------------------------- /API/Middleware/ExceptionMiddleware.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | using System.Text.Json; 4 | using System.Threading.Tasks; 5 | using API.Errors; 6 | using Microsoft.AspNetCore.Http; 7 | using Microsoft.Extensions.Hosting; 8 | using Microsoft.Extensions.Logging; 9 | 10 | namespace API.Middleware 11 | { 12 | public class ExceptionMiddleware 13 | { 14 | private readonly RequestDelegate _next; 15 | private readonly ILogger _logger; 16 | private readonly IHostEnvironment _env; 17 | public ExceptionMiddleware(RequestDelegate next, ILogger logger, 18 | IHostEnvironment env) 19 | { 20 | _env = env; 21 | _logger = logger; 22 | _next = next; 23 | } 24 | 25 | public async Task InvokeAsync(HttpContext context) 26 | { 27 | try 28 | { 29 | await _next(context); 30 | } 31 | catch (Exception ex) 32 | { 33 | _logger.LogError(ex, ex.Message); 34 | context.Response.ContentType = "application/json"; 35 | context.Response.StatusCode = (int) HttpStatusCode.InternalServerError; 36 | 37 | var response = _env.IsDevelopment() 38 | ? new ApiException(context.Response.StatusCode, ex.Message, ex.StackTrace?.ToString()) 39 | : new ApiException(context.Response.StatusCode, "Internal Server Error"); 40 | 41 | var options = new JsonSerializerOptions{PropertyNamingPolicy = JsonNamingPolicy.CamelCase}; 42 | 43 | var json = JsonSerializer.Serialize(response, options); 44 | 45 | await context.Response.WriteAsync(json); 46 | } 47 | } 48 | } 49 | } -------------------------------------------------------------------------------- /API/Program.cs: -------------------------------------------------------------------------------- 1 | var builder = WebApplication.CreateBuilder(args); 2 | 3 | // add services to the container 4 | 5 | builder.Services.AddApplicationServices(builder.Configuration); 6 | builder.Services.AddControllers(); 7 | builder.Services.AddCors(); 8 | builder.Services.AddIdentityServices(builder.Configuration); 9 | builder.Services.AddSignalR(); 10 | 11 | // Configure the HTTP request pipeline 12 | 13 | var app = builder.Build(); 14 | 15 | app.UseMiddleware(); 16 | 17 | app.UseHttpsRedirection(); 18 | 19 | app.UseCors(x => x.AllowAnyHeader() 20 | .AllowAnyMethod() 21 | .AllowCredentials() 22 | .WithOrigins("https://localhost:4200")); 23 | 24 | app.UseAuthentication(); 25 | app.UseAuthorization(); 26 | 27 | app.UseDefaultFiles(); 28 | app.UseStaticFiles(); 29 | 30 | app.MapControllers(); 31 | app.MapHub("hubs/presence"); 32 | app.MapHub("hubs/message"); 33 | app.MapFallbackToController("Index", "Fallback"); 34 | 35 | AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true); 36 | using var scope = app.Services.CreateScope(); 37 | var services = scope.ServiceProvider; 38 | try 39 | { 40 | var context = services.GetRequiredService(); 41 | var userManager = services.GetRequiredService>(); 42 | var roleManager = services.GetRequiredService>(); 43 | await context.Database.MigrateAsync(); 44 | await Seed.SeedUsers(userManager, roleManager); 45 | } 46 | catch (Exception ex) 47 | { 48 | var logger = services.GetRequiredService>(); 49 | logger.LogError(ex, "An error occurred during migration"); 50 | } 51 | 52 | await app.RunAsync(); -------------------------------------------------------------------------------- /API/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:32356", 8 | "sslPort": 44363 9 | } 10 | }, 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchBrowser": true, 15 | "launchUrl": "weatherforecast", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | } 19 | }, 20 | "API": { 21 | "commandName": "Project", 22 | "dotnetRunMessages": "true", 23 | "launchBrowser": false, 24 | "launchUrl": "weatherforecast", 25 | "applicationUrl": "https://localhost:5001;http://localhost:5000", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /API/Services/PhotoService.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using API.Helpers; 3 | using API.Interfaces; 4 | using CloudinaryDotNet; 5 | using CloudinaryDotNet.Actions; 6 | using Microsoft.AspNetCore.Http; 7 | using Microsoft.Extensions.Options; 8 | 9 | namespace API.Services 10 | { 11 | public class PhotoService : IPhotoService 12 | { 13 | private readonly Cloudinary _cloudinary; 14 | public PhotoService(IOptions config) 15 | { 16 | var acc = new Account 17 | ( 18 | config.Value.CloudName, 19 | config.Value.ApiKey, 20 | config.Value.ApiSecret 21 | ); 22 | 23 | _cloudinary = new Cloudinary(acc); 24 | } 25 | 26 | public async Task AddPhotoAsync(IFormFile file) 27 | { 28 | var uploadResult = new ImageUploadResult(); 29 | 30 | if (file.Length > 0) 31 | { 32 | using var stream = file.OpenReadStream(); 33 | var uploadParams = new ImageUploadParams 34 | { 35 | File = new FileDescription(file.FileName, stream), 36 | Transformation = new Transformation().Height(500).Width(500).Crop("fill").Gravity("face") 37 | }; 38 | uploadResult = await _cloudinary.UploadAsync(uploadParams); 39 | } 40 | 41 | return uploadResult; 42 | } 43 | 44 | public async Task DeletePhotoAsync(string publicId) 45 | { 46 | var deleteParams = new DeletionParams(publicId); 47 | 48 | var result = await _cloudinary.DestroyAsync(deleteParams); 49 | 50 | return result; 51 | } 52 | } 53 | } -------------------------------------------------------------------------------- /API/Services/TokenService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IdentityModel.Tokens.Jwt; 4 | using System.Linq; 5 | using System.Security.Claims; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | using API.Entities; 9 | using API.Interfaces; 10 | using Microsoft.AspNetCore.Identity; 11 | using Microsoft.Extensions.Configuration; 12 | using Microsoft.IdentityModel.Tokens; 13 | 14 | namespace API.Services 15 | { 16 | public class TokenService : ITokenService 17 | { 18 | private readonly SymmetricSecurityKey _key; 19 | private readonly UserManager _userManager; 20 | public TokenService(IConfiguration config, UserManager userManager) 21 | { 22 | _userManager = userManager; 23 | _key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["TokenKey"])); 24 | } 25 | 26 | public async Task CreateToken(AppUser user) 27 | { 28 | var claims = new List 29 | { 30 | new Claim(JwtRegisteredClaimNames.NameId, user.Id.ToString()), 31 | new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName), 32 | }; 33 | 34 | var roles = await _userManager.GetRolesAsync(user); 35 | 36 | claims.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role))); 37 | 38 | var creds = new SigningCredentials(_key, SecurityAlgorithms.HmacSha512Signature); 39 | 40 | var tokenDescriptor = new SecurityTokenDescriptor 41 | { 42 | Subject = new ClaimsIdentity(claims), 43 | Expires = DateTime.Now.AddDays(7), 44 | SigningCredentials = creds 45 | }; 46 | 47 | var tokenHandler = new JwtSecurityTokenHandler(); 48 | 49 | var token = tokenHandler.CreateToken(tokenDescriptor); 50 | 51 | return tokenHandler.WriteToken(token); 52 | } 53 | } 54 | } -------------------------------------------------------------------------------- /API/SignalR/PresenceHub.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading.Tasks; 3 | using API.Extensions; 4 | using API.Helpers; 5 | using Microsoft.AspNetCore.Authorization; 6 | using Microsoft.AspNetCore.Mvc; 7 | using Microsoft.AspNetCore.SignalR; 8 | 9 | namespace API.SignalR 10 | { 11 | [Authorize] 12 | public class PresenceHub : Hub 13 | { 14 | private readonly PresenceTracker _tracker; 15 | public PresenceHub(PresenceTracker tracker) 16 | { 17 | _tracker = tracker; 18 | } 19 | 20 | public override async Task OnConnectedAsync() 21 | { 22 | var isOnline = await _tracker.UserConnected(Context.User.GetUsername(), Context.ConnectionId); 23 | if (isOnline) 24 | await Clients.Others.SendAsync("UserIsOnline", Context.User.GetUsername()); 25 | 26 | var currentUsers = await _tracker.GetOnlineUsers(); 27 | await Clients.Caller.SendAsync("GetOnlineUsers", currentUsers); 28 | } 29 | 30 | public override async Task OnDisconnectedAsync(Exception exception) 31 | { 32 | var isOffline = await _tracker.UserDisconnected(Context.User.GetUsername(), Context.ConnectionId); 33 | 34 | if (isOffline) 35 | await Clients.Others.SendAsync("UserIsOffline", Context.User.GetUsername()); 36 | 37 | await base.OnDisconnectedAsync(exception); 38 | } 39 | } 40 | } -------------------------------------------------------------------------------- /API/SignalR/PresenceTracker.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using System.Threading.Tasks; 4 | using API.Helpers; 5 | using Microsoft.AspNetCore.Mvc; 6 | 7 | namespace API.SignalR 8 | { 9 | public class PresenceTracker 10 | { 11 | private static readonly Dictionary> OnlineUsers = 12 | new Dictionary>(); 13 | 14 | public Task UserConnected(string username, string connectionId) 15 | { 16 | bool isOnline = false; 17 | lock (OnlineUsers) 18 | { 19 | if (OnlineUsers.ContainsKey(username)) 20 | { 21 | OnlineUsers[username].Add(connectionId); 22 | } 23 | else 24 | { 25 | OnlineUsers.Add(username, new List { connectionId }); 26 | isOnline = true; 27 | } 28 | } 29 | 30 | return Task.FromResult(isOnline); 31 | } 32 | 33 | public Task UserDisconnected(string username, string connectionId) 34 | { 35 | bool isOffline = false; 36 | lock (OnlineUsers) 37 | { 38 | if (!OnlineUsers.ContainsKey(username)) return Task.FromResult(isOffline); 39 | 40 | OnlineUsers[username].Remove(connectionId); 41 | if (OnlineUsers[username].Count == 0) 42 | { 43 | OnlineUsers.Remove(username); 44 | isOffline = true; 45 | } 46 | } 47 | 48 | return Task.FromResult(isOffline); 49 | } 50 | 51 | public Task GetOnlineUsers() 52 | { 53 | string[] onlineUsers; 54 | lock (OnlineUsers) 55 | { 56 | onlineUsers = OnlineUsers.OrderBy(k => k.Key).Select(k => k.Key).ToArray(); 57 | } 58 | 59 | return Task.FromResult(onlineUsers); 60 | } 61 | 62 | public Task> GetConnectionsForUser(string username) 63 | { 64 | List connectionIds; 65 | lock (OnlineUsers) 66 | { 67 | connectionIds = OnlineUsers.GetValueOrDefault(username); 68 | } 69 | 70 | return Task.FromResult(connectionIds); 71 | } 72 | } 73 | } -------------------------------------------------------------------------------- /API/WeatherForecast.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace API 4 | { 5 | public class WeatherForecast 6 | { 7 | public DateTime Date { get; set; } 8 | 9 | public int TemperatureC { get; set; } 10 | 11 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); 12 | 13 | public string Summary { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /API/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "ConnectionStrings" : { 3 | "DefaultConnection": "Server=localhost; Port=5432; User Id=appuser; Password=secret; Database=datingapp" 4 | }, 5 | "TokenKey": "super secret unguessable key", 6 | "Logging": { 7 | "LogLevel": { 8 | "Default": "Information", 9 | "Microsoft": "Information", 10 | "Microsoft.Hosting.Lifetime": "Information" 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /API/wwwroot/assets/icons/icon-128x128.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TryCatchLearn/DatingApp-v6/d2fee1117ac86155ff5f43df661d452a0eb427ec/API/wwwroot/assets/icons/icon-128x128.png -------------------------------------------------------------------------------- /API/wwwroot/assets/icons/icon-144x144.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TryCatchLearn/DatingApp-v6/d2fee1117ac86155ff5f43df661d452a0eb427ec/API/wwwroot/assets/icons/icon-144x144.png -------------------------------------------------------------------------------- /API/wwwroot/assets/icons/icon-152x152.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TryCatchLearn/DatingApp-v6/d2fee1117ac86155ff5f43df661d452a0eb427ec/API/wwwroot/assets/icons/icon-152x152.png -------------------------------------------------------------------------------- /API/wwwroot/assets/icons/icon-192x192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TryCatchLearn/DatingApp-v6/d2fee1117ac86155ff5f43df661d452a0eb427ec/API/wwwroot/assets/icons/icon-192x192.png -------------------------------------------------------------------------------- /API/wwwroot/assets/icons/icon-384x384.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TryCatchLearn/DatingApp-v6/d2fee1117ac86155ff5f43df661d452a0eb427ec/API/wwwroot/assets/icons/icon-384x384.png -------------------------------------------------------------------------------- /API/wwwroot/assets/icons/icon-512x512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TryCatchLearn/DatingApp-v6/d2fee1117ac86155ff5f43df661d452a0eb427ec/API/wwwroot/assets/icons/icon-512x512.png -------------------------------------------------------------------------------- /API/wwwroot/assets/icons/icon-72x72.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TryCatchLearn/DatingApp-v6/d2fee1117ac86155ff5f43df661d452a0eb427ec/API/wwwroot/assets/icons/icon-72x72.png -------------------------------------------------------------------------------- /API/wwwroot/assets/icons/icon-96x96.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TryCatchLearn/DatingApp-v6/d2fee1117ac86155ff5f43df661d452a0eb427ec/API/wwwroot/assets/icons/icon-96x96.png -------------------------------------------------------------------------------- /API/wwwroot/assets/user.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TryCatchLearn/DatingApp-v6/d2fee1117ac86155ff5f43df661d452a0eb427ec/API/wwwroot/assets/user.png -------------------------------------------------------------------------------- /API/wwwroot/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TryCatchLearn/DatingApp-v6/d2fee1117ac86155ff5f43df661d452a0eb427ec/API/wwwroot/favicon.ico -------------------------------------------------------------------------------- /API/wwwroot/fontawesome-webfont.1e59d2330b4c6deb84b3.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TryCatchLearn/DatingApp-v6/d2fee1117ac86155ff5f43df661d452a0eb427ec/API/wwwroot/fontawesome-webfont.1e59d2330b4c6deb84b3.ttf -------------------------------------------------------------------------------- /API/wwwroot/fontawesome-webfont.20fd1704ea223900efa9.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TryCatchLearn/DatingApp-v6/d2fee1117ac86155ff5f43df661d452a0eb427ec/API/wwwroot/fontawesome-webfont.20fd1704ea223900efa9.woff2 -------------------------------------------------------------------------------- /API/wwwroot/fontawesome-webfont.8b43027f47b20503057d.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TryCatchLearn/DatingApp-v6/d2fee1117ac86155ff5f43df661d452a0eb427ec/API/wwwroot/fontawesome-webfont.8b43027f47b20503057d.eot -------------------------------------------------------------------------------- /API/wwwroot/fontawesome-webfont.f691f37e57f04c152e23.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TryCatchLearn/DatingApp-v6/d2fee1117ac86155ff5f43df661d452a0eb427ec/API/wwwroot/fontawesome-webfont.f691f37e57f04c152e23.woff -------------------------------------------------------------------------------- /API/wwwroot/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | DatingApp 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /API/wwwroot/manifest.webmanifest: -------------------------------------------------------------------------------- 1 | { 2 | "name": "client", 3 | "short_name": "client", 4 | "theme_color": "#1976d2", 5 | "background_color": "#fafafa", 6 | "display": "standalone", 7 | "scope": "./", 8 | "start_url": "./", 9 | "icons": [ 10 | { 11 | "src": "assets/icons/icon-72x72.png", 12 | "sizes": "72x72", 13 | "type": "image/png", 14 | "purpose": "maskable any" 15 | }, 16 | { 17 | "src": "assets/icons/icon-96x96.png", 18 | "sizes": "96x96", 19 | "type": "image/png", 20 | "purpose": "maskable any" 21 | }, 22 | { 23 | "src": "assets/icons/icon-128x128.png", 24 | "sizes": "128x128", 25 | "type": "image/png", 26 | "purpose": "maskable any" 27 | }, 28 | { 29 | "src": "assets/icons/icon-144x144.png", 30 | "sizes": "144x144", 31 | "type": "image/png", 32 | "purpose": "maskable any" 33 | }, 34 | { 35 | "src": "assets/icons/icon-152x152.png", 36 | "sizes": "152x152", 37 | "type": "image/png", 38 | "purpose": "maskable any" 39 | }, 40 | { 41 | "src": "assets/icons/icon-192x192.png", 42 | "sizes": "192x192", 43 | "type": "image/png", 44 | "purpose": "maskable any" 45 | }, 46 | { 47 | "src": "assets/icons/icon-384x384.png", 48 | "sizes": "384x384", 49 | "type": "image/png", 50 | "purpose": "maskable any" 51 | }, 52 | { 53 | "src": "assets/icons/icon-512x512.png", 54 | "sizes": "512x512", 55 | "type": "image/png", 56 | "purpose": "maskable any" 57 | } 58 | ] 59 | } 60 | -------------------------------------------------------------------------------- /API/wwwroot/runtime.f9956ac3c2762746a398.js: -------------------------------------------------------------------------------- 1 | !function(e){function r(r){for(var n,l,f=r[0],i=r[1],p=r[2],c=0,s=[];c { 5 | let page: AppPage; 6 | 7 | beforeEach(() => { 8 | page = new AppPage(); 9 | }); 10 | 11 | it('should display welcome message', () => { 12 | page.navigateTo(); 13 | expect(page.getTitleText()).toEqual('client app is running!'); 14 | }); 15 | 16 | afterEach(async () => { 17 | // Assert that there are no errors emitted from the browser 18 | const logs = await browser.manage().logs().get(logging.Type.BROWSER); 19 | expect(logs).not.toContain(jasmine.objectContaining({ 20 | level: logging.Level.SEVERE, 21 | } as logging.Entry)); 22 | }); 23 | }); 24 | -------------------------------------------------------------------------------- /client/e2e/src/app.po.ts: -------------------------------------------------------------------------------- 1 | import { browser, by, element } from 'protractor'; 2 | 3 | export class AppPage { 4 | navigateTo(): Promise { 5 | return browser.get(browser.baseUrl) as Promise; 6 | } 7 | 8 | getTitleText(): Promise { 9 | return element(by.css('app-root .content span')).getText() as Promise; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /client/e2e/tsconfig.json: -------------------------------------------------------------------------------- 1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */ 2 | { 3 | "extends": "../tsconfig.json", 4 | "compilerOptions": { 5 | "outDir": "../out-tsc/e2e", 6 | "module": "commonjs", 7 | "target": "es2018", 8 | "types": [ 9 | "jasmine", 10 | "jasminewd2", 11 | "node" 12 | ] 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /client/karma.conf.js: -------------------------------------------------------------------------------- 1 | // Karma configuration file, see link for more information 2 | // https://karma-runner.github.io/1.0/config/configuration-file.html 3 | 4 | module.exports = function (config) { 5 | config.set({ 6 | basePath: '', 7 | frameworks: ['jasmine', '@angular-devkit/build-angular'], 8 | plugins: [ 9 | require('karma-jasmine'), 10 | require('karma-chrome-launcher'), 11 | require('karma-jasmine-html-reporter'), 12 | require('karma-coverage-istanbul-reporter'), 13 | require('@angular-devkit/build-angular/plugins/karma') 14 | ], 15 | client: { 16 | clearContext: false // leave Jasmine Spec Runner output visible in browser 17 | }, 18 | coverageIstanbulReporter: { 19 | dir: require('path').join(__dirname, './coverage/client'), 20 | reports: ['html', 'lcovonly', 'text-summary'], 21 | fixWebpackSourcePaths: true 22 | }, 23 | reporters: ['progress', 'kjhtml'], 24 | port: 9876, 25 | colors: true, 26 | logLevel: config.LOG_INFO, 27 | autoWatch: true, 28 | browsers: ['Chrome'], 29 | singleRun: false, 30 | restartOnFileChange: true 31 | }); 32 | }; 33 | -------------------------------------------------------------------------------- /client/ngsw-config.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/service-worker/config/schema.json", 3 | "index": "/index.html", 4 | "assetGroups": [ 5 | { 6 | "name": "app", 7 | "installMode": "prefetch", 8 | "resources": { 9 | "files": [ 10 | "/favicon.ico", 11 | "/index.html", 12 | "/manifest.webmanifest", 13 | "/*.css", 14 | "/*.js" 15 | ] 16 | } 17 | }, 18 | { 19 | "name": "assets", 20 | "installMode": "lazy", 21 | "updateMode": "prefetch", 22 | "resources": { 23 | "files": [ 24 | "/assets/**", 25 | "/*.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)" 26 | ] 27 | } 28 | } 29 | ] 30 | } 31 | -------------------------------------------------------------------------------- /client/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "client", 3 | "version": "0.0.0", 4 | "scripts": { 5 | "ng": "ng", 6 | "start": "ng serve", 7 | "build": "ng build", 8 | "test": "ng test", 9 | "lint": "ng lint", 10 | "e2e": "ng e2e" 11 | }, 12 | "private": true, 13 | "dependencies": { 14 | "@angular/animations": "~12.2.13", 15 | "@angular/cdk": "^12.2.12", 16 | "@angular/common": "~12.2.13", 17 | "@angular/compiler": "~12.2.13", 18 | "@angular/core": "~12.2.13", 19 | "@angular/forms": "~12.2.13", 20 | "@angular/platform-browser": "~12.2.13", 21 | "@angular/platform-browser-dynamic": "~12.2.13", 22 | "@angular/router": "~12.2.13", 23 | "@kolkov/ngx-gallery": "^1.2.3", 24 | "@microsoft/signalr": "^5.0.11", 25 | "bootstrap": "^5.1.3", 26 | "bootswatch": "^5.1.3", 27 | "font-awesome": "^4.7.0", 28 | "ng2-file-upload": "^1.4.0", 29 | "ngx-bootstrap": "^7.1.0", 30 | "ngx-spinner": "^12.0.0", 31 | "ngx-timeago": "^2.0.0", 32 | "ngx-toastr": "^14.1.4", 33 | "rxjs": "^7.4.0", 34 | "tslib": "^2.3.1", 35 | "zone.js": "~0.11.4" 36 | }, 37 | "devDependencies": { 38 | "@angular-devkit/build-angular": "~12.2.13", 39 | "@angular/cli": "~12.2.13", 40 | "@angular/compiler-cli": "~12.2.13", 41 | "@types/jasmine": "^3.10.2", 42 | "@types/jasminewd2": "^2.0.10", 43 | "@types/node": "^16.11.6", 44 | "codelyzer": "^6.0.2", 45 | "jasmine-core": "^3.10.1", 46 | "jasmine-spec-reporter": "^7.0.0", 47 | "karma": "~6.3.7", 48 | "karma-chrome-launcher": "~3.1.0", 49 | "karma-coverage-istanbul-reporter": "~3.0.2", 50 | "karma-jasmine": "~4.0.0", 51 | "karma-jasmine-html-reporter": "^1.7.0", 52 | "protractor": "~7.0.0", 53 | "ts-node": "^10.4.0", 54 | "tslint": "~6.1.0", 55 | "typescript": "~4.3.5" 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /client/src/app/_directives/has-role.directive.ts: -------------------------------------------------------------------------------- 1 | import { Directive, Input, OnInit, TemplateRef, ViewContainerRef } from '@angular/core'; 2 | import { take } from 'rxjs/operators'; 3 | import { User } from '../_models/user'; 4 | import { AccountService } from '../_services/account.service'; 5 | 6 | @Directive({ 7 | selector: '[appHasRole]' 8 | }) 9 | export class HasRoleDirective implements OnInit { 10 | @Input() appHasRole: string[]; 11 | user: User; 12 | 13 | constructor(private viewContainerRef: ViewContainerRef, 14 | private templateRef: TemplateRef, 15 | private accountService: AccountService) { 16 | this.accountService.currentUser$.pipe(take(1)).subscribe(user => { 17 | this.user = user; 18 | }) 19 | } 20 | 21 | ngOnInit(): void { 22 | // clear view if no roles 23 | if (!this.user?.roles || this.user == null) { 24 | this.viewContainerRef.clear(); 25 | return; 26 | } 27 | 28 | if (this.user?.roles.some(r => this.appHasRole.includes(r))) { 29 | this.viewContainerRef.createEmbeddedView(this.templateRef); 30 | } else { 31 | this.viewContainerRef.clear(); 32 | } 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /client/src/app/_forms/date-input/date-input.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TryCatchLearn/DatingApp-v6/d2fee1117ac86155ff5f43df661d452a0eb427ec/client/src/app/_forms/date-input/date-input.component.css -------------------------------------------------------------------------------- /client/src/app/_forms/date-input/date-input.component.html: -------------------------------------------------------------------------------- 1 |
2 | 12 |
{{label}} is required
13 |
14 | -------------------------------------------------------------------------------- /client/src/app/_forms/date-input/date-input.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, Input, OnInit, Self } from '@angular/core'; 2 | import { ControlValueAccessor, NgControl } from '@angular/forms'; 3 | import { BsDatepickerConfig } from 'ngx-bootstrap/datepicker'; 4 | 5 | @Component({ 6 | selector: 'app-date-input', 7 | templateUrl: './date-input.component.html', 8 | styleUrls: ['./date-input.component.css'] 9 | }) 10 | export class DateInputComponent implements ControlValueAccessor { 11 | @Input() label: string; 12 | @Input() maxDate: Date; 13 | bsConfig: Partial; 14 | 15 | constructor(@Self() public ngControl: NgControl) { 16 | this.ngControl.valueAccessor = this; 17 | this.bsConfig = { 18 | containerClass: 'theme-red', 19 | dateInputFormat: 'DD MMMM YYYY' 20 | } 21 | } 22 | 23 | writeValue(obj: any): void { 24 | } 25 | 26 | registerOnChange(fn: any): void { 27 | } 28 | 29 | registerOnTouched(fn: any): void { 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /client/src/app/_forms/text-input/text-input.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TryCatchLearn/DatingApp-v6/d2fee1117ac86155ff5f43df661d452a0eb427ec/client/src/app/_forms/text-input/text-input.component.css -------------------------------------------------------------------------------- /client/src/app/_forms/text-input/text-input.component.html: -------------------------------------------------------------------------------- 1 |
2 | 8 |
Please enter a {{label}}
9 |
10 | {{label}} must be at least {{ngControl.control.errors.minlength['requiredLength']}} 11 |
12 |
13 | {{label}} must be at most {{ngControl.control.errors.maxlength['requiredLength']}} 14 |
15 |
16 | Passwords do not match 17 |
18 |
-------------------------------------------------------------------------------- /client/src/app/_forms/text-input/text-input.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, Input, OnInit, Self } from '@angular/core'; 2 | import { ControlValueAccessor, NgControl } from '@angular/forms'; 3 | 4 | @Component({ 5 | selector: 'app-text-input', 6 | templateUrl: './text-input.component.html', 7 | styleUrls: ['./text-input.component.css'] 8 | }) 9 | export class TextInputComponent implements ControlValueAccessor { 10 | @Input() label: string; 11 | @Input() type = 'text'; 12 | 13 | constructor(@Self() public ngControl: NgControl) { 14 | this.ngControl.valueAccessor = this; 15 | } 16 | 17 | writeValue(obj: any): void { 18 | } 19 | 20 | registerOnChange(fn: any): void { 21 | } 22 | 23 | registerOnTouched(fn: any): void { 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /client/src/app/_guards/admin.guard.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router'; 3 | import { ToastrService } from 'ngx-toastr'; 4 | import { Observable } from 'rxjs'; 5 | import { map } from 'rxjs/operators'; 6 | import { AccountService } from '../_services/account.service'; 7 | 8 | @Injectable({ 9 | providedIn: 'root' 10 | }) 11 | export class AdminGuard implements CanActivate { 12 | constructor(private accountService: AccountService, private toastr: ToastrService) { } 13 | 14 | canActivate(): Observable { 15 | return this.accountService.currentUser$.pipe( 16 | map(user => { 17 | if (user.roles.includes('Admin') || user.roles.includes('Moderator')) { 18 | return true; 19 | } 20 | this.toastr.error('You cannot enter this area'); 21 | }) 22 | ) 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /client/src/app/_guards/auth.guard.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router'; 3 | import { Observable } from 'rxjs'; 4 | import { AccountService } from '../_services/account.service'; 5 | import { ToastrService } from 'ngx-toastr'; 6 | import { map } from 'rxjs/operators'; 7 | 8 | @Injectable({ 9 | providedIn: 'root' 10 | }) 11 | export class AuthGuard implements CanActivate { 12 | constructor(private accountService: AccountService, private toastr: ToastrService) {} 13 | 14 | canActivate(): Observable { 15 | return this.accountService.currentUser$.pipe( 16 | map(user => { 17 | if (user) return true; 18 | this.toastr.error('You shall not pass!') 19 | }) 20 | ) 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /client/src/app/_guards/prevent-unsaved-changes.guard.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { CanDeactivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router'; 3 | import { Observable } from 'rxjs'; 4 | import { MemberEditComponent } from '../members/member-edit/member-edit.component'; 5 | import { ConfirmService } from '../_services/confirm.service'; 6 | 7 | @Injectable({ 8 | providedIn: 'root' 9 | }) 10 | export class PreventUnsavedChangesGuard implements CanDeactivate { 11 | 12 | constructor(private confirmService: ConfirmService) {} 13 | 14 | canDeactivate(component: MemberEditComponent): Observable | boolean { 15 | if (component.editForm.dirty) { 16 | return this.confirmService.confirm() 17 | } 18 | return true; 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /client/src/app/_interceptors/error.interceptor.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { 3 | HttpRequest, 4 | HttpHandler, 5 | HttpEvent, 6 | HttpInterceptor 7 | } from '@angular/common/http'; 8 | import { Observable, throwError } from 'rxjs'; 9 | import { Router, NavigationExtras } from '@angular/router'; 10 | import { ToastrService } from 'ngx-toastr'; 11 | import { catchError } from 'rxjs/operators'; 12 | 13 | @Injectable() 14 | export class ErrorInterceptor implements HttpInterceptor { 15 | 16 | constructor(private router: Router, private toastr: ToastrService) {} 17 | 18 | intercept(request: HttpRequest, next: HttpHandler): Observable> { 19 | return next.handle(request).pipe( 20 | catchError(error => { 21 | if (error) { 22 | switch (error.status) { 23 | case 400: 24 | if (error.error.errors) { 25 | const modalStateErrors = []; 26 | for (const key in error.error.errors) { 27 | if (error.error.errors[key]) { 28 | modalStateErrors.push(error.error.errors[key]) 29 | } 30 | } 31 | throw modalStateErrors.flat(); 32 | } else if (typeof(error.error) === 'object') { 33 | this.toastr.error(error.statusText, error.status); 34 | } else { 35 | this.toastr.error(error.error, error.status); 36 | } 37 | break; 38 | case 401: 39 | this.toastr.error(error.statusText, error.status); 40 | break; 41 | case 404: 42 | this.router.navigateByUrl('/not-found'); 43 | break; 44 | case 500: 45 | const navigationExtras: NavigationExtras = {state: {error: error.error}} 46 | this.router.navigateByUrl('/server-error', navigationExtras); 47 | break; 48 | default: 49 | this.toastr.error('Something unexpected went wrong'); 50 | console.log(error); 51 | break; 52 | } 53 | } 54 | return throwError(error); 55 | }) 56 | ) 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /client/src/app/_interceptors/jwt.interceptor.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { 3 | HttpRequest, 4 | HttpHandler, 5 | HttpEvent, 6 | HttpInterceptor 7 | } from '@angular/common/http'; 8 | import { Observable } from 'rxjs'; 9 | import { AccountService } from '../_services/account.service'; 10 | import { User } from '../_models/user'; 11 | import { take } from 'rxjs/operators'; 12 | 13 | @Injectable() 14 | export class JwtInterceptor implements HttpInterceptor { 15 | 16 | constructor(private accountService: AccountService) {} 17 | 18 | intercept(request: HttpRequest, next: HttpHandler): Observable> { 19 | let currentUser: User; 20 | 21 | this.accountService.currentUser$.pipe(take(1)).subscribe(user => currentUser = user); 22 | if (currentUser) { 23 | request = request.clone({ 24 | setHeaders: { 25 | Authorization: `Bearer ${currentUser.token}` 26 | } 27 | }) 28 | } 29 | 30 | return next.handle(request); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /client/src/app/_interceptors/loading.interceptor.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { 3 | HttpRequest, 4 | HttpHandler, 5 | HttpEvent, 6 | HttpInterceptor 7 | } from '@angular/common/http'; 8 | import { Observable } from 'rxjs'; 9 | import { BusyService } from '../_services/busy.service'; 10 | import { delay, finalize } from 'rxjs/operators'; 11 | 12 | @Injectable() 13 | export class LoadingInterceptor implements HttpInterceptor { 14 | 15 | constructor(private busyService: BusyService) {} 16 | 17 | intercept(request: HttpRequest, next: HttpHandler): Observable> { 18 | this.busyService.busy(); 19 | return next.handle(request).pipe( 20 | finalize(() => { 21 | this.busyService.idle(); 22 | }) 23 | ) 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /client/src/app/_models/group.ts: -------------------------------------------------------------------------------- 1 | export interface Group { 2 | name: string; 3 | connections: Connection[] 4 | } 5 | 6 | interface Connection { 7 | connectionId: string; 8 | username: string; 9 | } -------------------------------------------------------------------------------- /client/src/app/_models/member.ts: -------------------------------------------------------------------------------- 1 | import { Photo } from './photo'; 2 | 3 | export interface Member { 4 | id: number; 5 | username: string; 6 | photoUrl: string; 7 | age: number; 8 | knownAs: string; 9 | created: Date; 10 | lastActive: Date; 11 | gender: string; 12 | introduction: string; 13 | lookingFor: string; 14 | interests: string; 15 | city: string; 16 | country: string; 17 | photos: Photo[]; 18 | } 19 | 20 | -------------------------------------------------------------------------------- /client/src/app/_models/message.ts: -------------------------------------------------------------------------------- 1 | export interface Message { 2 | id: number; 3 | senderId: number; 4 | senderUsername: string; 5 | senderPhotoUrl: string; 6 | recipientId: number; 7 | recipientUsername: string; 8 | recipientPhotoUrl: string; 9 | content: string; 10 | dateRead?: Date; 11 | messageSent: Date; 12 | } -------------------------------------------------------------------------------- /client/src/app/_models/pagination.ts: -------------------------------------------------------------------------------- 1 | export interface Pagination { 2 | currentPage: number; 3 | itemsPerPage: number; 4 | totalItems: number; 5 | totalPages: number; 6 | } 7 | 8 | export class PaginatedResult { 9 | result: T; 10 | pagination: Pagination; 11 | } -------------------------------------------------------------------------------- /client/src/app/_models/photo.ts: -------------------------------------------------------------------------------- 1 | export interface Photo { 2 | id: number; 3 | url: string; 4 | isMain: boolean; 5 | } 6 | -------------------------------------------------------------------------------- /client/src/app/_models/user.ts: -------------------------------------------------------------------------------- 1 | export interface User { 2 | username: string; 3 | token: string; 4 | photoUrl: string; 5 | knownAs: string; 6 | gender: string; 7 | roles: string[]; 8 | } -------------------------------------------------------------------------------- /client/src/app/_models/userParams.ts: -------------------------------------------------------------------------------- 1 | import { User } from './user'; 2 | 3 | export class UserParams { 4 | gender: string; 5 | minAge = 18; 6 | maxAge = 99; 7 | pageNumber = 1; 8 | pageSize = 24; 9 | orderBy = 'lastActive'; 10 | 11 | constructor(user: User) { 12 | this.gender = user.gender === 'female' ? 'male' : 'female'; 13 | } 14 | } -------------------------------------------------------------------------------- /client/src/app/_modules/shared.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { CommonModule } from '@angular/common'; 3 | import { BsDropdownModule } from 'ngx-bootstrap/dropdown'; 4 | import { ToastrModule } from 'ngx-toastr'; 5 | import { TabsModule } from 'ngx-bootstrap/tabs'; 6 | import {NgxGalleryModule} from '@kolkov/ngx-gallery'; 7 | import {FileUploadModule} from 'ng2-file-upload'; 8 | import {BsDatepickerModule} from 'ngx-bootstrap/datepicker'; 9 | import { PaginationModule } from 'ngx-bootstrap/pagination'; 10 | import { ButtonsModule } from 'ngx-bootstrap/buttons'; 11 | import { TimeagoModule } from 'ngx-timeago'; 12 | import { ModalModule } from 'ngx-bootstrap/modal'; 13 | 14 | @NgModule({ 15 | declarations: [], 16 | imports: [ 17 | CommonModule, 18 | BsDropdownModule.forRoot(), 19 | ToastrModule.forRoot({ 20 | positionClass: 'toast-bottom-right' 21 | }), 22 | TabsModule.forRoot(), 23 | NgxGalleryModule, 24 | FileUploadModule, 25 | BsDatepickerModule.forRoot(), 26 | PaginationModule.forRoot(), 27 | ButtonsModule.forRoot(), 28 | TimeagoModule.forRoot(), 29 | ModalModule.forRoot() 30 | ], 31 | exports: [ 32 | BsDropdownModule, 33 | ToastrModule, 34 | TabsModule, 35 | NgxGalleryModule, 36 | FileUploadModule, 37 | BsDatepickerModule, 38 | PaginationModule, 39 | ButtonsModule, 40 | TimeagoModule, 41 | ModalModule 42 | ] 43 | }) 44 | export class SharedModule { } 45 | -------------------------------------------------------------------------------- /client/src/app/_resolvers/member-detailed.resolver.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { ActivatedRouteSnapshot, Resolve, RouterStateSnapshot } from '@angular/router'; 3 | import { Observable } from 'rxjs'; 4 | import { Member } from '../_models/member'; 5 | import { MembersService } from '../_services/members.service'; 6 | 7 | @Injectable({ 8 | providedIn: 'root' 9 | }) 10 | export class MemberDetailedResolver implements Resolve { 11 | 12 | constructor(private memberService: MembersService) {} 13 | 14 | resolve(route: ActivatedRouteSnapshot): Observable { 15 | return this.memberService.getMember(route.paramMap.get('username')); 16 | } 17 | 18 | } -------------------------------------------------------------------------------- /client/src/app/_services/account.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpClient } from '@angular/common/http'; 3 | import {map} from 'rxjs/operators'; 4 | import { User } from '../_models/user'; 5 | import { ReplaySubject } from 'rxjs'; 6 | import { environment } from 'src/environments/environment'; 7 | import { PresenceService } from './presence.service'; 8 | 9 | @Injectable({ 10 | providedIn: 'root' 11 | }) 12 | export class AccountService { 13 | baseUrl = environment.apiUrl; 14 | private currentUserSource = new ReplaySubject(1); 15 | currentUser$ = this.currentUserSource.asObservable(); 16 | 17 | constructor(private http: HttpClient, private presence: PresenceService) { } 18 | 19 | login(model: any) { 20 | return this.http.post(this.baseUrl + 'account/login', model).pipe( 21 | map((response: User) => { 22 | const user = response; 23 | if (user) { 24 | this.setCurrentUser(user); 25 | this.presence.createHubConnection(user); 26 | } 27 | }) 28 | ) 29 | } 30 | 31 | register(model: any) { 32 | return this.http.post(this.baseUrl + 'account/register', model).pipe( 33 | map((user: User) => { 34 | if (user) { 35 | this.setCurrentUser(user); 36 | this.presence.createHubConnection(user); 37 | } 38 | }) 39 | ) 40 | } 41 | 42 | setCurrentUser(user: User) { 43 | user.roles = []; 44 | const roles = this.getDecodedToken(user.token).role; 45 | Array.isArray(roles) ? user.roles = roles : user.roles.push(roles); 46 | localStorage.setItem('user', JSON.stringify(user)); 47 | this.currentUserSource.next(user); 48 | } 49 | 50 | logout() { 51 | localStorage.removeItem('user'); 52 | this.currentUserSource.next(null); 53 | this.presence.stopHubConnection(); 54 | } 55 | 56 | getDecodedToken(token) { 57 | return JSON.parse(atob(token.split('.')[1])); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /client/src/app/_services/admin.service.ts: -------------------------------------------------------------------------------- 1 | import { HttpClient } from '@angular/common/http'; 2 | import { Injectable } from '@angular/core'; 3 | import { environment } from 'src/environments/environment'; 4 | import { User } from '../_models/user'; 5 | 6 | @Injectable({ 7 | providedIn: 'root' 8 | }) 9 | export class AdminService { 10 | baseUrl = environment.apiUrl; 11 | 12 | constructor(private http: HttpClient) { } 13 | 14 | getUsersWithRoles() { 15 | return this.http.get>(this.baseUrl + 'admin/users-with-roles'); 16 | } 17 | 18 | updateUserRoles(username: string, roles: string[]) { 19 | return this.http.post(this.baseUrl + 'admin/edit-roles/' + username + '?roles=' + roles, {}); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /client/src/app/_services/busy.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { NgxSpinnerService } from 'ngx-spinner'; 3 | 4 | @Injectable({ 5 | providedIn: 'root' 6 | }) 7 | export class BusyService { 8 | busyRequestCount = 0; 9 | 10 | constructor(private spinnerService: NgxSpinnerService) { } 11 | 12 | busy() { 13 | this.busyRequestCount++; 14 | this.spinnerService.show(undefined, { 15 | type: 'line-scale-party', 16 | bdColor: 'rgba(255,255,255,0)', 17 | color: '#333333' 18 | }); 19 | } 20 | 21 | idle() { 22 | this.busyRequestCount--; 23 | if (this.busyRequestCount <= 0) { 24 | this.busyRequestCount = 0; 25 | this.spinnerService.hide(); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /client/src/app/_services/confirm.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { BsModalRef, BsModalService } from 'ngx-bootstrap/modal'; 3 | import { Observable } from 'rxjs'; 4 | import { ConfirmDialogComponent } from '../modals/confirm-dialog/confirm-dialog.component'; 5 | 6 | @Injectable({ 7 | providedIn: 'root' 8 | }) 9 | export class ConfirmService { 10 | bsModelRef: BsModalRef; 11 | 12 | constructor(private modalService: BsModalService) { } 13 | 14 | confirm(title = 'Confirmation', 15 | message = 'Are you sure you want to do this?', 16 | btnOkText = 'Ok', 17 | btnCancelText = 'Cancel'): Observable { 18 | const config = { 19 | initialState: { 20 | title, 21 | message, 22 | btnOkText, 23 | btnCancelText 24 | } 25 | } 26 | this.bsModelRef = this.modalService.show(ConfirmDialogComponent, config); 27 | 28 | return new Observable(this.getResult()); 29 | } 30 | 31 | private getResult() { 32 | return (observer) => { 33 | const subscription = this.bsModelRef.onHidden.subscribe(() => { 34 | observer.next(this.bsModelRef.content.result); 35 | observer.complete(); 36 | }); 37 | 38 | return { 39 | unsubscribe() { 40 | subscription.unsubscribe(); 41 | } 42 | } 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /client/src/app/_services/members.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { environment } from 'src/environments/environment'; 3 | import { HttpClient, HttpParams } from '@angular/common/http'; 4 | import { Member } from '../_models/member'; 5 | import { of, pipe } from 'rxjs'; 6 | import { map, take } from 'rxjs/operators'; 7 | import { PaginatedResult } from '../_models/pagination'; 8 | import { UserParams } from '../_models/userParams'; 9 | import { AccountService } from './account.service'; 10 | import { User } from '../_models/user'; 11 | import { getPaginatedResult, getPaginationHeaders } from './paginationHelper'; 12 | 13 | @Injectable({ 14 | providedIn: 'root' 15 | }) 16 | export class MembersService { 17 | baseUrl = environment.apiUrl; 18 | members: Member[] = []; 19 | memberCache = new Map(); 20 | user: User; 21 | userParams: UserParams; 22 | 23 | constructor(private http: HttpClient, private accountService: AccountService) { 24 | this.accountService.currentUser$.pipe(take(1)).subscribe(user => { 25 | this.user = user; 26 | this.userParams = new UserParams(user); 27 | }) 28 | } 29 | 30 | getUserParams() { 31 | return this.userParams; 32 | } 33 | 34 | setUserParams(params: UserParams) { 35 | this.userParams = params; 36 | } 37 | 38 | resetUserParams() { 39 | this.userParams = new UserParams(this.user); 40 | return this.userParams; 41 | } 42 | 43 | getMembers(userParams: UserParams) { 44 | var response = this.memberCache.get(Object.values(userParams).join('-')); 45 | if (response) { 46 | return of(response); 47 | } 48 | 49 | let params = getPaginationHeaders(userParams.pageNumber, userParams.pageSize); 50 | 51 | params = params.append('minAge', userParams.minAge.toString()); 52 | params = params.append('maxAge', userParams.maxAge.toString()); 53 | params = params.append('gender', userParams.gender); 54 | params = params.append('orderBy', userParams.orderBy); 55 | 56 | return getPaginatedResult(this.baseUrl + 'users', params, this.http) 57 | .pipe(map(response => { 58 | this.memberCache.set(Object.values(userParams).join('-'), response); 59 | return response; 60 | })) 61 | } 62 | 63 | getMember(username: string) { 64 | const member = [...this.memberCache.values()] 65 | .reduce((arr, elem) => arr.concat(elem.result), []) 66 | .find((member: Member) => member.username === username); 67 | 68 | if (member) { 69 | return of(member); 70 | } 71 | return this.http.get(this.baseUrl + 'users/' + username); 72 | } 73 | 74 | updateMember(member: Member) { 75 | return this.http.put(this.baseUrl + 'users', member).pipe( 76 | map(() => { 77 | const index = this.members.indexOf(member); 78 | this.members[index] = member; 79 | }) 80 | ) 81 | } 82 | 83 | setMainPhoto(photoId: number) { 84 | return this.http.put(this.baseUrl + 'users/set-main-photo/' + photoId, {}); 85 | } 86 | 87 | deletePhoto(photoId: number) { 88 | return this.http.delete(this.baseUrl + 'users/delete-photo/' + photoId); 89 | } 90 | 91 | addLike(username: string) { 92 | return this.http.post(this.baseUrl + 'likes/' + username, {}) 93 | } 94 | 95 | getLikes(predicate: string, pageNumber, pageSize) { 96 | let params = getPaginationHeaders(pageNumber, pageSize); 97 | params = params.append('predicate', predicate); 98 | return getPaginatedResult>(this.baseUrl + 'likes', params, this.http); 99 | } 100 | 101 | 102 | } 103 | -------------------------------------------------------------------------------- /client/src/app/_services/message.service.ts: -------------------------------------------------------------------------------- 1 | import { HttpClient } from '@angular/common/http'; 2 | import { Injectable } from '@angular/core'; 3 | import { HubConnection, HubConnectionBuilder } from '@microsoft/signalr'; 4 | import { BehaviorSubject } from 'rxjs'; 5 | import { take } from 'rxjs/operators'; 6 | import { environment } from 'src/environments/environment'; 7 | import { Group } from '../_models/group'; 8 | import { Message } from '../_models/message'; 9 | import { User } from '../_models/user'; 10 | import { BusyService } from './busy.service'; 11 | import { getPaginatedResult, getPaginationHeaders } from './paginationHelper'; 12 | 13 | @Injectable({ 14 | providedIn: 'root' 15 | }) 16 | export class MessageService { 17 | baseUrl = environment.apiUrl; 18 | hubUrl = environment.hubUrl; 19 | private hubConnection: HubConnection; 20 | private messageThreadSource = new BehaviorSubject([]); 21 | messageThread$ = this.messageThreadSource.asObservable(); 22 | 23 | constructor(private http: HttpClient, private busyService: BusyService) { } 24 | 25 | createHubConnection(user: User, otherUsername: string) { 26 | this.busyService.busy(); 27 | this.hubConnection = new HubConnectionBuilder() 28 | .withUrl(this.hubUrl + 'message?user=' + otherUsername, { 29 | accessTokenFactory: () => user.token 30 | }) 31 | .withAutomaticReconnect() 32 | .build() 33 | 34 | this.hubConnection.start() 35 | .catch(error => console.log(error)) 36 | .finally(() => this.busyService.idle()); 37 | 38 | this.hubConnection.on('ReceiveMessageThread', messages => { 39 | this.messageThreadSource.next(messages); 40 | }) 41 | 42 | this.hubConnection.on('NewMessage', message => { 43 | this.messageThread$.pipe(take(1)).subscribe(messages => { 44 | this.messageThreadSource.next([...messages, message]) 45 | }) 46 | }) 47 | 48 | this.hubConnection.on('UpdatedGroup', (group: Group) => { 49 | if (group.connections.some(x => x.username === otherUsername)) { 50 | this.messageThread$.pipe(take(1)).subscribe(messages => { 51 | messages.forEach(message => { 52 | if (!message.dateRead) { 53 | message.dateRead = new Date(Date.now()) 54 | } 55 | }) 56 | this.messageThreadSource.next([...messages]); 57 | }) 58 | } 59 | }) 60 | } 61 | 62 | stopHubConnection() { 63 | if (this.hubConnection) { 64 | this.messageThreadSource.next([]); 65 | this.hubConnection.stop(); 66 | } 67 | } 68 | 69 | getMessages(pageNumber, pageSize, container) { 70 | let params = getPaginationHeaders(pageNumber, pageSize); 71 | params = params.append('Container', container); 72 | return getPaginatedResult(this.baseUrl + 'messages', params, this.http); 73 | } 74 | 75 | getMessageThread(username: string) { 76 | return this.http.get(this.baseUrl + 'messages/thread/' + username); 77 | } 78 | 79 | async sendMessage(username: string, content: string) { 80 | return this.hubConnection.invoke('SendMessage', {recipientUsername: username, content}) 81 | .catch(error => console.log(error)); 82 | } 83 | 84 | deleteMessage(id: number) { 85 | return this.http.delete(this.baseUrl + 'messages/' + id); 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /client/src/app/_services/paginationHelper.ts: -------------------------------------------------------------------------------- 1 | import { HttpClient, HttpParams } from '@angular/common/http'; 2 | import { map } from 'rxjs/operators'; 3 | import { PaginatedResult } from '../_models/pagination'; 4 | 5 | export function getPaginatedResult(url, params, http: HttpClient) { 6 | const paginatedResult: PaginatedResult = new PaginatedResult(); 7 | return http.get(url, { observe: 'response', params }).pipe( 8 | map(response => { 9 | paginatedResult.result = response.body; 10 | if (response.headers.get('Pagination') !== null) { 11 | paginatedResult.pagination = JSON.parse(response.headers.get('Pagination')); 12 | } 13 | return paginatedResult; 14 | }) 15 | ); 16 | } 17 | 18 | export function getPaginationHeaders(pageNumber: number, pageSize: number) { 19 | let params = new HttpParams(); 20 | 21 | params = params.append('pageNumber', pageNumber.toString()); 22 | params = params.append('pageSize', pageSize.toString()); 23 | 24 | return params; 25 | } -------------------------------------------------------------------------------- /client/src/app/_services/presence.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Router } from '@angular/router'; 3 | import { HubConnection, HubConnectionBuilder } from '@microsoft/signalr'; 4 | import { ToastrService } from 'ngx-toastr'; 5 | import { BehaviorSubject } from 'rxjs'; 6 | import { take } from 'rxjs/operators'; 7 | import { environment } from 'src/environments/environment'; 8 | import { User } from '../_models/user'; 9 | 10 | @Injectable({ 11 | providedIn: 'root' 12 | }) 13 | export class PresenceService { 14 | hubUrl = environment.hubUrl; 15 | private hubConnection: HubConnection; 16 | private onlineUsersSource = new BehaviorSubject([]); 17 | onlineUsers$ = this.onlineUsersSource.asObservable(); 18 | 19 | constructor(private toastr: ToastrService, private router: Router) { } 20 | 21 | createHubConnection(user: User) { 22 | this.hubConnection = new HubConnectionBuilder() 23 | .withUrl(this.hubUrl + 'presence', { 24 | accessTokenFactory: () => user.token 25 | }) 26 | .withAutomaticReconnect() 27 | .build() 28 | 29 | this.hubConnection 30 | .start() 31 | .catch(error => console.log(error)); 32 | 33 | this.hubConnection.on('UserIsOnline', username => { 34 | this.onlineUsers$.pipe(take(1)).subscribe(usernames => { 35 | this.onlineUsersSource.next([...usernames, username]) 36 | }) 37 | }) 38 | 39 | this.hubConnection.on('UserIsOffline', username => { 40 | this.onlineUsers$.pipe(take(1)).subscribe(usernames => { 41 | this.onlineUsersSource.next([...usernames.filter(x => x !== username)]) 42 | }) 43 | }) 44 | 45 | this.hubConnection.on('GetOnlineUsers', (usernames: string[]) => { 46 | this.onlineUsersSource.next(usernames); 47 | }) 48 | 49 | this.hubConnection.on('NewMessageReceived', ({username, knownAs}) => { 50 | this.toastr.info(knownAs + ' has sent you a new message!') 51 | .onTap 52 | .pipe(take(1)) 53 | .subscribe(() => this.router.navigateByUrl('/members/' + username + '?tab=3')); 54 | }) 55 | } 56 | 57 | stopHubConnection() { 58 | this.hubConnection.stop().catch(error => console.log(error)); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /client/src/app/admin/admin-panel/admin-panel.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TryCatchLearn/DatingApp-v6/d2fee1117ac86155ff5f43df661d452a0eb427ec/client/src/app/admin/admin-panel/admin-panel.component.css -------------------------------------------------------------------------------- /client/src/app/admin/admin-panel/admin-panel.component.html: -------------------------------------------------------------------------------- 1 |

Admin Panel

2 |
3 | 4 | 5 |
6 | 7 |
8 |
9 | 10 |
11 | 12 |
13 |
14 |
15 |
16 | -------------------------------------------------------------------------------- /client/src/app/admin/admin-panel/admin-panel.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-admin-panel', 5 | templateUrl: './admin-panel.component.html', 6 | styleUrls: ['./admin-panel.component.css'] 7 | }) 8 | export class AdminPanelComponent implements OnInit { 9 | 10 | constructor() { } 11 | 12 | ngOnInit(): void { 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /client/src/app/admin/photo-management/photo-management.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TryCatchLearn/DatingApp-v6/d2fee1117ac86155ff5f43df661d452a0eb427ec/client/src/app/admin/photo-management/photo-management.component.css -------------------------------------------------------------------------------- /client/src/app/admin/photo-management/photo-management.component.html: -------------------------------------------------------------------------------- 1 |

photo-management works!

2 | -------------------------------------------------------------------------------- /client/src/app/admin/photo-management/photo-management.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-photo-management', 5 | templateUrl: './photo-management.component.html', 6 | styleUrls: ['./photo-management.component.css'] 7 | }) 8 | export class PhotoManagementComponent implements OnInit { 9 | 10 | constructor() { } 11 | 12 | ngOnInit(): void { 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /client/src/app/admin/user-management/user-management.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TryCatchLearn/DatingApp-v6/d2fee1117ac86155ff5f43df661d452a0eb427ec/client/src/app/admin/user-management/user-management.component.css -------------------------------------------------------------------------------- /client/src/app/admin/user-management/user-management.component.html: -------------------------------------------------------------------------------- 1 |
2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
UsernameActive roles
{{user.username}}{{user.roles}}
19 |
-------------------------------------------------------------------------------- /client/src/app/admin/user-management/user-management.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { BsModalRef, BsModalService } from 'ngx-bootstrap/modal'; 3 | import { RolesModalComponent } from 'src/app/modals/roles-modal/roles-modal.component'; 4 | import { User } from 'src/app/_models/user'; 5 | import { AdminService } from 'src/app/_services/admin.service'; 6 | 7 | @Component({ 8 | selector: 'app-user-management', 9 | templateUrl: './user-management.component.html', 10 | styleUrls: ['./user-management.component.css'] 11 | }) 12 | export class UserManagementComponent implements OnInit { 13 | users: Partial; 14 | bsModalRef: BsModalRef; 15 | 16 | constructor(private adminService: AdminService, private modalService: BsModalService) { } 17 | 18 | ngOnInit(): void { 19 | this.getUsersWithRoles(); 20 | } 21 | 22 | getUsersWithRoles() { 23 | this.adminService.getUsersWithRoles().subscribe(users => { 24 | this.users = users; 25 | }) 26 | } 27 | 28 | openRolesModal(user: User) { 29 | const config = { 30 | class: 'modal-dialog-centered', 31 | initialState: { 32 | user, 33 | roles: this.getRolesArray(user) 34 | } 35 | } 36 | this.bsModalRef = this.modalService.show(RolesModalComponent, config); 37 | this.bsModalRef.content.updateSelectedRoles.subscribe(values => { 38 | const rolesToUpdate = { 39 | roles: [...values.filter(el => el.checked === true).map(el => el.name)] 40 | }; 41 | if (rolesToUpdate) { 42 | this.adminService.updateUserRoles(user.username, rolesToUpdate.roles).subscribe(() => { 43 | user.roles = [...rolesToUpdate.roles] 44 | }) 45 | } 46 | }) 47 | } 48 | 49 | private getRolesArray(user) { 50 | const roles = []; 51 | const userRoles = user.roles; 52 | const availableRoles: any[] = [ 53 | {name: 'Admin', value: 'Admin'}, 54 | {name: 'Moderator', value: 'Moderator'}, 55 | {name: 'Member', value: 'Member'} 56 | ]; 57 | 58 | availableRoles.forEach(role => { 59 | let isMatch = false; 60 | for (const userRole of userRoles) { 61 | if (role.name === userRole) { 62 | isMatch = true; 63 | role.checked = true; 64 | roles.push(role); 65 | break; 66 | } 67 | } 68 | if (!isMatch) { 69 | role.checked = false; 70 | roles.push(role); 71 | } 72 | }) 73 | return roles; 74 | } 75 | 76 | } 77 | -------------------------------------------------------------------------------- /client/src/app/app-routing.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { Routes, RouterModule } from '@angular/router'; 3 | import { HomeComponent } from './home/home.component'; 4 | import { MemberListComponent } from './members/member-list/member-list.component'; 5 | import { MemberDetailComponent } from './members/member-detail/member-detail.component'; 6 | import { ListsComponent } from './lists/lists.component'; 7 | import { MessagesComponent } from './messages/messages.component'; 8 | import { AuthGuard } from './_guards/auth.guard'; 9 | import { TestErrorsComponent } from './errors/test-errors/test-errors.component'; 10 | import { NotFoundComponent } from './errors/not-found/not-found.component'; 11 | import { ServerErrorComponent } from './errors/server-error/server-error.component'; 12 | import { MemberEditComponent } from './members/member-edit/member-edit.component'; 13 | import { PreventUnsavedChangesGuard } from './_guards/prevent-unsaved-changes.guard'; 14 | import { MemberDetailedResolver } from './_resolvers/member-detailed.resolver'; 15 | import { AdminPanelComponent } from './admin/admin-panel/admin-panel.component'; 16 | import { AdminGuard } from './_guards/admin.guard'; 17 | 18 | const routes: Routes = [ 19 | {path: '', component: HomeComponent}, 20 | { 21 | path: '', 22 | runGuardsAndResolvers: 'always', 23 | canActivate: [AuthGuard], 24 | children: [ 25 | {path: 'members', component: MemberListComponent}, 26 | {path: 'members/:username', component: MemberDetailComponent, resolve: {member: MemberDetailedResolver}}, 27 | {path: 'member/edit', component: MemberEditComponent, canDeactivate: [PreventUnsavedChangesGuard]}, 28 | {path: 'lists', component: ListsComponent}, 29 | {path: 'messages', component: MessagesComponent}, 30 | {path: 'admin', component: AdminPanelComponent, canActivate: [AdminGuard]}, 31 | ] 32 | }, 33 | {path: 'errors', component: TestErrorsComponent}, 34 | {path: 'not-found', component: NotFoundComponent}, 35 | {path: 'server-error', component: ServerErrorComponent}, 36 | {path: '**', component: NotFoundComponent, pathMatch: 'full'}, 37 | ]; 38 | 39 | @NgModule({ 40 | imports: [RouterModule.forRoot(routes)], 41 | exports: [RouterModule] 42 | }) 43 | export class AppRoutingModule { } 44 | -------------------------------------------------------------------------------- /client/src/app/app.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TryCatchLearn/DatingApp-v6/d2fee1117ac86155ff5f43df661d452a0eb427ec/client/src/app/app.component.css -------------------------------------------------------------------------------- /client/src/app/app.component.html: -------------------------------------------------------------------------------- 1 | 2 |

Loading...

3 |
4 | 5 | 6 | 7 |
8 | 9 |
10 | -------------------------------------------------------------------------------- /client/src/app/app.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed } from '@angular/core/testing'; 2 | import { RouterTestingModule } from '@angular/router/testing'; 3 | import { AppComponent } from './app.component'; 4 | 5 | describe('AppComponent', () => { 6 | beforeEach(async () => { 7 | await TestBed.configureTestingModule({ 8 | imports: [ 9 | RouterTestingModule 10 | ], 11 | declarations: [ 12 | AppComponent 13 | ], 14 | }).compileComponents(); 15 | }); 16 | 17 | it('should create the app', () => { 18 | const fixture = TestBed.createComponent(AppComponent); 19 | const app = fixture.componentInstance; 20 | expect(app).toBeTruthy(); 21 | }); 22 | 23 | it(`should have as title 'client'`, () => { 24 | const fixture = TestBed.createComponent(AppComponent); 25 | const app = fixture.componentInstance; 26 | expect(app.title).toEqual('client'); 27 | }); 28 | 29 | it('should render title', () => { 30 | const fixture = TestBed.createComponent(AppComponent); 31 | fixture.detectChanges(); 32 | const compiled = fixture.nativeElement; 33 | expect(compiled.querySelector('.content span').textContent).toContain('client app is running!'); 34 | }); 35 | }); 36 | -------------------------------------------------------------------------------- /client/src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { HttpClient } from '@angular/common/http'; 3 | import { User } from './_models/user'; 4 | import { AccountService } from './_services/account.service'; 5 | import { PresenceService } from './_services/presence.service'; 6 | 7 | @Component({ 8 | selector: 'app-root', 9 | templateUrl: './app.component.html', 10 | styleUrls: ['./app.component.css'] 11 | }) 12 | export class AppComponent implements OnInit { 13 | title = 'The Dating app'; 14 | users: any; 15 | 16 | constructor(private accountService: AccountService, private presence: PresenceService) {} 17 | 18 | ngOnInit() { 19 | this.setCurrentUser(); 20 | } 21 | 22 | setCurrentUser() { 23 | const user: User = JSON.parse(localStorage.getItem('user')); 24 | if (user) { 25 | this.accountService.setCurrentUser(user); 26 | this.presence.createHubConnection(user); 27 | } 28 | 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /client/src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { BrowserModule } from '@angular/platform-browser'; 2 | import { NgModule } from '@angular/core'; 3 | import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; 4 | import { FormsModule, ReactiveFormsModule } from '@angular/forms'; 5 | 6 | import { AppRoutingModule } from './app-routing.module'; 7 | import { AppComponent } from './app.component'; 8 | import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; 9 | import { NavComponent } from './nav/nav.component'; 10 | import { HomeComponent } from './home/home.component'; 11 | import { RegisterComponent } from './register/register.component'; 12 | import { MemberListComponent } from './members/member-list/member-list.component'; 13 | import { MemberDetailComponent } from './members/member-detail/member-detail.component'; 14 | import { ListsComponent } from './lists/lists.component'; 15 | import { MessagesComponent } from './messages/messages.component'; 16 | import { SharedModule } from './_modules/shared.module'; 17 | import { TestErrorsComponent } from './errors/test-errors/test-errors.component'; 18 | import { ErrorInterceptor } from './_interceptors/error.interceptor'; 19 | import { NotFoundComponent } from './errors/not-found/not-found.component'; 20 | import { ServerErrorComponent } from './errors/server-error/server-error.component'; 21 | import { MemberCardComponent } from './members/member-card/member-card.component'; 22 | import { JwtInterceptor } from './_interceptors/jwt.interceptor'; 23 | import { MemberEditComponent } from './members/member-edit/member-edit.component'; 24 | import { NgxSpinnerModule } from 'ngx-spinner'; 25 | import { LoadingInterceptor } from './_interceptors/loading.interceptor'; 26 | import { PhotoEditorComponent } from './members/photo-editor/photo-editor.component'; 27 | import { TextInputComponent } from './_forms/text-input/text-input.component'; 28 | import { DateInputComponent } from './_forms/date-input/date-input.component'; 29 | import { MemberMessagesComponent } from './members/member-messages/member-messages.component'; 30 | import { AdminPanelComponent } from './admin/admin-panel/admin-panel.component'; 31 | import { HasRoleDirective } from './_directives/has-role.directive'; 32 | import { UserManagementComponent } from './admin/user-management/user-management.component'; 33 | import { PhotoManagementComponent } from './admin/photo-management/photo-management.component'; 34 | import { RolesModalComponent } from './modals/roles-modal/roles-modal.component'; 35 | import { ConfirmDialogComponent } from './modals/confirm-dialog/confirm-dialog.component'; 36 | 37 | @NgModule({ 38 | declarations: [ 39 | AppComponent, 40 | NavComponent, 41 | HomeComponent, 42 | RegisterComponent, 43 | MemberListComponent, 44 | MemberDetailComponent, 45 | ListsComponent, 46 | MessagesComponent, 47 | TestErrorsComponent, 48 | NotFoundComponent, 49 | ServerErrorComponent, 50 | MemberCardComponent, 51 | MemberEditComponent, 52 | PhotoEditorComponent, 53 | TextInputComponent, 54 | DateInputComponent, 55 | MemberMessagesComponent, 56 | AdminPanelComponent, 57 | HasRoleDirective, 58 | UserManagementComponent, 59 | PhotoManagementComponent, 60 | RolesModalComponent, 61 | ConfirmDialogComponent 62 | ], 63 | imports: [ 64 | BrowserModule, 65 | AppRoutingModule, 66 | HttpClientModule, 67 | BrowserAnimationsModule, 68 | FormsModule, 69 | ReactiveFormsModule, 70 | SharedModule, 71 | NgxSpinnerModule, 72 | ], 73 | providers: [ 74 | { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }, 75 | { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true }, 76 | { provide: HTTP_INTERCEPTORS, useClass: LoadingInterceptor, multi: true } 77 | ], 78 | bootstrap: [AppComponent] 79 | }) 80 | export class AppModule { } 81 | -------------------------------------------------------------------------------- /client/src/app/errors/not-found/not-found.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TryCatchLearn/DatingApp-v6/d2fee1117ac86155ff5f43df661d452a0eb427ec/client/src/app/errors/not-found/not-found.component.css -------------------------------------------------------------------------------- /client/src/app/errors/not-found/not-found.component.html: -------------------------------------------------------------------------------- 1 |
2 |

Not found

3 | 4 |
5 | -------------------------------------------------------------------------------- /client/src/app/errors/not-found/not-found.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-not-found', 5 | templateUrl: './not-found.component.html', 6 | styleUrls: ['./not-found.component.css'] 7 | }) 8 | export class NotFoundComponent implements OnInit { 9 | 10 | constructor() { } 11 | 12 | ngOnInit(): void { 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /client/src/app/errors/server-error/server-error.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TryCatchLearn/DatingApp-v6/d2fee1117ac86155ff5f43df661d452a0eb427ec/client/src/app/errors/server-error/server-error.component.css -------------------------------------------------------------------------------- /client/src/app/errors/server-error/server-error.component.html: -------------------------------------------------------------------------------- 1 |

Internal server error - refreshing the page will make the error disappear!

2 | 3 |
Error: {{error.message}}
4 |

Note: If you are seeing this then Angular is probably not to blame

5 |

What to do next?

6 |
    7 |
  1. Open the chrome dev tools
  2. 8 |
  3. Inspect the network tab
  4. 9 |
  5. Check the failing request
  6. 10 |
  7. Examine the request URL - make sure it is correct
  8. 11 |
  9. Reproduce the error in Postman - if we see the same response, then the issue is not with Angular
  10. 12 |
13 |

Following is the stack trace - this is where your investigation should start!

14 | {{error.details}} 15 |
16 | -------------------------------------------------------------------------------- /client/src/app/errors/server-error/server-error.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { Router } from '@angular/router'; 3 | 4 | @Component({ 5 | selector: 'app-server-error', 6 | templateUrl: './server-error.component.html', 7 | styleUrls: ['./server-error.component.css'] 8 | }) 9 | export class ServerErrorComponent implements OnInit { 10 | error: any; 11 | 12 | constructor(private router: Router) { 13 | const navigation = this.router.getCurrentNavigation(); 14 | this.error = navigation?.extras?.state?.error; 15 | } 16 | 17 | ngOnInit(): void { 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /client/src/app/errors/test-errors/test-errors.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TryCatchLearn/DatingApp-v6/d2fee1117ac86155ff5f43df661d452a0eb427ec/client/src/app/errors/test-errors/test-errors.component.css -------------------------------------------------------------------------------- /client/src/app/errors/test-errors/test-errors.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 8 | 9 |
10 |
    11 |
  • 12 | {{error}} 13 |
  • 14 |
15 |
16 |
-------------------------------------------------------------------------------- /client/src/app/errors/test-errors/test-errors.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { HttpClient } from '@angular/common/http'; 3 | import { environment } from 'src/environments/environment'; 4 | 5 | @Component({ 6 | selector: 'app-test-errors', 7 | templateUrl: './test-errors.component.html', 8 | styleUrls: ['./test-errors.component.css'] 9 | }) 10 | export class TestErrorsComponent implements OnInit { 11 | baseUrl = environment.apiUrl; 12 | validationErrors: string[] = []; 13 | 14 | constructor(private http: HttpClient) { } 15 | 16 | ngOnInit(): void { 17 | } 18 | 19 | get404Error() { 20 | this.http.get(this.baseUrl + 'buggy/not-found').subscribe(response => { 21 | console.log(response); 22 | }, error => { 23 | console.log(error); 24 | }) 25 | } 26 | 27 | get400Error() { 28 | this.http.get(this.baseUrl + 'buggy/bad-request').subscribe(response => { 29 | console.log(response); 30 | }, error => { 31 | console.log(error); 32 | }) 33 | } 34 | 35 | get500Error() { 36 | this.http.get(this.baseUrl + 'buggy/server-error').subscribe(response => { 37 | console.log(response); 38 | }, error => { 39 | console.log(error); 40 | }) 41 | } 42 | 43 | get401Error() { 44 | this.http.get(this.baseUrl + 'buggy/auth').subscribe(response => { 45 | console.log(response); 46 | }, error => { 47 | console.log(error); 48 | }) 49 | } 50 | 51 | get400ValidationError() { 52 | this.http.post(this.baseUrl + 'account/register', {}).subscribe(response => { 53 | console.log(response); 54 | }, error => { 55 | console.log(error); 56 | this.validationErrors = error; 57 | }) 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /client/src/app/home/home.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TryCatchLearn/DatingApp-v6/d2fee1117ac86155ff5f43df661d452a0eb427ec/client/src/app/home/home.component.css -------------------------------------------------------------------------------- /client/src/app/home/home.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |

Find your match

4 |

Come on in to view your matches... all you need to do is sign up!

5 |
6 | 7 | 8 |
9 |
10 | 11 |
12 |
13 |
14 | 15 |
16 |
17 |
18 |
19 | -------------------------------------------------------------------------------- /client/src/app/home/home.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { HttpClient } from '@angular/common/http'; 3 | 4 | @Component({ 5 | selector: 'app-home', 6 | templateUrl: './home.component.html', 7 | styleUrls: ['./home.component.css'] 8 | }) 9 | export class HomeComponent implements OnInit { 10 | registerMode = false; 11 | 12 | constructor() { } 13 | 14 | ngOnInit(): void { 15 | } 16 | 17 | registerToggle() { 18 | this.registerMode = !this.registerMode; 19 | } 20 | 21 | cancelRegisterMode(event: boolean) { 22 | this.registerMode = event; 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /client/src/app/lists/lists.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TryCatchLearn/DatingApp-v6/d2fee1117ac86155ff5f43df661d452a0eb427ec/client/src/app/lists/lists.component.css -------------------------------------------------------------------------------- /client/src/app/lists/lists.component.html: -------------------------------------------------------------------------------- 1 |
2 |

{{predicate === 'liked' ? 'Members I like' : 'Members who like me'}}

3 |
4 | 5 |
6 |
7 |
8 | 10 | 12 |
13 |
14 | 15 |
16 |
17 | 18 |
19 |
20 |
21 | 22 |
23 | 33 | 34 |
-------------------------------------------------------------------------------- /client/src/app/lists/lists.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { Member } from '../_models/member'; 3 | import { Pagination } from '../_models/pagination'; 4 | import { MembersService } from '../_services/members.service'; 5 | 6 | @Component({ 7 | selector: 'app-lists', 8 | templateUrl: './lists.component.html', 9 | styleUrls: ['./lists.component.css'] 10 | }) 11 | export class ListsComponent implements OnInit { 12 | members: Partial; 13 | predicate = 'liked'; 14 | pageNumber = 1; 15 | pageSize = 5; 16 | pagination: Pagination; 17 | 18 | constructor(private memberService: MembersService) { } 19 | 20 | ngOnInit(): void { 21 | this.loadLikes(); 22 | } 23 | 24 | loadLikes() { 25 | this.memberService.getLikes(this.predicate, this.pageNumber, this.pageSize).subscribe(response => { 26 | this.members = response.result; 27 | this.pagination = response.pagination; 28 | }) 29 | } 30 | 31 | pageChanged(event: any) { 32 | this.pageNumber = event.page; 33 | this.loadLikes(); 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /client/src/app/members/member-card/member-card.component.css: -------------------------------------------------------------------------------- 1 | .card:hover img { 2 | transform: scale(1.2, 1.2); 3 | transition-duration: 500ms; 4 | transition-timing-function: ease-out; 5 | opacity: 0.7; 6 | } 7 | 8 | .card img { 9 | transform: scale(1.0, 1.0); 10 | transition-duration: 500ms; 11 | transition-timing-function: ease-out; 12 | } 13 | 14 | .card-img-wrapper { 15 | overflow: hidden; 16 | position: relative; 17 | } 18 | 19 | .member-icons { 20 | position: absolute; 21 | bottom: -30%; 22 | left: 0; 23 | right: 0; 24 | margin-right: auto; 25 | margin-left: auto; 26 | opacity: 0; 27 | } 28 | 29 | .card-img-wrapper:hover .member-icons { 30 | bottom: 0; 31 | opacity: 1; 32 | } 33 | 34 | .animate { 35 | transition: all 0.3s ease-in-out; 36 | } 37 | 38 | @keyframes fa-blink { 39 | 0% {opacity: 1;} 40 | 100% {opacity: 0.4;} 41 | } 42 | 43 | .is-online { 44 | animation: fa-blink 1.5s linear infinite; 45 | color: rgb(1, 189, 42); 46 | } -------------------------------------------------------------------------------- /client/src/app/members/member-card/member-card.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 | {{member.knownAs}} 4 |
    5 |
  • 7 |
  • 9 |
  • 10 |
  • 16 |
17 |
18 |
19 |
20 | 21 | 22 | 23 | 24 | {{member.knownAs}}, {{member.age}} 25 |
26 |

{{member.city}}

27 |
28 |
29 | -------------------------------------------------------------------------------- /client/src/app/members/member-card/member-card.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit, Input } from '@angular/core'; 2 | import { ToastrService } from 'ngx-toastr'; 3 | import { Member } from 'src/app/_models/member'; 4 | import { MembersService } from 'src/app/_services/members.service'; 5 | import { PresenceService } from 'src/app/_services/presence.service'; 6 | 7 | @Component({ 8 | selector: 'app-member-card', 9 | templateUrl: './member-card.component.html', 10 | styleUrls: ['./member-card.component.css'], 11 | }) 12 | export class MemberCardComponent implements OnInit { 13 | @Input() member: Member; 14 | 15 | constructor(private memberService: MembersService, private toastr: ToastrService, 16 | public presence: PresenceService) { } 17 | 18 | ngOnInit(): void { 19 | } 20 | 21 | addLike(member: Member) { 22 | this.memberService.addLike(member.username).subscribe(() => { 23 | this.toastr.success('You have liked ' + member.knownAs); 24 | }) 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /client/src/app/members/member-detail/member-detail.component.css: -------------------------------------------------------------------------------- 1 | .img-thumbnail { 2 | margin: 25px; 3 | width: 85%; 4 | height: 85%; 5 | } 6 | 7 | .card-body { 8 | padding: 0 25px; 9 | } 10 | 11 | .card-footer { 12 | padding: 10px 15px; 13 | background-color: #fff; 14 | border-top: none; 15 | } -------------------------------------------------------------------------------- /client/src/app/members/member-detail/member-detail.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 | {{member.knownAs}} 6 |
7 |
8 | Online now 9 |
10 |
11 | Location: 12 |

{{member.city}}, {{member.country}}

13 |
14 |
15 | Age: 16 |

{{member.age}}

17 |
18 |
19 | Last Active: 20 |

{{member.lastActive | timeago}}

21 |
22 |
23 | Member since: 24 |

{{member.created | date: 'dd MMM yyyy'}}

25 |
26 |
27 | 33 |
34 |
35 | 36 |
37 | 38 | 39 |

Description

40 |

{{member.introduction}}

41 |

Looking for

42 |

{{member.lookingFor}}

43 |
44 | 45 |

Interests

46 |

{{member.interests}}

47 |
48 | 49 | 51 | 52 | 53 | 54 | 55 |
56 |
57 |
58 | -------------------------------------------------------------------------------- /client/src/app/members/member-detail/member-detail.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core'; 2 | import { Member } from 'src/app/_models/member'; 3 | import { MembersService } from 'src/app/_services/members.service'; 4 | import { ActivatedRoute, Router } from '@angular/router'; 5 | import { NgxGalleryOptions, NgxGalleryImage, NgxGalleryAnimation } from '@kolkov/ngx-gallery'; 6 | import { TabDirective, TabsetComponent } from 'ngx-bootstrap/tabs'; 7 | import { Message } from 'src/app/_models/message'; 8 | import { MessageService } from 'src/app/_services/message.service'; 9 | import { PresenceService } from 'src/app/_services/presence.service'; 10 | import { AccountService } from 'src/app/_services/account.service'; 11 | import { User } from 'src/app/_models/user'; 12 | import { take } from 'rxjs/operators'; 13 | 14 | @Component({ 15 | selector: 'app-member-detail', 16 | templateUrl: './member-detail.component.html', 17 | styleUrls: ['./member-detail.component.css'] 18 | }) 19 | export class MemberDetailComponent implements OnInit, OnDestroy { 20 | @ViewChild('memberTabs', {static: true}) memberTabs: TabsetComponent; 21 | member: Member; 22 | galleryOptions: NgxGalleryOptions[]; 23 | galleryImages: NgxGalleryImage[]; 24 | activeTab: TabDirective; 25 | messages: Message[] = []; 26 | user: User; 27 | 28 | constructor(public presence: PresenceService, private route: ActivatedRoute, 29 | private messageService: MessageService, private accountService: AccountService, 30 | private router: Router) { 31 | this.accountService.currentUser$.pipe(take(1)).subscribe(user => this.user = user); 32 | this.router.routeReuseStrategy.shouldReuseRoute = () => false; 33 | } 34 | 35 | ngOnInit(): void { 36 | this.route.data.subscribe(data => { 37 | this.member = data.member; 38 | }) 39 | 40 | this.route.queryParams.subscribe(params => { 41 | params.tab ? this.selectTab(params.tab) : this.selectTab(0); 42 | }) 43 | 44 | this.galleryOptions = [ 45 | { 46 | width: '500px', 47 | height: '500px', 48 | imagePercent: 100, 49 | thumbnailsColumns: 4, 50 | imageAnimation: NgxGalleryAnimation.Slide, 51 | preview: false 52 | } 53 | ] 54 | 55 | this.galleryImages = this.getImages(); 56 | } 57 | 58 | getImages(): NgxGalleryImage[] { 59 | const imageUrls = []; 60 | for (const photo of this.member.photos) { 61 | imageUrls.push({ 62 | small: photo?.url, 63 | medium: photo?.url, 64 | big: photo?.url 65 | }) 66 | } 67 | return imageUrls; 68 | } 69 | 70 | loadMessages() { 71 | this.messageService.getMessageThread(this.member.username).subscribe(messages => { 72 | this.messages = messages; 73 | }) 74 | } 75 | 76 | selectTab(tabId: number) { 77 | this.memberTabs.tabs[tabId].active = true; 78 | } 79 | 80 | onTabActivated(data: TabDirective) { 81 | this.activeTab = data; 82 | if (this.activeTab.heading === 'Messages' && this.messages.length === 0) { 83 | this.messageService.createHubConnection(this.user, this.member.username); 84 | } else { 85 | this.messageService.stopHubConnection(); 86 | } 87 | } 88 | 89 | ngOnDestroy(): void { 90 | this.messageService.stopHubConnection(); 91 | } 92 | 93 | } 94 | -------------------------------------------------------------------------------- /client/src/app/members/member-edit/member-edit.component.css: -------------------------------------------------------------------------------- 1 | .img-thumbnail { 2 | margin: 25px; 3 | width: 85%; 4 | height: 85%; 5 | } 6 | 7 | .card-body { 8 | padding: 0 25px; 9 | } 10 | 11 | .card-footer { 12 | padding: 10px 15px; 13 | background-color: #fff; 14 | border-top: none; 15 | } -------------------------------------------------------------------------------- /client/src/app/members/member-edit/member-edit.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |

Your profile

4 |
5 |
6 |
7 | Information: You have made changes. Any unsaved changes will be lost 8 |
9 |
10 |
11 |
12 | {{member.knownAs}} 14 |
15 |
16 | Location: 17 |

{{member.city}}, {{member.country}}

18 |
19 |
20 | Age: 21 |

{{member.age}}

22 |
23 |
24 | Last Active: 25 |

{{member.lastActive | timeago}}

26 |
27 |
28 | Member since: 29 |

{{member.created | date: 'dd MMM yyyy'}}

30 |
31 |
32 | 35 |
36 |
37 | 38 |
39 | 40 | 41 |
42 |

Description

43 | 44 |

Looking for

45 | 46 |

Interests

47 | 48 |

Location Details:

49 |
50 | 51 | 52 | 53 | 54 |
55 |
56 | 57 |
58 | 59 | 60 | 61 |
62 |
63 |
64 | 65 | -------------------------------------------------------------------------------- /client/src/app/members/member-edit/member-edit.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit, ViewChild, HostListener } from '@angular/core'; 2 | import { Member } from 'src/app/_models/member'; 3 | import { User } from 'src/app/_models/user'; 4 | import { AccountService } from 'src/app/_services/account.service'; 5 | import { MembersService } from 'src/app/_services/members.service'; 6 | import { take } from 'rxjs/operators'; 7 | import { ToastrService } from 'ngx-toastr'; 8 | import { NgForm } from '@angular/forms'; 9 | 10 | @Component({ 11 | selector: 'app-member-edit', 12 | templateUrl: './member-edit.component.html', 13 | styleUrls: ['./member-edit.component.css'] 14 | }) 15 | export class MemberEditComponent implements OnInit { 16 | @ViewChild('editForm') editForm: NgForm; 17 | member: Member; 18 | user: User; 19 | @HostListener('window:beforeunload', ['$event']) unloadNotification($event: any) { 20 | if (this.editForm.dirty) { 21 | $event.returnValue = true; 22 | } 23 | } 24 | 25 | constructor(private accountService: AccountService, private memberService: MembersService, 26 | private toastr: ToastrService) { 27 | this.accountService.currentUser$.pipe(take(1)).subscribe(user => this.user = user); 28 | } 29 | 30 | ngOnInit(): void { 31 | this.loadMember(); 32 | } 33 | 34 | loadMember() { 35 | this.memberService.getMember(this.user.username).subscribe(member => { 36 | this.member = member; 37 | }) 38 | } 39 | 40 | updateMember() { 41 | this.memberService.updateMember(this.member).subscribe(() => { 42 | this.toastr.success('Profile updated successfully'); 43 | this.editForm.reset(this.member); 44 | }) 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /client/src/app/members/member-list/member-list.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TryCatchLearn/DatingApp-v6/d2fee1117ac86155ff5f43df661d452a0eb427ec/client/src/app/members/member-list/member-list.component.css -------------------------------------------------------------------------------- /client/src/app/members/member-list/member-list.component.html: -------------------------------------------------------------------------------- 1 |
2 |

Your matches - {{pagination?.totalItems}} found

3 |
4 | 5 |
6 |
7 |
8 | 9 | 11 |
12 | 13 |
14 | 15 | 17 |
18 | 19 |
20 | 21 | 26 |
27 | 28 | 29 | 30 |
31 |
32 | 39 | 40 | 47 |
48 |
49 | 50 | 51 |
52 |
53 | 54 |
55 |
56 | 57 |
58 |
59 | 60 |
61 | 72 | 73 |
-------------------------------------------------------------------------------- /client/src/app/members/member-list/member-list.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { Member } from 'src/app/_models/member'; 3 | import { MembersService } from 'src/app/_services/members.service'; 4 | import { Observable } from 'rxjs'; 5 | import { Pagination } from 'src/app/_models/pagination'; 6 | import { UserParams } from 'src/app/_models/userParams'; 7 | import { AccountService } from 'src/app/_services/account.service'; 8 | import { take } from 'rxjs/operators'; 9 | import { User } from 'src/app/_models/user'; 10 | 11 | @Component({ 12 | selector: 'app-member-list', 13 | templateUrl: './member-list.component.html', 14 | styleUrls: ['./member-list.component.css'] 15 | }) 16 | export class MemberListComponent implements OnInit { 17 | members: Member[]; 18 | pagination: Pagination; 19 | userParams: UserParams; 20 | user: User; 21 | genderList = [{ value: 'male', display: 'Males' }, { value: 'female', display: 'Females' }]; 22 | 23 | constructor(private memberService: MembersService) { 24 | this.userParams = this.memberService.getUserParams(); 25 | } 26 | 27 | ngOnInit(): void { 28 | this.loadMembers(); 29 | } 30 | 31 | loadMembers() { 32 | this.memberService.setUserParams(this.userParams); 33 | this.memberService.getMembers(this.userParams).subscribe(response => { 34 | this.members = response.result; 35 | this.pagination = response.pagination; 36 | }) 37 | } 38 | 39 | resetFilters() { 40 | this.userParams = this.memberService.resetUserParams(); 41 | this.loadMembers(); 42 | } 43 | 44 | pageChanged(event: any) { 45 | this.userParams.pageNumber = event.page; 46 | this.memberService.setUserParams(this.userParams); 47 | this.loadMembers(); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /client/src/app/members/member-messages/member-messages.component.css: -------------------------------------------------------------------------------- 1 | .card { 2 | border: none; 3 | } 4 | 5 | .chat { 6 | list-style: none; 7 | margin: 0; 8 | padding: 0; 9 | } 10 | 11 | .chat li { 12 | margin-bottom: 10px; 13 | padding-bottom: 10px; 14 | border-bottom: 1px dotted #B3A9A9; 15 | } 16 | 17 | .rounded-circle { 18 | max-height: 50px; 19 | } -------------------------------------------------------------------------------- /client/src/app/members/member-messages/member-messages.component.html: -------------------------------------------------------------------------------- 1 |
2 |
7 |
8 | No messages yet... say hi by using the message box below 9 |
10 | 11 |
    14 |
  • 15 |
    16 | 17 | {{message.senderUsername}} 19 | 20 |
    21 |
    22 | 23 | {{message.messageSent | timeago}} 24 | 26 | (unread) 27 | 28 | 30 | (read {{message.dateRead | timeago}}) 31 | 32 | 33 |
    34 |

    {{message.content}}

    35 |
    36 |
    37 |
  • 38 |
39 |
40 | 41 | 59 |
60 | -------------------------------------------------------------------------------- /client/src/app/members/member-messages/member-messages.component.ts: -------------------------------------------------------------------------------- 1 | import { ChangeDetectionStrategy, Component, Input, OnInit, ViewChild } from '@angular/core'; 2 | import { NgForm } from '@angular/forms'; 3 | import { Message } from 'src/app/_models/message'; 4 | import { MembersService } from 'src/app/_services/members.service'; 5 | import { MessageService } from 'src/app/_services/message.service'; 6 | 7 | @Component({ 8 | changeDetection: ChangeDetectionStrategy.OnPush, 9 | selector: 'app-member-messages', 10 | templateUrl: './member-messages.component.html', 11 | styleUrls: ['./member-messages.component.css'] 12 | }) 13 | export class MemberMessagesComponent implements OnInit { 14 | @ViewChild('messageForm') messageForm: NgForm; 15 | @Input() messages: Message[]; 16 | @Input() username: string; 17 | messageContent: string; 18 | loading = false; 19 | 20 | constructor(public messageService: MessageService) { } 21 | 22 | ngOnInit(): void { 23 | } 24 | 25 | sendMessage() { 26 | this.loading = true; 27 | this.messageService.sendMessage(this.username, this.messageContent).then(() => { 28 | this.messageForm.reset(); 29 | }).finally(() => this.loading = false); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /client/src/app/members/photo-editor/photo-editor.component.css: -------------------------------------------------------------------------------- 1 | img.img-thumbnail { 2 | height: 100px; 3 | min-width: 100px !important; 4 | margin-bottom: 2px; 5 | } 6 | 7 | .nv-file-over { 8 | border: dotted 3px red; 9 | } 10 | 11 | input[type=file] { 12 | color: transparent; 13 | } -------------------------------------------------------------------------------- /client/src/app/members/photo-editor/photo-editor.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 | {{photo.url}} 4 |
5 | 11 | 16 |
17 |
18 |
19 | 20 |
21 | 22 |
23 | 24 |

Add Photos

25 | 26 |
31 | 32 | Drop photos here 33 |
34 | 35 | Multiple 36 |
37 | 38 | Single 39 | 40 |
41 | 42 |
43 | 44 |

Upload queue

45 |

Queue length: {{ uploader?.queue?.length }}

46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 |
NameSize
{{ item?.file?.name }}{{ item?.file?.size/1024/1024 | number:'.2' }} MB
61 | 62 |
63 |
64 | Queue progress: 65 |
66 |
67 |
68 |
69 | 73 | 77 | 81 |
82 | 83 |
84 | 85 |
86 | -------------------------------------------------------------------------------- /client/src/app/members/photo-editor/photo-editor.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit, Input } from '@angular/core'; 2 | import { Member } from 'src/app/_models/member'; 3 | import { FileUploader } from 'ng2-file-upload'; 4 | import { environment } from 'src/environments/environment'; 5 | import { AccountService } from 'src/app/_services/account.service'; 6 | import { User } from 'src/app/_models/user'; 7 | import { take } from 'rxjs/operators'; 8 | import { MembersService } from 'src/app/_services/members.service'; 9 | import { Photo } from 'src/app/_models/photo'; 10 | 11 | @Component({ 12 | selector: 'app-photo-editor', 13 | templateUrl: './photo-editor.component.html', 14 | styleUrls: ['./photo-editor.component.css'] 15 | }) 16 | export class PhotoEditorComponent implements OnInit { 17 | @Input() member: Member; 18 | uploader: FileUploader; 19 | hasBaseDropzoneOver = false; 20 | baseUrl = environment.apiUrl; 21 | user: User; 22 | 23 | constructor(private accountService: AccountService, private memberService: MembersService) { 24 | this.accountService.currentUser$.pipe(take(1)).subscribe(user => this.user = user); 25 | } 26 | 27 | ngOnInit(): void { 28 | this.initializeUploader(); 29 | } 30 | 31 | fileOverBase(e: any) { 32 | this.hasBaseDropzoneOver = e; 33 | } 34 | 35 | setMainPhoto(photo: Photo) { 36 | this.memberService.setMainPhoto(photo.id).subscribe(() => { 37 | this.user.photoUrl = photo.url; 38 | this.accountService.setCurrentUser(this.user); 39 | this.member.photoUrl = photo.url; 40 | this.member.photos.forEach(p => { 41 | if (p.isMain) p.isMain = false; 42 | if (p.id === photo.id) p.isMain = true; 43 | }) 44 | }) 45 | } 46 | 47 | deletePhoto(photoId: number) { 48 | this.memberService.deletePhoto(photoId).subscribe(() => { 49 | this.member.photos = this.member.photos.filter(x => x.id !== photoId); 50 | }) 51 | } 52 | 53 | initializeUploader() { 54 | this.uploader = new FileUploader({ 55 | url: this.baseUrl + 'users/add-photo', 56 | authToken: 'Bearer ' + this.user.token, 57 | isHTML5: true, 58 | allowedFileType: ['image'], 59 | removeAfterUpload: true, 60 | autoUpload: false, 61 | maxFileSize: 10 * 1024 * 1024 62 | }); 63 | 64 | this.uploader.onAfterAddingFile = (file) => { 65 | file.withCredentials = false; 66 | } 67 | 68 | this.uploader.onSuccessItem = (item, response, status, headers) => { 69 | if (response) { 70 | const photo: Photo = JSON.parse(response); 71 | this.member.photos.push(photo); 72 | if (photo.isMain) { 73 | this.user.photoUrl = photo.url; 74 | this.member.photoUrl = photo.url; 75 | this.accountService.setCurrentUser(this.user); 76 | } 77 | } 78 | } 79 | } 80 | 81 | } 82 | -------------------------------------------------------------------------------- /client/src/app/messages/messages.component.css: -------------------------------------------------------------------------------- 1 | .img-circle { 2 | max-height: 50px; 3 | } -------------------------------------------------------------------------------- /client/src/app/messages/messages.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 | 7 | 11 | 15 |
16 |
17 | 18 |
19 |

No messages

20 |
21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 37 | 38 | 54 | 55 | 58 | 59 | 60 | 61 |
MessageFrom / ToSent / Received
{{message.content}} 39 |
40 | {{message.recipientUsername}} 44 | {{message.recipientUsername | titlecase}} 45 |
46 |
47 | {{message.senderUsername}} 51 | {{message.senderUsername | titlecase}} 52 |
53 |
{{message.messageSent | timeago}} 56 | 57 |
62 |
63 | 64 |
65 | 76 | 77 |
-------------------------------------------------------------------------------- /client/src/app/messages/messages.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { Message } from '../_models/message'; 3 | import { Pagination } from '../_models/pagination'; 4 | import { ConfirmService } from '../_services/confirm.service'; 5 | import { MessageService } from '../_services/message.service'; 6 | 7 | @Component({ 8 | selector: 'app-messages', 9 | templateUrl: './messages.component.html', 10 | styleUrls: ['./messages.component.css'] 11 | }) 12 | export class MessagesComponent implements OnInit { 13 | messages: Message[] = []; 14 | pagination: Pagination; 15 | container = 'Unread'; 16 | pageNumber = 1; 17 | pageSize = 5; 18 | loading = false; 19 | 20 | constructor(private messageService: MessageService, private confirmService: ConfirmService) { } 21 | 22 | ngOnInit(): void { 23 | this.loadMessages(); 24 | } 25 | 26 | loadMessages() { 27 | this.loading = true; 28 | this.messageService.getMessages(this.pageNumber, this.pageSize, this.container).subscribe(response => { 29 | this.messages = response.result; 30 | this.pagination = response.pagination; 31 | this.loading = false; 32 | }) 33 | } 34 | 35 | deleteMessage(id: number) { 36 | this.confirmService.confirm('Confirm delete message', 'This cannot be undone').subscribe(result => { 37 | if (result) { 38 | this.messageService.deleteMessage(id).subscribe(() => { 39 | this.messages.splice(this.messages.findIndex(m => m.id === id), 1); 40 | }) 41 | } 42 | }) 43 | 44 | } 45 | 46 | pageChanged(event: any) { 47 | if (this.pageNumber !== event.page) { 48 | this.pageNumber = event.page; 49 | this.loadMessages(); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /client/src/app/modals/confirm-dialog/confirm-dialog.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TryCatchLearn/DatingApp-v6/d2fee1117ac86155ff5f43df661d452a0eb427ec/client/src/app/modals/confirm-dialog/confirm-dialog.component.css -------------------------------------------------------------------------------- /client/src/app/modals/confirm-dialog/confirm-dialog.component.html: -------------------------------------------------------------------------------- 1 | 4 | 7 | 11 | -------------------------------------------------------------------------------- /client/src/app/modals/confirm-dialog/confirm-dialog.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { BsModalRef } from 'ngx-bootstrap/modal'; 3 | 4 | @Component({ 5 | selector: 'app-confirm-dialog', 6 | templateUrl: './confirm-dialog.component.html', 7 | styleUrls: ['./confirm-dialog.component.css'] 8 | }) 9 | export class ConfirmDialogComponent implements OnInit { 10 | title: string; 11 | message: string; 12 | btnOkText: string; 13 | btnCancelText: string; 14 | result: boolean; 15 | 16 | constructor(public bsModalRef: BsModalRef) { } 17 | 18 | ngOnInit(): void { 19 | } 20 | 21 | confirm() { 22 | this.result = true; 23 | this.bsModalRef.hide(); 24 | } 25 | 26 | decline() { 27 | this.result = false; 28 | this.bsModalRef.hide(); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /client/src/app/modals/roles-modal/roles-modal.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TryCatchLearn/DatingApp-v6/d2fee1117ac86155ff5f43df661d452a0eb427ec/client/src/app/modals/roles-modal/roles-modal.component.css -------------------------------------------------------------------------------- /client/src/app/modals/roles-modal/roles-modal.component.html: -------------------------------------------------------------------------------- 1 | 7 | 21 | 25 | 26 | -------------------------------------------------------------------------------- /client/src/app/modals/roles-modal/roles-modal.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, EventEmitter, Input, OnInit } from '@angular/core'; 2 | import { BsModalRef } from 'ngx-bootstrap/modal'; 3 | import { User } from 'src/app/_models/user'; 4 | 5 | @Component({ 6 | selector: 'app-roles-modal', 7 | templateUrl: './roles-modal.component.html', 8 | styleUrls: ['./roles-modal.component.css'] 9 | }) 10 | export class RolesModalComponent implements OnInit { 11 | @Input() updateSelectedRoles = new EventEmitter(); 12 | user: User; 13 | roles: any[]; 14 | 15 | constructor(public bsModalRef: BsModalRef) { } 16 | 17 | ngOnInit(): void { 18 | } 19 | 20 | updateRoles() { 21 | this.updateSelectedRoles.emit(this.roles); 22 | this.bsModalRef.hide(); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /client/src/app/nav/nav.component.css: -------------------------------------------------------------------------------- 1 | .dropdown-toggle, .dropdown-item { 2 | cursor: pointer; 3 | } 4 | 5 | img { 6 | max-height: 50px; 7 | border: 2px solid #fff; 8 | display: inline; 9 | } -------------------------------------------------------------------------------- /client/src/app/nav/nav.component.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /client/src/app/nav/nav.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { AccountService } from '../_services/account.service'; 3 | import { Observable } from 'rxjs'; 4 | import { User } from '../_models/user'; 5 | import { Router } from '@angular/router'; 6 | import { ToastrService } from 'ngx-toastr'; 7 | 8 | @Component({ 9 | selector: 'app-nav', 10 | templateUrl: './nav.component.html', 11 | styleUrls: ['./nav.component.css'] 12 | }) 13 | export class NavComponent implements OnInit { 14 | model: any = {} 15 | 16 | constructor(public accountService: AccountService, private router: Router, 17 | private toastr: ToastrService) { } 18 | 19 | ngOnInit(): void { 20 | } 21 | 22 | login() { 23 | this.accountService.login(this.model).subscribe(response => { 24 | this.router.navigateByUrl('/members'); 25 | }) 26 | } 27 | 28 | logout() { 29 | this.accountService.logout(); 30 | this.router.navigateByUrl('/') 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /client/src/app/register/register.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TryCatchLearn/DatingApp-v6/d2fee1117ac86155ff5f43df661d452a0eb427ec/client/src/app/register/register.component.css -------------------------------------------------------------------------------- /client/src/app/register/register.component.html: -------------------------------------------------------------------------------- 1 |
2 |

Sign up

3 |
4 | 5 |
6 | 7 | 10 | 13 |
14 | 15 | 17 | 19 | 21 | 23 | 25 | 27 | 28 | 31 | 32 |
33 |
    34 |
  • 35 | {{error}} 36 |
  • 37 |
38 |
39 | 40 |
41 | 42 | 43 |
44 |
-------------------------------------------------------------------------------- /client/src/app/register/register.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; 2 | import { AccountService } from '../_services/account.service'; 3 | import { ToastrService } from 'ngx-toastr'; 4 | import { AbstractControl, FormBuilder, FormControl, FormGroup, ValidatorFn, Validators } from '@angular/forms'; 5 | import { Router } from '@angular/router'; 6 | 7 | @Component({ 8 | selector: 'app-register', 9 | templateUrl: './register.component.html', 10 | styleUrls: ['./register.component.css'] 11 | }) 12 | export class RegisterComponent implements OnInit { 13 | @Output() cancelRegister = new EventEmitter(); 14 | registerForm: FormGroup; 15 | maxDate: Date; 16 | validationErrors: string[] = []; 17 | 18 | constructor(private accountService: AccountService, private toastr: ToastrService, 19 | private fb: FormBuilder, private router: Router) { } 20 | 21 | ngOnInit(): void { 22 | this.intitializeForm(); 23 | this.maxDate = new Date(); 24 | this.maxDate.setFullYear(this.maxDate.getFullYear() -18); 25 | } 26 | 27 | intitializeForm() { 28 | this.registerForm = this.fb.group({ 29 | gender: ['male'], 30 | username: ['', Validators.required], 31 | knownAs: ['', Validators.required], 32 | dateOfBirth: ['', Validators.required], 33 | city: ['', Validators.required], 34 | country: ['', Validators.required], 35 | password: ['', [Validators.required, 36 | Validators.minLength(4), Validators.maxLength(8)]], 37 | confirmPassword: ['', [Validators.required, this.matchValues('password')]] 38 | }) 39 | } 40 | 41 | matchValues(matchTo: string): ValidatorFn { 42 | return (control: AbstractControl) => { 43 | return control?.value === control?.parent?.controls[matchTo].value 44 | ? null : {isMatching: true} 45 | } 46 | } 47 | 48 | register() { 49 | this.accountService.register(this.registerForm.value).subscribe(response => { 50 | this.router.navigateByUrl('/members'); 51 | }, error => { 52 | this.validationErrors = error; 53 | }) 54 | } 55 | 56 | cancel() { 57 | this.cancelRegister.emit(false); 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /client/src/assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TryCatchLearn/DatingApp-v6/d2fee1117ac86155ff5f43df661d452a0eb427ec/client/src/assets/.gitkeep -------------------------------------------------------------------------------- /client/src/assets/icons/icon-128x128.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TryCatchLearn/DatingApp-v6/d2fee1117ac86155ff5f43df661d452a0eb427ec/client/src/assets/icons/icon-128x128.png -------------------------------------------------------------------------------- /client/src/assets/icons/icon-144x144.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TryCatchLearn/DatingApp-v6/d2fee1117ac86155ff5f43df661d452a0eb427ec/client/src/assets/icons/icon-144x144.png -------------------------------------------------------------------------------- /client/src/assets/icons/icon-152x152.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TryCatchLearn/DatingApp-v6/d2fee1117ac86155ff5f43df661d452a0eb427ec/client/src/assets/icons/icon-152x152.png -------------------------------------------------------------------------------- /client/src/assets/icons/icon-192x192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TryCatchLearn/DatingApp-v6/d2fee1117ac86155ff5f43df661d452a0eb427ec/client/src/assets/icons/icon-192x192.png -------------------------------------------------------------------------------- /client/src/assets/icons/icon-384x384.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TryCatchLearn/DatingApp-v6/d2fee1117ac86155ff5f43df661d452a0eb427ec/client/src/assets/icons/icon-384x384.png -------------------------------------------------------------------------------- /client/src/assets/icons/icon-512x512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TryCatchLearn/DatingApp-v6/d2fee1117ac86155ff5f43df661d452a0eb427ec/client/src/assets/icons/icon-512x512.png -------------------------------------------------------------------------------- /client/src/assets/icons/icon-72x72.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TryCatchLearn/DatingApp-v6/d2fee1117ac86155ff5f43df661d452a0eb427ec/client/src/assets/icons/icon-72x72.png -------------------------------------------------------------------------------- /client/src/assets/icons/icon-96x96.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TryCatchLearn/DatingApp-v6/d2fee1117ac86155ff5f43df661d452a0eb427ec/client/src/assets/icons/icon-96x96.png -------------------------------------------------------------------------------- /client/src/assets/user.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TryCatchLearn/DatingApp-v6/d2fee1117ac86155ff5f43df661d452a0eb427ec/client/src/assets/user.png -------------------------------------------------------------------------------- /client/src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true, 3 | apiUrl: 'api/', 4 | hubUrl: 'hubs/' 5 | }; 6 | -------------------------------------------------------------------------------- /client/src/environments/environment.ts: -------------------------------------------------------------------------------- 1 | // This file can be replaced during build by using the `fileReplacements` array. 2 | // `ng build --prod` replaces `environment.ts` with `environment.prod.ts`. 3 | // The list of file replacements can be found in `angular.json`. 4 | 5 | export const environment = { 6 | production: false, 7 | apiUrl: 'https://localhost:5001/api/', 8 | hubUrl: 'https://localhost:5001/hubs/' 9 | }; 10 | 11 | /* 12 | * For easier debugging in development mode, you can import the following file 13 | * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`. 14 | * 15 | * This import should be commented out in production mode because it will have a negative impact 16 | * on performance if an error is thrown. 17 | */ 18 | // import 'zone.js/plugins/zone-error'; // Included with Angular CLI. 19 | -------------------------------------------------------------------------------- /client/src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TryCatchLearn/DatingApp-v6/d2fee1117ac86155ff5f43df661d452a0eb427ec/client/src/favicon.ico -------------------------------------------------------------------------------- /client/src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | DatingApp 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /client/src/main.ts: -------------------------------------------------------------------------------- 1 | import { enableProdMode } from '@angular/core'; 2 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; 3 | 4 | import { AppModule } from './app/app.module'; 5 | import { environment } from './environments/environment'; 6 | 7 | if (environment.production) { 8 | enableProdMode(); 9 | } 10 | 11 | platformBrowserDynamic().bootstrapModule(AppModule) 12 | .catch(err => console.error(err)); 13 | -------------------------------------------------------------------------------- /client/src/manifest.webmanifest: -------------------------------------------------------------------------------- 1 | { 2 | "name": "client", 3 | "short_name": "client", 4 | "theme_color": "#1976d2", 5 | "background_color": "#fafafa", 6 | "display": "standalone", 7 | "scope": "./", 8 | "start_url": "./", 9 | "icons": [ 10 | { 11 | "src": "assets/icons/icon-72x72.png", 12 | "sizes": "72x72", 13 | "type": "image/png", 14 | "purpose": "maskable any" 15 | }, 16 | { 17 | "src": "assets/icons/icon-96x96.png", 18 | "sizes": "96x96", 19 | "type": "image/png", 20 | "purpose": "maskable any" 21 | }, 22 | { 23 | "src": "assets/icons/icon-128x128.png", 24 | "sizes": "128x128", 25 | "type": "image/png", 26 | "purpose": "maskable any" 27 | }, 28 | { 29 | "src": "assets/icons/icon-144x144.png", 30 | "sizes": "144x144", 31 | "type": "image/png", 32 | "purpose": "maskable any" 33 | }, 34 | { 35 | "src": "assets/icons/icon-152x152.png", 36 | "sizes": "152x152", 37 | "type": "image/png", 38 | "purpose": "maskable any" 39 | }, 40 | { 41 | "src": "assets/icons/icon-192x192.png", 42 | "sizes": "192x192", 43 | "type": "image/png", 44 | "purpose": "maskable any" 45 | }, 46 | { 47 | "src": "assets/icons/icon-384x384.png", 48 | "sizes": "384x384", 49 | "type": "image/png", 50 | "purpose": "maskable any" 51 | }, 52 | { 53 | "src": "assets/icons/icon-512x512.png", 54 | "sizes": "512x512", 55 | "type": "image/png", 56 | "purpose": "maskable any" 57 | } 58 | ] 59 | } 60 | -------------------------------------------------------------------------------- /client/src/polyfills.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file includes polyfills needed by Angular and is loaded before the app. 3 | * You can add your own extra polyfills to this file. 4 | * 5 | * This file is divided into 2 sections: 6 | * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. 7 | * 2. Application imports. Files imported after ZoneJS that should be loaded before your main 8 | * file. 9 | * 10 | * The current setup is for so-called "evergreen" browsers; the last versions of browsers that 11 | * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), 12 | * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. 13 | * 14 | * Learn more in https://angular.io/guide/browser-support 15 | */ 16 | 17 | /*************************************************************************************************** 18 | * BROWSER POLYFILLS 19 | */ 20 | 21 | /** IE10 and IE11 requires the following for NgClass support on SVG elements */ 22 | // import 'classlist.js'; // Run `npm install --save classlist.js`. 23 | 24 | /** 25 | * Web Animations `@angular/platform-browser/animations` 26 | * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari. 27 | * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0). 28 | */ 29 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`. 30 | 31 | /** 32 | * By default, zone.js will patch all possible macroTask and DomEvents 33 | * user can disable parts of macroTask/DomEvents patch by setting following flags 34 | * because those flags need to be set before `zone.js` being loaded, and webpack 35 | * will put import in the top of bundle, so user need to create a separate file 36 | * in this directory (for example: zone-flags.ts), and put the following flags 37 | * into that file, and then add the following code before importing zone.js. 38 | * import './zone-flags'; 39 | * 40 | * The flags allowed in zone-flags.ts are listed here. 41 | * 42 | * The following flags will work for all browsers. 43 | * 44 | * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame 45 | * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick 46 | * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames 47 | * 48 | * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js 49 | * with the following flag, it will bypass `zone.js` patch for IE/Edge 50 | * 51 | * (window as any).__Zone_enable_cross_context_check = true; 52 | * 53 | */ 54 | 55 | /*************************************************************************************************** 56 | * Zone JS is required by default for Angular itself. 57 | */ 58 | import 'zone.js'; // Included with Angular CLI. 59 | 60 | 61 | /*************************************************************************************************** 62 | * APPLICATION IMPORTS 63 | */ 64 | -------------------------------------------------------------------------------- /client/src/styles.css: -------------------------------------------------------------------------------- 1 | /* You can add global styles to this file, and also import other style files */ 2 | .tab-panel { 3 | border: 1px solid #ddd; 4 | padding: 10px; 5 | border-radius: 4px; 6 | } 7 | 8 | .nav-tabs > li.open, .member-tabset > .nav-tabs > li:hover { 9 | border-bottom: 4px solid #fbcdcf; 10 | } 11 | 12 | .member-tabset > .nav-tabs > li.open > a, .member-tabset > .nav-tabs > li:hover > a { 13 | border: 0; 14 | background: none !important; 15 | color: #333333; 16 | } 17 | 18 | .member-tabset > .nav-tabs > li.open > a > i, .member-tabset > .nav-tabs > li:hover > a > i { 19 | color: #a6a6a6; 20 | } 21 | 22 | .member-tabset > .nav-tabs > li.open .dropdown-menu, .member-tabset > .nav-tabs > li:hover .dropdown-menu { 23 | margin-top: 0px; 24 | } 25 | 26 | .member-tabset > .nav-tabs > li.active { 27 | border-bottom: 4px solid #E95420; 28 | position: relative; 29 | } 30 | 31 | .member-tabset > .nav-tabs > li.active > a { 32 | border: 0 !important; 33 | color: #333333; 34 | } 35 | 36 | .member-tabset > .nav-tabs > li.active > a > i { 37 | color: #404040; 38 | } 39 | 40 | .member-tabset > .tab-content { 41 | margin-top: -3px; 42 | background-color: #fff; 43 | border: 0; 44 | border-top: 1px solid #eee; 45 | padding: 15px 0; 46 | } 47 | -------------------------------------------------------------------------------- /client/src/test.ts: -------------------------------------------------------------------------------- 1 | // This file is required by karma.conf.js and loads recursively all the .spec and framework files 2 | 3 | import 'zone.js/testing'; 4 | import { getTestBed } from '@angular/core/testing'; 5 | import { 6 | BrowserDynamicTestingModule, 7 | platformBrowserDynamicTesting 8 | } from '@angular/platform-browser-dynamic/testing'; 9 | 10 | declare const require: { 11 | context(path: string, deep?: boolean, filter?: RegExp): { 12 | keys(): string[]; 13 | (id: string): T; 14 | }; 15 | }; 16 | 17 | // First, initialize the Angular testing environment. 18 | getTestBed().initTestEnvironment( 19 | BrowserDynamicTestingModule, 20 | platformBrowserDynamicTesting() 21 | ); 22 | // Then we find all the tests. 23 | const context = require.context('./', true, /\.spec\.ts$/); 24 | // And load the modules. 25 | context.keys().map(context); 26 | -------------------------------------------------------------------------------- /client/tsconfig.app.json: -------------------------------------------------------------------------------- 1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */ 2 | { 3 | "extends": "./tsconfig.json", 4 | "compilerOptions": { 5 | "outDir": "./out-tsc/app", 6 | "types": [] 7 | }, 8 | "files": [ 9 | "src/main.ts", 10 | "src/polyfills.ts" 11 | ], 12 | "include": [ 13 | "src/**/*.d.ts" 14 | ] 15 | } 16 | -------------------------------------------------------------------------------- /client/tsconfig.json: -------------------------------------------------------------------------------- 1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */ 2 | { 3 | "compileOnSave": false, 4 | "compilerOptions": { 5 | "baseUrl": "./", 6 | "outDir": "./dist/out-tsc", 7 | "sourceMap": true, 8 | "declaration": false, 9 | "downlevelIteration": true, 10 | "experimentalDecorators": true, 11 | "moduleResolution": "node", 12 | "importHelpers": true, 13 | "target": "es2015", 14 | "module": "es2020", 15 | "lib": [ 16 | "es2019", 17 | "es2018", 18 | "dom" 19 | ] 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /client/tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */ 2 | { 3 | "extends": "./tsconfig.json", 4 | "compilerOptions": { 5 | "outDir": "./out-tsc/spec", 6 | "types": [ 7 | "jasmine" 8 | ] 9 | }, 10 | "files": [ 11 | "src/test.ts", 12 | "src/polyfills.ts" 13 | ], 14 | "include": [ 15 | "src/**/*.spec.ts", 16 | "src/**/*.d.ts" 17 | ] 18 | } 19 | -------------------------------------------------------------------------------- /client/tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "tslint:recommended", 3 | "rulesDirectory": [ 4 | "codelyzer" 5 | ], 6 | "rules": { 7 | "align": { 8 | "options": [ 9 | "parameters", 10 | "statements" 11 | ] 12 | }, 13 | "array-type": false, 14 | "arrow-return-shorthand": true, 15 | "curly": true, 16 | "deprecation": { 17 | "severity": "warning" 18 | }, 19 | "eofline": true, 20 | "import-blacklist": [ 21 | true, 22 | "rxjs/Rx" 23 | ], 24 | "import-spacing": true, 25 | "indent": { 26 | "options": [ 27 | "spaces" 28 | ] 29 | }, 30 | "max-classes-per-file": false, 31 | "max-line-length": [ 32 | true, 33 | 140 34 | ], 35 | "member-ordering": [ 36 | true, 37 | { 38 | "order": [ 39 | "static-field", 40 | "instance-field", 41 | "static-method", 42 | "instance-method" 43 | ] 44 | } 45 | ], 46 | "no-console": [ 47 | true, 48 | "debug", 49 | "info", 50 | "time", 51 | "timeEnd", 52 | "trace" 53 | ], 54 | "no-empty": false, 55 | "no-inferrable-types": [ 56 | true, 57 | "ignore-params" 58 | ], 59 | "no-non-null-assertion": true, 60 | "no-redundant-jsdoc": true, 61 | "no-switch-case-fall-through": true, 62 | "no-var-requires": false, 63 | "object-literal-key-quotes": [ 64 | true, 65 | "as-needed" 66 | ], 67 | "quotemark": [ 68 | true, 69 | "single" 70 | ], 71 | "semicolon": { 72 | "options": [ 73 | "always" 74 | ] 75 | }, 76 | "space-before-function-paren": { 77 | "options": { 78 | "anonymous": "never", 79 | "asyncArrow": "always", 80 | "constructor": "never", 81 | "method": "never", 82 | "named": "never" 83 | } 84 | }, 85 | "typedef": [ 86 | true, 87 | "call-signature" 88 | ], 89 | "typedef-whitespace": { 90 | "options": [ 91 | { 92 | "call-signature": "nospace", 93 | "index-signature": "nospace", 94 | "parameter": "nospace", 95 | "property-declaration": "nospace", 96 | "variable-declaration": "nospace" 97 | }, 98 | { 99 | "call-signature": "onespace", 100 | "index-signature": "onespace", 101 | "parameter": "onespace", 102 | "property-declaration": "onespace", 103 | "variable-declaration": "onespace" 104 | } 105 | ] 106 | }, 107 | "variable-name": { 108 | "options": [ 109 | "ban-keywords", 110 | "check-format", 111 | "allow-pascal-case" 112 | ] 113 | }, 114 | "whitespace": { 115 | "options": [ 116 | "check-branch", 117 | "check-decl", 118 | "check-operator", 119 | "check-separator", 120 | "check-type", 121 | "check-typecast" 122 | ] 123 | }, 124 | "component-class-suffix": true, 125 | "contextual-lifecycle": true, 126 | "directive-class-suffix": true, 127 | "no-conflicting-lifecycle": true, 128 | "no-host-metadata-property": true, 129 | "no-input-rename": true, 130 | "no-inputs-metadata-property": true, 131 | "no-output-native": true, 132 | "no-output-on-prefix": true, 133 | "no-output-rename": true, 134 | "no-outputs-metadata-property": true, 135 | "template-banana-in-box": true, 136 | "template-no-negated-async": true, 137 | "use-lifecycle-interface": true, 138 | "use-pipe-transform-interface": true, 139 | "directive-selector": [ 140 | true, 141 | "attribute", 142 | "app", 143 | "camelCase" 144 | ], 145 | "component-selector": [ 146 | true, 147 | "element", 148 | "app", 149 | "kebab-case" 150 | ] 151 | } 152 | } 153 | --------------------------------------------------------------------------------