├── client ├── src │ ├── assets │ │ ├── .gitkeep │ │ └── user.png │ ├── app │ │ ├── app.component.css │ │ ├── home │ │ │ ├── home.component.css │ │ │ ├── home.component.html │ │ │ └── home.component.ts │ │ ├── list │ │ │ ├── list.component.css │ │ │ ├── list.component.ts │ │ │ └── list.component.html │ │ ├── _forms │ │ │ ├── date-input │ │ │ │ ├── date-input.component.css │ │ │ │ ├── date-input.component.html │ │ │ │ └── date-input.component.ts │ │ │ └── text-input │ │ │ │ ├── text-input.component.css │ │ │ │ ├── text-input.component.ts │ │ │ │ └── text-input.component.html │ │ ├── admin │ │ │ ├── admin-panel │ │ │ │ ├── admin-panel.component.css │ │ │ │ ├── admin-panel.component.ts │ │ │ │ └── admin-panel.component.html │ │ │ ├── user-management │ │ │ │ ├── user-management.component.css │ │ │ │ ├── user-management.component.html │ │ │ │ └── user-management.component.ts │ │ │ └── photo-management │ │ │ │ ├── photo-management.component.css │ │ │ │ ├── photo-management.component.html │ │ │ │ └── photo-management.component.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.ts │ │ │ │ └── server-error.component.html │ │ │ └── test-errors │ │ │ │ ├── test-errors.component.css │ │ │ │ ├── test-errors.component.html │ │ │ │ └── test-errors.component.ts │ │ ├── reset-password │ │ │ ├── reset-password.component.css │ │ │ ├── reset-password.component.html │ │ │ └── reset-password.component.ts │ │ ├── forgot-password │ │ │ ├── forgot-password.component.css │ │ │ ├── forgot-password.component.ts │ │ │ └── forgot-password.component.html │ │ ├── modals │ │ │ ├── roles-modal │ │ │ │ ├── roles-modal.component.css │ │ │ │ ├── roles-modal.component.ts │ │ │ │ └── roles-modal.component.html │ │ │ └── confirm-dialog │ │ │ │ ├── confirm-dialog.component.css │ │ │ │ ├── confirm-dialog.component.html │ │ │ │ └── confirm-dialog.component.ts │ │ ├── confirm-password-sent │ │ │ ├── confirm-password-sent.component.css │ │ │ ├── confirm-password-sent.component.html │ │ │ └── confirm-password-sent.component.ts │ │ ├── confirmation-email-sent │ │ │ ├── confirmation-email-sent.component.css │ │ │ ├── confirmation-email-sent.component.html │ │ │ └── confirmation-email-sent.component.ts │ │ ├── reset-password-complete │ │ │ ├── reset-password-complete.component.css │ │ │ ├── reset-password-complete.component.html │ │ │ └── reset-password-complete.component.ts │ │ ├── messages │ │ │ ├── messages.component.css │ │ │ ├── messages.component.ts │ │ │ └── messages.component.html │ │ ├── login │ │ │ ├── login.component.css │ │ │ ├── login.component.ts │ │ │ └── login.component.html │ │ ├── confirm-email │ │ │ ├── confirm-email.component.css │ │ │ ├── confirm-email.component.html │ │ │ └── confirm-email.component.ts │ │ ├── register │ │ │ ├── register.component.css │ │ │ └── register.component.ts │ │ ├── _models │ │ │ ├── photo.ts │ │ │ ├── user.ts │ │ │ ├── group.ts │ │ │ ├── pagination.ts │ │ │ ├── message.ts │ │ │ ├── userParams.ts │ │ │ └── member.ts │ │ ├── nav │ │ │ ├── nav.component.css │ │ │ ├── nav.component.ts │ │ │ └── nav.component.html │ │ ├── app.component.html │ │ ├── members │ │ │ ├── member-list │ │ │ │ ├── member-list.component.css │ │ │ │ ├── member-list.component.ts │ │ │ │ └── member-list.component.html │ │ │ ├── member-edit │ │ │ │ ├── member-edit.component.css │ │ │ │ ├── member-edit.component.ts │ │ │ │ └── member-edit.component.html │ │ │ ├── member-detail │ │ │ │ ├── member-detail.component.css │ │ │ │ ├── member-detail.component.html │ │ │ │ └── member-detail.component.ts │ │ │ ├── member-messages │ │ │ │ ├── member-messages.component.css │ │ │ │ ├── member-messages.component.ts │ │ │ │ └── member-messages.component.html │ │ │ ├── photo-editor │ │ │ │ ├── photo-editor.component.css │ │ │ │ └── photo-editor.component.ts │ │ │ └── member-card │ │ │ │ ├── member-card.component.css │ │ │ │ ├── member-card.component.ts │ │ │ │ └── member-card.component.html │ │ ├── _resolvers │ │ │ └── member-detailed.resolver.ts │ │ ├── _services │ │ │ ├── busy.service.ts │ │ │ ├── paginationHelper.ts │ │ │ ├── admin.service.ts │ │ │ ├── confirm.service.ts │ │ │ ├── presence.service.ts │ │ │ ├── account.service.ts │ │ │ ├── message.service.ts │ │ │ └── members.service.ts │ │ ├── _interceptors │ │ │ ├── loading.interceptor.ts │ │ │ ├── jwt.interceptor.ts │ │ │ └── error.interceptor.ts │ │ ├── _guards │ │ │ ├── prevent-unsaved-changes.guard.ts │ │ │ ├── auth.guard.ts │ │ │ └── admin.guard.ts │ │ ├── _directives │ │ │ └── has-role.directive.ts │ │ ├── app.component.spec.ts │ │ ├── _modules │ │ │ └── shared.module.ts │ │ ├── app.component.ts │ │ └── app-routing.module.ts │ ├── favicon.ico │ ├── environments │ │ ├── environment.prod.ts │ │ └── environment.ts │ ├── index.html │ ├── main.ts │ ├── test.ts │ ├── styles.css │ └── polyfills.ts ├── .editorconfig ├── e2e │ ├── src │ │ ├── app.po.ts │ │ └── app.e2e-spec.ts │ ├── tsconfig.json │ └── protractor.conf.js ├── tsconfig.app.json ├── tsconfig.spec.json ├── tsconfig.json ├── .gitignore ├── .browserslistrc ├── README.md ├── karma.conf.js └── package.json ├── API ├── wwwroot │ ├── favicon.ico │ ├── assets │ │ └── user.png │ ├── fontawesome-webfont.1e59d2330b4c6deb84b3.ttf │ ├── fontawesome-webfont.8b43027f47b20503057d.eot │ ├── fontawesome-webfont.20fd1704ea223900efa9.woff2 │ ├── fontawesome-webfont.f691f37e57f04c152e23.woff │ ├── index.html │ └── runtime.acf0dec4155e77772545.js ├── DTOs │ ├── ConfirmEmailDto.cs │ ├── CreateMessageDto.cs │ ├── LoginDTO.cs │ ├── ResetPasswordDto.cs │ ├── ForgotPasswordDto.cs │ ├── PhotoDto.cs │ ├── PhotoForApprovalDto.cs │ ├── UserDto.cs │ ├── MemberUpdateDTO.cs │ ├── LikeDTO.cs │ ├── MemberDto.cs │ ├── RegisterDto.cs │ └── MessageDto.cs ├── Helpers │ ├── LikesParams.cs │ ├── MessageParams.cs │ ├── CloudinarySettings.cs │ ├── PaginationParams.cs │ ├── UserParams.cs │ ├── PaginationHeader.cs │ ├── HttpExtensions.cs │ ├── LogUserActivity.cs │ ├── AutomapperProfiles.cs │ ├── PageList.cs │ └── URLBuilder.cs ├── Interfaces │ ├── ITokenService.cs │ ├── IPhotoService.cs │ ├── IPhotoRepository.cs │ ├── IUnitOfWork.cs │ ├── ILikeRepository.cs │ ├── IUserRepository.cs │ └── IMessageRepository.cs ├── Entities │ ├── AppRole.cs │ ├── AppUserRole.cs │ ├── UserLike.cs │ ├── Connection.cs │ ├── Group.cs │ ├── Photo.cs │ ├── Message.cs │ └── AppUser.cs ├── Controllers │ ├── BaseAPIController.cs │ ├── FallbackController.cs │ ├── BuggyController.cs │ ├── LikesController.cs │ └── MessagesController.cs ├── Extentions │ ├── DateTimeExtensions.cs │ ├── ClaimsPrincipleExtentions.cs │ ├── IdentityServiceExtensions.cs │ └── ApplicationServiceExtensions.cs ├── Errors │ └── ApiException.cs ├── Data │ ├── ForgotPasswordRepository.cs │ ├── UnitOfWork.cs │ ├── PhotoRepository.cs │ ├── Seed.cs │ └── LikesRepository.cs ├── appsettings.Development.json ├── appsettings.json ├── Properties │ └── launchSettings.json ├── SignalR │ ├── PresenceHub.cs │ └── PresenceTracker.cs ├── API.csproj ├── Middleware │ └── ExceptionMiddleware.cs ├── Program.cs ├── Services │ ├── PhotoService.cs │ └── TokenService.cs └── Startup.cs ├── EmailService ├── IEmailSender.cs ├── EmailConfiguration.cs ├── EmailService.csproj └── Message.cs ├── .vscode ├── tasks.json └── launch.json ├── DatingApp.sln └── .gitattributes /client/src/assets/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /client/src/app/app.component.css: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /client/src/app/home/home.component.css: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /client/src/app/list/list.component.css: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /client/src/app/_forms/date-input/date-input.component.css: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /client/src/app/_forms/text-input/text-input.component.css: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /client/src/app/admin/admin-panel/admin-panel.component.css: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /client/src/app/errors/not-found/not-found.component.css: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /client/src/app/reset-password/reset-password.component.css: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /client/src/app/errors/server-error/server-error.component.css: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /client/src/app/errors/test-errors/test-errors.component.css: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /client/src/app/forgot-password/forgot-password.component.css: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /client/src/app/modals/roles-modal/roles-modal.component.css: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /client/src/app/admin/user-management/user-management.component.css: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /client/src/app/modals/confirm-dialog/confirm-dialog.component.css: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /client/src/app/confirm-password-sent/confirm-password-sent.component.css: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /client/src/app/confirmation-email-sent/confirmation-email-sent.component.css: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /client/src/app/reset-password-complete/reset-password-complete.component.css: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /client/src/app/messages/messages.component.css: -------------------------------------------------------------------------------- 1 | .img-circle{ 2 | max-height: 50px; 3 | } -------------------------------------------------------------------------------- /API/wwwroot/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tonymatute/DatingApp/HEAD/API/wwwroot/favicon.ico -------------------------------------------------------------------------------- /client/src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tonymatute/DatingApp/HEAD/client/src/favicon.ico -------------------------------------------------------------------------------- /client/src/app/login/login.component.css: -------------------------------------------------------------------------------- 1 | 2 | .div-border { 3 | border: 2px solid ; 4 | } 5 | 6 | 7 | -------------------------------------------------------------------------------- /client/src/assets/user.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tonymatute/DatingApp/HEAD/client/src/assets/user.png -------------------------------------------------------------------------------- /API/wwwroot/assets/user.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tonymatute/DatingApp/HEAD/API/wwwroot/assets/user.png -------------------------------------------------------------------------------- /client/src/app/confirm-email/confirm-email.component.css: -------------------------------------------------------------------------------- 1 | .div-border { 2 | border: 2px solid ; 3 | } -------------------------------------------------------------------------------- /client/src/app/register/register.component.css: -------------------------------------------------------------------------------- 1 | 2 | .div-border { 3 | border: 2px solid ; 4 | 5 | } -------------------------------------------------------------------------------- /client/src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true, 3 | apiUrl: 'api/', 4 | hubUrl: 'hubs/' 5 | }; 6 | -------------------------------------------------------------------------------- /API/wwwroot/fontawesome-webfont.1e59d2330b4c6deb84b3.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tonymatute/DatingApp/HEAD/API/wwwroot/fontawesome-webfont.1e59d2330b4c6deb84b3.ttf -------------------------------------------------------------------------------- /API/wwwroot/fontawesome-webfont.8b43027f47b20503057d.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tonymatute/DatingApp/HEAD/API/wwwroot/fontawesome-webfont.8b43027f47b20503057d.eot -------------------------------------------------------------------------------- /API/wwwroot/fontawesome-webfont.20fd1704ea223900efa9.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tonymatute/DatingApp/HEAD/API/wwwroot/fontawesome-webfont.20fd1704ea223900efa9.woff2 -------------------------------------------------------------------------------- /API/wwwroot/fontawesome-webfont.f691f37e57f04c152e23.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tonymatute/DatingApp/HEAD/API/wwwroot/fontawesome-webfont.f691f37e57f04c152e23.woff -------------------------------------------------------------------------------- /client/src/app/_models/photo.ts: -------------------------------------------------------------------------------- 1 | export interface Photo { 2 | id: number; 3 | url: string; 4 | isMain: boolean; 5 | isApproved: boolean; 6 | username?: string; 7 | } 8 | -------------------------------------------------------------------------------- /client/src/app/admin/photo-management/photo-management.component.css: -------------------------------------------------------------------------------- 1 | img-thumbnail { 2 | height: 150px; 3 | min-width: 150px !important; 4 | margin-bottom: 2px; 5 | } -------------------------------------------------------------------------------- /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 white; 8 | display: inline; 9 | } -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /API/DTOs/ConfirmEmailDto.cs: -------------------------------------------------------------------------------- 1 | namespace API.DTOs 2 | { 3 | public class ConfirmEmailDto 4 | { 5 | public string userid { get; set; } 6 | public string token { get; set; } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /client/src/app/_models/group.ts: -------------------------------------------------------------------------------- 1 | export interface Group { 2 | name: string; 3 | connection: Connection[]; 4 | } 5 | 6 | interface Connection { 7 | connectionId: string; 8 | username: string; 9 | } -------------------------------------------------------------------------------- /client/src/app/confirm-password-sent/confirm-password-sent.component.html: -------------------------------------------------------------------------------- 1 |

Password Reset Sent

2 |
3 |

An email was sent to your email address with link to change your password.

4 | 5 | 6 | -------------------------------------------------------------------------------- /client/src/app/errors/not-found/not-found.component.html: -------------------------------------------------------------------------------- 1 |
2 |

Not Found

3 | 4 |
5 | -------------------------------------------------------------------------------- /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 | } 9 | -------------------------------------------------------------------------------- /API/DTOs/LoginDTO.cs: -------------------------------------------------------------------------------- 1 | 2 | 3 | namespace API.DTOs 4 | { 5 | public class LoginDTO 6 | { 7 | public string Username { get; set; } 8 | public string Password { get; set; } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /client/src/app/confirm-email/confirm-email.component.html: -------------------------------------------------------------------------------- 1 |

Thank you!

2 |
3 |

Your email address has been confirmed. Proceed to  4 | Login

5 | -------------------------------------------------------------------------------- /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 | } 9 | -------------------------------------------------------------------------------- /client/src/app/reset-password-complete/reset-password-complete.component.html: -------------------------------------------------------------------------------- 1 |

Reset Password

2 |
3 |

Your password has been reset. Proceed to  4 | Login

-------------------------------------------------------------------------------- /client/src/app/app.component.html: -------------------------------------------------------------------------------- 1 | 2 |

Loading...

3 |
4 | 5 | 6 | 7 |
8 | 9 |
10 | -------------------------------------------------------------------------------- /API/Interfaces/ITokenService.cs: -------------------------------------------------------------------------------- 1 | 2 | using API.Entities; 3 | using System.Threading.Tasks; 4 | 5 | namespace API.Interfaces 6 | { 7 | public interface ITokenService 8 | { 9 | Task CreateToken(AppUser user); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /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 | } 9 | } 10 | -------------------------------------------------------------------------------- /API/DTOs/ResetPasswordDto.cs: -------------------------------------------------------------------------------- 1 | namespace API.DTOs 2 | { 3 | public class ResetPasswordDto 4 | { 5 | public string UserId { get; set; } 6 | public string Token { get; set; } 7 | public string Password { get; set; } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /API/Entities/AppRole.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Identity; 2 | using System.Collections.Generic; 3 | 4 | namespace API.Entities 5 | { 6 | public class AppRole : IdentityRole 7 | { 8 | public ICollection UserRoles { get; set; } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /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 | 9 | public AppRole Role { get; set; } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /API/Helpers/CloudinarySettings.cs: -------------------------------------------------------------------------------- 1 | 2 | namespace API.Helpers 3 | { 4 | public class CloudinarySettings 5 | { 6 | public string CloudName { get; set; } 7 | public string ApiKey { get; set; } 8 | public string ApiSecret { get; set; } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /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 PaginateResult { 9 | result: T; 10 | pagination: Pagination; 11 | } -------------------------------------------------------------------------------- /API/DTOs/ForgotPasswordDto.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace API.DTOs 7 | { 8 | public class ForgotPasswordDto 9 | { 10 | public string Email { get; set; } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /API/DTOs/PhotoDto.cs: -------------------------------------------------------------------------------- 1 | 2 | 3 | namespace API.DTOs 4 | { 5 | public class PhotoDto 6 | { 7 | public int id { get; set; } 8 | public string Url { get; set; } 9 | public bool IsMain { get; set; } 10 | public bool IsApproved { get; set; } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /client/src/app/confirmation-email-sent/confirmation-email-sent.component.html: -------------------------------------------------------------------------------- 1 |

A verification link has been sent to your email account

2 |
3 |

Please click on the link that has just been sent to your email account to verify your email and continue the registration process.

4 | 5 | 6 | -------------------------------------------------------------------------------- /client/src/app/members/member-list/member-list.component.css: -------------------------------------------------------------------------------- 1 | .img-thumbnail { 2 | margin: 25px; 3 | width: 85%; 4 | height: 85%; 5 | } 6 | .card-body { 7 | padding: 0 25px; 8 | } 9 | .card-footer{ 10 | padding:10px 15px; 11 | background-color: white; 12 | border-top: none; 13 | } -------------------------------------------------------------------------------- /API/DTOs/PhotoForApprovalDto.cs: -------------------------------------------------------------------------------- 1 | namespace API.DTOs 2 | { 3 | public class PhotoForApprovalDto 4 | { 5 | public int id { get; set; } 6 | public string Url { get; set; } 7 | public string Username { get; set; } 8 | public bool IsApproved { get; set; } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /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 | public AppUser LikedUser { get; set; } 8 | public int LikedUserId { get; set; } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /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 | .card-footer { 11 | padding: 10px 15px; 12 | background-color: white; 13 | border-top: none; 14 | } -------------------------------------------------------------------------------- /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 | .card-footer { 11 | padding: 10px 15px; 12 | background-color: white; 13 | border-top: none; 14 | } -------------------------------------------------------------------------------- /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 | } 14 | -------------------------------------------------------------------------------- /EmailService/IEmailSender.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace EmailService 7 | { 8 | public interface IEmailSender 9 | { 10 | void SendEmail(Message message); 11 | Task SendEmailAsync(Message message); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /API/DTOs/UserDto.cs: -------------------------------------------------------------------------------- 1 | 2 | namespace API.DTOs 3 | { 4 | public class UserDto 5 | { 6 | public string Username { get; set; } 7 | public string Token { get; set; } 8 | public string PhotoUrl { get; set; } 9 | public string KnownAs { get; set; } 10 | public string Gender { get; set; } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /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/.editorconfig: -------------------------------------------------------------------------------- 1 | # Editor configuration, see https://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | indent_style = space 7 | indent_size = 2 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | 11 | [*.ts] 12 | quote_type = single 13 | 14 | [*.md] 15 | max_line_length = off 16 | trim_trailing_whitespace = false 17 | -------------------------------------------------------------------------------- /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/src/app/members/member-messages/member-messages.component.css: -------------------------------------------------------------------------------- 1 | .card { 2 | border: none; 3 | } 4 | .chat { 5 | list-style: none; 6 | margin: 0; 7 | padding: 0; 8 | } 9 | .chat li { 10 | margin-bottom: 10px; 11 | padding-bottom: 10px; 12 | border-bottom: 1px dotted #B3A9A9; 13 | } 14 | .rounded-circle { 15 | max-height: 50px; 16 | } -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /API/Interfaces/IPhotoService.cs: -------------------------------------------------------------------------------- 1 | using CloudinaryDotNet.Actions; 2 | using Microsoft.AspNetCore.Http; 3 | using System.Threading.Tasks; 4 | 5 | namespace API.Interfaces 6 | { 7 | public interface IPhotoService 8 | { 9 | Task AddPhotoAsync(IFormFile file); 10 | Task DeletePhotoAsync(string publicId); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /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/src/app/home/home.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |

Find your match

4 |

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

5 | 6 |
7 |
-------------------------------------------------------------------------------- /client/src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Dating App 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /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/_models/userParams.ts: -------------------------------------------------------------------------------- 1 | import { User } from './user'; 2 | 3 | export class UserParams { 4 | gender: string; 5 | minAge: number = 18; 6 | maxAge: number = 99; 7 | pageNumber: number = 1; 8 | pageSize: number = 5; 9 | orderBy = 'lastActive'; 10 | 11 | constructor(user: User) { 12 | this.gender = user.gender === 'female' ? 'male' : 'female'; 13 | } 14 | } -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /API/Interfaces/IPhotoRepository.cs: -------------------------------------------------------------------------------- 1 | using API.DTOs; 2 | using API.Entities; 3 | using System.Collections.Generic; 4 | using System.Threading.Tasks; 5 | 6 | namespace API.Interfaces 7 | { 8 | public interface IPhotoRepository 9 | { 10 | Task> GetUnapprovedPhotos(); 11 | Task GetPhotoById(int id); 12 | void RemovePhoto(Photo photo); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /API/Controllers/FallbackController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using System.IO; 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 | } 15 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /API/Extentions/DateTimeExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace API.Extentions 4 | { 5 | public static class DateTimeExtensions 6 | { 7 | public static int CalculateAge(this DateTime dob) 8 | { 9 | var today = DateTime.UtcNow; 10 | var age = today.Year - dob.Year; 11 | if (dob.Date > today.AddYears(-age)) age--; 12 | return age; 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /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 | ILikeRepository LikeRepository { get; } 10 | IPhotoRepository PhotoRepository { get; } 11 | Task Complete(); 12 | bool HasChanges(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /API/Helpers/PaginationParams.cs: -------------------------------------------------------------------------------- 1 | namespace API.Helpers 2 | { 3 | public class PaginationParams 4 | { 5 | private const int MaxPageSize = 50; 6 | private int _pageSize = 10; 7 | 8 | public int PageNumber { get; set; } = 1; 9 | 10 | public int PageSize 11 | { 12 | get => _pageSize; 13 | set => _pageSize = (value > MaxPageSize) ? MaxPageSize : value; 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /API/Helpers/UserParams.cs: -------------------------------------------------------------------------------- 1 | 2 | using System.Security.Permissions; 3 | 4 | namespace API.Helpers 5 | { 6 | public class UserParams: PaginationParams 7 | { 8 | public string CurrentUsername { get; set; } 9 | public string Gender { get; set; } 10 | public int MinAge { get; set; } = 18; 11 | public int MaxAge { get; set; } = 100; 12 | 13 | public string OrderBy { get; set; } = "lastActive"; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /EmailService/EmailConfiguration.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace EmailService 6 | { 7 | public class EmailConfiguration 8 | { 9 | public string From { get; set; } 10 | public string SmtpServer { get; set; } 11 | public int Port { get; set; } 12 | public string UserName { get; set; } 13 | public string Password { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /client/src/app/confirm-password-sent/confirm-password-sent.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-confirm-password-sent', 5 | templateUrl: './confirm-password-sent.component.html', 6 | styleUrls: ['./confirm-password-sent.component.css'] 7 | }) 8 | export class ConfirmPasswordSentComponent implements OnInit { 9 | 10 | constructor() { } 11 | 12 | ngOnInit(): void { 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /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 | interest?: any; 15 | city: string; 16 | country: string; 17 | photos: Photo[]; 18 | } 19 | 20 | -------------------------------------------------------------------------------- /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 | .nv-file-over{ 7 | border: dotted 3px red; 8 | } 9 | 10 | input[type=file] { 11 | color: transparent; 12 | } 13 | 14 | .not-approved { 15 | opacity: 0.2; 16 | } 17 | 18 | .img-wrapper { 19 | position: relative; 20 | } 21 | 22 | .img-text { 23 | position: absolute; 24 | bottom: 30%; 25 | } -------------------------------------------------------------------------------- /client/src/app/modals/confirm-dialog/confirm-dialog.component.html: -------------------------------------------------------------------------------- 1 | 4 | 7 | -------------------------------------------------------------------------------- /client/src/app/confirmation-email-sent/confirmation-email-sent.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-confirmation-email-sent', 5 | templateUrl: './confirmation-email-sent.component.html', 6 | styleUrls: ['./confirmation-email-sent.component.css'] 7 | }) 8 | export class ConfirmationEmailSentComponent implements OnInit { 9 | 10 | constructor() { } 11 | 12 | ngOnInit(): void { 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /client/src/app/reset-password-complete/reset-password-complete.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-reset-password-complete', 5 | templateUrl: './reset-password-complete.component.html', 6 | styleUrls: ['./reset-password-complete.component.css'] 7 | }) 8 | export class ResetPasswordCompleteComponent implements OnInit { 9 | 10 | constructor() { } 11 | 12 | ngOnInit(): void { 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /API/DTOs/MemberUpdateDTO.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace API.DTOs 7 | { 8 | public class MemberUpdateDTO 9 | { 10 | public string Introduction { get; set; } 11 | public string LookingFor { get; set; } 12 | public string Interest { get; set; } 13 | public string City { get; set; } 14 | public string Country { get; set; } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /API/Interfaces/ILikeRepository.cs: -------------------------------------------------------------------------------- 1 | using API.DTOs; 2 | using API.Entities; 3 | using API.Helpers; 4 | using System.Collections.Generic; 5 | using System.Threading.Tasks; 6 | 7 | namespace API.Interfaces 8 | { 9 | public interface ILikeRepository 10 | { 11 | Task GetUserLike(int sourceUserId, int likeUserId); 12 | Task GetUserWithLikes(int userId); 13 | Task> GetUserLikes(LikesParams likesParams); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /EmailService/EmailService.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /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/DTOs/LikeDTO.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace API.DTOs 7 | { 8 | public class LikeDTO 9 | { 10 | public int Id { get; set; } 11 | public string Username { get; set; } 12 | public int Age { get; set; } 13 | public string KnownAs { get; set; } 14 | public string PhotoUrl { get; set; } 15 | public string City { get; set; } 16 | 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /API/Data/ForgotPasswordRepository.cs: -------------------------------------------------------------------------------- 1 | using EmailService; 2 | using System.Threading.Tasks; 3 | 4 | namespace API.Data 5 | 6 | { 7 | public class ForgotPasswordRepository : IEmailSender 8 | { 9 | public void SendEmail(Message message) 10 | { 11 | throw new System.NotImplementedException(); 12 | } 13 | 14 | public Task SendEmailAsync(Message message) 15 | { 16 | throw new System.NotImplementedException(); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /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 | public Group(string name) 12 | { 13 | Name = name; 14 | } 15 | 16 | [Key] 17 | public string Name { get; set; } 18 | public ICollection Connections { get; set; } = new List(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /API/Extentions/ClaimsPrincipleExtentions.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 | } 18 | 19 | -------------------------------------------------------------------------------- /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 int MyProperty { get; set; } 10 | public string Url { get; set; } 11 | public bool IsMain { get; set; } 12 | public bool IsApproved { get; set; } 13 | public string PublicId { get; set; } 14 | public AppUser AppUser { get; set; } 15 | public int AppUserId { get; set; } 16 | } 17 | } -------------------------------------------------------------------------------- /client/src/app/_forms/date-input/date-input.component.html: -------------------------------------------------------------------------------- 1 |
2 | 12 |
{{label}} is required
13 |
14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /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/src/app/admin/user-management/user-management.component.html: -------------------------------------------------------------------------------- 1 |
2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |
UsernameActive Roles
{{user.username}}{{user.roles}}
14 |
15 | -------------------------------------------------------------------------------- /API/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "ConnectionStrings": { 3 | "DefaultConnection": "Server=localhost; Port=5432; User Id=appuser; Password=Passw0rd; Database=datingapp;" 4 | }, 5 | "TokenKey": "super secret unguessable token key", 6 | "Logging": { 7 | "LogLevel": { 8 | "Default": "Information", 9 | "Microsoft": "information", 10 | "Microsoft.Hosting.Lifetime": "Information" 11 | } 12 | }, 13 | "ReturnPaths": { 14 | "ConfirmEmail": "https://localhost:5001/confirm-email", 15 | "PasswordChange": "https://localhost:5001/reset-password" 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /API/wwwroot/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Dating App 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /API/Helpers/PaginationHeader.cs: -------------------------------------------------------------------------------- 1 | 2 | namespace API.Helpers 3 | { 4 | public class PaginationHeader 5 | { 6 | public PaginationHeader(int currentPage, int itemsPerPage, int totalItems, int totalPages) 7 | { 8 | CurrentPage = currentPage; 9 | ItemsPerPage = itemsPerPage; 10 | TotalItems = totalItems; 11 | TotalPages = totalPages; 12 | } 13 | 14 | public int CurrentPage { get; set; } 15 | public int ItemsPerPage { get; set; } 16 | public int TotalItems { get; set; } 17 | public int TotalPages { get; set; } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /client/src/app/admin/photo-management/photo-management.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |

{{photo.username | titlecase}}

4 | {{photo.username}} 5 |
6 | 7 |
8 |
9 | 10 |
11 |
12 |
13 | -------------------------------------------------------------------------------- /API/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "information", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "CloudinarySettings": { 10 | "CloudName": "tonymatute", 11 | "ApiKey": "471616553398763", 12 | "ApiSecret": "ykGXniBfsDDq3fdCQAO1f7espJk" 13 | }, 14 | "EmailConfiguration": { 15 | "From": "AppDating@comcast.com", 16 | "SmtpServer": "smtp.comcast.net", 17 | "Port": 465, 18 | "Username": "tony.matute@comcast.net", 19 | "Password": "Tm$654.8933.P1" 20 | }, 21 | "AllowedHosts": "*" 22 | } 23 | -------------------------------------------------------------------------------- /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 | 18 | ngOnInit(): void { 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /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 |
17 | -------------------------------------------------------------------------------- /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 | resolve(route: ActivatedRouteSnapshot): Observable { 14 | return this.memberService.getMember(route.paramMap.get('username')); 15 | } 16 | 17 | } -------------------------------------------------------------------------------- /client/src/app/nav/nav.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { Router } from '@angular/router'; 3 | import { Observable } from 'rxjs'; 4 | import {AccountService} from '../_services/account.service' 5 | 6 | @Component({ 7 | selector: 'app-nav', 8 | templateUrl: './nav.component.html', 9 | styleUrls: ['./nav.component.css'] 10 | }) 11 | export class NavComponent implements OnInit { 12 | 13 | model: any = {}; 14 | 15 | constructor( 16 | public accountService: AccountService, 17 | private router: Router) { } 18 | 19 | ngOnInit(): void { 20 | } 21 | 22 | logout() { 23 | this.accountService.logout(); 24 | this.router.navigateByUrl('/') 25 | }; 26 | 27 | } 28 | -------------------------------------------------------------------------------- /client/src/app/_forms/text-input/text-input.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, Input, 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 | writeValue(obj: any): void {} 17 | registerOnChange(fn: any): void {} 18 | registerOnTouched(fn: any): void {} 19 | 20 | 21 | 22 | 23 | } 24 | -------------------------------------------------------------------------------- /client/e2e/src/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { AppPage } from './app.po'; 2 | import { browser, logging } from 'protractor'; 3 | 4 | describe('workspace-project App', () => { 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/src/app/_services/busy.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { NgxSpinnerService } from 'ngx-spinner'; 3 | 4 | 5 | @Injectable({ 6 | providedIn: 'root' 7 | }) 8 | export class BusyService { 9 | busyRequestCount = 0; 10 | 11 | constructor(private spinnerService: NgxSpinnerService) { } 12 | 13 | busy() { 14 | this.busyRequestCount++; 15 | this.spinnerService.show(undefined, { 16 | type: 'line-scale-party', 17 | bdColor: 'rgba(255,255,255,0)', 18 | color: '#333333' 19 | }); 20 | } 21 | 22 | idle() { 23 | this.busyRequestCount--; 24 | if (this.busyRequestCount <= 0) { 25 | this.busyRequestCount = 0 26 | this.spinnerService.hide(); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /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 | 9 | public int SenderId { get; set; } 10 | public string SenderUsername { get; set; } 11 | public AppUser Sender { get; set; } 12 | 13 | public int RecipientId { get; set; } 14 | public string RecipientUsername { get; set; } 15 | public AppUser Recipient { get; set; } 16 | 17 | public string Content { get; set; } 18 | public DateTime? DateRead { get; set; } 19 | public DateTime MessageSent { get; set; } = DateTime.UtcNow; 20 | public bool SenderDeleted { get; set; } 21 | public bool RecipientDeleted { get; set; } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /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/_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/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 | } -------------------------------------------------------------------------------- /API/Helpers/HttpExtensions.cs: -------------------------------------------------------------------------------- 1 | 2 | using Microsoft.AspNetCore.Http; 3 | using System.Text.Json; 4 | 5 | namespace API.Helpers 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 { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; 15 | 16 | response.Headers.Add("Pagination", JsonSerializer.Serialize(paginationHeader, options)); 17 | response.Headers.Add("Access-Control-Expose-Headers", "Pagination"); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /API/Interfaces/IUserRepository.cs: -------------------------------------------------------------------------------- 1 | using API.DTOs; 2 | using API.Entities; 3 | using API.Helpers; 4 | using System.Collections.Generic; 5 | using System.Threading.Tasks; 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, bool isCurrentUser); 17 | Task GetUserGender(string username); 18 | Task GetUserByPhotoId(int photoId); 19 | Task GetUserByEmailAsync(string email); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /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/dist/zone-error'; // Included with Angular CLI. 19 | -------------------------------------------------------------------------------- /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 Interest { get; set; } 19 | public string City { get; set; } 20 | public string Country { get; set; } 21 | public ICollection Photos { get; set; } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /client/src/app/_guards/prevent-unsaved-changes.guard.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { CanDeactivate} 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 | canDeactivate(component: MemberEditComponent): Observable | boolean { 14 | if (component.editForm.dirty) { 15 | return this.confirmService.confirm('Warning', 'Are you sure you want to continue? Any Unsaved changes will be lost!', 'Ok', 'Cancel'); 16 | } 17 | return true; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /client/src/app/_guards/auth.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 { AccountService } from '../_services/account.service'; 6 | import { map } from 'rxjs/operators'; 7 | 8 | @Injectable({ 9 | providedIn: 'root' 10 | }) 11 | export class AuthGuard implements CanActivate { 12 | constructor(private accountService: AccountService, 13 | private toastr: ToastrService ) { } 14 | 15 | canActivate(): Observable { 16 | return this.accountService.currentUser$.pipe( 17 | map(user => { 18 | if (user) return true; 19 | this.toastr.error('You shall not pass!!'); 20 | }) 21 | ); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /client/src/app/errors/test-errors/test-errors.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 |
    9 |
  • 10 | {{error}} 11 |
  • 12 |
13 |
14 |
15 | -------------------------------------------------------------------------------- /API/DTOs/RegisterDto.cs: -------------------------------------------------------------------------------- 1 | 2 | using System; 3 | using System.ComponentModel.DataAnnotations; 4 | 5 | namespace API.DTOs 6 | { 7 | public class RegisterDto 8 | { 9 | [Required] 10 | public string Username { get; set; } 11 | [Required] 12 | public string KnownAs { get; set; } 13 | [Required] 14 | public string City { get; set; } 15 | [Required] 16 | public string Country { get; set; } 17 | [Required] 18 | public string Gender { get; set; } 19 | [Required] 20 | public DateTime DateOfBirth { get; set; } 21 | 22 | [Required] 23 | [StringLength(8, MinimumLength = 4)] 24 | public string Password { get; set; } 25 | [Required] 26 | public string Email { get; set; } 27 | public bool confirmedEmail { get; set; } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /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/dist/zone-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 | -------------------------------------------------------------------------------- /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 | 10 | public int SenderId { get; set; } 11 | public string SenderUsername { get; set; } 12 | public string SenderPhotoUrl { get; set; } 13 | 14 | public int RecipientId { get; set; } 15 | public string RecipientUsername { get; set; } 16 | public string RecipientPhotoUrl { get; set; } 17 | 18 | public string Content { get; set; } 19 | public DateTime? DateRead { get; set; } 20 | public DateTime MessageSent { get; set; } 21 | 22 | [JsonIgnore] 23 | public bool SenderDeleted { get; set; } 24 | 25 | [JsonIgnore] 26 | public bool RecipientDeleted { get; set; } 27 | 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /EmailService/Message.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Http; 2 | using MimeKit; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | 8 | namespace EmailService 9 | { 10 | public class Message 11 | { 12 | public List To { get; set; } 13 | public string Subject { get; set; } 14 | public string Content { get; set; } 15 | 16 | public IFormFileCollection Attachments { get; set; } 17 | 18 | public Message(IEnumerable to, string subject, string content, IFormFileCollection attachments) 19 | { 20 | To = new List(); 21 | 22 | To.AddRange(to.Select(x => new MailboxAddress(x))); 23 | Subject = subject; 24 | Content = content; 25 | Attachments = attachments; 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /client/.gitignore: -------------------------------------------------------------------------------- 1 | # See http://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # SSL files 4 | ssl 5 | 6 | # compiled output 7 | /dist 8 | /tmp 9 | /out-tsc 10 | # Only exists if Bazel was run 11 | /bazel-out 12 | 13 | # dependencies 14 | /node_modules 15 | 16 | # profiling files 17 | chrome-profiler-events*.json 18 | speed-measure-plugin*.json 19 | 20 | # IDEs and editors 21 | /.idea 22 | .project 23 | .classpath 24 | .c9/ 25 | *.launch 26 | .settings/ 27 | *.sublime-workspace 28 | 29 | # IDE - VSCode 30 | .vscode/* 31 | !.vscode/settings.json 32 | !.vscode/tasks.json 33 | !.vscode/launch.json 34 | !.vscode/extensions.json 35 | .history/* 36 | 37 | # misc 38 | /.sass-cache 39 | /connect.lock 40 | /coverage 41 | /libpeerconnection.log 42 | npm-debug.log 43 | yarn-error.log 44 | testem.log 45 | /typings 46 | 47 | # System Files 48 | .DS_Store 49 | Thumbs.db 50 | -------------------------------------------------------------------------------- /API/Interfaces/IMessageRepository.cs: -------------------------------------------------------------------------------- 1 | using API.DTOs; 2 | using API.Entities; 3 | using API.Helpers; 4 | using System.Collections.Generic; 5 | using System.Threading.Tasks; 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 | } 23 | -------------------------------------------------------------------------------- /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:57780", 8 | "sslPort": 44362 9 | } 10 | }, 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchBrowser": false, 15 | "launchUrl": "weatherforecast", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | } 19 | }, 20 | "API": { 21 | "commandName": "Project", 22 | "launchBrowser": false, 23 | "launchUrl": "weatherforecast", 24 | "applicationUrl": "https://localhost:5001;http://localhost:5000", 25 | "environmentVariables": { 26 | "ASPNETCORE_ENVIRONMENT": "Development" 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /client/.browserslistrc: -------------------------------------------------------------------------------- 1 | # This file is used by the build system to adjust CSS and JS output to support the specified browsers below. 2 | # For additional information regarding the format and rule options, please see: 3 | # https://github.com/browserslist/browserslist#queries 4 | 5 | # For the full list of supported browsers by the Angular framework, please see: 6 | # https://angular.io/guide/browser-support 7 | 8 | # You can see what browsers were selected by your queries by running: 9 | # npx browserslist 10 | 11 | last 1 Chrome version 12 | last 1 Firefox version 13 | last 2 Edge major versions 14 | last 2 Safari major versions 15 | last 2 iOS major versions 16 | Firefox ESR 17 | not IE 9-10 # Angular support for IE 9-10 has been deprecated and will be removed as of Angular v11. To opt-in, remove the 'not' prefix on this line. 18 | not IE 11 # Angular supports IE 11 only as an opt-in. To opt-in, remove the 'not' prefix on this line. 19 | -------------------------------------------------------------------------------- /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 | 13 | constructor(private accountService: AccountService, private toastr: ToastrService) { } 14 | 15 | canActivate(): Observable { 16 | return this.accountService.currentUser$.pipe( 17 | map(user => { 18 | if (user.roles.includes('Admin') || user.roles.includes("Moderator")) { 19 | return true; 20 | } 21 | this.toastr.error('You cannot enter this area!') 22 | }) 23 | ) 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /client/src/app/errors/server-error/server-error.component.html: -------------------------------------------------------------------------------- 1 |
2 |

Internal Server Error

3 |

Refreshing the page will make this error dissapear!

4 |
5 | 6 |
Error: {{error.message}}
7 |

Note: if you are seeing this error then Angular is probably not to blame.

8 |

What to do next:

9 |
    10 |
  1. Open browser development Tools
  2. 11 |
  3. Inspect the Network tab
  4. 12 |
  5. Checking the failing request
  6. 13 |
  7. Examine the request URL - make sure it is correct!
  8. 14 |
  9. Reproduce the error in Postman - if we see the same response, then the issue is not in Angular
  10. 15 |
16 |

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

17 | {{error.details}} 18 |
-------------------------------------------------------------------------------- /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 | .card img{ 8 | transform: scale(1.0, 1.0); 9 | transition-duration: 500ms; 10 | transition-timing-function: ease-out; 11 | } 12 | .card-img-wrapper { 13 | overflow: hidden; 14 | position: relative; 15 | } 16 | .member-icons { 17 | position: absolute; 18 | bottom: -30%; 19 | left: 0; 20 | right: 0; 21 | margin-right: auto; 22 | margin-left: auto ; 23 | opacity: 0; 24 | } 25 | .card-img-wrapper:hover .member-icons { 26 | bottom: 0; 27 | opacity: 1; 28 | } 29 | 30 | .animate{ 31 | transition: all 0.3s ease-in-out; 32 | } 33 | 34 | @keyframes fa-blink { 35 | 0% {opacity: 1;} 36 | 100% {opacity: 0.4;} 37 | } 38 | .is-online { 39 | animation: fa-blink 1.5s linear infinite; 40 | color: green; 41 | } -------------------------------------------------------------------------------- /API/Helpers/LogUserActivity.cs: -------------------------------------------------------------------------------- 1 | using API.Extensions; 2 | using API.Interfaces; 3 | using Microsoft.AspNetCore.Mvc.Filters; 4 | using System.Threading.Tasks; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using System; 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 | if (!resultContext.HttpContext.User.Identity.IsAuthenticated) return; 16 | 17 | int userId = resultContext.HttpContext.User.GetUserId(); 18 | 19 | var repository = resultContext.HttpContext.RequestServices.GetService(); 20 | var user = await repository.UserRepository.GetUserByIdAsync(userId); 21 | user.LastActive = DateTime.UtcNow; 22 | await repository.Complete(); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /client/src/app/home/home.component.ts: -------------------------------------------------------------------------------- 1 | import { HttpClient } from '@angular/common/http'; 2 | import { Component, OnInit } from '@angular/core'; 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 | loginMode = false; 12 | formMode = false; 13 | 14 | constructor() { } 15 | 16 | ngOnInit(): void { 17 | 18 | } 19 | 20 | loginToggle(){ 21 | this.loginMode = !this.loginMode; 22 | this.formMode = this.loginMode; 23 | } 24 | registerToggle() { 25 | this.registerMode = !this.registerMode; 26 | this.formMode = this.registerMode; 27 | } 28 | 29 | cancelRegisterMode(event: boolean) { 30 | this.registerMode = event; 31 | this.formMode = this.registerMode; 32 | } 33 | 34 | cancelLoginMode(event: boolean) { 35 | this.loginMode = event; 36 | this.formMode = this.loginMode; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /client/src/app/_forms/date-input/date-input.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, Input, 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: 'MM/DD/YYYY', 20 | isAnimated: true, 21 | adaptivePosition: true 22 | } 23 | } 24 | 25 | writeValue(obj: any): void {} 26 | registerOnChange(fn: any): void {} 27 | registerOnTouched(fn: any): void { } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /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 | this.accountService.currentUser$.pipe(take(1)).subscribe(user => currentUser = user); 21 | if (currentUser) { 22 | request = request.clone({ 23 | setHeaders: { 24 | Authorization: `Bearer ${currentUser.token}` 25 | } 26 | }) 27 | } 28 | return next.handle(request); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /client/src/app/members/member-card/member-card.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, Input, OnInit } 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( 16 | private memberService: MembersService, 17 | private toastr: ToastrService, 18 | public presence: PresenceService) { } 19 | 20 | ngOnInit(): void { 21 | 22 | } 23 | 24 | addlike(member: Member) { 25 | this.memberService.addLike(member.username).subscribe(() => { 26 | this.toastr.success("You have liked " + member.knownAs); 27 | }) 28 | } 29 | 30 | 31 | } 32 | -------------------------------------------------------------------------------- /client/e2e/protractor.conf.js: -------------------------------------------------------------------------------- 1 | // @ts-check 2 | // Protractor configuration file, see link for more information 3 | // https://github.com/angular/protractor/blob/master/lib/config.ts 4 | 5 | const { SpecReporter, StacktraceOption } = require('jasmine-spec-reporter'); 6 | 7 | /** 8 | * @type { import("protractor").Config } 9 | */ 10 | exports.config = { 11 | allScriptsTimeout: 11000, 12 | specs: [ 13 | './src/**/*.e2e-spec.ts' 14 | ], 15 | capabilities: { 16 | browserName: 'chrome' 17 | }, 18 | directConnect: true, 19 | baseUrl: 'http://localhost:4200/', 20 | framework: 'jasmine', 21 | jasmineNodeOpts: { 22 | showColors: true, 23 | defaultTimeoutInterval: 30000, 24 | print: function() {} 25 | }, 26 | onPrepare() { 27 | require('ts-node').register({ 28 | project: require('path').join(__dirname, './tsconfig.json') 29 | }); 30 | jasmine.getEnv().addReporter(new SpecReporter({ 31 | spec: { 32 | displayStacktrace: StacktraceOption.PRETTY 33 | } 34 | })); 35 | } 36 | }; -------------------------------------------------------------------------------- /client/src/app/list/list.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-list', 8 | templateUrl: './list.component.html', 9 | styleUrls: ['./list.component.css'] 10 | }) 11 | export class ListComponent implements OnInit { 12 | members: Partial; 13 | predicate: string = 'liked'; 14 | pageNumber: number = 1; 15 | pageSize: number = 5; 16 | pagination: Pagination; 17 | 18 | constructor(private memberServices: MembersService) { } 19 | 20 | ngOnInit(): void { 21 | this.loadLikes() 22 | } 23 | 24 | 25 | loadLikes() { 26 | this.memberServices.getLikes(this.predicate,this.pageNumber,this.pageSize).subscribe(response => { 27 | this.members = response.result; 28 | this.pagination = response.pagination; 29 | }) 30 | } 31 | 32 | pageChanged(event: any) { 33 | this.pageNumber = event.page; 34 | this.loadLikes(); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /API/Data/UnitOfWork.cs: -------------------------------------------------------------------------------- 1 | using API.Interfaces; 2 | using AutoMapper; 3 | using System.Threading.Tasks; 4 | 5 | namespace API.Data 6 | { 7 | public class UnitOfWork : IUnitOfWork 8 | { 9 | private readonly DataContext _context; 10 | private readonly IMapper _mapper; 11 | 12 | public UnitOfWork(DataContext context, IMapper mapper) 13 | { 14 | _context = context; 15 | _mapper = mapper; 16 | } 17 | 18 | public IUserRepository UserRepository => new UserRepository(_context, _mapper); 19 | 20 | public IMessageRepository MessageRepository => new MessageRepository(_context, _mapper); 21 | 22 | public ILikeRepository LikeRepository => new LikesRepository(_context); 23 | 24 | public IPhotoRepository PhotoRepository => new PhotoRepository(_context); 25 | 26 | public async Task Complete() 27 | { 28 | return await _context.SaveChangesAsync() > 0; 29 | } 30 | 31 | public bool HasChanges() 32 | { 33 | return _context.ChangeTracker.HasChanges(); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /client/README.md: -------------------------------------------------------------------------------- 1 | # Client 2 | 3 | This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 10.1.7. 4 | 5 | ## Development server 6 | 7 | Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. 8 | 9 | ## Code scaffolding 10 | 11 | Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`. 12 | 13 | ## Build 14 | 15 | Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build. 16 | 17 | ## Running unit tests 18 | 19 | Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). 20 | 21 | ## Running end-to-end tests 22 | 23 | Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/). 24 | 25 | ## Further help 26 | 27 | To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md). 28 | -------------------------------------------------------------------------------- /client/src/app/_services/paginationHelper.ts: -------------------------------------------------------------------------------- 1 | import { HttpClient, HttpParams } from '@angular/common/http'; 2 | import { map } from 'rxjs/operators'; 3 | import { PaginateResult } from '../_models/pagination'; 4 | 5 | export function getPaginationHeaders(pageNumber: number, pageSize: number) { 6 | let params = new HttpParams(); 7 | 8 | params = params.append('pageNumber', pageNumber.toString()); 9 | params = params.append('pageSize', pageSize.toString()); 10 | 11 | return params; 12 | } 13 | 14 | export function getPaginationResult(url: string, params: HttpParams, http: HttpClient) { 15 | const paginateResult: PaginateResult = new PaginateResult(); 16 | 17 | return http 18 | .get(url, { observe: 'response', params }) 19 | .pipe( 20 | map((response) => { 21 | paginateResult.result = response.body; 22 | if (response.headers.get('Pagination') !== null) { 23 | paginateResult.pagination = JSON.parse( 24 | response.headers.get('Pagination') 25 | ); 26 | } 27 | return paginateResult; 28 | }) 29 | ); 30 | } -------------------------------------------------------------------------------- /client/src/app/_forms/text-input/text-input.component.html: -------------------------------------------------------------------------------- 1 |
2 | 8 |
Please enter a {{label}}
9 |
{{label}} must be at least {{ngControl.control.errors.minlength['requiredLength']}} characters
11 |
{{label}} must be at most {{ngControl.control.errors.maxlength['requiredLength']}} characters
13 |
Passwords do not match
14 |
Please provide a valid email address
15 |
Emails do not match
16 |
-------------------------------------------------------------------------------- /client/src/app/members/member-messages/member-messages.component.ts: -------------------------------------------------------------------------------- 1 | import { Message } from 'src/app/_models/message'; 2 | import { ChangeDetectionStrategy, Component, Input, OnInit, ViewChild } from '@angular/core'; 3 | import { MessageService } from 'src/app/_services/message.service'; 4 | import { NgForm } from '@angular/forms'; 5 | 6 | @Component({ 7 | changeDetection: ChangeDetectionStrategy.OnPush, 8 | selector: 'app-member-messages', 9 | templateUrl: './member-messages.component.html', 10 | styleUrls: ['./member-messages.component.css'] 11 | }) 12 | export class MemberMessagesComponent implements OnInit { 13 | @ViewChild('messageForm') messageForm: NgForm; 14 | @Input() messages: Message[]; 15 | @Input() username: string; 16 | messageContent: string; 17 | loading: boolean = false; 18 | 19 | constructor(public messageService: MessageService) { } 20 | 21 | ngOnInit(): void { } 22 | 23 | sendMessage() { 24 | this.loading = true; 25 | this.messageService.sendMessage(this.username, this.messageContent).then(() => { 26 | this.messageForm.reset(); 27 | }).finally(() => this.loading = false); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /API/Entities/AppUser.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Identity; 2 | using System; 3 | using System.Collections.Generic; 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.UtcNow; 12 | public DateTime LastActive { get; set; } = DateTime.UtcNow; 13 | public string Gender { get; set; } 14 | public string Introduction { get; set; } 15 | public string LookingFor { get; set; } 16 | public string Interest { 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 | 27 | public ICollection UserRoles { get; set; } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /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( 14 | private viewContainerRef: ViewContainerRef, 15 | private templateRef: TemplateRef, 16 | private accountService: AccountService 17 | ) { 18 | this.accountService.currentUser$.pipe(take(1)).subscribe(user => { 19 | this.user = user; 20 | }) 21 | } 22 | 23 | ngOnInit(): void { 24 | //clear the view if not roles 25 | if (!this.user?.roles || this.user == null) { 26 | this.viewContainerRef.clear(); 27 | return; 28 | } 29 | if (this.user?.roles.some(r => this.appHasRole.includes(r))) { 30 | this.viewContainerRef.createEmbeddedView(this.templateRef); 31 | } else { 32 | this.viewContainerRef.clear(); 33 | }; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /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 { Photo } from '../_models/photo'; 5 | import { User } from '../_models/user'; 6 | 7 | @Injectable({ 8 | providedIn: 'root' 9 | }) 10 | export class AdminService { 11 | baseUrl = environment.apiUrl; 12 | 13 | 14 | constructor(private http: HttpClient) { } 15 | 16 | getUsersWithRoles() { 17 | return this.http.get>(this.baseUrl + "admin/users-with-roles"); 18 | } 19 | 20 | updateUserRoles(username: string, roles: string[]) { 21 | return this.http.post(this.baseUrl + 'admin/edit-roles/' + username + '?roles=' + roles, {}); 22 | } 23 | 24 | getPhotoForApproval() { 25 | return this.http.get(this.baseUrl + "admin/photos-to-moderate"); 26 | } 27 | 28 | approvePhoto(photoId: number) { 29 | return this.http.post(this.baseUrl + 'admin/approve-photo/' + photoId, {}); 30 | } 31 | 32 | rejectPhoto(photoId: number) { 33 | return this.http.post(this.baseUrl + 'admin/reject-photo/' + photoId,{}); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /API/Helpers/AutomapperProfiles.cs: -------------------------------------------------------------------------------- 1 | using API.DTOs; 2 | using API.Entities; 3 | using API.Extentions; 4 | using AutoMapper; 5 | using System; 6 | using System.Linq; 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 => 23 | opt.MapFrom(src => src.Sender.Photos.FirstOrDefault(x => x.IsMain).Url)) 24 | .ForMember(dest => dest.RecipientPhotoUrl, 25 | opt => opt.MapFrom(src => src.Recipient.Photos.FirstOrDefault(x => x.IsMain).Url)); 26 | 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /API/Helpers/PageList.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | namespace API.Helpers 8 | { 9 | public class PageList : List 10 | { 11 | public PageList(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, int pageSize) 26 | { 27 | var count = await source.CountAsync(); 28 | var items = await source.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToListAsync(); 29 | return new PageList(items, count, pageNumber, pageSize); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /client/src/app/admin/photo-management/photo-management.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { Photo } from 'src/app/_models/photo'; 3 | import { AdminService } from 'src/app/_services/admin.service'; 4 | 5 | @Component({ 6 | selector: 'app-photo-management', 7 | templateUrl: './photo-management.component.html', 8 | styleUrls: ['./photo-management.component.css'] 9 | }) 10 | export class PhotoManagementComponent implements OnInit { 11 | photos: Photo[]; 12 | 13 | constructor(private adminService: AdminService) { } 14 | 15 | ngOnInit(): void { 16 | this.getPhotosForApproval(); 17 | } 18 | 19 | getPhotosForApproval() { 20 | this.adminService.getPhotoForApproval().subscribe(photos => { 21 | this.photos = photos; 22 | }) 23 | } 24 | 25 | approvePhoto(photoId: number) { 26 | this.adminService.approvePhoto(photoId).subscribe(() => { 27 | this.photos.splice(this.photos.findIndex(p => p.id === photoId), 1); 28 | }) 29 | } 30 | rejectPhoto(photoId: number) { 31 | this.adminService.rejectPhoto(photoId).subscribe(() => { 32 | this.photos.splice(this.photos.findIndex(p => p.id === photoId), 1); 33 | }) 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /client/src/app/modals/roles-modal/roles-modal.component.html: -------------------------------------------------------------------------------- 1 | 7 | 23 | 27 | -------------------------------------------------------------------------------- /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/list/list.component.html: -------------------------------------------------------------------------------- 1 |
2 |

3 | {{predicate==='liked' ? 'Member I like' : 'Member who like me'}} 4 |

5 |
6 |
7 |
8 |
9 | 11 | 13 |
14 |
15 |
16 |
17 | 18 |
19 |
20 |
21 |
22 | 25 |
26 | -------------------------------------------------------------------------------- /client/src/styles.css: -------------------------------------------------------------------------------- 1 | .tab-panel { 2 | border: 1px solid #ddd; 3 | padding: 10px; 4 | border-radius: 4px; 5 | } 6 | 7 | .nav-tabs > li.open, .member-tabset > .nav-tabs > li:hover { 8 | border-bottom: 4px solid #fbcdcf; 9 | } 10 | 11 | .member-tabset > .nav-tabs > li.open > a, .member-tabset > .nav-tabs > li:hover > a { 12 | border: 0; 13 | background: none !important; 14 | color: #333333; 15 | } 16 | 17 | .member-tabset > .nav-tabs > li.open > a > i, .member-tabset > .nav-tabs > li:hover > a > i { 18 | color: #a6a6a6; 19 | } 20 | 21 | .member-tabset > .nav-tabs > li.open .dropdown-menu, .member-tabset > .nav-tabs > li:hover .dropdown-menu { 22 | margin-top: 0px; 23 | } 24 | 25 | .member-tabset > .nav-tabs > li.active { 26 | border-bottom: 4px solid #E95420; 27 | position: relative; 28 | } 29 | 30 | .member-tabset > .nav-tabs > li.active > a { 31 | border: 0 !important; 32 | color: #333333; 33 | } 34 | 35 | .member-tabset > .nav-tabs > li.active > a > i { 36 | color: #404040; 37 | } 38 | 39 | .member-tabset > .tab-content { 40 | margin-top: -3px; 41 | background-color: #fff; 42 | border: 0; 43 | border-top: 1px solid #eee; 44 | padding: 15px 0; 45 | } 46 | -------------------------------------------------------------------------------- /client/src/app/confirm-email/confirm-email.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { ActivatedRoute } from '@angular/router'; 3 | import { ToastrService } from 'ngx-toastr'; 4 | import { AccountService } from '../_services/account.service'; 5 | 6 | @Component({ 7 | selector: 'app-confirm-email', 8 | templateUrl: './confirm-email.component.html', 9 | styleUrls: ['./confirm-email.component.css'], 10 | }) 11 | export class ConfirmEmailComponent implements OnInit { 12 | emailConfirmed: boolean = false; 13 | urlParams: any = {}; 14 | 15 | constructor( 16 | private route: ActivatedRoute, 17 | private accountService: AccountService, 18 | private toastrService: ToastrService 19 | ) {} 20 | 21 | ngOnInit(): void { 22 | this.urlParams.token = this.route.snapshot.queryParamMap.get('token'); 23 | this.urlParams.userid = this.route.snapshot.queryParamMap.get('userid'); 24 | this.confirmEmail(); 25 | } 26 | 27 | confirmEmail() { 28 | this.accountService.confirmEmail(this.urlParams).subscribe(() => { 29 | this.toastrService.success("Email Confirmed succesful"); 30 | this.emailConfirmed = true; 31 | }, (error) => { 32 | this.toastrService.error("Unable to confirm your email!"); 33 | this.emailConfirmed = false; 34 | }) 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /API/Controllers/BuggyController.cs: -------------------------------------------------------------------------------- 1 | using API.Data; 2 | using API.Entities; 3 | using Microsoft.AspNetCore.Authorization; 4 | using Microsoft.AspNetCore.Mvc; 5 | using System; 6 | 7 | namespace API.Controllers 8 | { 9 | public class BuggyController : BaseAPIController 10 | { 11 | private readonly DataContext _context; 12 | 13 | public BuggyController(DataContext context) 14 | { 15 | _context = context; 16 | } 17 | 18 | [Authorize] 19 | [HttpGet("auth")] 20 | public ActionResult GetSecret() 21 | { 22 | return "secret text"; 23 | } 24 | 25 | [HttpGet("not-found")] 26 | public ActionResult GetNotFound() 27 | { 28 | var thing = _context.Users.Find(-1); 29 | if (thing == null) return NotFound(); 30 | return Ok(thing); 31 | } 32 | 33 | [HttpGet("server-error")] 34 | public ActionResult GetServerError() 35 | { 36 | var thing = _context.Users.Find(-1); 37 | var thingToReturn = thing.ToString(); 38 | return thingToReturn; 39 | } 40 | 41 | [HttpGet("bad-request")] 42 | public ActionResult GetBadRequest() 43 | { 44 | return BadRequest("This is not a good request."); 45 | } 46 | } 47 | } -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /.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/SignalR/PresenceHub.cs: -------------------------------------------------------------------------------- 1 | using API.Extensions; 2 | using Microsoft.AspNetCore.Authorization; 3 | using Microsoft.AspNetCore.SignalR; 4 | using System; 5 | using System.Threading.Tasks; 6 | 7 | namespace API.SignalR 8 | { 9 | [Authorize] 10 | public class PresenceHub : Hub 11 | { 12 | private readonly PresenceTracker _tracker; 13 | 14 | public PresenceHub(PresenceTracker tracker) 15 | { 16 | _tracker = tracker; 17 | } 18 | 19 | public override async Task OnConnectedAsync() 20 | { 21 | var isOnline = await _tracker.UserConnected(Context.User.GetUsername(), Context.ConnectionId); 22 | if (isOnline) 23 | await Clients.Others.SendAsync("UserIsOnline", Context.User.GetUsername()); 24 | 25 | var currentUsers = await _tracker.GetOnlineUsers(); 26 | await Clients.Caller.SendAsync("GetOnlineUsers", currentUsers); 27 | } 28 | 29 | public override async Task OnDisconnectedAsync(Exception exception) 30 | { 31 | var isOffline = await _tracker.UserDisconnected(Context.User.GetUsername(), Context.ConnectionId); 32 | if (isOffline) 33 | await Clients.Others.SendAsync("UserIsOffline", Context.User.GetUsername()); 34 | 35 | await base.OnDisconnectedAsync(exception); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /client/src/app/reset-password/reset-password.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 |
5 |

Reset Password

6 |
7 |
8 |
9 |
10 | 12 |
13 |
14 | 16 |
17 |
18 | 20 |
21 |
22 |
23 | 24 |
25 |
26 |
-------------------------------------------------------------------------------- /API/Data/PhotoRepository.cs: -------------------------------------------------------------------------------- 1 | using API.DTOs; 2 | using API.Entities; 3 | using API.Interfaces; 4 | using System.Collections.Generic; 5 | using System.Threading.Tasks; 6 | using System.Linq; 7 | using Microsoft.EntityFrameworkCore; 8 | 9 | namespace API.Data 10 | { 11 | public class PhotoRepository : IPhotoRepository 12 | { 13 | private readonly DataContext _context; 14 | 15 | public PhotoRepository(DataContext context) 16 | { 17 | _context = context; 18 | } 19 | 20 | public async Task GetPhotoById(int id) 21 | { 22 | return await _context.Photos 23 | .IgnoreQueryFilters() 24 | .SingleOrDefaultAsync(x => x.id == id); 25 | } 26 | 27 | public async Task> GetUnapprovedPhotos() 28 | { 29 | return await _context.Photos 30 | .IgnoreQueryFilters() 31 | .Where(p => p.IsApproved == false) 32 | .Select(u => new PhotoForApprovalDto 33 | { 34 | id = u.id, 35 | Username = u.AppUser.UserName, 36 | Url = u.Url, 37 | IsApproved = u.IsApproved 38 | }).ToListAsync(); 39 | } 40 | 41 | public void RemovePhoto(Photo photo) 42 | { 43 | _context.Photos.Remove(photo); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /client/src/app/login/login.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, EventEmitter, OnInit, Output } from '@angular/core'; 2 | import { FormBuilder, FormGroup, Validators } from '@angular/forms'; 3 | import { Router } from '@angular/router'; 4 | import { ToastrService } from 'ngx-toastr'; 5 | import { AccountService } from '../_services/account.service'; 6 | 7 | 8 | @Component({ 9 | selector: 'app-login', 10 | templateUrl: './login.component.html', 11 | styleUrls: ['./login.component.css'] 12 | }) 13 | export class LoginComponent implements OnInit { 14 | @Output() cancelLogin = new EventEmitter(); 15 | loginForm: FormGroup; 16 | model: any = {}; 17 | validationErrors: string[] = []; 18 | 19 | constructor( 20 | private accountService: AccountService, 21 | private fb: FormBuilder, 22 | private router: Router) { } 23 | 24 | ngOnInit(): void { 25 | this.initializeForm(); 26 | } 27 | 28 | initializeForm() { 29 | this.loginForm = this.fb.group({ 30 | username: ['', Validators.required], 31 | password: ['', [ 32 | Validators.required 33 | ]], 34 | }) 35 | } 36 | 37 | login() { 38 | this.accountService.login(this.model).subscribe(response => { 39 | this.router.navigateByUrl('/members'); 40 | }); 41 | } 42 | 43 | cancel() { 44 | this.cancelLogin.emit(false); 45 | } 46 | 47 | forgotPassword() { 48 | this.router.navigateByUrl('../forgot-password/'); 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /API/wwwroot/runtime.acf0dec4155e77772545.js: -------------------------------------------------------------------------------- 1 | !function(e){function r(r){for(var n,l,f=r[0],i=r[1],p=r[2],c=0,s=[];c 2 | 3 | 4 | netcoreapp3.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | all 15 | runtime; build; native; contentfiles; analyzers; buildtransitive 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /.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/netcoreapp3.1/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 | } -------------------------------------------------------------------------------- /client/src/app/forgot-password/forgot-password.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { 3 | FormBuilder, 4 | FormControl, 5 | FormGroup, 6 | Validators, 7 | } from '@angular/forms'; 8 | import { Router } from '@angular/router'; 9 | import { AccountService } from '../_services/account.service'; 10 | 11 | @Component({ 12 | selector: 'app-forgot-password', 13 | templateUrl: './forgot-password.component.html', 14 | styleUrls: ['./forgot-password.component.css'], 15 | }) 16 | export class ForgotPasswordComponent implements OnInit { 17 | forgotPasswordForm: FormGroup; 18 | email: FormControl; 19 | validationErrors: string[] = []; 20 | 21 | constructor( 22 | private accountService: AccountService, 23 | private fb: FormBuilder, 24 | private router: Router 25 | ) {} 26 | 27 | ngOnInit(): void { 28 | this.email = new FormControl('', [ 29 | Validators.required, 30 | Validators.pattern('^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$'), 31 | Validators.email, 32 | ]); 33 | this.forgotPasswordForm = this.fb.group({ 34 | email: this.email, 35 | }); 36 | } 37 | 38 | cancel() { 39 | this.router.navigateByUrl('/'); 40 | } 41 | 42 | resetPassword() { 43 | let emailInfo = this.forgotPasswordForm.value; 44 | this.accountService.sendForgotPasswordEmail(emailInfo).subscribe( 45 | (respond) => { 46 | this.router.navigateByUrl('/confirm-password-sent'); 47 | }, 48 | (error) => { 49 | this.validationErrors = error; 50 | } 51 | ); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /client/src/app/login/login.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 |
5 |

Login

6 |
7 |
8 |
9 |
10 | 12 |
13 |
14 | 16 |
17 |
18 | 19 |
20 |
21 |
22 | 26 |
27 |
28 |
-------------------------------------------------------------------------------- /client/src/app/members/member-card/member-card.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 | {{member.knownAs}} 4 |
    5 |
  • 6 | 9 |
  • 10 |
  • 11 | 14 |
  • 15 |
  • 16 | 21 |
  • 22 |
23 |
24 |
25 |
26 | 27 | 28 | 29 | {{member.knownAs}}, {{member.age}} 30 |
31 |

32 | {{member.city}}, {{member.country}} 33 |

34 |
35 |
36 | -------------------------------------------------------------------------------- /DatingApp.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.30611.23 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "API", "API\API.csproj", "{64B1FEDA-0C65-487D-B4D2-91FC5E932AA5}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EmailService", "EmailService\EmailService.csproj", "{22B19990-26EE-4981-B479-D11D53F8F43E}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {64B1FEDA-0C65-487D-B4D2-91FC5E932AA5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {64B1FEDA-0C65-487D-B4D2-91FC5E932AA5}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {64B1FEDA-0C65-487D-B4D2-91FC5E932AA5}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {64B1FEDA-0C65-487D-B4D2-91FC5E932AA5}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {22B19990-26EE-4981-B479-D11D53F8F43E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {22B19990-26EE-4981-B479-D11D53F8F43E}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {22B19990-26EE-4981-B479-D11D53F8F43E}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {22B19990-26EE-4981-B479-D11D53F8F43E}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {37E4BA09-8A1A-428A-8EE7-CB8C2D7FCA79} 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /client/src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { HttpClient } from '@angular/common/http'; 2 | import { Component, OnDestroy, OnInit } from '@angular/core'; 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( 17 | private accountService: AccountService, 18 | private presence: PresenceService 19 | ) {} 20 | ngOnInit() { 21 | this.setCurrentUser(); 22 | } 23 | 24 | setCurrentUser() { 25 | const user: User = JSON.parse(localStorage.getItem('user')); 26 | if (user) { 27 | this.accountService.setCurrentUser(user); 28 | this.presence.createHubConnection(user); 29 | this.onBeforeUnload(); 30 | this.OnUnload(); 31 | } 32 | } 33 | onBeforeUnload() { 34 | let context = this; 35 | window.addEventListener('beforeunload', function (e) { 36 | let user: User = JSON.parse(localStorage.getItem('user')); 37 | if (user) { 38 | context.logoutOnClose(); 39 | } 40 | }); 41 | } 42 | 43 | OnUnload() { 44 | let context = this; 45 | window.addEventListener('onunload', function (e) { 46 | let user: User = JSON.parse(localStorage.getItem('user')); 47 | if (user) { 48 | context.logoutOnClose(); 49 | } 50 | }); 51 | } 52 | 53 | logoutOnClose() { 54 | this.accountService.logout(); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /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', 'Delete Messages cannot be undo, do you want to continue?').subscribe(result => { 37 | if (result) { 38 | this.messageService.deleteMessage(id).subscribe(() => { 39 | this.messages.splice(this.messages.findIndex(i => i.id === id), 1); 40 | }) 41 | } 42 | }); 43 | } 44 | 45 | pageChanged(event: any) { 46 | this.pageNumber = event.page; 47 | this.loadMessages(); 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /client/src/app/members/member-edit/member-edit.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, HostListener, OnInit, ViewChild } from '@angular/core'; 2 | import { NgForm } from '@angular/forms'; 3 | import { ToastrService } from 'ngx-toastr'; 4 | import { take } from 'rxjs/operators'; 5 | import { Member } from 'src/app/_models/member'; 6 | import { User } from 'src/app/_models/user'; 7 | import { AccountService } from 'src/app/_services/account.service'; 8 | import { MembersService } from 'src/app/_services/members.service'; 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( 20 | $event: any 21 | ) { 22 | if (this.editForm.dirty) { 23 | $event.returnValue = true; 24 | } 25 | } 26 | 27 | constructor( 28 | private accountService: AccountService, 29 | private memberService: MembersService, 30 | private toastx: ToastrService 31 | ) { 32 | this.accountService.currentUser$ 33 | .pipe(take(1)) 34 | .subscribe((user) => (this.user = user)); 35 | } 36 | 37 | ngOnInit(): void { 38 | this.loadMember(); 39 | } 40 | 41 | loadMember() { 42 | this.memberService.getMember(this.user.username).subscribe((member) => { 43 | this.member = member; 44 | }); 45 | } 46 | 47 | updateMember() { 48 | this.memberService.updateMember(this.member).subscribe(() => { 49 | this.toastx.success('Profile Updated Successfuly.'); 50 | this.editForm.reset(this.member); 51 | }); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /client/src/app/members/member-list/member-list.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { Observable } from 'rxjs'; 3 | import { take } from 'rxjs/operators'; 4 | import { Member } from 'src/app/_models/member'; 5 | import { Pagination } from 'src/app/_models/pagination'; 6 | import { User } from 'src/app/_models/user'; 7 | import { UserParams } from 'src/app/_models/userParams'; 8 | import { AccountService } from 'src/app/_services/account.service'; 9 | import { MembersService } from 'src/app/_services/members.service'; 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: 'Male' }, { value: 'female', display: 'Female' }]; 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 | pageChanged(event: any) { 40 | this.userParams.pageNumber = event.page; 41 | this.memberService.setUserParams(this.userParams); 42 | this.loadMembers(); 43 | } 44 | 45 | resetFilter() { 46 | this.userParams = this.memberService.resetUserParams(); 47 | this.loadMembers(); 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /client/src/app/errors/test-errors/test-errors.component.ts: -------------------------------------------------------------------------------- 1 | import { HttpClient } from '@angular/common/http'; 2 | import { Component, OnInit } from '@angular/core'; 3 | import { environment } from 'src/environments/environment.prod'; 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/nav/nav.component.html: -------------------------------------------------------------------------------- 1 | 33 | -------------------------------------------------------------------------------- /API/Middleware/ExceptionMiddleware.cs: -------------------------------------------------------------------------------- 1 | using API.Errors; 2 | using Microsoft.AspNetCore.Http; 3 | using Microsoft.Extensions.Hosting; 4 | using Microsoft.Extensions.Logging; 5 | using System; 6 | using System.Net; 7 | using System.Text.Json; 8 | using System.Threading.Tasks; 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 | 18 | public ExceptionMiddleware(RequestDelegate next, 19 | ILogger logger, 20 | IHostEnvironment env) 21 | { 22 | _next = next; 23 | _logger = logger; 24 | _env = env; 25 | } 26 | 27 | public async Task InvokeAsync(HttpContext context) 28 | { 29 | try 30 | { 31 | await _next(context); 32 | } 33 | catch (Exception ex) 34 | { 35 | _logger.LogError(ex, ex.Message); 36 | context.Response.ContentType = "application/json"; 37 | context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; 38 | var response = _env.IsDevelopment() 39 | ? new ApiException(context.Response.StatusCode, ex.Message, ex.StackTrace?.ToString()) 40 | : new ApiException(context.Response.StatusCode, "Internal Server Error"); 41 | 42 | var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; 43 | var json = JsonSerializer.Serialize(response, options); 44 | await context.Response.WriteAsync(json); 45 | } 46 | 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /API/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using API.Data; 6 | using API.Entities; 7 | using Microsoft.AspNetCore.Hosting; 8 | using Microsoft.AspNetCore.Identity; 9 | using Microsoft.EntityFrameworkCore; 10 | using Microsoft.Extensions.Configuration; 11 | using Microsoft.Extensions.DependencyInjection; 12 | using Microsoft.Extensions.Hosting; 13 | using Microsoft.Extensions.Logging; 14 | 15 | namespace API 16 | { 17 | public class Program 18 | { 19 | public static async Task Main(string[] args) 20 | { 21 | var host = CreateHostBuilder(args).Build(); 22 | using var scope = host.Services.CreateScope(); 23 | var services = scope.ServiceProvider; 24 | try 25 | { 26 | var context = services.GetRequiredService(); 27 | var userManager = services.GetRequiredService>(); 28 | var roleManager = services.GetRequiredService>(); 29 | await context.Database.MigrateAsync(); 30 | await Seed.SeedUsers(userManager, roleManager); 31 | } 32 | catch (Exception ex) 33 | { 34 | var logger = services.GetRequiredService>(); 35 | logger.LogError(ex, "An Error Occurred during MIgration."); 36 | } 37 | await host.RunAsync(); 38 | } 39 | 40 | public static IHostBuilder CreateHostBuilder(string[] args) => 41 | Host.CreateDefaultBuilder(args) 42 | .ConfigureWebHostDefaults(webBuilder => 43 | { 44 | webBuilder.UseStartup(); 45 | }); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /API/Services/PhotoService.cs: -------------------------------------------------------------------------------- 1 | using API.Helpers; 2 | using API.Interfaces; 3 | using CloudinaryDotNet; 4 | using CloudinaryDotNet.Actions; 5 | using Microsoft.AspNetCore.Http; 6 | using Microsoft.Extensions.Options; 7 | using System.Threading.Tasks; 8 | using Newtonsoft.Json; 9 | 10 | namespace API.Services 11 | { 12 | public class PhotoService : IPhotoService 13 | { 14 | private readonly Cloudinary _cloudinary; 15 | 16 | public PhotoService(IOptions config) 17 | { 18 | var acc = new Account 19 | ( 20 | config.Value.CloudName, 21 | config.Value.ApiKey, 22 | config.Value.ApiSecret 23 | ); 24 | _cloudinary = new Cloudinary(acc); 25 | 26 | } 27 | 28 | public async Task AddPhotoAsync(IFormFile file) 29 | { 30 | var uploadResult = new ImageUploadResult(); 31 | if (file.Length > 0) 32 | { 33 | using var stream = file.OpenReadStream(); 34 | var uploadParams = new ImageUploadParams 35 | { 36 | File = new FileDescription(file.FileName, stream), 37 | Transformation = new Transformation().Height(500).Width(500).Crop("fill").Gravity("face") 38 | }; 39 | uploadResult = await _cloudinary.UploadAsync(uploadParams); 40 | } 41 | return uploadResult; 42 | } 43 | 44 | public async Task DeletePhotoAsync(string publicId) 45 | { 46 | var deleteParams = new DeletionParams(publicId); 47 | var deleteResult = await _cloudinary.DestroyAsync(deleteParams); 48 | return deleteResult; 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /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": "~10.1.6", 15 | "@angular/cdk": "^10.2.6", 16 | "@angular/common": "~10.1.6", 17 | "@angular/compiler": "~10.1.6", 18 | "@angular/core": "~10.1.6", 19 | "@angular/forms": "~10.1.6", 20 | "@angular/platform-browser": "~10.1.6", 21 | "@angular/platform-browser-dynamic": "~10.1.6", 22 | "@angular/router": "~10.1.6", 23 | "@kolkov/ngx-gallery": "^1.2.3", 24 | "@microsoft/signalr": "^5.0.0", 25 | "@types/jquery": "^3.5.4", 26 | "bootstrap": "4.1.1", 27 | "bootswatch": "^4.5.3", 28 | "font-awesome": "^4.7.0", 29 | "jquery": "^3.5.1", 30 | "ng2-file-upload": "^1.4.0", 31 | "ngx-bootstrap": "^6.1.0", 32 | "ngx-cookie-service": "^10.1.1", 33 | "ngx-spinner": "^10.0.1", 34 | "ngx-timeago": "^2.0.0", 35 | "ngx-toastr": "^13.1.0", 36 | "rxjs": "~6.6.0", 37 | "tslib": "^2.0.0", 38 | "zone.js": "~0.10.2" 39 | }, 40 | "devDependencies": { 41 | "@angular-devkit/build-angular": "~0.1001.7", 42 | "@angular/cli": "~10.1.7", 43 | "@angular/compiler-cli": "~10.1.6", 44 | "@types/node": "^12.11.1", 45 | "@types/jasmine": "~3.5.0", 46 | "@types/jasminewd2": "~2.0.3", 47 | "codelyzer": "^6.0.0", 48 | "jasmine-core": "~3.6.0", 49 | "jasmine-spec-reporter": "~5.0.0", 50 | "karma": "~5.0.0", 51 | "karma-chrome-launcher": "~3.1.0", 52 | "karma-coverage-istanbul-reporter": "~3.0.2", 53 | "karma-jasmine": "~4.0.0", 54 | "karma-jasmine-html-reporter": "^1.5.0", 55 | "protractor": "~7.0.0", 56 | "ts-node": "~8.3.0", 57 | "tslint": "~6.1.0", 58 | "typescript": "~4.0.2" 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /client/src/app/forgot-password/forgot-password.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 |
5 |

Reset Password

6 |
7 |
8 |
9 |
10 |
11 | 12 |
13 | 15 | 16 |
17 |
18 | 20 | 21 |
22 |
23 |
24 | Email is required. 25 |
26 |
27 |
28 |
29 | 34 |
35 |
36 |
-------------------------------------------------------------------------------- /API/Services/TokenService.cs: -------------------------------------------------------------------------------- 1 | using API.Entities; 2 | using API.Interfaces; 3 | using Microsoft.AspNetCore.Identity; 4 | using Microsoft.Extensions.Configuration; 5 | using Microsoft.IdentityModel.Tokens; 6 | using System; 7 | using System.Collections.Generic; 8 | using System.IdentityModel.Tokens.Jwt; 9 | using System.Linq; 10 | using System.Security.Claims; 11 | using System.Text; 12 | using System.Threading.Tasks; 13 | using JwtRegisteredClaimNames = Microsoft.IdentityModel.JsonWebTokens.JwtRegisteredClaimNames; 14 | 15 | namespace API.Services 16 | { 17 | public class TokenService : ITokenService 18 | { 19 | private readonly SymmetricSecurityKey _key; 20 | private readonly UserManager _userManager; 21 | 22 | public TokenService(IConfiguration config, UserManager userManager) 23 | { 24 | _key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["TokenKey"])); 25 | _userManager = userManager; 26 | } 27 | 28 | public async Task CreateToken(AppUser user) 29 | { 30 | var claims = new List 31 | { 32 | new Claim(JwtRegisteredClaimNames.NameId, user.Id.ToString()), 33 | new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName) 34 | }; 35 | 36 | var roles = await _userManager.GetRolesAsync(user); 37 | 38 | claims.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role))); 39 | 40 | 41 | var creds = new SigningCredentials(_key, SecurityAlgorithms.HmacSha512Signature); 42 | 43 | var tokenDecripton = new SecurityTokenDescriptor 44 | { 45 | Subject = new ClaimsIdentity(claims), 46 | Expires = DateTime.UtcNow.AddDays(1), 47 | SigningCredentials = creds 48 | }; 49 | 50 | var tokenHandler = new JwtSecurityTokenHandler(); 51 | var token = tokenHandler.CreateToken(tokenDecripton); 52 | 53 | return tokenHandler.WriteToken(token); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /API/Data/Seed.cs: -------------------------------------------------------------------------------- 1 | using API.Entities; 2 | using Microsoft.AspNetCore.Identity; 3 | using Microsoft.EntityFrameworkCore; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text.Json; 7 | using System.Threading.Tasks; 8 | 9 | namespace API.Data 10 | { 11 | public class Seed 12 | { 13 | public static async Task SeedUsers(UserManager userManager, 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 = "Admin"}, 24 | new AppRole{Name = "Member"}, 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.Photos.First().IsApproved = true; 36 | user.UserName = user.UserName.ToLower(); 37 | user.EmailConfirmed = true; 38 | await userManager.CreateAsync(user, "Pa$$w0rd"); 39 | await userManager.AddToRoleAsync(user, "Member"); 40 | } 41 | 42 | var admin = new AppUser 43 | { 44 | UserName = "admin", 45 | EmailConfirmed = true 46 | 47 | }; 48 | 49 | // Create Admin User and confirm email flag to true 50 | await userManager.CreateAsync(admin, "Pa$$w0rd"); 51 | var token = await userManager.GenerateEmailConfirmationTokenAsync(admin); 52 | await userManager.ConfirmEmailAsync(admin, token); 53 | await userManager.AddToRolesAsync(admin, new[] { "Admin", "Moderator" }); 54 | 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /API/Helpers/URLBuilder.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using System.Web; 4 | 5 | namespace API.Helpers 6 | { 7 | public static class URLBuilder 8 | { 9 | public enum MessageType 10 | { 11 | ConfirmEmail = 0, 12 | ResetPassword = 1 13 | }; 14 | 15 | public static string BuildUrl(string urlPath, string token, string userId) 16 | { 17 | var uriBuilder = new UriBuilder(urlPath); 18 | var query = HttpUtility.ParseQueryString(uriBuilder.Query); 19 | query["token"] = token; 20 | query["userid"] = userId; 21 | uriBuilder.Query = query.ToString(); 22 | return uriBuilder.ToString(); 23 | } 24 | public static string BuildContext(MessageType messageType, string link, string username) 25 | { 26 | 27 | var usernameToTittleCase = CultureInfo.InvariantCulture.TextInfo.ToTitleCase(username); 28 | string contextMessage = ""; 29 | switch (messageType) 30 | { 31 | case MessageType.ConfirmEmail: 32 | contextMessage = string.Format("Dear {0}

We are Happy you register with us.
" + 33 | "Please click on the link below or copy the link to your browser to confirm your email address.
" + 34 | "This confirm email link is only valid for the next 24 hours.


", usernameToTittleCase) + link; 35 | break; 36 | case MessageType.ResetPassword: 37 | contextMessage = string.Format("Dear {0}

You recently request to reset your password account.
" + 38 | "Please click on the link below or copy the link to your browser to reset it.
" + 39 | "This password reset link is only valid for the next 24 hours.


", usernameToTittleCase) + link; 40 | break; 41 | } 42 | 43 | return contextMessage; 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /API/Controllers/LikesController.cs: -------------------------------------------------------------------------------- 1 | using API.DTOs; 2 | using API.Entities; 3 | using API.Extensions; 4 | using API.Helpers; 5 | using API.Interfaces; 6 | using Microsoft.AspNetCore.Authorization; 7 | using Microsoft.AspNetCore.Mvc; 8 | using System.Collections.Generic; 9 | using System.Threading.Tasks; 10 | 11 | namespace API.Controllers 12 | { 13 | [Authorize] 14 | public class LikesController : BaseAPIController 15 | { 16 | private readonly IUnitOfWork _unitOfWork; 17 | 18 | public LikesController(IUnitOfWork unitOfWork) 19 | { 20 | _unitOfWork = unitOfWork; 21 | } 22 | 23 | [HttpPost("{username}")] 24 | public async Task AddLike(string username) 25 | { 26 | var sourceUserId = User.GetUserId(); 27 | var likedUser = await _unitOfWork.UserRepository.GetUserByUsernameAsync(username); 28 | var sourceUser = await _unitOfWork.LikeRepository.GetUserWithLikes(sourceUserId); 29 | 30 | if (likedUser == null) return NotFound(); 31 | if (sourceUser.UserName == username) return BadRequest(" You cannot like yourself"); 32 | 33 | var userLike = await _unitOfWork.LikeRepository.GetUserLike(sourceUserId, likedUser.Id); 34 | if (userLike != null) return BadRequest("You already like this user"); 35 | 36 | userLike = new UserLike 37 | { 38 | SourceUserId = sourceUserId, 39 | LikedUserId = likedUser.Id 40 | }; 41 | 42 | sourceUser.LikedUsers.Add(userLike); 43 | 44 | if (await _unitOfWork.Complete()) return Ok(); 45 | 46 | return BadRequest("Failed to like this user"); 47 | 48 | } 49 | 50 | [HttpGet] 51 | public async Task>> GetUserLikes([FromQuery]LikesParams likeParams) 52 | { 53 | likeParams.UserId = User.GetUserId(); 54 | 55 | var users = await _unitOfWork.LikeRepository.GetUserLikes(likeParams); 56 | 57 | Response.AddPaginationHeader(users.CurrentPage, users.PageSize,users.TotalCount, users.TotalPages); 58 | 59 | return Ok(users); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /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.start().catch((error) => console.log(error)); 30 | 31 | this.hubConnection.on('UserIsOnline', (username) => { 32 | this.onlineUsers$.pipe(take(1)).subscribe(usernames => { 33 | this.onlineUsersSource.next([...usernames, username]); 34 | }) 35 | }); 36 | 37 | this.hubConnection.on('UserIsOffline', (username) => { 38 | this.onlineUsers$.pipe(take(1)).subscribe(usernames => { 39 | this.onlineUsersSource.next([...usernames.filter(x => x !== username)]); 40 | }) 41 | }); 42 | 43 | this.hubConnection.on('GetOnlineUsers', (username) => { 44 | this.onlineUsersSource.next(username); 45 | }); 46 | 47 | this.hubConnection.on('NewMessageReceived', ({ username, knownAs }) => { 48 | this.toastr.info(knownAs + ' has sent you a new message!') 49 | .onTap 50 | .pipe(take(1)).subscribe(() => this.router.navigateByUrl('/members/' + username + '?tab=3')); 51 | }); 52 | } 53 | 54 | stopHubConnection() { 55 | if (this.hubConnection) { 56 | this.hubConnection.stop().catch((error) => console.log(error)); 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /API/Startup.cs: -------------------------------------------------------------------------------- 1 | using API.Extentions; 2 | using API.MiddleWare; 3 | using API.SignalR; 4 | using EmailService; 5 | using Microsoft.AspNetCore.Builder; 6 | using Microsoft.AspNetCore.Hosting; 7 | using Microsoft.Extensions.Configuration; 8 | using Microsoft.Extensions.DependencyInjection; 9 | 10 | namespace API { 11 | public class Startup { 12 | private readonly IConfiguration _config; 13 | 14 | public Startup (IConfiguration config) { 15 | _config = config; 16 | } 17 | 18 | // This method gets called by the runtime. Use this method to add services to the container. 19 | public void ConfigureServices (IServiceCollection services) { 20 | services.AddApplicationServices (_config); 21 | services.AddControllers (); 22 | services.AddCors (); 23 | services.AddIdentityServices (_config); 24 | services.AddSignalR (); 25 | var emailConfig = _config 26 | .GetSection ("EmailConfiguration") 27 | .Get (); 28 | services.AddSingleton (emailConfig); 29 | services.AddScoped (); 30 | 31 | } 32 | 33 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 34 | public void Configure (IApplicationBuilder app, IWebHostEnvironment env) { 35 | app.UseMiddleware (); 36 | 37 | app.UseHttpsRedirection (); 38 | 39 | app.UseRouting (); 40 | 41 | app.UseCors (policy => policy.AllowAnyHeader () 42 | .AllowAnyMethod () 43 | .AllowCredentials () 44 | .WithOrigins ("https://localhost:5001")); 45 | 46 | app.UseAuthentication (); 47 | app.UseAuthorization (); 48 | 49 | app.UseDefaultFiles (); 50 | app.UseStaticFiles (); 51 | 52 | app.UseEndpoints (endpoints => { 53 | endpoints.MapControllers (); 54 | endpoints.MapHub ("hubs/presence"); 55 | endpoints.MapHub ("hubs/message"); 56 | endpoints.MapFallbackToController("Index", "Fallback"); 57 | }); 58 | } 59 | } 60 | } -------------------------------------------------------------------------------- /API/Data/LikesRepository.cs: -------------------------------------------------------------------------------- 1 | using API.DTOs; 2 | using API.Entities; 3 | using API.Extentions; 4 | using API.Helpers; 5 | using API.Interfaces; 6 | using Microsoft.EntityFrameworkCore; 7 | using System.Collections.Generic; 8 | using System.Linq; 9 | using System.Threading.Tasks; 10 | 11 | namespace API.Data 12 | { 13 | public class LikesRepository : ILikeRepository 14 | { 15 | private readonly DataContext _context; 16 | 17 | public LikesRepository(DataContext context) 18 | { 19 | _context = context; 20 | } 21 | 22 | public async Task GetUserLike(int sourceUserId, int likedUserId) 23 | { 24 | return await _context.Likes.FindAsync(sourceUserId, likedUserId); 25 | } 26 | 27 | public async Task> GetUserLikes(LikesParams likesParams) 28 | { 29 | var users = _context.Users.OrderBy(u => u.UserName).AsQueryable(); 30 | var likes = _context.Likes.AsQueryable(); 31 | 32 | if (likesParams.Predicate == "liked") 33 | { 34 | likes = likes.Where(like => like.SourceUserId == likesParams.UserId); 35 | users = likes.Select(like => like.LikedUser); 36 | } 37 | 38 | if (likesParams.Predicate == "likedBy") 39 | { 40 | likes = likes.Where(like => like.LikedUserId == likesParams.UserId); 41 | users = likes.Select(like => like.SourceUser); 42 | } 43 | 44 | var likedUsers = users.Select(user => new LikeDTO 45 | { 46 | Username = user.UserName, 47 | KnownAs = user.KnownAs, 48 | City = user.City, 49 | Age = user.DateOfBirth.CalculateAge(), 50 | PhotoUrl = user.Photos.FirstOrDefault(p => p.IsMain).Url, 51 | Id = user.Id 52 | }); 53 | 54 | return await PageList.CreateAsync(likedUsers, 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(u => u.Id == userId); 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /client/src/app/reset-password/reset-password.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { AbstractControl, FormBuilder, FormGroup, ValidatorFn, Validators } from '@angular/forms'; 3 | import { ActivatedRoute, Router } from '@angular/router'; 4 | import { ToastrService } from 'ngx-toastr'; 5 | import { AccountService } from '../_services/account.service'; 6 | 7 | @Component({ 8 | selector: 'app-reset-password', 9 | templateUrl: './reset-password.component.html', 10 | styleUrls: ['./reset-password.component.css'] 11 | }) 12 | export class ResetPasswordComponent implements OnInit { 13 | resetPasswordForm: FormGroup; 14 | validationErrors: string[] = []; 15 | passwordchanged: boolean = false; 16 | model: any = {}; 17 | 18 | constructor(private accountService: AccountService, 19 | private toastrService: ToastrService, 20 | private route: ActivatedRoute, 21 | private router: Router, 22 | private fb: FormBuilder) { } 23 | 24 | ngOnInit(): void { 25 | this.model.token = this.route.snapshot.queryParamMap.get('token'); 26 | this.model.userid = this.route.snapshot.queryParamMap.get('userid'); 27 | this.initializeForm(); 28 | } 29 | 30 | resetPassword() { 31 | this.model.password = this.resetPasswordForm.value.password; 32 | this.accountService.resetPassword(this.model).subscribe(() => { 33 | this.toastrService.success("Reset Password Sent"); 34 | this.passwordchanged = true; 35 | this.router.navigateByUrl('/reset-password-complete'); 36 | }, (error) => { 37 | this.toastrService.error("Unable to reset your password!"); 38 | this.passwordchanged = false; 39 | }) 40 | } 41 | 42 | initializeForm() { 43 | this.resetPasswordForm = this.fb.group({ 44 | password: [ 45 | '', 46 | [Validators.required, Validators.minLength(8), Validators.maxLength(20)], 47 | ], 48 | confirmPassword: [ 49 | '', 50 | [Validators.required, this.matchPassword('password')], 51 | ] 52 | }); 53 | } 54 | 55 | matchPassword(matchTo: string): ValidatorFn { 56 | return (control: AbstractControl) => { 57 | return control?.value === control?.parent?.controls[matchTo].value 58 | ? null 59 | : { isMatching: true }; 60 | }; 61 | } 62 | 63 | 64 | } 65 | -------------------------------------------------------------------------------- /API/SignalR/PresenceTracker.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using System.Threading.Tasks; 4 | 5 | namespace API.SignalR 6 | { 7 | public class PresenceTracker 8 | { 9 | private static readonly Dictionary> OnLineUsers = 10 | new Dictionary>(); 11 | 12 | public Task UserConnected(string username, string connectionId) 13 | { 14 | bool isOnline = false; 15 | lock (OnLineUsers) 16 | { 17 | if (OnLineUsers.ContainsKey(username)) 18 | { 19 | OnLineUsers[username].Add(connectionId); 20 | } 21 | else 22 | { 23 | OnLineUsers.Add(username, new List { connectionId }); 24 | isOnline = true; 25 | } 26 | } 27 | 28 | return Task.FromResult(isOnline); 29 | } 30 | 31 | public Task UserDisconnected(string username, string connectionId) 32 | { 33 | bool isOffline = false; 34 | lock (OnLineUsers) 35 | { 36 | if (!OnLineUsers.ContainsKey(username)) return Task.FromResult(isOffline); 37 | 38 | OnLineUsers[username].Remove(connectionId); 39 | if (OnLineUsers[username].Count == 0) 40 | { 41 | OnLineUsers.Remove(username); 42 | isOffline = true; 43 | } 44 | } 45 | return Task.FromResult(isOffline); 46 | } 47 | 48 | public Task GetOnlineUsers() 49 | { 50 | string[] onlineUsers; 51 | 52 | lock (OnLineUsers) 53 | { 54 | onlineUsers = OnLineUsers 55 | .OrderBy(k => k.Key) 56 | .Select(k => k.Key) 57 | .ToArray(); 58 | } 59 | return Task.FromResult(onlineUsers); 60 | } 61 | 62 | public Task> GetConnectionForUser(string username) 63 | { 64 | List connectionIds; 65 | lock (OnLineUsers) 66 | { 67 | connectionIds = OnLineUsers.GetValueOrDefault(username); 68 | } 69 | return Task.FromResult(connectionIds); 70 | } 71 | 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /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.getUsersWithRole(); 20 | } 21 | 22 | getUsersWithRole() { 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/members/member-list/member-list.component.html: -------------------------------------------------------------------------------- 1 |
2 |

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

3 |
4 |
5 |
6 |
7 | 8 | 10 |
11 |
12 | 13 | 15 |
16 |
17 | 18 | 23 |
24 | 25 | 26 | 27 |
28 |
29 | 31 | 32 | 34 |
35 |
36 |
37 |
38 |
39 |
40 | 41 |
42 |
43 | 44 |
45 | 48 | 49 |
-------------------------------------------------------------------------------- /client/src/app/_services/account.service.ts: -------------------------------------------------------------------------------- 1 | import { HttpClient } from '@angular/common/http'; 2 | import { Injectable } from '@angular/core'; 3 | import { CookieService } from 'ngx-cookie-service'; 4 | import { of, ReplaySubject } from 'rxjs'; 5 | import { map } from 'rxjs/operators'; 6 | import { environment } from 'src/environments/environment'; 7 | import { User } from '../_models/user'; 8 | import { PresenceService } from './presence.service'; 9 | 10 | @Injectable({ 11 | providedIn: 'root', 12 | }) 13 | export class AccountService { 14 | baseUrl = environment.apiUrl; 15 | private currentUserSource = new ReplaySubject(1); 16 | 17 | currentUser$ = this.currentUserSource.asObservable(); 18 | 19 | constructor( 20 | private http: HttpClient, 21 | private presence: PresenceService, 22 | private cookieService: CookieService 23 | ) {} 24 | 25 | login(model: any) { 26 | return this.http.post(this.baseUrl + 'account/login', model).pipe( 27 | map((response: User) => { 28 | const user = response; 29 | if (user) { 30 | this.setCurrentUser(user); 31 | this.presence.createHubConnection(user); 32 | } 33 | }) 34 | ); 35 | } 36 | 37 | register(model: any) { 38 | return this.http.post(this.baseUrl + 'account/register', model); 39 | } 40 | 41 | setCurrentUser(user: User) { 42 | user.roles = []; 43 | const roles = this.getDecodedToken(user.token).role; 44 | Array.isArray(roles) ? (user.roles = roles) : user.roles.push(roles); 45 | 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 | this.clearCookies(); 55 | } 56 | 57 | getDecodedToken(token) { 58 | return JSON.parse(atob(token.split('.')[1])); 59 | } 60 | 61 | sendForgotPasswordEmail(model:any) { 62 | return this.http.post(this.baseUrl + 'account/forgotpassword' , model); 63 | } 64 | 65 | resetPassword(model:any) { 66 | return this.http.post(this.baseUrl + 'account/resetpassword' , model); 67 | } 68 | 69 | clearCookies() { 70 | localStorage.removeItem('twoFactorToken'); 71 | localStorage.removeItem('codeExpiry'); 72 | localStorage.removeItem('isSessionActive'); 73 | localStorage.removeItem('attemptsRemaining'); 74 | localStorage.removeItem('codeSendSuccess'); 75 | localStorage.removeItem('user'); 76 | } 77 | 78 | 79 | confirmEmail(model: any) { 80 | return this.http.post(this.baseUrl + 'account/confirmemail', model); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /client/src/app/members/member-detail/member-detail.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 | {{member.knownAs}} 5 |
6 |
7 | Online Now 8 |
9 |
10 | Location: 11 |

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

12 |
13 |
14 | Age: 15 |

{{member.age}}

16 |
17 |
18 | Last Activity: 19 |

{{member.lastActive | timeago}}

20 |
21 |
22 | Member since: 23 |

{{member.created | date: 'longDate'}}

24 |
25 |
26 | 32 |
33 |
34 |
35 | 36 | 37 |

Description:

38 |

{{member.introduction}}

39 |

Looking For:

40 |

{{member.lookingFor}}

41 |
42 | 43 |

Interests:

44 |

{{member.introduction}}

45 |
46 | 47 | 51 | 52 | 53 | 54 | 55 |
56 |
57 |
58 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /client/src/app/members/member-messages/member-messages.component.html: -------------------------------------------------------------------------------- 1 |
2 |
6 |
7 | No Messages yet 8 |
9 |
    10 |
  • 11 |
    12 | 13 | {{message.senderUsername}} 17 | 18 |
    19 |
    20 | 21 | {{message.messageSent | timeago}} 22 | 24 | (unread) 25 | 26 | 28 | (read {{message.dateRead | timeago}}) 29 | 30 | 31 |
    32 |

    {{message.content}}

    33 |
    34 |
    35 |
  • 36 |
37 |
38 | 56 |
57 | -------------------------------------------------------------------------------- /API/Extentions/IdentityServiceExtensions.cs: -------------------------------------------------------------------------------- 1 | 2 | using API.Data; 3 | using API.Entities; 4 | using Microsoft.AspNetCore.Authentication.JwtBearer; 5 | using Microsoft.AspNetCore.Identity; 6 | using Microsoft.Extensions.Configuration; 7 | using Microsoft.Extensions.DependencyInjection; 8 | using Microsoft.IdentityModel.Tokens; 9 | using System.Text; 10 | using System.Threading.Tasks; 11 | 12 | namespace API.Extentions 13 | { 14 | public static class IdentityServiceExtensions 15 | { 16 | public static IServiceCollection AddIdentityServices(this IServiceCollection services, IConfiguration config) 17 | { 18 | services.AddIdentityCore(opt => 19 | { 20 | opt.Password.RequireNonAlphanumeric = false; 21 | opt.SignIn.RequireConfirmedEmail = true; 22 | }) 23 | .AddRoles() 24 | .AddRoleManager>() 25 | .AddSignInManager>() 26 | .AddRoleValidator>() 27 | .AddEntityFrameworkStores().AddDefaultTokenProviders(); 28 | 29 | 30 | services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) 31 | .AddJwtBearer(options => 32 | { 33 | options.TokenValidationParameters = new TokenValidationParameters 34 | { 35 | ValidateIssuerSigningKey = true, 36 | IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["TokenKey"])), 37 | ValidateIssuer = false, 38 | ValidateAudience = false 39 | }; 40 | 41 | options.Events = new JwtBearerEvents 42 | { 43 | OnMessageReceived = context => 44 | { 45 | var accessToken = context.Request.Query["access_token"]; 46 | 47 | var path = context.HttpContext.Request.Path; 48 | if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/hubs")) 49 | { 50 | context.Token = accessToken; 51 | } 52 | 53 | return Task.CompletedTask; 54 | } 55 | }; 56 | }); 57 | 58 | services.AddAuthorization(opt => 59 | { 60 | opt.AddPolicy("RequireAdminRole", policy => policy.RequireRole("Admin")); 61 | opt.AddPolicy("ModeratePhotoRole", policy => policy.RequireRole("Admin", "Moderator")); 62 | }); 63 | 64 | return services; 65 | } 66 | 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /client/src/app/register/register.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; 2 | import { 3 | AbstractControl, 4 | FormBuilder, 5 | FormControl, 6 | FormGroup, 7 | ValidatorFn, 8 | Validators, 9 | } from '@angular/forms'; 10 | import { Router } from '@angular/router'; 11 | import { ToastrService } from 'ngx-toastr'; 12 | import { AccountService } from '../_services/account.service'; 13 | 14 | @Component({ 15 | selector: 'app-register', 16 | templateUrl: './register.component.html', 17 | styleUrls: ['./register.component.css'], 18 | }) 19 | export class RegisterComponent implements OnInit { 20 | @Output() cancelRegister = new EventEmitter(); 21 | 22 | registerForm: FormGroup; 23 | maxDate: Date; 24 | validationErrors: string[] = []; 25 | 26 | 27 | constructor( 28 | private accountService: AccountService, 29 | private toastr: ToastrService, 30 | private fb: FormBuilder, 31 | private router: Router 32 | ) {} 33 | 34 | ngOnInit(): void { 35 | this.initializeForm(); 36 | } 37 | 38 | initializeForm() { 39 | this.registerForm = this.fb.group({ 40 | username: ['', Validators.required], 41 | gender: ['male'], 42 | knownAs: ['', Validators.required], 43 | dateOfBirth: ['', Validators.required], 44 | city: ['', Validators.required], 45 | country: ['', Validators.required], 46 | password: [ 47 | '', 48 | [Validators.required, Validators.minLength(8), Validators.maxLength(20)], 49 | ], 50 | confirmPassword: [ 51 | '', 52 | [Validators.required, this.matchPassword('password')], 53 | ], 54 | email: new FormControl('', [ 55 | Validators.required, 56 | Validators.pattern('^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$') 57 | ]), 58 | confirmEmail: new FormControl('', [ 59 | Validators.required, 60 | Validators.pattern('^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$'), 61 | this.matchEmail('email') 62 | ]), 63 | }); 64 | } 65 | 66 | matchEmail(email: string): ValidatorFn { 67 | return (control: AbstractControl) => { 68 | return control?.value === control?.parent?.controls[email].value 69 | ? null 70 | : { emailMatch: true }; 71 | }; 72 | } 73 | matchPassword(matchTo: string): ValidatorFn { 74 | return (control: AbstractControl) => { 75 | return control?.value === control?.parent?.controls[matchTo].value 76 | ? null 77 | : { isMatching: true }; 78 | }; 79 | } 80 | 81 | register() { 82 | this.accountService.register(this.registerForm.value).subscribe( 83 | (response) => { 84 | this.router.navigateByUrl('/confirmation-email-sent'); 85 | }, 86 | (error) => { 87 | this.validationErrors = error; 88 | } 89 | ); 90 | } 91 | cancel() { 92 | this.router.navigateByUrl('/'); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /client/src/app/members/photo-editor/photo-editor.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, Input, OnInit } from '@angular/core'; 2 | import { FileUploader, FileUploadModule } from 'ng2-file-upload'; 3 | import { take } from 'rxjs/operators'; 4 | import { Member } from 'src/app/_models/member'; 5 | import { Photo } from 'src/app/_models/photo'; 6 | import { User } from 'src/app/_models/user'; 7 | import { AccountService } from 'src/app/_services/account.service'; 8 | import { MembersService } from 'src/app/_services/members.service'; 9 | import { environment } from 'src/environments/environment'; 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 | hasAnotherDropZoneOver = false; 21 | baseUrl = environment.apiUrl; 22 | user: User; 23 | 24 | constructor(private accountService: AccountService, private memberService: MembersService) { 25 | this.accountService.currentUser$.pipe(take(1)).subscribe(user => this.user = user); 26 | } 27 | 28 | ngOnInit(): void { 29 | this.initializeUploader(); 30 | 31 | } 32 | 33 | fileOverBase(e:any) { 34 | this.hasBaseDropZoneOver = e; 35 | } 36 | 37 | setMainPhoto(photo: Photo ) { 38 | this.memberService.setMainPhoto(photo.id).subscribe(() => { 39 | this.user.photoUrl = photo.url; 40 | this.accountService.setCurrentUser(this.user); 41 | this.member.photoUrl = photo.url; 42 | this.member.photos.forEach(p => { 43 | if (p.isMain) p.isMain = false; 44 | if (p.id === photo.id) p.isMain = true; 45 | }) 46 | }) 47 | 48 | } 49 | 50 | deletePhoto(photoId: number) { 51 | this.memberService.deletePhoto(photoId).subscribe(() => { 52 | this.member.photos = this.member.photos.filter(x => x.id !== photoId); 53 | }) 54 | } 55 | 56 | initializeUploader() { 57 | this.uploader = new FileUploader({ 58 | url: this.baseUrl + 'users/add-photo', 59 | authToken: 'Bearer ' + this.user.token, 60 | isHTML5: true, 61 | allowedFileType: ['image'], 62 | removeAfterUpload: true, 63 | autoUpload: false, 64 | maxFileSize: 10 * 1024 * 1024 65 | }); 66 | 67 | this.uploader.onAfterAddingFile = (file) => { 68 | file.withCredentials = false; 69 | } 70 | 71 | this.uploader.onSuccessItem = (item, response, status, header) => { 72 | if (response) { 73 | const photo : Photo = JSON.parse(response); 74 | this.member.photos.push(photo); 75 | if (photo.isMain) { 76 | this.user.photoUrl = photo.url; 77 | this.member.photoUrl = photo.url; 78 | this.accountService.setCurrentUser(this.user); 79 | } 80 | } 81 | } 82 | 83 | 84 | 85 | } 86 | 87 | } 88 | -------------------------------------------------------------------------------- /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 { NavigationExtras, Router } 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 | const modalStateErrors = []; 25 | 26 | if (error.error) { 27 | for (const key in error.error) { 28 | if (error.error[key]) { 29 | modalStateErrors.push(error.error[key].description); 30 | } 31 | } 32 | modalStateErrors.flat().forEach(err => { 33 | this.toastr.error(err); 34 | }); 35 | } 36 | else if (error.error.errors) { 37 | for (const key in error.error.errors) { 38 | if (error.error.errors[key]) { 39 | modalStateErrors.push(error.error.errors[key]); 40 | } 41 | } 42 | modalStateErrors.flat().forEach(err => { 43 | this.toastr.error(err); 44 | }); 45 | } else if(typeof(error.error) === 'object') { 46 | this.toastr.error(error.statusText, error.status); 47 | } else { 48 | this.toastr.error(error.error); 49 | } 50 | break; 51 | case 401: 52 | if (error.error) { 53 | this.toastr.error(error.error); 54 | } else { 55 | this.toastr.error("Unauthorized User", error.status); 56 | } 57 | break; 58 | case 404: 59 | this.router.navigateByUrl("/not-found"); 60 | break; 61 | case 500: 62 | const navigationExtras: NavigationExtras = { state: { error: error.error } } 63 | this.router.navigateByUrl("/server-error", navigationExtras); 64 | break; 65 | default: 66 | this.toastr.error("something unexpected went very wrong!"); 67 | console.log(error); 68 | break; 69 | } 70 | } 71 | return throwError(error); 72 | }) 73 | ) 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /API/Extentions/ApplicationServiceExtensions.cs: -------------------------------------------------------------------------------- 1 | using API.Data; 2 | using API.Helpers; 3 | using API.Interfaces; 4 | using API.Services; 5 | using API.SignalR; 6 | using AutoMapper; 7 | using Microsoft.EntityFrameworkCore; 8 | using Microsoft.Extensions.Configuration; 9 | using Microsoft.Extensions.DependencyInjection; 10 | using System; 11 | 12 | namespace API.Extentions 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 | string connStr; 29 | 30 | // Depending on if in development or production, use either Heroku-provided 31 | // connection string, or development connection string from env var. 32 | if (env.ToLower() == "development") 33 | { 34 | // Use connection string from file. 35 | connStr = config.GetConnectionString("DefaultConnection"); 36 | } 37 | else 38 | { 39 | // Use connection string provided at runtime by Heroku. 40 | var connUrl = Environment.GetEnvironmentVariable("DATABASE_URL"); 41 | 42 | // Parse connection URL to connection string for Npgsql 43 | connUrl = connUrl.Replace("postgres://", string.Empty); 44 | var pgUserPass = connUrl.Split("@")[0]; 45 | var pgHostPortDb = connUrl.Split("@")[1]; 46 | var pgHostPort = pgHostPortDb.Split("/")[0]; 47 | var pgDb = pgHostPortDb.Split("/")[1]; 48 | var pgUser = pgUserPass.Split(":")[0]; 49 | var pgPass = pgUserPass.Split(":")[1]; 50 | var pgHost = pgHostPort.Split(":")[0]; 51 | var pgPort = pgHostPort.Split(":")[1]; 52 | 53 | connStr = $"Server={pgHost};Port={pgPort};User Id={pgUser};Password={pgPass};Database={pgDb}"; 54 | } 55 | // Whether the connection string came from the local development configuration file 56 | // or from the environment variable from Heroku, use it to set up your DbContext. 57 | options.UseNpgsql(connStr); 58 | }); 59 | return services; 60 | } 61 | } 62 | } -------------------------------------------------------------------------------- /client/src/app/messages/messages.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 | 6 | 9 | 12 |
13 |
14 |
15 |

No Messages

16 |
17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 29 | 30 | 44 | 45 | 48 | 49 |
MessageFrom / ToSent / Received
{{message.content}} 31 |
32 | {{message.recipientUsername}} 35 | {{message.recipientUsername | titlecase}} 36 |
37 |
38 | {{message.senderUsername}} 41 | {{message.senderUsername | titlecase}} 42 |
43 |
{{message.messageSent | timeago}} 46 | 47 |
50 |
51 |
52 | 63 | 64 |
65 | -------------------------------------------------------------------------------- /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/dist/zone'; // Included with Angular CLI. 59 | 60 | 61 | /*************************************************************************************************** 62 | * APPLICATION IMPORTS 63 | */ 64 | -------------------------------------------------------------------------------- /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 Activity: 25 |

{{member.lastActive | timeago}}

26 |
27 |
28 | Member since: 29 |

{{member.created | date: 'longDate'}}

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

Location:

43 |
44 | 45 | 46 |
47 |

Description:

48 | 50 |

Looking For:

51 | 53 |

Interest:

54 | 56 |
57 |
58 | 59 | 60 | 61 |
62 |
63 | 64 |
-------------------------------------------------------------------------------- /client/src/app/members/member-detail/member-detail.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core'; 2 | import { ActivatedRoute, Router } from '@angular/router'; 3 | import { NgxGalleryAnimation, NgxGalleryImage, NgxGalleryOptions } from '@kolkov/ngx-gallery'; 4 | import { TabDirective, TabsetComponent } from 'ngx-bootstrap/tabs'; 5 | import { take } from 'rxjs/operators'; 6 | import { Member } from 'src/app/_models/member'; 7 | import { Message } from 'src/app/_models/message'; 8 | import { User } from 'src/app/_models/user'; 9 | import { AccountService } from 'src/app/_services/account.service'; 10 | import { MessageService } from 'src/app/_services/message.service'; 11 | import { PresenceService } from 'src/app/_services/presence.service'; 12 | 13 | @Component({ 14 | selector: 'app-member-detail', 15 | templateUrl: './member-detail.component.html', 16 | styleUrls: ['./member-detail.component.css'] 17 | }) 18 | export class MemberDetailComponent implements OnInit, OnDestroy { 19 | @ViewChild('memberTabs', {static: true}) memberTabs: TabsetComponent; 20 | member: Member; 21 | galleryOptions: NgxGalleryOptions[]; 22 | galleryImages: NgxGalleryImage[]; 23 | activeTab: TabDirective; 24 | messages: Message[] = []; 25 | user: User; 26 | 27 | constructor 28 | (public presence: PresenceService, 29 | private route: ActivatedRoute, 30 | private messageService: MessageService, 31 | private accountService: AccountService, 32 | private router: Router) { 33 | this.router.routeReuseStrategy.shouldReuseRoute = () => false; 34 | this.accountService.currentUser$.pipe(take(1)).subscribe(user => this.user = user); 35 | } 36 | 37 | ngOnInit(): void { 38 | this.route.data.subscribe(data => { 39 | this.member = data.member; 40 | }) 41 | 42 | this.route.queryParams.subscribe(params => { 43 | params.tab ? this.selectTab(3) : this.selectTab(0); 44 | }); 45 | 46 | this.galleryOptions = [ 47 | { 48 | width: '500px', 49 | height: '500px', 50 | imagePercent: 100, 51 | thumbnailsColumns: 4, 52 | imageAnimation: NgxGalleryAnimation.Slide, 53 | preview: false 54 | } 55 | ] 56 | 57 | this.galleryImages = this.getImages(); 58 | } 59 | 60 | getImages(): NgxGalleryImage[] { 61 | const imageUrls = []; 62 | for (const photo of this.member.photos) { 63 | imageUrls.push({ 64 | small: photo?.url, 65 | medium: photo?.url, 66 | big: photo?.url 67 | }); 68 | } 69 | return imageUrls; 70 | } 71 | 72 | loadMessages() { 73 | this.messageService.getMessagesThread(this.member.username).subscribe(messages => { 74 | this.messages = messages; 75 | }) 76 | } 77 | 78 | selectTab(tabId: number) { 79 | this.memberTabs.tabs[tabId].active = true; 80 | } 81 | 82 | onTabActivated(data: TabDirective) { 83 | this.activeTab = data; 84 | if (this.activeTab.heading === 'Messages' && this.messages.length === 0) { 85 | this.messageService.createHubConnection(this.user, this.member.username); 86 | } else { 87 | this.messageService.stopHubConnection(); 88 | } 89 | } 90 | 91 | ngOnDestroy(): void { 92 | this.messageService.stopHubConnection(); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /client/src/app/app-routing.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { Routes, RouterModule } from '@angular/router'; 3 | import { AdminPanelComponent } from './admin/admin-panel/admin-panel.component'; 4 | import { ConfirmEmailComponent } from './confirm-email/confirm-email.component'; 5 | import { ConfirmPasswordSentComponent } from './confirm-password-sent/confirm-password-sent.component'; 6 | import { ConfirmationEmailSentComponent } from './confirmation-email-sent/confirmation-email-sent.component'; 7 | import { NotFoundComponent } from './errors/not-found/not-found.component'; 8 | import { ServerErrorComponent } from './errors/server-error/server-error.component'; 9 | import { TestErrorsComponent } from './errors/test-errors/test-errors.component'; 10 | import { ForgotPasswordComponent } from './forgot-password/forgot-password.component'; 11 | import { HomeComponent } from './home/home.component'; 12 | import { ListComponent } from './list/list.component'; 13 | import { MemberDetailComponent } from './members/member-detail/member-detail.component'; 14 | import { MemberEditComponent } from './members/member-edit/member-edit.component'; 15 | import { MemberListComponent } from './members/member-list/member-list.component'; 16 | import { MessagesComponent } from './messages/messages.component'; 17 | import { RegisterComponent } from './register/register.component'; 18 | import { ResetPasswordCompleteComponent } from './reset-password-complete/reset-password-complete.component'; 19 | import { ResetPasswordComponent } from './reset-password/reset-password.component'; 20 | import { AdminGuard } from './_guards/admin.guard'; 21 | import { AuthGuard } from './_guards/auth.guard'; 22 | import { PreventUnsavedChangesGuard } from './_guards/prevent-unsaved-changes.guard'; 23 | import { MemberDetailedResolver } from './_resolvers/member-detailed.resolver'; 24 | 25 | const routes: Routes = [ 26 | { path: '', component: HomeComponent }, 27 | { 28 | path: '', 29 | runGuardsAndResolvers: 'always', 30 | canActivate: [AuthGuard], 31 | children: [ 32 | { path: 'members', component: MemberListComponent }, 33 | { path: 'members/:username', component: MemberDetailComponent, resolve: {member: MemberDetailedResolver} }, 34 | { path: 'member/edit', component: MemberEditComponent , canDeactivate: [PreventUnsavedChangesGuard]}, 35 | { path: 'lists', component: ListComponent }, 36 | { path: 'messages', component: MessagesComponent }, 37 | { path: 'admin', component: AdminPanelComponent, canActivate: [AdminGuard] } 38 | ] 39 | }, 40 | { path: 'errors', component: TestErrorsComponent }, 41 | { path: 'server-error', component: ServerErrorComponent }, 42 | { path: 'not-found', component: NotFoundComponent }, 43 | { path: 'forgot-password', component: ForgotPasswordComponent }, 44 | { path: 'register', component: RegisterComponent }, 45 | { path: 'confirm-email', component: ConfirmEmailComponent }, 46 | { path: 'confirmation-email-sent', component: ConfirmationEmailSentComponent }, 47 | { path: 'confirm-password-sent', component: ConfirmPasswordSentComponent }, 48 | { path: 'reset-password', component: ResetPasswordComponent }, 49 | { path: 'reset-password-complete', component: ResetPasswordCompleteComponent }, 50 | { path: '**', component: NotFoundComponent, pathMatch: 'full' } 51 | ]; 52 | 53 | @NgModule({ 54 | imports: [RouterModule.forRoot(routes)], 55 | exports: [RouterModule] 56 | }) 57 | export class AppRoutingModule { } 58 | -------------------------------------------------------------------------------- /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 { group, table } from 'console'; 5 | import { datepickerAnimation } from 'ngx-bootstrap/datepicker/datepicker-animations'; 6 | import { BehaviorSubject } from 'rxjs'; 7 | import { take } from 'rxjs/operators'; 8 | import { environment } from 'src/environments/environment'; 9 | import { Group } from '../_models/group'; 10 | import { Message } from '../_models/message'; 11 | import { User } from '../_models/user'; 12 | import { BusyService } from './busy.service'; 13 | import { getPaginationHeaders, getPaginationResult } from './paginationHelper'; 14 | 15 | @Injectable({ 16 | providedIn: 'root', 17 | }) 18 | export class MessageService { 19 | baseUrl = environment.apiUrl; 20 | hubUrl = environment.hubUrl; 21 | private hubConnection: HubConnection; 22 | private messageThreadSource = new BehaviorSubject([]); 23 | messageThread$ = this.messageThreadSource.asObservable(); 24 | 25 | constructor(private http: HttpClient, private busyService: BusyService) {} 26 | 27 | createHubConnection(user: User, otherUsername: string) { 28 | this.busyService.busy(); 29 | this.hubConnection = new HubConnectionBuilder() 30 | .withUrl(this.hubUrl + 'message?user=' + otherUsername, { 31 | accessTokenFactory: () => user.token, 32 | }) 33 | .withAutomaticReconnect() 34 | .build(); 35 | 36 | this.hubConnection.start() 37 | .catch((error) => console.log(error)) 38 | .finally(() => this.busyService.idle()); 39 | 40 | this.hubConnection.on('ReceiveMessageThread', (message) => { 41 | this.messageThreadSource.next(message); 42 | }); 43 | 44 | this.hubConnection.on('NewMessage', (message) => { 45 | this.messageThread$.pipe(take(1)).subscribe((messages) => { 46 | this.messageThreadSource.next([...messages, message]); 47 | }); 48 | }); 49 | 50 | this.hubConnection.on('UpdatedGroup', (group: Group) => { 51 | if (group.connection.some((x) => x.username === otherUsername)) { 52 | this.messageThread$.pipe(take(1)).subscribe((messages) => { 53 | messages.forEach((message) => { 54 | if (!message.dateRead) { 55 | message.dateRead = new Date(Date.now()); 56 | } 57 | }); 58 | this.messageThreadSource.next([...messages]); 59 | }); 60 | } 61 | }); 62 | } 63 | 64 | stopHubConnection() { 65 | if (this.hubConnection) { 66 | this.messageThreadSource.next([]); 67 | this.hubConnection.stop().catch((error) => console.log(error)); 68 | } 69 | } 70 | 71 | getMessages(pageNumber, pageSize, container) { 72 | let params = getPaginationHeaders(pageNumber, pageSize); 73 | params = params.append('Container', container); 74 | return getPaginationResult( 75 | this.baseUrl + 'Messages', 76 | params, 77 | this.http 78 | ); 79 | } 80 | 81 | getMessagesThread(username: string) { 82 | return this.http.get( 83 | this.baseUrl + 'messages/thread/' + username 84 | ); 85 | } 86 | 87 | async sendMessage(username: string, content: string) { 88 | return this.hubConnection 89 | .invoke('SendMessage', { recipientUsername: username, content }) 90 | .catch((error) => console.log(error)); 91 | } 92 | 93 | deleteMessage(id: number) { 94 | return this.http.delete(this.baseUrl + 'messages/' + id); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /client/src/app/_services/members.service.ts: -------------------------------------------------------------------------------- 1 | import { HttpClient, HttpParams } from '@angular/common/http'; 2 | import { Injectable } from '@angular/core'; 3 | import { of } from 'rxjs'; 4 | import { map, take } from 'rxjs/operators'; 5 | import { environment } from 'src/environments/environment'; 6 | import { Member } from '../_models/member'; 7 | import { User } from '../_models/user'; 8 | import { UserParams } from '../_models/userParams'; 9 | import { AccountService } from './account.service'; 10 | import { getPaginationHeaders, getPaginationResult } from './paginationHelper'; 11 | 12 | @Injectable({ 13 | providedIn: 'root', 14 | }) 15 | export class MembersService { 16 | baseUrl = environment.apiUrl; 17 | members: Member[] = []; 18 | memberCache = new Map(); 19 | userParams: UserParams; 20 | user: User; 21 | 22 | constructor( 23 | private http: HttpClient, 24 | private accountService: AccountService 25 | ) { 26 | this.accountService.currentUser$.pipe(take(1)).subscribe((user) => { 27 | this.user = user; 28 | this.userParams = new UserParams(user); 29 | }); 30 | } 31 | 32 | getUserParams() { 33 | return this.userParams; 34 | } 35 | 36 | setUserParams(userParams: UserParams) { 37 | this.userParams = userParams; 38 | } 39 | 40 | resetUserParams() { 41 | this.userParams = new UserParams(this.user); 42 | return this.userParams; 43 | } 44 | 45 | getMembers(userParams: UserParams) { 46 | var response = this.memberCache.get(Object.values(userParams).join('-')); 47 | if (response) { 48 | return of(response); 49 | } 50 | 51 | let params = getPaginationHeaders(userParams.pageNumber, userParams.pageSize); 52 | 53 | params = params.append('minAge', userParams.minAge.toString()); 54 | params = params.append('maxAge', userParams.maxAge.toString()); 55 | params = params.append('gender', userParams.gender); 56 | params = params.append('orderBy', userParams.orderBy); 57 | 58 | return getPaginationResult(this.baseUrl + 'users', params, this.http).pipe( 59 | map((response) => { 60 | this.memberCache.set(Object.values(userParams).join('-'), response); 61 | return response; 62 | }) 63 | ); 64 | } 65 | 66 | getMember(username: string) { 67 | const member = [...this.memberCache.values()] 68 | .reduce((arr, elem) => arr.concat(elem.result), []) 69 | .find((member: Member) => member.username === username); 70 | 71 | if (member) { 72 | return of(member); 73 | } 74 | return this.http.get(this.baseUrl + 'users/' + username); 75 | } 76 | 77 | updateMember(member: Member) { 78 | return this.http.put(this.baseUrl + 'users', member).pipe( 79 | map(() => { 80 | const index = this.members.indexOf(member); 81 | this.members[index] = member; 82 | }) 83 | ); 84 | } 85 | 86 | setMainPhoto(photoId: number) { 87 | return this.http.put(this.baseUrl + 'users/set-main-photo/' + photoId, {}); 88 | } 89 | 90 | deletePhoto(photoId: number) { 91 | return this.http.delete(this.baseUrl + 'users/delete-photo/' + photoId); 92 | } 93 | 94 | addLike(username: string) { 95 | return this.http.post(this.baseUrl + 'likes/' + username, {}); 96 | } 97 | 98 | getLikes(predicate: string, pageNumber: number, pageSize: number) { 99 | let params = getPaginationHeaders(pageNumber, pageSize); 100 | params = params.append('predicate', predicate); 101 | 102 | return getPaginationResult>(this.baseUrl + 'likes', params, this.http); 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /API/Controllers/MessagesController.cs: -------------------------------------------------------------------------------- 1 | using API.DTOs; 2 | using API.Entities; 3 | using API.Extensions; 4 | using API.Helpers; 5 | using API.Interfaces; 6 | using AutoMapper; 7 | using Microsoft.AspNetCore.Authorization; 8 | using Microsoft.AspNetCore.Mvc; 9 | using System.Collections.Generic; 10 | using System.Threading.Tasks; 11 | 12 | namespace API.Controllers 13 | { 14 | [Authorize] 15 | public class MessagesController : BaseAPIController 16 | { 17 | private readonly IUnitOfWork _unitOfWork; 18 | private readonly IMapper _mapper; 19 | 20 | public MessagesController(IUnitOfWork unitOfWork, IMapper mapper) 21 | { 22 | _unitOfWork = unitOfWork; 23 | _mapper = mapper; 24 | } 25 | 26 | [HttpPost] 27 | public async Task> CreateMessage(CreateMessageDto createMessage) 28 | { 29 | var username = User.GetUsername(); 30 | if (createMessage.RecipientUsername.ToLower() == username.ToLower()) 31 | return BadRequest("You cannot send messages to yourself"); 32 | 33 | var sender = await _unitOfWork.UserRepository.GetUserByUsernameAsync(username); 34 | var recipient = await _unitOfWork.UserRepository.GetUserByUsernameAsync(createMessage.RecipientUsername); 35 | 36 | if (recipient == null) return NotFound(); 37 | 38 | var message = new Message 39 | { 40 | Sender = sender, 41 | Recipient = recipient, 42 | SenderUsername = sender.UserName, 43 | RecipientUsername = recipient.UserName, 44 | Content = createMessage.Content 45 | }; 46 | 47 | _unitOfWork.MessageRepository.AddMessage(message); 48 | 49 | if (await _unitOfWork.Complete()) return Ok(_mapper.Map(message)); 50 | return BadRequest("Failed to send Message to " + recipient.UserName); 51 | } 52 | 53 | [HttpGet] 54 | public async Task>> GetMessagesForUser([FromQuery] MessageParams messageParams) 55 | { 56 | messageParams.Username = User.GetUsername(); 57 | 58 | var messages = await _unitOfWork.MessageRepository.GetMessagesForUser(messageParams); 59 | Response.AddPaginationHeader(messages.CurrentPage, messages.PageSize, messages.TotalCount, messages.TotalPages); 60 | 61 | return messages; 62 | } 63 | 64 | //[HttpGet("thread/{username}")] 65 | //public async Task>> GetMessageThread(string username) 66 | //{ 67 | // var currentUsername = User.GetUsername(); 68 | 69 | // return Ok(await _unitOfWork.MessageRepository.GetMessageThread(currentUsername, username)); 70 | //} 71 | 72 | 73 | [HttpDelete("{id}")] 74 | public async Task DeleteMessage(int id) 75 | { 76 | var username = User.GetUsername(); 77 | 78 | var message = await _unitOfWork.MessageRepository.GetMessage(id); 79 | 80 | if (message.Sender.UserName != username && message.Recipient.UserName != username) 81 | return Unauthorized(); 82 | 83 | if (message.Sender.UserName == username) message.SenderDeleted = true; 84 | if (message.Recipient.UserName == username) message.RecipientDeleted = true; 85 | 86 | if (message.SenderDeleted && message.RecipientDeleted) 87 | _unitOfWork.MessageRepository.DeleteMessage(message); 88 | 89 | if (await _unitOfWork.Complete()) return Ok(); 90 | 91 | return BadRequest("Problem Deleting the message"); 92 | 93 | } 94 | 95 | } 96 | } 97 | --------------------------------------------------------------------------------