├── src ├── assets │ ├── .gitkeep │ ├── icon.png │ ├── icons │ │ ├── icon-192x192.png │ │ ├── icon-256x256.png │ │ ├── icon-384x384.png │ │ └── icon-512x512.png │ └── tones │ │ └── message-tone.mp3 ├── app │ ├── app.component.scss │ ├── features │ │ ├── room │ │ │ ├── pages │ │ │ │ ├── rooms-page │ │ │ │ │ ├── rooms-page.component.scss │ │ │ │ │ ├── rooms-page.component.html │ │ │ │ │ └── rooms-page.component.ts │ │ │ │ └── room-page │ │ │ │ │ ├── room-page.component.scss │ │ │ │ │ ├── room-page.component.html │ │ │ │ │ └── room-page.component.ts │ │ │ ├── components │ │ │ │ ├── join-room-dialog │ │ │ │ │ ├── join-room-dialog.component.scss │ │ │ │ │ ├── join-room-dialog.component.html │ │ │ │ │ └── join-room-dialog.component.ts │ │ │ │ ├── upsert-room-dialog │ │ │ │ │ ├── upsert-room-dialog.component.scss │ │ │ │ │ ├── upsert-room-dialog.component.html │ │ │ │ │ └── upsert-room-dialog.component.ts │ │ │ │ └── room-item │ │ │ │ │ ├── room-item.component.scss │ │ │ │ │ ├── room-item.component.spec.ts │ │ │ │ │ ├── room-item.component.html │ │ │ │ │ └── room-item.component.ts │ │ │ ├── room.module.ts │ │ │ └── service │ │ │ │ └── room.service.ts │ │ ├── user │ │ │ ├── pages │ │ │ │ ├── recover-page │ │ │ │ │ ├── recover-page.component.scss │ │ │ │ │ ├── recover-page.component.html │ │ │ │ │ └── recover-page.component.ts │ │ │ │ ├── recover-change-password-page │ │ │ │ │ ├── recover-change-password-page.component.scss │ │ │ │ │ ├── recover-change-password-page.component.html │ │ │ │ │ └── recover-change-password-page.component.ts │ │ │ │ └── settings-page │ │ │ │ │ ├── settings-page.component.scss │ │ │ │ │ ├── settings-page.component.html │ │ │ │ │ └── settings-page.component.ts │ │ │ ├── service │ │ │ │ ├── recover.service.ts │ │ │ │ ├── user.service.ts │ │ │ │ └── subscription.service.ts │ │ │ └── user.module.ts │ │ ├── messages │ │ │ ├── pages │ │ │ │ └── direct-message-page │ │ │ │ │ ├── direct-message-page.component.scss │ │ │ │ │ ├── direct-message-page.component.html │ │ │ │ │ └── direct-message-page.component.ts │ │ │ ├── messages.module.ts │ │ │ ├── components │ │ │ │ └── messages │ │ │ │ │ ├── messages.component.scss │ │ │ │ │ ├── messages.component.html │ │ │ │ │ └── messages.component.ts │ │ │ └── service │ │ │ │ └── message.service.ts │ │ ├── notification │ │ │ ├── components │ │ │ │ └── push-notification │ │ │ │ │ ├── push-notification.component.html │ │ │ │ │ ├── push-notification.component.scss │ │ │ │ │ └── push-notification.component.ts │ │ │ ├── notification.module.ts │ │ │ └── service │ │ │ │ └── notification.service.ts │ │ ├── auth │ │ │ ├── pages │ │ │ │ ├── login-page │ │ │ │ │ ├── login-page.component.scss │ │ │ │ │ ├── login-page.component.html │ │ │ │ │ └── login-page.component.ts │ │ │ │ └── register-page │ │ │ │ │ ├── register-page.component.scss │ │ │ │ │ ├── register-page.component.html │ │ │ │ │ └── register-page.component.ts │ │ │ ├── guard │ │ │ │ └── auth.guard.ts │ │ │ ├── auth.module.ts │ │ │ ├── provider │ │ │ │ └── apple-login.provider.ts │ │ │ ├── interceptor │ │ │ │ └── auth-token.interceptor.ts │ │ │ └── service │ │ │ │ └── auth.service.ts │ │ ├── main │ │ │ ├── main.component.scss │ │ │ ├── main.component.html │ │ │ └── main.component.ts │ │ ├── features.module.ts │ │ └── routes.ts │ ├── shared │ │ ├── components │ │ │ ├── error-dialog │ │ │ │ ├── error-dialog.component.scss │ │ │ │ ├── error-dialog.component.html │ │ │ │ └── error-dialog.component.ts │ │ │ └── confirm-dialog │ │ │ │ ├── confirm-dialog.component.scss │ │ │ │ ├── confirm-dialog.component.html │ │ │ │ └── confirm-dialog.component.ts │ │ ├── utils │ │ │ └── upsert-item.ts │ │ ├── services │ │ │ ├── sound.service.spec.ts │ │ │ └── sound.service.ts │ │ ├── shared.module.ts │ │ └── material │ │ │ └── material.module.ts │ ├── app.component.html │ ├── core │ │ ├── core.module.ts │ │ ├── socket │ │ │ └── main-socket.ts │ │ └── interceptor │ │ │ └── error-dialog.interceptor.ts │ ├── app.component.ts │ └── app.module.ts ├── styles │ ├── _bootstrap-globals.scss │ └── styles.scss ├── main.ts ├── environments │ ├── environment.prod.ts │ └── environment.ts ├── test.ts ├── index.html ├── manifest.webmanifest └── polyfills.ts ├── .dockerignore ├── nginx.conf ├── tsconfig.app.json ├── .editorconfig ├── tsconfig.spec.json ├── .prettierrc ├── Dockerfile ├── README.md ├── tsconfig.json ├── ngsw-config.json ├── .gitignore ├── .browserslistrc ├── karma.conf.js ├── package.json ├── tslint.json └── angular.json /src/assets/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | node_modules -------------------------------------------------------------------------------- /src/app/app.component.scss: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/app/features/room/pages/rooms-page/rooms-page.component.scss: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/app/features/user/pages/recover-page/recover-page.component.scss: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/app/shared/components/error-dialog/error-dialog.component.scss: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/app/shared/components/confirm-dialog/confirm-dialog.component.scss: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/app/features/room/components/join-room-dialog/join-room-dialog.component.scss: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/app/features/messages/pages/direct-message-page/direct-message-page.component.scss: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/app/features/room/components/upsert-room-dialog/upsert-room-dialog.component.scss: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/app/features/notification/components/push-notification/push-notification.component.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/app/features/notification/components/push-notification/push-notification.component.scss: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/app/features/user/pages/recover-change-password-page/recover-change-password-page.component.scss: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/app/features/auth/pages/login-page/login-page.component.scss: -------------------------------------------------------------------------------- 1 | .mr { 2 | margin-right: 1rem; 3 | } 4 | -------------------------------------------------------------------------------- /src/app/features/auth/pages/register-page/register-page.component.scss: -------------------------------------------------------------------------------- 1 | .mr { 2 | margin-right: 1rem; 3 | } 4 | -------------------------------------------------------------------------------- /src/assets/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DenzelCode/nest-angular-auth-client/HEAD/src/assets/icon.png -------------------------------------------------------------------------------- /src/app/app.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /src/assets/icons/icon-192x192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DenzelCode/nest-angular-auth-client/HEAD/src/assets/icons/icon-192x192.png -------------------------------------------------------------------------------- /src/assets/icons/icon-256x256.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DenzelCode/nest-angular-auth-client/HEAD/src/assets/icons/icon-256x256.png -------------------------------------------------------------------------------- /src/assets/icons/icon-384x384.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DenzelCode/nest-angular-auth-client/HEAD/src/assets/icons/icon-384x384.png -------------------------------------------------------------------------------- /src/assets/icons/icon-512x512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DenzelCode/nest-angular-auth-client/HEAD/src/assets/icons/icon-512x512.png -------------------------------------------------------------------------------- /src/assets/tones/message-tone.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DenzelCode/nest-angular-auth-client/HEAD/src/assets/tones/message-tone.mp3 -------------------------------------------------------------------------------- /src/app/features/room/components/room-item/room-item.component.scss: -------------------------------------------------------------------------------- 1 | .description { 2 | text-decoration: none; 3 | color: #444; 4 | } 5 | -------------------------------------------------------------------------------- /src/app/features/main/main.component.scss: -------------------------------------------------------------------------------- 1 | .container { 2 | margin-top: 50px; 3 | 4 | .mat-button { 5 | margin-right: 20px; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /nginx.conf: -------------------------------------------------------------------------------- 1 | server { 2 | listen 80; 3 | 4 | location / { 5 | root /usr/share/nginx/html; 6 | index index.html; 7 | try_files $uri $uri/ /index.html; 8 | } 9 | } -------------------------------------------------------------------------------- /src/app/features/user/pages/settings-page/settings-page.component.scss: -------------------------------------------------------------------------------- 1 | h3 { 2 | font-weight: 600; 3 | margin-bottom: 0.2rem; 4 | } 5 | 6 | .mb-1 { 7 | margin-bottom: 1rem !important; 8 | } 9 | -------------------------------------------------------------------------------- /src/app/shared/utils/upsert-item.ts: -------------------------------------------------------------------------------- 1 | export const updateItem = ( 2 | arr: T[], 3 | predicate: (item: T) => boolean, 4 | object: Partial, 5 | ) => { 6 | const item = arr.find(predicate); 7 | 8 | if (!item) { 9 | return; 10 | } 11 | 12 | Object.assign(item, object); 13 | }; 14 | -------------------------------------------------------------------------------- /src/styles/_bootstrap-globals.scss: -------------------------------------------------------------------------------- 1 | @import 'functions', 'variables', 'mixins'; 2 | 3 | $theme-colors: ( 4 | 'primary': #1266f1, 5 | 'secondary': #b23cfd, 6 | 'success': #00b74a, 7 | 'danger': #f93154, 8 | 'warning': #ffa900, 9 | 'info': #39c0ed, 10 | 'light': #fbfbfb, 11 | 'dark': #262626, 12 | ); 13 | -------------------------------------------------------------------------------- /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": ["src/main.ts", "src/polyfills.ts"], 9 | "include": ["src/**/*.d.ts"] 10 | } 11 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /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": ["jasmine"] 7 | }, 8 | "files": ["src/test.ts", "src/polyfills.ts"], 9 | "include": ["src/**/*.spec.ts", "src/**/*.d.ts"] 10 | } 11 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "bracketSpacing": true, 3 | "singleQuote": true, 4 | "printWidth": 80, 5 | "trailingComma": "all", 6 | "tabWidth": 2, 7 | "arrowParens": "avoid", 8 | "overrides": [ 9 | { 10 | "files": "**/*.md", 11 | "options": { 12 | "parser": "markdown", 13 | "proseWrap": "always" 14 | } 15 | } 16 | ] 17 | } 18 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:16.19.0-alpine AS builder 2 | WORKDIR /app 3 | COPY package.json /app 4 | COPY yarn.lock /app 5 | RUN yarn install --frozen-lockfile 6 | COPY . . 7 | RUN yarn run build 8 | 9 | FROM nginx:alpine 10 | COPY --from=builder /app/nginx.conf /etc/nginx/templates/default.conf.conf 11 | COPY --from=builder /app/dist/task /usr/share/nginx/html 12 | 13 | EXPOSE 80 -------------------------------------------------------------------------------- /src/app/shared/components/confirm-dialog/confirm-dialog.component.html: -------------------------------------------------------------------------------- 1 |

{{ title }}

2 | 3 | {{ description }} 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /src/app/core/core.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { CommonModule } from '@angular/common'; 3 | import { MainSocket } from './socket/main-socket'; 4 | import { ErrorDialogInterceptor } from './interceptor/error-dialog.interceptor'; 5 | 6 | @NgModule({ 7 | imports: [CommonModule], 8 | providers: [MainSocket, ErrorDialogInterceptor], 9 | }) 10 | export class CoreModule {} 11 | -------------------------------------------------------------------------------- /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() 12 | .bootstrapModule(AppModule) 13 | .catch(err => console.error(err)); 14 | -------------------------------------------------------------------------------- /src/app/shared/services/sound.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed } from '@angular/core/testing'; 2 | 3 | import { SoundService } from './sound.service'; 4 | 5 | describe('SoundService', () => { 6 | let service: SoundService; 7 | 8 | beforeEach(() => { 9 | TestBed.configureTestingModule({}); 10 | service = TestBed.inject(SoundService); 11 | }); 12 | 13 | it('should be created', () => { 14 | expect(service).toBeTruthy(); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true, 3 | api: 'https://nest-auth.ubbly.club/api', 4 | socket: 'https://nest-auth.ubbly.club/', 5 | apps: { 6 | facebook: '535472397651204', 7 | google: 8 | '331672215174-0hlpm8fhjphiou05ovsd82vglor401ct.apps.googleusercontent.com', 9 | apple: { 10 | clientId: 'nest-auth.ubbly.club', 11 | redirectUri: 'https://nest-auth.ubbly.club/', 12 | }, 13 | }, 14 | }; 15 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Angular client for NestJS Authentication (Messages, Rooms, Login, Register, Google Login, Facebook Login, Apple Login) 2 | 3 | To use this client, get the [server](https://github.com/DenzelCode/nest-auth) up and running. 4 | 5 | Try it out now! [Demo](https://nest-auth.ubbly.club/) 6 | 7 | It also contains a websocket implementation of the authentication too :D 8 | 9 | ![image](https://user-images.githubusercontent.com/27902328/118452301-047bce80-b6c4-11eb-86c8-5eb2f7352585.png) 10 | -------------------------------------------------------------------------------- /src/app/shared/services/sound.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | 3 | export enum Sound { 4 | Message = 'message-tone', 5 | } 6 | 7 | @Injectable({ 8 | providedIn: 'root', 9 | }) 10 | export class SoundService { 11 | constructor() {} 12 | 13 | playSound(sound: Sound) { 14 | const path = `assets/tones/${sound}.mp3`; 15 | 16 | if (sound) { 17 | const audio = new Audio(path); 18 | audio.muted = false; 19 | audio.play(); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/app/features/notification/notification.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { CommonModule } from '@angular/common'; 3 | import { SharedModule } from '../../shared/shared.module'; 4 | import { PushNotificationComponent } from './components/push-notification/push-notification.component'; 5 | 6 | @NgModule({ 7 | declarations: [PushNotificationComponent], 8 | imports: [CommonModule, SharedModule], 9 | exports: [PushNotificationComponent], 10 | }) 11 | export class NotificationModule {} 12 | -------------------------------------------------------------------------------- /src/app/features/room/components/join-room-dialog/join-room-dialog.component.html: -------------------------------------------------------------------------------- 1 |
2 |

Join

3 |
4 | 5 | Code 6 | 12 | 13 | 14 |
15 |
16 | -------------------------------------------------------------------------------- /src/app/shared/components/error-dialog/error-dialog.component.html: -------------------------------------------------------------------------------- 1 |

{{ title }}

2 | 3 |

{{ message[0] }}

4 | 5 | 6 |
    7 |
  • 8 | {{ msg }} 9 |
  • 10 |
11 |
12 |
13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /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 | "resolveJsonModule": true, 12 | "moduleResolution": "node", 13 | "importHelpers": true, 14 | "target": "es2015", 15 | "module": "es2020", 16 | "lib": ["es2018", "dom"] 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/styles/styles.scss: -------------------------------------------------------------------------------- 1 | /* Bootstrap */ 2 | @import 'bootstrap'; 3 | 4 | body { 5 | background-color: #f3f3f3; 6 | } 7 | 8 | .full-width { 9 | width: 100%; 10 | } 11 | 12 | mat-card-footer { 13 | margin: 5px; 14 | } 15 | 16 | .position-absolute { 17 | position: absolute !important; 18 | z-index: 3; 19 | } 20 | 21 | .spacer { 22 | flex: 1 1 auto; 23 | } 24 | 25 | .flex-grow { 26 | flex: 1 1 0; 27 | } 28 | 29 | body, 30 | html, 31 | app-root, 32 | ng-component { 33 | display: flex; 34 | flex-direction: column; 35 | flex-grow: 1; 36 | height: 100%; 37 | } 38 | -------------------------------------------------------------------------------- /src/app/features/messages/pages/direct-message-page/direct-message-page.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |

4 | Chatting with {{ to.username }} ({{ to.online ? 'Online' : 'Offline' }}) 5 |

6 | 7 | logout 8 | 9 |
10 | 16 |
17 | -------------------------------------------------------------------------------- /src/app/features/messages/messages.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { CommonModule } from '@angular/common'; 3 | import { MessagesComponent } from './components/messages/messages.component'; 4 | import { SharedModule } from '../../shared/shared.module'; 5 | import { DirectMessagePageComponent } from './pages/direct-message-page/direct-message-page.component'; 6 | 7 | @NgModule({ 8 | declarations: [MessagesComponent, DirectMessagePageComponent], 9 | imports: [CommonModule, SharedModule], 10 | exports: [MessagesComponent, DirectMessagePageComponent], 11 | }) 12 | export class MessagesModule {} 13 | -------------------------------------------------------------------------------- /src/app/features/main/main.component.html: -------------------------------------------------------------------------------- 1 | 6 | 7 | 8 |
9 |

10 | Welcome, {{ user.username }}! 12 |

13 | 14 | Rooms 15 | Settings 16 |
17 |
18 | -------------------------------------------------------------------------------- /ngsw-config.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/service-worker/config/schema.json", 3 | "index": "/index.html", 4 | "assetGroups": [ 5 | { 6 | "name": "app", 7 | "installMode": "prefetch", 8 | "resources": { 9 | "files": [ 10 | "/favicon.ico", 11 | "/index.html", 12 | "/manifest.webmanifest", 13 | "/*.css", 14 | "/*.js" 15 | ] 16 | } 17 | }, 18 | { 19 | "name": "assets", 20 | "installMode": "lazy", 21 | "updateMode": "prefetch", 22 | "resources": { 23 | "files": [ 24 | "/assets/**", 25 | "/*.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)" 26 | ] 27 | } 28 | } 29 | ] 30 | } 31 | -------------------------------------------------------------------------------- /src/app/features/room/components/room-item/room-item.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { RoomItemComponent } from './room-item.component'; 4 | 5 | describe('RoomItemComponent', () => { 6 | let component: RoomItemComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async () => { 10 | await TestBed.configureTestingModule({ 11 | declarations: [ RoomItemComponent ] 12 | }) 13 | .compileComponents(); 14 | }); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(RoomItemComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /src/app/shared/components/error-dialog/error-dialog.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, Inject, OnInit } from '@angular/core'; 2 | import { MAT_DIALOG_DATA } from '@angular/material/dialog'; 3 | 4 | export interface ErrorDialogData { 5 | title: string; 6 | message: string | string[]; 7 | } 8 | 9 | @Component({ 10 | templateUrl: './error-dialog.component.html', 11 | styleUrls: ['./error-dialog.component.scss'], 12 | }) 13 | export class ErrorDialogComponent implements OnInit { 14 | title: ErrorDialogData['title']; 15 | message: ErrorDialogData['message']; 16 | 17 | constructor(@Inject(MAT_DIALOG_DATA) data: ErrorDialogData) { 18 | this.title = data.title || 'Error'; 19 | this.message = 20 | data.message instanceof Array ? data.message : [data.message || '']; 21 | } 22 | 23 | ngOnInit(): void {} 24 | } 25 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See http://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # compiled output 4 | /dist 5 | /tmp 6 | /out-tsc 7 | # Only exists if Bazel was run 8 | /bazel-out 9 | 10 | # dependencies 11 | /node_modules 12 | 13 | # profiling files 14 | chrome-profiler-events*.json 15 | speed-measure-plugin*.json 16 | 17 | # IDEs and editors 18 | /.idea 19 | .project 20 | .classpath 21 | .c9/ 22 | *.launch 23 | .settings/ 24 | *.sublime-workspace 25 | 26 | # IDE - VSCode 27 | .vscode/* 28 | !.vscode/settings.json 29 | !.vscode/tasks.json 30 | !.vscode/launch.json 31 | !.vscode/extensions.json 32 | .history/* 33 | 34 | # misc 35 | /.sass-cache 36 | /connect.lock 37 | /coverage 38 | /libpeerconnection.log 39 | npm-debug.log 40 | yarn-error.log 41 | testem.log 42 | /typings 43 | 44 | # System Files 45 | .DS_Store 46 | Thumbs.db 47 | 48 | .vscode -------------------------------------------------------------------------------- /src/app/features/user/service/recover.service.ts: -------------------------------------------------------------------------------- 1 | import { HttpClient } from '@angular/common/http'; 2 | import { Injectable } from '@angular/core'; 3 | import { environment } from '../../../../environments/environment'; 4 | 5 | const { api } = environment; 6 | 7 | export interface ChangePasswordBody { 8 | password: string; 9 | confirmPassword: string; 10 | } 11 | 12 | @Injectable({ 13 | providedIn: 'root', 14 | }) 15 | export class RecoverService { 16 | constructor(private http: HttpClient) {} 17 | 18 | recoverPassword(email: string) { 19 | return this.http.post(`${api}/recover`, { email }); 20 | } 21 | 22 | validateCode(code: string) { 23 | return this.http.get(`${api}/recover/${code}`); 24 | } 25 | 26 | changePassword(code: string, body: ChangePasswordBody) { 27 | return this.http.post(`${api}/recover/${code}`, body); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/app/features/user/user.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { CommonModule } from '@angular/common'; 3 | import { SettingsPageComponent } from './pages/settings-page/settings-page.component'; 4 | import { SharedModule } from '../../shared/shared.module'; 5 | import { RecoverPageComponent } from './pages/recover-page/recover-page.component'; 6 | import { RecoverChangePasswordPageComponent } from './pages/recover-change-password-page/recover-change-password-page.component'; 7 | 8 | @NgModule({ 9 | declarations: [ 10 | SettingsPageComponent, 11 | RecoverPageComponent, 12 | RecoverChangePasswordPageComponent, 13 | ], 14 | imports: [CommonModule, SharedModule], 15 | exports: [ 16 | SettingsPageComponent, 17 | RecoverPageComponent, 18 | RecoverChangePasswordPageComponent, 19 | ], 20 | }) 21 | export class UserModule {} 22 | -------------------------------------------------------------------------------- /src/app/features/room/components/upsert-room-dialog/upsert-room-dialog.component.html: -------------------------------------------------------------------------------- 1 |
2 |

Create Room

3 |
4 | 5 | Title 6 | 12 | 13 | 18 | Public 19 | 20 | 23 |
24 |
25 | 26 | 27 |

Update Room {{ room.title }}

28 |
29 | -------------------------------------------------------------------------------- /src/test.ts: -------------------------------------------------------------------------------- 1 | // This file is required by karma.conf.js and loads recursively all the .spec and framework files 2 | 3 | import 'zone.js/testing'; 4 | import { getTestBed } from '@angular/core/testing'; 5 | import { 6 | BrowserDynamicTestingModule, 7 | platformBrowserDynamicTesting, 8 | } from '@angular/platform-browser-dynamic/testing'; 9 | 10 | declare const require: { 11 | context( 12 | path: string, 13 | deep?: boolean, 14 | filter?: RegExp, 15 | ): { 16 | keys(): string[]; 17 | (id: string): T; 18 | }; 19 | }; 20 | 21 | // First, initialize the Angular testing environment. 22 | getTestBed().initTestEnvironment( 23 | BrowserDynamicTestingModule, 24 | platformBrowserDynamicTesting(), 25 | ); 26 | // Then we find all the tests. 27 | const context = require.context('./', true, /\.spec\.ts$/); 28 | // And load the modules. 29 | context.keys().map(context); 30 | -------------------------------------------------------------------------------- /src/app/features/main/main.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnDestroy, OnInit } from '@angular/core'; 2 | import { Subject } from 'rxjs'; 3 | import { takeUntil } from 'rxjs/operators'; 4 | import { AuthService, User } from 'src/app/features/auth/service/auth.service'; 5 | 6 | @Component({ 7 | templateUrl: './main.component.html', 8 | styleUrls: ['./main.component.scss'], 9 | }) 10 | export class MainComponent implements OnInit, OnDestroy { 11 | user: User; 12 | 13 | destroy$ = new Subject(); 14 | 15 | constructor(private authService: AuthService) {} 16 | 17 | ngOnInit() { 18 | this.authService.user$ 19 | .pipe(takeUntil(this.destroy$)) 20 | .subscribe(user => (this.user = user)); 21 | } 22 | 23 | ngOnDestroy() { 24 | this.destroy$.next(); 25 | this.destroy$.complete(); 26 | } 27 | 28 | logout() { 29 | this.authService.logout(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CodeAuth 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /src/manifest.webmanifest: -------------------------------------------------------------------------------- 1 | { 2 | "name": "CodeAuth", 3 | "short_name": "CodeAuth", 4 | "theme_color": "#f3f3f3", 5 | "background_color": "#f3f3f3", 6 | "display": "standalone", 7 | "scope": "./", 8 | "start_url": "./", 9 | "icons": [ 10 | { 11 | "src": "assets/icons/icon-192x192.png", 12 | "sizes": "192x192", 13 | "type": "image/png", 14 | "purpose": "maskable any" 15 | }, 16 | { 17 | "src": "assets/icons/icon-256x256.png", 18 | "sizes": "256x256", 19 | "type": "image/png", 20 | "purpose": "maskable any" 21 | }, 22 | { 23 | "src": "assets/icons/icon-384x384.png", 24 | "sizes": "384x384", 25 | "type": "image/png", 26 | "purpose": "maskable any" 27 | }, 28 | { 29 | "src": "assets/icons/icon-512x512.png", 30 | "sizes": "512x512", 31 | "type": "image/png", 32 | "purpose": "maskable any" 33 | } 34 | ] 35 | } 36 | -------------------------------------------------------------------------------- /src/app/features/user/pages/recover-page/recover-page.component.html: -------------------------------------------------------------------------------- 1 | 6 | 7 |
8 | 9 |

Forgot my password

10 |

Recover your password

11 | 12 |
13 | 14 | Email 15 | 21 | 22 | 23 | 24 | Back 25 | 26 | 27 |
28 |
29 |
30 | -------------------------------------------------------------------------------- /src/environments/environment.ts: -------------------------------------------------------------------------------- 1 | // export const environment = { 2 | // production: false, 3 | // api: 'http://localhost:3000', 4 | // socket: 'http://localhost:3000', 5 | // apps: { 6 | // facebook: '513024756601831', 7 | // google: 8 | // '331672215174-0hlpm8fhjphiou05ovsd82vglor401ct.apps.googleusercontent.com', 9 | // apple: { 10 | // clientId: 'nest-auth.ubbly.club', 11 | // redirectUri: 'https://nest-auth.ubbly.club/', 12 | // }, 13 | // }, 14 | // }; 15 | 16 | export const environment = { 17 | production: true, 18 | api: 'https://nest-auth.ubbly.club/api', 19 | socket: 'https://nest-auth.ubbly.club/', 20 | apps: { 21 | facebook: '535472397651204', 22 | google: 23 | '331672215174-0hlpm8fhjphiou05ovsd82vglor401ct.apps.googleusercontent.com', 24 | apple: { 25 | clientId: 'nest-auth.ubbly.club', 26 | redirectUri: 'https://nest-auth.ubbly.club/', 27 | }, 28 | }, 29 | }; 30 | -------------------------------------------------------------------------------- /src/app/features/room/components/room-item/room-item.component.html: -------------------------------------------------------------------------------- 1 | 2 | person 3 |

{{ room.title }} ({{ room.members.length }})

4 | 10 | {{ $any(room.owner).username }} 11 | 12 | 13 |
14 | 15 |
16 | 17 |
18 | 19 | 20 |
21 |
22 | 25 |
26 |
27 | -------------------------------------------------------------------------------- /src/app/features/features.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { RouterModule } from '@angular/router'; 3 | import { routes } from './routes'; 4 | import { MainComponent } from './main/main.component'; 5 | import { UserModule } from './user/user.module'; 6 | import { AuthModule } from './auth/auth.module'; 7 | import { SharedModule } from '../shared/shared.module'; 8 | import { RoomModule } from './room/room.module'; 9 | import { MessagesModule } from './messages/messages.module'; 10 | import { NotificationModule } from './notification/notification.module'; 11 | 12 | @NgModule({ 13 | declarations: [MainComponent], 14 | imports: [ 15 | SharedModule, 16 | UserModule, 17 | AuthModule, 18 | RoomModule, 19 | MessagesModule, 20 | NotificationModule, 21 | RouterModule.forRoot(routes, { relativeLinkResolution: 'legacy' }), 22 | ], 23 | exports: [RouterModule, NotificationModule], 24 | }) 25 | export class FeaturesModule {} 26 | -------------------------------------------------------------------------------- /src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnDestroy, OnInit } from '@angular/core'; 2 | import { Subject } from 'rxjs'; 3 | import { takeUntil } from 'rxjs/operators'; 4 | import { 5 | ErrorDialogInterceptor, 6 | HttpError, 7 | } from './core/interceptor/error-dialog.interceptor'; 8 | import { MainSocket } from './core/socket/main-socket'; 9 | 10 | @Component({ 11 | selector: 'app-root', 12 | templateUrl: './app.component.html', 13 | styleUrls: ['./app.component.scss'], 14 | }) 15 | export class AppComponent implements OnInit, OnDestroy { 16 | destroy$ = new Subject(); 17 | 18 | constructor( 19 | private errorHandler: ErrorDialogInterceptor, 20 | private socket: MainSocket, 21 | ) {} 22 | 23 | ngOnInit() { 24 | this.socket 25 | .fromEvent('exception') 26 | .pipe(takeUntil(this.destroy$)) 27 | .subscribe(e => this.errorHandler.handleError(e)); 28 | } 29 | 30 | ngOnDestroy() { 31 | this.destroy$.next(); 32 | this.destroy$.complete(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/app/shared/shared.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { CommonModule } from '@angular/common'; 3 | import { ConfirmDialogComponent } from './components/confirm-dialog/confirm-dialog.component'; 4 | import { ErrorDialogComponent } from './components/error-dialog/error-dialog.component'; 5 | import { MaterialModule } from './material/material.module'; 6 | import { FormsModule, ReactiveFormsModule } from '@angular/forms'; 7 | import { RouterModule } from '@angular/router'; 8 | import { HttpClientModule } from '@angular/common/http'; 9 | 10 | @NgModule({ 11 | declarations: [ConfirmDialogComponent, ErrorDialogComponent], 12 | imports: [ 13 | CommonModule, 14 | MaterialModule, 15 | ReactiveFormsModule, 16 | FormsModule, 17 | HttpClientModule, 18 | ], 19 | exports: [ 20 | ConfirmDialogComponent, 21 | ErrorDialogComponent, 22 | MaterialModule, 23 | ReactiveFormsModule, 24 | FormsModule, 25 | RouterModule, 26 | HttpClientModule, 27 | ], 28 | }) 29 | export class SharedModule {} 30 | -------------------------------------------------------------------------------- /src/app/features/user/service/user.service.ts: -------------------------------------------------------------------------------- 1 | import { HttpClient } from '@angular/common/http'; 2 | import { Injectable } from '@angular/core'; 3 | import { environment } from '../../../../environments/environment'; 4 | import { User } from '../../auth/service/auth.service'; 5 | 6 | const { api } = environment; 7 | 8 | export interface UpdatePasswordBody { 9 | currentPassword?: string; 10 | password?: string; 11 | confirmPassword?: string; 12 | } 13 | 14 | @Injectable({ 15 | providedIn: 'root', 16 | }) 17 | export class UserService { 18 | constructor(private http: HttpClient) {} 19 | 20 | getUser(username: string) { 21 | return this.http.get(`${api}/user/${username}`); 22 | } 23 | 24 | updateUsername(username: string) { 25 | return this.http.put(`${api}/settings/username`, { username }); 26 | } 27 | 28 | updateEmail(email: string) { 29 | return this.http.put(`${api}/settings/email`, { email }); 30 | } 31 | 32 | updatePassword(data: UpdatePasswordBody) { 33 | return this.http.put(`${api}/settings/password`, data); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /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/task'), 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 | -------------------------------------------------------------------------------- /src/app/features/room/room.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { CommonModule } from '@angular/common'; 3 | import { RoomsPageComponent } from './pages/rooms-page/rooms-page.component'; 4 | import { SharedModule } from '../../shared/shared.module'; 5 | import { RoomService } from './service/room.service'; 6 | import { UpsertRoomDialogComponent } from './components/upsert-room-dialog/upsert-room-dialog.component'; 7 | import { JoinRoomDialogComponent } from './components/join-room-dialog/join-room-dialog.component'; 8 | import { RoomPageComponent } from './pages/room-page/room-page.component'; 9 | import { MessagesModule } from '../messages/messages.module'; 10 | import { RoomItemComponent } from './components/room-item/room-item.component'; 11 | 12 | @NgModule({ 13 | declarations: [ 14 | RoomsPageComponent, 15 | UpsertRoomDialogComponent, 16 | JoinRoomDialogComponent, 17 | RoomPageComponent, 18 | RoomItemComponent, 19 | ], 20 | imports: [CommonModule, SharedModule, MessagesModule], 21 | providers: [RoomService], 22 | exports: [RoomsPageComponent, RoomPageComponent], 23 | }) 24 | export class RoomModule {} 25 | -------------------------------------------------------------------------------- /src/app/shared/components/confirm-dialog/confirm-dialog.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, Inject, OnInit } from '@angular/core'; 2 | import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; 3 | 4 | export interface ConfirmDialogData { 5 | title: string; 6 | description: string | string[]; 7 | } 8 | 9 | @Component({ 10 | selector: 'app-confirm-dialog', 11 | templateUrl: './confirm-dialog.component.html', 12 | styleUrls: ['./confirm-dialog.component.scss'], 13 | }) 14 | export class ConfirmDialogComponent implements OnInit { 15 | title: ConfirmDialogData['title']; 16 | description: ConfirmDialogData['description']; 17 | 18 | constructor( 19 | @Inject(MAT_DIALOG_DATA) data: ConfirmDialogData, 20 | private dialogRef: MatDialogRef, 21 | ) { 22 | this.title = data?.title || 'Are you sure?'; 23 | this.description = 24 | data?.description || 'You are not going to be able to undo this action'; 25 | } 26 | 27 | ngOnInit(): void {} 28 | 29 | accept(): void { 30 | this.dialogRef.close(true); 31 | } 32 | 33 | close(): void { 34 | this.dialogRef.close(false); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/app/features/room/components/join-room-dialog/join-room-dialog.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | import { FormBuilder } from '@angular/forms'; 3 | import { MatDialogRef } from '@angular/material/dialog'; 4 | import { Router } from '@angular/router'; 5 | import { take } from 'rxjs/operators'; 6 | import { RoomService } from '../../service/room.service'; 7 | 8 | @Component({ 9 | selector: 'app-join-room-dialog', 10 | templateUrl: './join-room-dialog.component.html', 11 | styleUrls: ['./join-room-dialog.component.scss'], 12 | }) 13 | export class JoinRoomDialogComponent { 14 | joinForm = this.formBuilder.group({ 15 | code: '', 16 | }); 17 | 18 | constructor( 19 | private formBuilder: FormBuilder, 20 | private roomService: RoomService, 21 | private dialog: MatDialogRef, 22 | private router: Router, 23 | ) {} 24 | 25 | submit() { 26 | const array = this.joinForm.value.code.trim().split('/'); 27 | const code = array[array.length - 1]; 28 | 29 | if (!code) { 30 | return; 31 | } 32 | 33 | this.roomService 34 | .getRoom(code) 35 | .pipe(take(1)) 36 | .subscribe(room => { 37 | this.dialog.close(); 38 | 39 | this.router.navigate(['/room', room._id]); 40 | }); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/app/features/user/pages/recover-page/recover-page.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | import { FormBuilder } from '@angular/forms'; 3 | import { take, tap } from 'rxjs/operators'; 4 | import Swal from 'sweetalert2'; 5 | import { RecoverService } from '../../service/recover.service'; 6 | 7 | @Component({ 8 | templateUrl: './recover-page.component.html', 9 | styleUrls: ['./recover-page.component.scss'], 10 | }) 11 | export class RecoverPageComponent { 12 | recoverForm = this.formBuilder.group({ 13 | email: '', 14 | }); 15 | 16 | loading = false; 17 | 18 | constructor( 19 | private formBuilder: FormBuilder, 20 | private recoverService: RecoverService, 21 | ) {} 22 | 23 | submit() { 24 | if (this.loading) { 25 | return; 26 | } 27 | 28 | this.loading = true; 29 | 30 | const clear = () => { 31 | this.loading = false; 32 | 33 | this.recoverForm.patchValue({ email: '' }); 34 | }; 35 | 36 | this.recoverService 37 | .recoverPassword(this.recoverForm.value.email) 38 | .pipe(tap(clear, clear), take(1)) 39 | .subscribe(() => 40 | Swal.fire({ 41 | title: 'Good job!', 42 | text: 'Check your email and change your password!', 43 | icon: 'success', 44 | }), 45 | ); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/app/features/user/pages/recover-change-password-page/recover-change-password-page.component.html: -------------------------------------------------------------------------------- 1 | 6 |
7 | 8 |

Change your password

9 |

Change your password by completing the form

10 | 11 |
12 | 13 | Password 14 | 20 | 21 | 22 | 23 | Confirm Password 24 | 30 | 31 | 32 | 33 | Back 34 | 37 | 38 |
39 |
40 |
41 | -------------------------------------------------------------------------------- /src/app/features/room/pages/room-page/room-page.component.scss: -------------------------------------------------------------------------------- 1 | @import 'bootstrap-globals'; 2 | 3 | $button-background: rgba(0, 0, 0, 0.04); 4 | $top-height: 64px; 5 | 6 | .top-header { 7 | height: $top-height; 8 | background-color: $button-background; 9 | font: 500 20px/32px Roboto, 'Helvetica Neue', sans-serif; 10 | } 11 | 12 | .toolbar { 13 | height: $top-height; 14 | } 15 | 16 | .scroll { 17 | height: 100%; 18 | overflow: auto; 19 | } 20 | 21 | .members { 22 | @include media-breakpoint-up(md) { 23 | width: 40%; 24 | } 25 | 26 | @include media-breakpoint-up(xl) { 27 | width: 30%; 28 | } 29 | 30 | @include media-breakpoint-down(md) { 31 | width: 100%; 32 | } 33 | 34 | transition: 0.5s ease width; 35 | 36 | &.hide { 37 | width: 0%; 38 | } 39 | 40 | a { 41 | color: #444; 42 | text-decoration: none; 43 | cursor: pointer; 44 | 45 | &:nth-child(2n) { 46 | background-color: $button-background; 47 | } 48 | 49 | span { 50 | width: 100%; 51 | display: inline-block; 52 | } 53 | 54 | .circle { 55 | width: 10px; 56 | height: 10px; 57 | display: inline-block; 58 | border-radius: 50%; 59 | 60 | &.online { 61 | background-color: map-get($theme-colors, 'success'); 62 | } 63 | 64 | &.offline { 65 | background-color: map-get($theme-colors, 'danger'); 66 | } 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/app/features/notification/components/push-notification/push-notification.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnDestroy, OnInit } from '@angular/core'; 2 | import { Subject } from 'rxjs'; 3 | import { filter, mergeMap, takeUntil } from 'rxjs/operators'; 4 | import { AuthService, User } from '../../../auth/service/auth.service'; 5 | import { SubscriptionService } from '../../../user/service/subscription.service'; 6 | import { NotificationService } from '../../service/notification.service'; 7 | 8 | @Component({ 9 | selector: 'app-push-notification', 10 | templateUrl: './push-notification.component.html', 11 | styleUrls: ['./push-notification.component.scss'], 12 | }) 13 | export class PushNotificationComponent implements OnInit, OnDestroy { 14 | destroy$ = new Subject(); 15 | 16 | constructor( 17 | private authService: AuthService, 18 | private notificationService: NotificationService, 19 | private subscriptionService: SubscriptionService, 20 | ) {} 21 | 22 | ngOnInit() { 23 | this.authService.user$ 24 | .pipe( 25 | takeUntil(this.destroy$), 26 | filter(user => user != null), 27 | mergeMap(() => this.subscriptionService.requestSubscription()), 28 | ) 29 | .subscribe(); 30 | 31 | this.notificationService.updateAvailable$.subscribe(); 32 | 33 | this.notificationService.checkForUpdates(); 34 | } 35 | 36 | ngOnDestroy() { 37 | this.destroy$.next(); 38 | this.destroy$.complete(); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/app/features/auth/guard/auth.guard.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { 3 | CanActivate, 4 | ActivatedRouteSnapshot, 5 | RouterStateSnapshot, 6 | Router, 7 | } from '@angular/router'; 8 | import { AuthService } from '../service/auth.service'; 9 | 10 | @Injectable({ 11 | providedIn: 'root', 12 | }) 13 | export class AuthGuard implements CanActivate { 14 | constructor(private router: Router, private authService: AuthService) {} 15 | 16 | canActivate( 17 | next: ActivatedRouteSnapshot, 18 | state: RouterStateSnapshot, 19 | ): boolean { 20 | const { redirect, requireAuth } = next.data; 21 | 22 | const { isAuthenticated } = this.authService; 23 | 24 | const isAuthRequired = requireAuth == null || requireAuth; 25 | 26 | const isAccessAllowed = 27 | (isAuthRequired && isAuthenticated) || 28 | (!isAuthRequired && !isAuthenticated); 29 | 30 | if (!isAccessAllowed) { 31 | if (requireAuth == null || requireAuth) { 32 | this.authService.setLoginCallbackUrl(state.url); 33 | } 34 | 35 | if (redirect) { 36 | if (redirect instanceof Array) { 37 | this.router.navigate([...redirect]); 38 | } else { 39 | this.router.navigate([redirect]); 40 | } 41 | 42 | return false; 43 | } 44 | 45 | if (this.router.routerState.snapshot.url === '') { 46 | this.router.navigate(isAuthRequired ? ['/login'] : ['/']); 47 | 48 | return false; 49 | } 50 | } 51 | 52 | return isAccessAllowed; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/app/features/user/service/subscription.service.ts: -------------------------------------------------------------------------------- 1 | import { HttpClient } from '@angular/common/http'; 2 | import { Injectable } from '@angular/core'; 3 | import { of } from 'rxjs'; 4 | import { mergeMap, take } from 'rxjs/operators'; 5 | import { environment } from '../../../../environments/environment'; 6 | import { ErrorDialogInterceptor } from '../../../core/interceptor/error-dialog.interceptor'; 7 | import { AuthTokenInterceptor } from '../../auth/interceptor/auth-token.interceptor'; 8 | import { NotificationService } from '../../notification/service/notification.service'; 9 | 10 | const { api } = environment; 11 | 12 | @Injectable({ 13 | providedIn: 'root', 14 | }) 15 | export class SubscriptionService { 16 | constructor( 17 | private http: HttpClient, 18 | private notificationService: NotificationService, 19 | ) {} 20 | 21 | requestSubscription() { 22 | return this.notificationService 23 | .requestSubscription() 24 | .pipe(mergeMap(subscription => this.registerSubscription(subscription))); 25 | } 26 | 27 | registerSubscription(subscription: PushSubscription) { 28 | return this.http.post(`${api}/subscription/web`, { 29 | subscription, 30 | }); 31 | } 32 | 33 | delete() { 34 | const subscription = this.notificationService.getSubscription(); 35 | 36 | if (!subscription) { 37 | return of(); 38 | } 39 | 40 | return this.http.delete(`${api}/subscription/web`, { 41 | body: { 42 | subscription, 43 | }, 44 | headers: { 45 | [AuthTokenInterceptor.skipHeader]: 'true', 46 | [ErrorDialogInterceptor.skipHeader]: 'true', 47 | }, 48 | }); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/app/shared/material/material.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { CommonModule } from '@angular/common'; 3 | 4 | // Angular modules 5 | import { MatButtonModule } from '@angular/material/button'; 6 | import { MatCardModule } from '@angular/material/card'; 7 | import { MatGridListModule } from '@angular/material/grid-list'; 8 | import { MatInputModule } from '@angular/material/input'; 9 | import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; 10 | import { MatDialogModule } from '@angular/material/dialog'; 11 | import { MatDividerModule } from '@angular/material/divider'; 12 | import { MatListModule } from '@angular/material/list'; 13 | import { MatIconModule } from '@angular/material/icon'; 14 | import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; 15 | import { MatFormFieldModule } from '@angular/material/form-field'; 16 | import { MatSlideToggleModule } from '@angular/material/slide-toggle'; 17 | import { ClipboardModule } from '@angular/cdk/clipboard'; 18 | import { MatToolbarModule } from '@angular/material/toolbar'; 19 | import { MatRippleModule } from '@angular/material/core'; 20 | 21 | @NgModule({ 22 | declarations: [], 23 | imports: [CommonModule], 24 | exports: [ 25 | MatInputModule, 26 | BrowserAnimationsModule, 27 | MatButtonModule, 28 | MatCardModule, 29 | MatGridListModule, 30 | MatDialogModule, 31 | MatDividerModule, 32 | MatListModule, 33 | MatIconModule, 34 | MatProgressSpinnerModule, 35 | MatFormFieldModule, 36 | MatSlideToggleModule, 37 | ClipboardModule, 38 | MatToolbarModule, 39 | MatRippleModule, 40 | ], 41 | }) 42 | export class MaterialModule {} 43 | -------------------------------------------------------------------------------- /src/app/features/room/pages/rooms-page/rooms-page.component.html: -------------------------------------------------------------------------------- 1 | 6 |
7 | 8 |

Rooms

9 | 10 | 11 | 12 | Back 13 |
14 | 15 | 16 |

Your Rooms

17 |
18 | 25 | 26 | 27 |
28 |
29 | 30 | 31 |

Joined Rooms

32 |
33 | 40 | 41 | 42 |
43 |
44 | 45 | 46 |

Public Rooms

47 |
48 | 55 | 56 | 57 |
58 |
59 |
60 | -------------------------------------------------------------------------------- /src/app/core/socket/main-socket.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { boundMethod } from 'autobind-decorator'; 3 | import { Socket } from 'ngx-socket-io'; 4 | import { mergeMap, take } from 'rxjs/operators'; 5 | import { AuthService } from 'src/app/features/auth/service/auth.service'; 6 | import { environment } from '../../../environments/environment'; 7 | 8 | const getOptions = (authService: AuthService) => ({ 9 | transportOptions: { 10 | polling: { 11 | extraHeaders: { 12 | Authorization: `Bearer ${authService.getAccessToken()}`, 13 | }, 14 | }, 15 | }, 16 | autoConnect: false, 17 | }); 18 | 19 | @Injectable() 20 | export class MainSocket extends Socket { 21 | constructor(private authService: AuthService) { 22 | super({ 23 | url: environment.socket, 24 | options: getOptions(authService), 25 | }); 26 | 27 | const io = this.ioSocket.io; 28 | io.on('reconnect_attempt', this.updateAccessToken); 29 | 30 | this.onConnect().subscribe(() => this.emit('user:subscribe')); 31 | 32 | this.onDisconnect().subscribe(reason => { 33 | if (reason !== 'io server disconnect') { 34 | return; 35 | } 36 | 37 | this.authService 38 | .loginWithRefreshToken() 39 | .pipe(take(1)) 40 | .subscribe(() => this.connect()); 41 | }); 42 | } 43 | 44 | connect() { 45 | this.updateAccessToken(); 46 | 47 | super.connect(); 48 | } 49 | 50 | onConnect() { 51 | return this.fromEvent('connect'); 52 | } 53 | 54 | onDisconnect() { 55 | return this.fromEvent('disconnect'); 56 | } 57 | 58 | @boundMethod 59 | updateAccessToken() { 60 | Object.assign(this.ioSocket?.io?.opts || {}, getOptions(this.authService)); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/app/features/auth/auth.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { CommonModule } from '@angular/common'; 3 | import { 4 | FacebookLoginProvider, 5 | GoogleLoginProvider, 6 | SocialAuthServiceConfig, 7 | SocialLoginModule, 8 | } from 'angularx-social-login'; 9 | import { environment } from 'src/environments/environment'; 10 | import { AppleLoginProvider } from './provider/apple-login.provider'; 11 | import { MaterialModule } from '../../shared/material/material.module'; 12 | import { RegisterPageComponent } from './pages/register-page/register-page.component'; 13 | import { LoginPageComponent } from './pages/login-page/login-page.component'; 14 | import { ReactiveFormsModule } from '@angular/forms'; 15 | import { SharedModule } from '../../shared/shared.module'; 16 | 17 | const apps = environment.apps; 18 | 19 | @NgModule({ 20 | declarations: [RegisterPageComponent, LoginPageComponent], 21 | providers: [ 22 | { 23 | provide: 'SocialAuthServiceConfig', 24 | useValue: { 25 | autoLogin: false, 26 | providers: [ 27 | { 28 | id: GoogleLoginProvider.PROVIDER_ID, 29 | provider: new GoogleLoginProvider(apps.google), 30 | }, 31 | { 32 | id: FacebookLoginProvider.PROVIDER_ID, 33 | provider: new FacebookLoginProvider(apps.facebook), 34 | }, 35 | { 36 | id: AppleLoginProvider.PROVIDER_ID, 37 | provider: new AppleLoginProvider(apps.apple), 38 | }, 39 | ], 40 | } as SocialAuthServiceConfig, 41 | }, 42 | ], 43 | imports: [CommonModule, SocialLoginModule, SharedModule], 44 | exports: [SocialLoginModule, RegisterPageComponent, LoginPageComponent], 45 | }) 46 | export class AuthModule {} 47 | -------------------------------------------------------------------------------- /src/app/features/auth/provider/apple-login.provider.ts: -------------------------------------------------------------------------------- 1 | import { BaseLoginProvider, SocialUser } from 'angularx-social-login'; 2 | import { environment } from '../../../../environments/environment'; 3 | 4 | declare const AppleID: any; 5 | 6 | export class AppleLoginProvider extends BaseLoginProvider { 7 | public static readonly PROVIDER_ID: string = 'APPLE'; 8 | 9 | protected auth2: any; 10 | 11 | constructor(private app: typeof environment.apps.apple) { 12 | super(); 13 | } 14 | 15 | public initialize(): Promise { 16 | return new Promise(resolve => { 17 | this.loadScript( 18 | AppleLoginProvider.PROVIDER_ID, 19 | 'https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/en_US/appleid.auth.js', 20 | () => { 21 | AppleID.auth.init({ 22 | clientId: this.app.clientId, 23 | scope: 'name email', 24 | redirectURI: this.app.redirectUri, 25 | usePopup: true, 26 | }); 27 | 28 | resolve(); 29 | }, 30 | ); 31 | }); 32 | } 33 | 34 | public getLoginStatus(): Promise { 35 | return new Promise(resolve => resolve(null)); 36 | } 37 | 38 | public async signIn(signInOptions?: any): Promise { 39 | try { 40 | const data = await AppleID.auth.signIn(); 41 | 42 | return { 43 | name: `${data.user?.firstName} ${data.user?.lastName}`, 44 | authorizationCode: data.authorization.code, 45 | authToken: data.authorization.id_token, 46 | } as SocialUser; 47 | } catch (err) { 48 | console.error(err); 49 | 50 | throw err; 51 | } 52 | } 53 | 54 | public signOut(revoke?: boolean): Promise { 55 | return new Promise(resolve => resolve()); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/app/features/auth/pages/login-page/login-page.component.html: -------------------------------------------------------------------------------- 1 | 6 |
7 | 8 |

Login

9 |

Sign into your account

10 | 11 |
12 | 13 | Username 14 | 20 | 21 | 22 | 23 | Password 24 | 30 | 31 | 32 | 33 | Back 34 | 35 | 36 |
37 | 46 | 47 | 56 | 57 | 65 |
66 |
67 | -------------------------------------------------------------------------------- /src/app/features/room/components/upsert-room-dialog/upsert-room-dialog.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, Inject, OnInit } from '@angular/core'; 2 | import { FormBuilder } from '@angular/forms'; 3 | import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; 4 | import { take } from 'rxjs/operators'; 5 | import { Room, RoomService } from '../../service/room.service'; 6 | 7 | export enum ActionType { 8 | Update, 9 | Create, 10 | } 11 | 12 | export interface UpsertDialogData { 13 | type: ActionType; 14 | room?: Room; 15 | } 16 | 17 | @Component({ 18 | selector: 'app-upsert-room-dialog', 19 | templateUrl: './upsert-room-dialog.component.html', 20 | styleUrls: ['./upsert-room-dialog.component.scss'], 21 | }) 22 | export class UpsertRoomDialogComponent { 23 | type: ActionType; 24 | upsertForm = this.formBuilder.group({ 25 | title: '', 26 | isPublic: false, 27 | }); 28 | 29 | room: Room; 30 | 31 | ActionType = ActionType; 32 | 33 | constructor( 34 | @Inject(MAT_DIALOG_DATA) data: UpsertDialogData, 35 | private roomService: RoomService, 36 | private formBuilder: FormBuilder, 37 | private dialogRef: MatDialogRef, 38 | ) { 39 | this.type = data.type; 40 | this.room = data.room; 41 | 42 | this.upsertForm.patchValue({ 43 | ...this.room, 44 | }); 45 | } 46 | 47 | submit() { 48 | const roomInput = this.upsertForm.value; 49 | 50 | let request = this.roomService.createRoom(roomInput); 51 | 52 | if (this.type === ActionType.Update) { 53 | request = this.roomService.updateRoom(this.room._id, roomInput); 54 | } 55 | 56 | request.pipe(take(1)).subscribe(room => 57 | this.dialogRef.close({ 58 | ...room, 59 | title: roomInput.title, 60 | isPublic: roomInput.isPublic, 61 | }), 62 | ); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/app/features/notification/service/notification.service.ts: -------------------------------------------------------------------------------- 1 | import { HttpClient } from '@angular/common/http'; 2 | import { Injectable } from '@angular/core'; 3 | import { SwPush, SwUpdate } from '@angular/service-worker'; 4 | import { of } from 'rxjs'; 5 | import { catchError, mergeMap, tap, timeout } from 'rxjs/operators'; 6 | import { environment } from '../../../../environments/environment'; 7 | import { AuthTokenInterceptor } from '../../auth/interceptor/auth-token.interceptor'; 8 | 9 | interface Config { 10 | webPublicKey: string; 11 | } 12 | 13 | const { api } = environment; 14 | 15 | @Injectable({ 16 | providedIn: 'root', 17 | }) 18 | export class NotificationService { 19 | updateAvailable$ = this.swUpdate.available.pipe( 20 | tap(async () => { 21 | await this.swUpdate.activateUpdate(); 22 | 23 | document.location.reload(); 24 | }), 25 | ); 26 | 27 | constructor( 28 | private http: HttpClient, 29 | private swPush: SwPush, 30 | private swUpdate: SwUpdate, 31 | ) {} 32 | 33 | getConfig() { 34 | return this.http.get(`${api}/notification/config`); 35 | } 36 | 37 | requestSubscription() { 38 | return this.getConfig().pipe( 39 | mergeMap(({ webPublicKey: serverPublicKey }) => 40 | this.swPush.requestSubscription({ serverPublicKey }), 41 | ), 42 | tap(subscription => this.setSubscription(subscription)), 43 | ); 44 | } 45 | 46 | getSubscription(): PushSubscription { 47 | return JSON.parse(sessionStorage.getItem('notificationToken') || '{}'); 48 | } 49 | 50 | setSubscription(subscription: PushSubscription) { 51 | sessionStorage.setItem('notificationToken', JSON.stringify(subscription)); 52 | } 53 | 54 | async checkForUpdates() { 55 | try { 56 | await this.swUpdate.checkForUpdate(); 57 | } catch (e) { 58 | console.error('An error occured checking service worker updates', e); 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/app/core/interceptor/error-dialog.interceptor.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { 3 | HttpRequest, 4 | HttpHandler, 5 | HttpEvent, 6 | HttpInterceptor, 7 | HttpErrorResponse, 8 | } from '@angular/common/http'; 9 | import { Observable } from 'rxjs'; 10 | import { tap } from 'rxjs/operators'; 11 | import { MatDialog } from '@angular/material/dialog'; 12 | import { 13 | ErrorDialogComponent, 14 | ErrorDialogData, 15 | } from '../../shared/components/error-dialog/error-dialog.component'; 16 | import { AuthService } from 'src/app/features/auth/service/auth.service'; 17 | import { AuthTokenInterceptor } from '../../features/auth/interceptor/auth-token.interceptor'; 18 | 19 | export interface HttpError { 20 | statusCode: number; 21 | message: string; 22 | error?: string; 23 | } 24 | 25 | @Injectable() 26 | export class ErrorDialogInterceptor implements HttpInterceptor { 27 | static skipHeader = 'errorDialog'; 28 | 29 | constructor(private dialog: MatDialog, private authService: AuthService) {} 30 | 31 | intercept( 32 | request: HttpRequest, 33 | next: HttpHandler, 34 | ): Observable> { 35 | if (request.headers.has(ErrorDialogInterceptor.skipHeader)) { 36 | return next.handle(request); 37 | } 38 | 39 | return next.handle(request).pipe( 40 | tap( 41 | () => {}, 42 | response => { 43 | if (response instanceof HttpErrorResponse) { 44 | if ( 45 | response.status === 401 && 46 | this.authService.getRefreshToken() && 47 | !request.headers.has(AuthTokenInterceptor.skipHeader) 48 | ) { 49 | return; 50 | } 51 | 52 | this.handleError(response.error); 53 | } 54 | }, 55 | ), 56 | ); 57 | } 58 | 59 | handleError(err: HttpError) { 60 | this.dialog.open(ErrorDialogComponent, { 61 | data: { 62 | title: err.error || 'Error', 63 | message: err.message, 64 | }, 65 | width: '350px', 66 | }); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { MaterialModule } from './shared/material/material.module'; 2 | import { BrowserModule } from '@angular/platform-browser'; 3 | import { APP_INITIALIZER, NgModule } from '@angular/core'; 4 | 5 | import { AppComponent } from './app.component'; 6 | import { FeaturesModule } from './features/features.module'; 7 | import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; 8 | import { HTTP_INTERCEPTORS } from '@angular/common/http'; 9 | import { AuthTokenInterceptor } from './features/auth/interceptor/auth-token.interceptor'; 10 | import { ErrorDialogInterceptor } from './core/interceptor/error-dialog.interceptor'; 11 | import { CoreModule } from './core/core.module'; 12 | import { AuthService } from './features/auth/service/auth.service'; 13 | import { APP_BASE_HREF } from '@angular/common'; 14 | import { ServiceWorkerModule } from '@angular/service-worker'; 15 | import { SharedModule } from './shared/shared.module'; 16 | 17 | const initialize = (authService: AuthService) => async () => { 18 | if (authService.getAccessToken()) { 19 | try { 20 | await authService.getProfile().toPromise(); 21 | } catch {} 22 | } 23 | }; 24 | 25 | @NgModule({ 26 | declarations: [AppComponent], 27 | imports: [ 28 | BrowserModule, 29 | MaterialModule, 30 | SharedModule, 31 | FeaturesModule, 32 | BrowserAnimationsModule, 33 | CoreModule, 34 | ServiceWorkerModule.register('ngsw-worker.js', { 35 | enabled: true, 36 | registrationStrategy: 'registerWhenStable:30000', 37 | }), 38 | ], 39 | providers: [ 40 | { provide: APP_BASE_HREF, useValue: '/' }, 41 | { 42 | provide: APP_INITIALIZER, 43 | useFactory: initialize, 44 | deps: [AuthService], 45 | multi: true, 46 | }, 47 | { 48 | provide: HTTP_INTERCEPTORS, 49 | useClass: AuthTokenInterceptor, 50 | multi: true, 51 | }, 52 | { 53 | provide: HTTP_INTERCEPTORS, 54 | useClass: ErrorDialogInterceptor, 55 | multi: true, 56 | }, 57 | ], 58 | bootstrap: [AppComponent], 59 | }) 60 | export class AppModule {} 61 | -------------------------------------------------------------------------------- /src/app/features/auth/pages/register-page/register-page.component.html: -------------------------------------------------------------------------------- 1 | 6 |
7 | 8 |

Register

9 |

Register a new account

10 | 11 |
12 | 13 | Username 14 | 20 | 21 | 22 | 23 | Password 24 | 30 | 31 | 32 | 33 | Email 34 | 40 | 41 | 42 | 43 | Back 44 | 45 | 46 |
47 | 48 | 57 | 58 | 67 | 68 | 76 |
77 |
78 | -------------------------------------------------------------------------------- /src/app/features/room/pages/room-page/room-page.component.html: -------------------------------------------------------------------------------- 1 |
2 |
6 |
11 | {{ showTotalMembers ? 'All' : 'Online' }} members ({{ 13 | (showTotalMembers ? room.members : onlineMembers).length 14 | }}) 16 |
17 | 40 |
41 |
42 | 43 | 51 | {{ room.title }} 52 | 53 | 54 | logout 55 | 56 | 57 | 63 |
64 |
65 | -------------------------------------------------------------------------------- /src/app/features/auth/pages/login-page/login-page.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | import { FormBuilder } from '@angular/forms'; 3 | import { take } from 'rxjs/operators'; 4 | import { AuthService } from '../../service/auth.service'; 5 | 6 | @Component({ 7 | templateUrl: './login-page.component.html', 8 | styleUrls: ['./login-page.component.scss'], 9 | }) 10 | export class LoginPageComponent { 11 | loginForm = this.formBuilder.group({ 12 | username: '', 13 | password: '', 14 | }); 15 | 16 | loading = false; 17 | 18 | constructor( 19 | private formBuilder: FormBuilder, 20 | private authService: AuthService, 21 | ) {} 22 | 23 | submit() { 24 | if (this.loading) { 25 | return; 26 | } 27 | 28 | this.loading = true; 29 | 30 | const user = this.loginForm.value; 31 | 32 | this.authService 33 | .login(user) 34 | .pipe(take(1)) 35 | .subscribe( 36 | () => this.authService.redirectToCallback(), 37 | () => { 38 | this.loading = false; 39 | 40 | this.loginForm.patchValue({ 41 | password: '', 42 | }); 43 | }, 44 | ); 45 | } 46 | 47 | async loginWithFacebook() { 48 | if (this.loading) { 49 | return; 50 | } 51 | 52 | this.loading = true; 53 | 54 | try { 55 | await this.authService.handleSocialLogin(() => 56 | this.authService.loginWithFacebook(), 57 | ); 58 | } finally { 59 | this.loading = false; 60 | } 61 | } 62 | 63 | async loginWithApple() { 64 | if (this.loading) { 65 | return; 66 | } 67 | 68 | this.loading = true; 69 | 70 | try { 71 | await this.authService.handleSocialLogin(() => 72 | this.authService.loginWithApple(), 73 | ); 74 | } finally { 75 | this.loading = false; 76 | } 77 | } 78 | 79 | async loginWithGoogle() { 80 | if (this.loading) { 81 | return; 82 | } 83 | 84 | this.loading = true; 85 | 86 | try { 87 | await this.authService.handleSocialLogin(() => 88 | this.authService.loginWithGoogle(), 89 | ); 90 | } finally { 91 | this.loading = false; 92 | } 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/app/features/auth/pages/register-page/register-page.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | import { FormBuilder } from '@angular/forms'; 3 | import { take } from 'rxjs/operators'; 4 | import { AuthService } from 'src/app/features/auth/service/auth.service'; 5 | 6 | @Component({ 7 | templateUrl: './register-page.component.html', 8 | styleUrls: ['./register-page.component.scss'], 9 | }) 10 | export class RegisterPageComponent { 11 | registerForm = this.formBuilder.group({ 12 | username: '', 13 | password: '', 14 | email: '', 15 | }); 16 | 17 | loading = false; 18 | 19 | constructor( 20 | private formBuilder: FormBuilder, 21 | private authService: AuthService, 22 | ) {} 23 | 24 | submit() { 25 | this.loading = true; 26 | 27 | const user = this.registerForm.value; 28 | 29 | this.authService 30 | .register(user) 31 | .pipe(take(1)) 32 | .subscribe( 33 | () => this.authService.redirectToCallback(), 34 | () => { 35 | this.loading = false; 36 | 37 | this.registerForm.patchValue({ 38 | password: '', 39 | }); 40 | }, 41 | ); 42 | } 43 | 44 | async registerWithFacebook() { 45 | if (this.loading) { 46 | return; 47 | } 48 | 49 | this.loading = true; 50 | 51 | try { 52 | await this.authService.handleSocialLogin(() => 53 | this.authService.loginWithFacebook(), 54 | ); 55 | } finally { 56 | this.loading = false; 57 | } 58 | } 59 | 60 | async registerWithGoogle() { 61 | if (this.loading) { 62 | return; 63 | } 64 | 65 | this.loading = true; 66 | 67 | try { 68 | await this.authService.handleSocialLogin(() => 69 | this.authService.loginWithGoogle(), 70 | ); 71 | } finally { 72 | this.loading = false; 73 | } 74 | } 75 | 76 | async registerWithApple() { 77 | if (this.loading) { 78 | return; 79 | } 80 | 81 | this.loading = true; 82 | 83 | try { 84 | await this.authService.handleSocialLogin(() => 85 | this.authService.loginWithApple(), 86 | ); 87 | } finally { 88 | this.loading = false; 89 | } 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "task", 3 | "version": "0.0.0", 4 | "scripts": { 5 | "ng": "ng", 6 | "start": "ng serve", 7 | "start:worker": "ng build; npm run store:404; npm run store:worker; http-server -p 8080 -c-1 dist/task", 8 | "build": "ng build --configuration production; npm run store:worker;", 9 | "store:404": "cp ./src/index.html ./dist/task/404.html", 10 | "store:worker": "cp ./src/ngsw-worker.js ./dist/task", 11 | "test": "ng test", 12 | "lint": "ng lint", 13 | "e2e": "ng e2e", 14 | "format": "prettier --write \"src/**/*.ts\"" 15 | }, 16 | "private": true, 17 | "dependencies": { 18 | "@angular/animations": "~12.1.2", 19 | "@angular/cdk": "^12.1.2", 20 | "@angular/common": "~12.1.2", 21 | "@angular/compiler": "~12.1.2", 22 | "@angular/core": "~12.1.2", 23 | "@angular/forms": "~12.1.2", 24 | "@angular/material": "^12.1.2", 25 | "@angular/platform-browser": "~12.1.2", 26 | "@angular/platform-browser-dynamic": "~12.1.2", 27 | "@angular/router": "~12.1.2", 28 | "@angular/service-worker": "~12.1.2", 29 | "angularx-social-login": "^4.0.1", 30 | "autobind-decorator": "^2.4.0", 31 | "bootstrap": "^5.0.0-beta3", 32 | "jquery": "^3.6.0", 33 | "lodash": "^4.17.21", 34 | "ngx-socket-io": "^4.0.0", 35 | "popper.js": "^1.16.1", 36 | "rxjs": "~6.5.5", 37 | "socket.io-client": "^4.1.1", 38 | "sweetalert2": "^11.0.17", 39 | "tslib": "^2.0.0", 40 | "zone.js": "~0.11.4" 41 | }, 42 | "devDependencies": { 43 | "@angular-devkit/build-angular": "~12.1.2", 44 | "@angular/cli": "~12.1.2", 45 | "@angular/compiler-cli": "~12.1.2", 46 | "@types/jasmine": "~3.6.0", 47 | "@types/jasminewd2": "~2.0.3", 48 | "@types/lodash": "^4.14.168", 49 | "@types/node": "^12.11.1", 50 | "codelyzer": "^6.0.0", 51 | "http-server": "^13.0.0", 52 | "jasmine-core": "~3.6.0", 53 | "jasmine-spec-reporter": "~5.0.0", 54 | "karma": "~6.3.4", 55 | "karma-chrome-launcher": "~3.1.0", 56 | "karma-coverage-istanbul-reporter": "~3.0.2", 57 | "karma-jasmine": "~4.0.0", 58 | "karma-jasmine-html-reporter": "^1.5.0", 59 | "protractor": "~7.0.0", 60 | "sass": "~1.32.12", 61 | "ts-node": "~8.3.0", 62 | "tslint": "~6.1.0", 63 | "typescript": "~4.3.5" 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/app/features/routes.ts: -------------------------------------------------------------------------------- 1 | import { Routes } from '@angular/router'; 2 | import { LoginPageComponent } from './auth/pages/login-page/login-page.component'; 3 | import { MainComponent } from './main/main.component'; 4 | import { RegisterPageComponent } from './auth/pages/register-page/register-page.component'; 5 | import { AuthGuard } from './auth/guard/auth.guard'; 6 | import { SettingsPageComponent } from './user/pages/settings-page/settings-page.component'; 7 | import { RecoverChangePasswordPageComponent } from './user/pages/recover-change-password-page/recover-change-password-page.component'; 8 | import { RoomsPageComponent } from './room/pages/rooms-page/rooms-page.component'; 9 | import { RoomPageComponent } from './room/pages/room-page/room-page.component'; 10 | import { RecoverPageComponent } from './user/pages/recover-page/recover-page.component'; 11 | import { DirectMessagePageComponent } from './messages/pages/direct-message-page/direct-message-page.component'; 12 | 13 | export const routes: Routes = [ 14 | { path: '', component: MainComponent }, 15 | { 16 | path: 'login', 17 | component: LoginPageComponent, 18 | canActivate: [AuthGuard], 19 | data: { 20 | requireAuth: false, 21 | }, 22 | }, 23 | { 24 | path: 'register', 25 | component: RegisterPageComponent, 26 | canActivate: [AuthGuard], 27 | data: { 28 | requireAuth: false, 29 | }, 30 | }, 31 | { 32 | path: 'recover', 33 | pathMatch: 'full', 34 | component: RecoverPageComponent, 35 | canActivate: [AuthGuard], 36 | data: { 37 | requireAuth: false, 38 | }, 39 | }, 40 | { 41 | path: 'recover/:code', 42 | pathMatch: 'full', 43 | component: RecoverChangePasswordPageComponent, 44 | canActivate: [AuthGuard], 45 | data: { 46 | requireAuth: false, 47 | }, 48 | }, 49 | { 50 | path: 'settings', 51 | component: SettingsPageComponent, 52 | canActivate: [AuthGuard], 53 | }, 54 | { 55 | path: 'rooms', 56 | component: RoomsPageComponent, 57 | canActivate: [AuthGuard], 58 | }, 59 | { 60 | path: 'room/:id', 61 | component: RoomPageComponent, 62 | canActivate: [AuthGuard], 63 | }, 64 | { 65 | path: 'direct-message/:username', 66 | component: DirectMessagePageComponent, 67 | canActivate: [AuthGuard], 68 | }, 69 | { path: '**', redirectTo: '/' }, 70 | ]; 71 | -------------------------------------------------------------------------------- /src/app/features/user/pages/recover-change-password-page/recover-change-password-page.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnDestroy, OnInit } from '@angular/core'; 2 | import { FormBuilder } from '@angular/forms'; 3 | import { ActivatedRoute, Router } from '@angular/router'; 4 | import { Subscription } from 'rxjs'; 5 | import Swal from 'sweetalert2'; 6 | import { mergeMap, take } from 'rxjs/operators'; 7 | import { RecoverService } from '../../service/recover.service'; 8 | 9 | @Component({ 10 | templateUrl: './recover-change-password-page.component.html', 11 | styleUrls: ['./recover-change-password-page.component.scss'], 12 | }) 13 | export class RecoverChangePasswordPageComponent implements OnInit, OnDestroy { 14 | changePasswordForm = this.formBuilder.group({ 15 | password: '', 16 | confirmPassword: '', 17 | }); 18 | 19 | code: string; 20 | 21 | paramsSubscription: Subscription; 22 | 23 | loading = true; 24 | 25 | constructor( 26 | private formBuilder: FormBuilder, 27 | private recoverService: RecoverService, 28 | private activatedRoute: ActivatedRoute, 29 | private router: Router, 30 | ) {} 31 | 32 | ngOnInit() { 33 | this.paramsSubscription = this.activatedRoute.params 34 | .pipe( 35 | mergeMap(({ code }) => { 36 | this.code = code; 37 | 38 | return this.recoverService.validateCode(this.code).pipe(take(1)); 39 | }), 40 | ) 41 | .subscribe( 42 | () => (this.loading = false), 43 | () => this.router.navigate(['/']), 44 | ); 45 | } 46 | 47 | ngOnDestroy() { 48 | this.paramsSubscription.unsubscribe(); 49 | } 50 | 51 | submit() { 52 | if (this.loading) { 53 | return; 54 | } 55 | 56 | this.loading = true; 57 | 58 | const clear = () => { 59 | this.loading = false; 60 | 61 | this.changePasswordForm.patchValue({ 62 | password: '', 63 | confirmPassword: '', 64 | }); 65 | }; 66 | 67 | this.recoverService 68 | .changePassword(this.code, this.changePasswordForm.value) 69 | .pipe(take(1)) 70 | .subscribe(() => { 71 | this.loading = false; 72 | 73 | Swal.fire({ 74 | title: 'Good job!', 75 | text: 'Your password was sucessfully updated!', 76 | icon: 'success', 77 | }); 78 | 79 | this.router.navigate(['/login']); 80 | }, clear); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/app/features/auth/interceptor/auth-token.interceptor.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { 3 | HttpRequest, 4 | HttpHandler, 5 | HttpEvent, 6 | HttpInterceptor, 7 | HttpErrorResponse, 8 | } from '@angular/common/http'; 9 | import { Observable, throwError } from 'rxjs'; 10 | import { tap, take, mergeMap, catchError } from 'rxjs/operators'; 11 | import { AuthService } from '../service/auth.service'; 12 | 13 | @Injectable() 14 | export class AuthTokenInterceptor implements HttpInterceptor { 15 | static skipHeader = 'skipTokenInterceptor'; 16 | 17 | constructor(private authService: AuthService) {} 18 | 19 | intercept( 20 | request: HttpRequest, 21 | next: HttpHandler, 22 | ): Observable> { 23 | request = this.handleRequest(request); 24 | 25 | if (request.headers.has(AuthTokenInterceptor.skipHeader)) { 26 | return next.handle(request); 27 | } 28 | 29 | return next.handle(request).pipe( 30 | catchError(response => { 31 | if (response instanceof HttpErrorResponse && response.status === 401) { 32 | if (this.authService.getRefreshToken()) { 33 | return this.authService.loginWithRefreshToken().pipe( 34 | take(1), 35 | tap( 36 | () => {}, 37 | () => this.authService.logout(), 38 | ), 39 | mergeMap(() => 40 | next.handle(this.skipRequest(request)).pipe( 41 | tap( 42 | () => {}, 43 | () => this.authService.logout(), 44 | ), 45 | ), 46 | ), 47 | ); 48 | } 49 | 50 | this.authService.logout(); 51 | } 52 | 53 | return throwError(response); 54 | }), 55 | ); 56 | } 57 | 58 | private skipRequest(request: HttpRequest) { 59 | request = request.clone({ 60 | headers: request.headers.set(AuthTokenInterceptor.skipHeader, 'true'), 61 | }); 62 | 63 | return this.handleRequest(request); 64 | } 65 | 66 | private handleRequest(request: HttpRequest) { 67 | const token = this.authService.getAccessToken(); 68 | 69 | if (token) { 70 | request = request.clone({ 71 | headers: request.headers.set('Authorization', `Bearer ${token}`), 72 | }); 73 | } 74 | 75 | return request; 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/app/features/messages/pages/direct-message-page/direct-message-page.component.ts: -------------------------------------------------------------------------------- 1 | import { Message } from '@angular/compiler/src/i18n/i18n_ast'; 2 | import { ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core'; 3 | import { ActivatedRoute, Router } from '@angular/router'; 4 | import { interval, Subject } from 'rxjs'; 5 | import { 6 | catchError, 7 | filter, 8 | mergeMap, 9 | take, 10 | takeUntil, 11 | tap, 12 | } from 'rxjs/operators'; 13 | import { User } from '../../../auth/service/auth.service'; 14 | import { UserService } from '../../../user/service/user.service'; 15 | import { MessageType } from '../../components/messages/messages.component'; 16 | 17 | @Component({ 18 | templateUrl: './direct-message-page.component.html', 19 | styleUrls: ['./direct-message-page.component.scss'], 20 | }) 21 | export class DirectMessagePageComponent implements OnInit, OnDestroy { 22 | MessageType = MessageType; 23 | updateMessages$ = new Subject(); 24 | messages: Message[] = []; 25 | destroy$ = new Subject(); 26 | toName: string; 27 | to: User; 28 | 29 | constructor( 30 | private userService: UserService, 31 | private route: ActivatedRoute, 32 | private router: Router, 33 | private changeDetector: ChangeDetectorRef, 34 | ) {} 35 | 36 | ngOnInit() { 37 | this.route.params 38 | .pipe( 39 | takeUntil(this.destroy$), 40 | mergeMap(params => { 41 | this.toName = params.username; 42 | 43 | return this.userService.getUser(this.toName).pipe(take(1)); 44 | }), 45 | catchError(() => this.router.navigate(['/'])), 46 | filter(user => typeof user !== 'boolean'), 47 | tap(user => { 48 | this.to = user; 49 | 50 | this.changeDetector.detectChanges(); 51 | 52 | this.updateMessages$.next(); 53 | }), 54 | ) 55 | .subscribe(); 56 | 57 | interval(5000) 58 | .pipe( 59 | takeUntil(this.destroy$), 60 | filter(() => this.to != null), 61 | mergeMap(() => this.userService.getUser(this.toName).pipe(take(1))), 62 | tap( 63 | user => (this.to = user), 64 | () => this.router.navigate(['/rooms']), 65 | ), 66 | ) 67 | .subscribe(); 68 | } 69 | 70 | ngOnDestroy() { 71 | this.destroy$.next(); 72 | this.destroy$.complete(); 73 | 74 | this.updateMessages$.complete(); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/app/features/messages/components/messages/messages.component.scss: -------------------------------------------------------------------------------- 1 | @import 'bootstrap-globals'; 2 | 3 | :host { 4 | display: flex; 5 | flex-grow: 1; 6 | } 7 | 8 | .messages { 9 | overflow: auto; 10 | 11 | .message { 12 | word-break: break-word; 13 | overflow-wrap: break-all; 14 | 15 | & > i { 16 | font-size: 0.8rem; 17 | } 18 | 19 | &:first-child { 20 | margin-top: 1rem; 21 | } 22 | 23 | &:last-child { 24 | margin-bottom: 1rem; 25 | } 26 | 27 | & > a { 28 | font-size: 0.8rem; 29 | color: #444; 30 | text-decoration: none; 31 | } 32 | 33 | * { 34 | display: inline-flex; 35 | } 36 | 37 | .typing { 38 | span { 39 | height: 1rem; 40 | width: 1rem; 41 | float: left; 42 | margin: 0 1px; 43 | background-color: #9e9ea1; 44 | display: block; 45 | border-radius: 50%; 46 | opacity: 0.4; 47 | @for $i from 1 through 3 { 48 | &:nth-of-type(#{$i}) { 49 | animation: 1s blink infinite ($i * 0.3333s); 50 | } 51 | } 52 | } 53 | 54 | .bubble { 55 | white-space: initial; 56 | } 57 | } 58 | 59 | .bubble-container { 60 | .delete { 61 | display: none; 62 | } 63 | 64 | &:hover, 65 | &:focus { 66 | .delete { 67 | display: flex; 68 | } 69 | } 70 | 71 | .bubble { 72 | box-shadow: 2px 2px 5px 0 rgba($color: #000000, $alpha: 0.2); 73 | border-radius: 0.5rem; 74 | white-space: pre-wrap; 75 | font-size: 1rem; 76 | } 77 | } 78 | 79 | &.partner { 80 | align-items: flex-start; 81 | 82 | .bubble-container { 83 | flex-direction: row-reverse; 84 | 85 | .bubble { 86 | background-color: map-get($theme-colors, 'primary'); 87 | border-top-right-radius: 0; 88 | color: #fff; 89 | } 90 | } 91 | } 92 | 93 | &.me { 94 | align-items: flex-end; 95 | 96 | .bubble { 97 | background-color: rgba($color: #000000, $alpha: 0.03); 98 | border-top-left-radius: 0; 99 | } 100 | } 101 | } 102 | } 103 | 104 | .mt-6 { 105 | margin-top: 8rem; 106 | } 107 | 108 | .z-10 { 109 | z-index: 10; 110 | } 111 | 112 | @keyframes blink { 113 | 50% { 114 | opacity: 1; 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /src/app/features/room/service/room.service.ts: -------------------------------------------------------------------------------- 1 | import { HttpClient } from '@angular/common/http'; 2 | import { Injectable } from '@angular/core'; 3 | import { map, tap } from 'rxjs/operators'; 4 | import { environment } from '../../../../environments/environment'; 5 | import { MainSocket } from '../../../core/socket/main-socket'; 6 | import { User } from '../../auth/service/auth.service'; 7 | 8 | const { api } = environment; 9 | 10 | export interface Room { 11 | _id: string; 12 | title: string; 13 | isPublic: boolean; 14 | members: User[] | string[]; 15 | owner: User | string; 16 | } 17 | 18 | @Injectable({ 19 | providedIn: 'root', 20 | }) 21 | export class RoomService { 22 | constructor(private socket: MainSocket, private http: HttpClient) {} 23 | 24 | getRoom(roomId: string) { 25 | return this.http 26 | .get(`${api}/room/id/${roomId}`) 27 | .pipe(map(this.getRoomWithSortedMembers)); 28 | } 29 | 30 | getPublicRooms() { 31 | return this.http.get(`${api}/room/public`); 32 | } 33 | 34 | getRoomsByMember() { 35 | return this.http.get(`${api}/room/member`); 36 | } 37 | 38 | getUserRooms() { 39 | return this.http.get(`${api}/room`); 40 | } 41 | 42 | createRoom(room: Partial) { 43 | return this.http.post(`${api}/room`, room); 44 | } 45 | 46 | deleteRoom(room: Room) { 47 | return this.http.delete(`${api}/room/delete/${room._id}`); 48 | } 49 | 50 | updateRoom(id: string, room: Room) { 51 | return this.http.put(`${api}/room/${id}`, room); 52 | } 53 | 54 | joinRoom(roomId: string) { 55 | return this.http 56 | .post(`${api}/room/join`, { roomId }) 57 | .pipe(map(this.getRoomWithSortedMembers)); 58 | } 59 | 60 | leaveRoom(roomId: string) { 61 | return this.http.delete(`${api}/room/leave/${roomId}`); 62 | } 63 | 64 | subscribeRoom(room: Room) { 65 | this.socket.emit('room:subscribe', room._id); 66 | } 67 | 68 | onLeaveEvent() { 69 | return this.socket.fromEvent('room:leave'); 70 | } 71 | 72 | onJoinEvent() { 73 | return this.socket.fromEvent('room:join'); 74 | } 75 | 76 | onUpdateEvent() { 77 | return this.socket 78 | .fromEvent('room:update') 79 | .pipe(map(this.getRoomWithSortedMembers)); 80 | } 81 | 82 | onDeleteEvent() { 83 | return this.socket.fromEvent('room:delete'); 84 | } 85 | 86 | getRoomWithSortedMembers(room: Room) { 87 | room.members = room.members.sort((a: any, b: any) => 88 | a.online === b.online ? 0 : a.online ? -1 : b.online ? 1 : 0, 89 | ); 90 | 91 | return room; 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/app/features/user/pages/settings-page/settings-page.component.html: -------------------------------------------------------------------------------- 1 | 6 |
7 | 8 |

Settings

9 |

Update your account

10 | 11 |
12 |

Username

13 | 14 | Username 15 | 21 | 22 | 23 | 24 | 27 | 28 |
29 | 30 |
31 |

Email

32 | 33 | Email 34 | 40 | 41 | 42 | 43 | 46 | 47 |
48 | 49 |
50 |

Password

51 | 52 | Current Password 53 | 59 | 60 | 61 | 62 | New Password 63 | 69 | 70 | 71 | 72 | Confirm Password 73 | 79 | 80 | 81 | 82 | Back 83 | 86 | 87 |
88 |
89 |
90 | -------------------------------------------------------------------------------- /src/app/features/messages/service/message.service.ts: -------------------------------------------------------------------------------- 1 | import { HttpClient } from '@angular/common/http'; 2 | import { Injectable } from '@angular/core'; 3 | import { environment } from '../../../../environments/environment'; 4 | import { MainSocket } from '../../../core/socket/main-socket'; 5 | import { AuthTokenInterceptor } from '../../auth/interceptor/auth-token.interceptor'; 6 | import { User } from '../../auth/service/auth.service'; 7 | import { Room } from '../../room/service/room.service'; 8 | import { MessageType } from '../components/messages/messages.component'; 9 | 10 | export interface Message { 11 | _id: string; 12 | message: string; 13 | to: string; 14 | room?: string; 15 | from?: User; 16 | createdAt?: string; 17 | } 18 | 19 | export interface TypingResponse { 20 | room?: Room; 21 | user: User; 22 | } 23 | 24 | const { api } = environment; 25 | 26 | @Injectable({ 27 | providedIn: 'root', 28 | }) 29 | export class MessageService { 30 | constructor(private socket: MainSocket, private http: HttpClient) {} 31 | 32 | getMessages(type: MessageType, id: string, limit: number, before?: string) { 33 | const params = { limit, before }; 34 | 35 | for (const key of Object.keys(params)) { 36 | if (!params[key]) { 37 | delete params[key]; 38 | } 39 | } 40 | 41 | return this.http.get(`${api}/message/${type}/${id}`, { params }); 42 | } 43 | 44 | getFirstMessage(type: MessageType, id: string) { 45 | return this.http.get(`${api}/message/${type}-first-message/${id}`); 46 | } 47 | 48 | onMessage(type: MessageType) { 49 | return this.socket.fromEvent(`message:${type}`); 50 | } 51 | 52 | sendMessage( 53 | type: MessageType, 54 | id: string, 55 | message: string, 56 | callback?: (data: T) => void, 57 | ) { 58 | return this.socket.emit( 59 | `message:${type}`, 60 | { 61 | to: id, 62 | roomId: id, 63 | message, 64 | }, 65 | callback, 66 | ); 67 | } 68 | 69 | sendTyping(type: MessageType, id: string) { 70 | return this.socket.emit(`message:${type}:typing`, id); 71 | } 72 | 73 | deleteMessage(type: MessageType, message: Message) { 74 | return this.http.delete(`${api}/message/${type}`, { 75 | body: { 76 | messageId: message._id, 77 | roomId: message.room, 78 | to: message.to, 79 | }, 80 | headers: { 81 | [AuthTokenInterceptor.skipHeader]: 'true', 82 | }, 83 | }); 84 | } 85 | 86 | onDeleteMessagesEvent(type: MessageType) { 87 | return this.socket.fromEvent(`${type}:delete_messages`); 88 | } 89 | 90 | onDeleteMessageEvent(type: MessageType) { 91 | return this.socket.fromEvent(`${type}:delete_message`); 92 | } 93 | 94 | onTyping(type: MessageType, id: string) { 95 | return this.socket.fromEvent(`message:${type}:typing`); 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/app/features/room/pages/rooms-page/rooms-page.component.ts: -------------------------------------------------------------------------------- 1 | import { Clipboard } from '@angular/cdk/clipboard'; 2 | import { Component, OnDestroy, OnInit } from '@angular/core'; 3 | import { MatDialog } from '@angular/material/dialog'; 4 | import { Router } from '@angular/router'; 5 | import { remove } from 'lodash'; 6 | import { forkJoin, Subject } from 'rxjs'; 7 | import { take, takeUntil, tap } from 'rxjs/operators'; 8 | import { ConfirmDialogComponent } from '../../../../shared/components/confirm-dialog/confirm-dialog.component'; 9 | import { updateItem } from '../../../../shared/utils/upsert-item'; 10 | import { AuthService, User } from '../../../auth/service/auth.service'; 11 | import { JoinRoomDialogComponent } from '../../components/join-room-dialog/join-room-dialog.component'; 12 | import { 13 | ActionType, 14 | UpsertRoomDialogComponent, 15 | } from '../../components/upsert-room-dialog/upsert-room-dialog.component'; 16 | import { Room, RoomService } from '../../service/room.service'; 17 | 18 | @Component({ 19 | templateUrl: './rooms-page.component.html', 20 | styleUrls: ['./rooms-page.component.scss'], 21 | }) 22 | export class RoomsPageComponent implements OnInit, OnDestroy { 23 | publicRooms: Room[] = []; 24 | userRooms: Room[] = []; 25 | memberRooms: Room[] = []; 26 | user: User; 27 | 28 | loading = false; 29 | 30 | destroy$ = new Subject(); 31 | 32 | constructor( 33 | private roomService: RoomService, 34 | private dialog: MatDialog, 35 | private authService: AuthService, 36 | private clipboard: Clipboard, 37 | private router: Router, 38 | ) {} 39 | 40 | ngOnInit() { 41 | this.loading = true; 42 | 43 | const process = () => (this.loading = false); 44 | 45 | forkJoin({ 46 | userRooms: this.roomService.getUserRooms().pipe(take(1)), 47 | publicRooms: this.roomService.getPublicRooms().pipe(take(1)), 48 | memberRooms: this.roomService.getRoomsByMember().pipe(take(1)), 49 | }) 50 | .pipe(tap(process, process)) 51 | .subscribe(({ userRooms, publicRooms, memberRooms }) => { 52 | this.publicRooms = publicRooms; 53 | this.userRooms = userRooms; 54 | this.memberRooms = memberRooms; 55 | }); 56 | 57 | this.authService.user$ 58 | .pipe(takeUntil(this.destroy$)) 59 | .subscribe(user => (this.user = user)); 60 | } 61 | 62 | ngOnDestroy() { 63 | this.destroy$.next(); 64 | this.destroy$.complete(); 65 | } 66 | 67 | openCreateDialog() { 68 | const dialog = this.dialog.open(UpsertRoomDialogComponent, { 69 | data: { 70 | type: ActionType.Create, 71 | }, 72 | }); 73 | 74 | dialog 75 | .afterClosed() 76 | .pipe(take(1)) 77 | .subscribe((room: Room) => { 78 | if (room.isPublic) { 79 | this.publicRooms.push(room); 80 | } 81 | 82 | this.userRooms.push(room); 83 | }); 84 | } 85 | 86 | openJoinRoomDialog() { 87 | this.dialog.open(JoinRoomDialogComponent); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/polyfills.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file includes polyfills needed by Angular and is loaded before the app. 3 | * You can add your own extra polyfills to this file. 4 | * 5 | * This file is divided into 2 sections: 6 | * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. 7 | * 2. Application imports. Files imported after ZoneJS that should be loaded before your main 8 | * file. 9 | * 10 | * The current setup is for so-called "evergreen" browsers; the last versions of browsers that 11 | * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), 12 | * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. 13 | * 14 | * Learn more in https://angular.io/guide/browser-support 15 | */ 16 | 17 | /*************************************************************************************************** 18 | * BROWSER POLYFILLS 19 | */ 20 | 21 | /** IE10 and IE11 requires the following for NgClass support on SVG elements */ 22 | // import 'classlist.js'; // Run `npm install --save classlist.js`. 23 | 24 | /** 25 | * Web Animations `@angular/platform-browser/animations` 26 | * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari. 27 | * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0). 28 | */ 29 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`. 30 | 31 | /** 32 | * By default, zone.js will patch all possible macroTask and DomEvents 33 | * user can disable parts of macroTask/DomEvents patch by setting following flags 34 | * because those flags need to be set before `zone.js` being loaded, and webpack 35 | * will put import in the top of bundle, so user need to create a separate file 36 | * in this directory (for example: zone-flags.ts), and put the following flags 37 | * into that file, and then add the following code before importing zone.js. 38 | * import './zone-flags'; 39 | * 40 | * The flags allowed in zone-flags.ts are listed here. 41 | * 42 | * The following flags will work for all browsers. 43 | * 44 | * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame 45 | * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick 46 | * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames 47 | * 48 | * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js 49 | * with the following flag, it will bypass `zone.js` patch for IE/Edge 50 | * 51 | * (window as any).__Zone_enable_cross_context_check = true; 52 | * 53 | */ 54 | 55 | /*************************************************************************************************** 56 | * Zone JS is required by default for Angular itself. 57 | */ 58 | import 'zone.js'; // Included with Angular CLI. 59 | 60 | /*************************************************************************************************** 61 | * APPLICATION IMPORTS 62 | */ 63 | -------------------------------------------------------------------------------- /src/app/features/messages/components/messages/messages.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |
7 | 8 |

Connecting

9 |
10 |
15 |
20 | {{ message.from.username }} 25 |
26 |
{{ message.message }}
27 | delete 38 |
39 | {{ message.createdAtDate | date: 'short' }} 40 |
41 | 42 |
47 | {{ userTyping.username }} 52 |
53 |
54 | 55 | 56 | 57 |
58 |
59 |
60 |
61 |
62 |
63 |
68 | 69 | Message 70 | 79 | 80 |
81 | 84 |
85 |
86 |
87 |
88 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "tslint:recommended", 3 | "rules": { 4 | "align": { 5 | "options": ["parameters", "statements"] 6 | }, 7 | "array-type": false, 8 | "arrow-return-shorthand": true, 9 | "curly": true, 10 | "deprecation": { 11 | "severity": "warning" 12 | }, 13 | "component-class-suffix": true, 14 | "contextual-lifecycle": true, 15 | "directive-class-suffix": true, 16 | "directive-selector": [true, "attribute", "app", "camelCase"], 17 | "component-selector": [true, "element", "app", "kebab-case"], 18 | "eofline": true, 19 | "import-blacklist": [true, "rxjs/Rx"], 20 | "import-spacing": true, 21 | "indent": { 22 | "options": ["spaces"] 23 | }, 24 | "max-classes-per-file": false, 25 | "max-line-length": [true, 140], 26 | "member-ordering": [ 27 | true, 28 | { 29 | "order": [ 30 | "static-field", 31 | "instance-field", 32 | "static-method", 33 | "instance-method" 34 | ] 35 | } 36 | ], 37 | "no-console": [true, "debug", "info", "time", "timeEnd", "trace"], 38 | "no-empty": false, 39 | "no-inferrable-types": [true, "ignore-params"], 40 | "no-non-null-assertion": true, 41 | "no-redundant-jsdoc": true, 42 | "no-switch-case-fall-through": true, 43 | "no-var-requires": false, 44 | "object-literal-key-quotes": [true, "as-needed"], 45 | "quotemark": [true, "single"], 46 | "semicolon": { 47 | "options": ["always"] 48 | }, 49 | "space-before-function-paren": { 50 | "options": { 51 | "anonymous": "never", 52 | "asyncArrow": "always", 53 | "constructor": "never", 54 | "method": "never", 55 | "named": "never" 56 | } 57 | }, 58 | "typedef": [false, "call-signature"], 59 | "typedef-whitespace": { 60 | "options": [ 61 | { 62 | "call-signature": "nospace", 63 | "index-signature": "nospace", 64 | "parameter": "nospace", 65 | "property-declaration": "nospace", 66 | "variable-declaration": "nospace" 67 | }, 68 | { 69 | "call-signature": "onespace", 70 | "index-signature": "onespace", 71 | "parameter": "onespace", 72 | "property-declaration": "onespace", 73 | "variable-declaration": "onespace" 74 | } 75 | ] 76 | }, 77 | "variable-name": { 78 | "options": ["ban-keywords", "check-format", "allow-pascal-case"] 79 | }, 80 | "whitespace": { 81 | "options": [ 82 | "check-branch", 83 | "check-decl", 84 | "check-operator", 85 | "check-separator", 86 | "check-type", 87 | "check-typecast" 88 | ] 89 | }, 90 | "no-conflicting-lifecycle": true, 91 | "no-host-metadata-property": true, 92 | "no-input-rename": true, 93 | "no-inputs-metadata-property": true, 94 | "no-output-native": true, 95 | "no-output-on-prefix": true, 96 | "no-output-rename": true, 97 | "no-outputs-metadata-property": true, 98 | "template-banana-in-box": true, 99 | "template-no-negated-async": true, 100 | "use-lifecycle-interface": true, 101 | "use-pipe-transform-interface": true 102 | }, 103 | "rulesDirectory": ["codelyzer"] 104 | } 105 | -------------------------------------------------------------------------------- /src/app/features/room/pages/room-page/room-page.component.ts: -------------------------------------------------------------------------------- 1 | import { ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core'; 2 | import { ActivatedRoute, Router } from '@angular/router'; 3 | import { remove } from 'lodash'; 4 | import { interval, Subject } from 'rxjs'; 5 | import { 6 | catchError, 7 | filter, 8 | mergeMap, 9 | take, 10 | takeUntil, 11 | tap, 12 | } from 'rxjs/operators'; 13 | import { MainSocket } from '../../../../core/socket/main-socket'; 14 | import { AuthService, User } from '../../../auth/service/auth.service'; 15 | import { MessageType } from '../../../messages/components/messages/messages.component'; 16 | import { Message } from '../../../messages/service/message.service'; 17 | import { Room, RoomService } from '../../service/room.service'; 18 | 19 | interface InternalRoom extends Room { 20 | members: User[]; 21 | } 22 | 23 | @Component({ 24 | templateUrl: './room-page.component.html', 25 | styleUrls: ['./room-page.component.scss'], 26 | }) 27 | export class RoomPageComponent implements OnInit, OnDestroy { 28 | roomId: string; 29 | room: InternalRoom; 30 | destroy$ = new Subject(); 31 | MessageType = MessageType; 32 | areMembersShown = false; 33 | messages: Message[] = []; 34 | updateMessages$ = new Subject(); 35 | user: User; 36 | showTotalMembers = true; 37 | 38 | constructor( 39 | private roomService: RoomService, 40 | private route: ActivatedRoute, 41 | private socket: MainSocket, 42 | private router: Router, 43 | private authService: AuthService, 44 | private changeDetector: ChangeDetectorRef, 45 | ) {} 46 | 47 | get onlineMembers() { 48 | return this.room.members.filter(user => user.online); 49 | } 50 | 51 | ngOnInit() { 52 | // Subscribe to room events 53 | this.route.params 54 | .pipe( 55 | takeUntil(this.destroy$), 56 | mergeMap(params => { 57 | this.roomId = params.id; 58 | 59 | return this.roomService.joinRoom(this.roomId).pipe(take(1)); 60 | }), 61 | catchError(() => this.router.navigate(['/rooms'])), 62 | filter(room => typeof room !== 'boolean'), 63 | mergeMap(room => { 64 | this.room = room; 65 | 66 | this.changeDetector.detectChanges(); 67 | 68 | return this.socket.onConnect(); 69 | }), 70 | tap(() => { 71 | this.roomService.subscribeRoom(this.room); 72 | 73 | this.updateMessages$.next(); 74 | }), 75 | takeUntil(this.destroy$), 76 | ) 77 | .subscribe(); 78 | 79 | interval(5000) 80 | .pipe( 81 | takeUntil(this.destroy$), 82 | filter(() => this.room != null), 83 | mergeMap(() => this.roomService.getRoom(this.roomId).pipe(take(1))), 84 | tap( 85 | room => (this.room = room), 86 | () => this.router.navigate(['/rooms']), 87 | ), 88 | ) 89 | .subscribe(); 90 | 91 | this.roomService 92 | .onJoinEvent() 93 | .pipe(takeUntil(this.destroy$)) 94 | .subscribe(user => { 95 | this.room.members.push(user); 96 | 97 | this.room = this.roomService.getRoomWithSortedMembers( 98 | this.room, 99 | ) as InternalRoom; 100 | }); 101 | 102 | this.roomService 103 | .onLeaveEvent() 104 | .pipe(takeUntil(this.destroy$)) 105 | .subscribe(user => { 106 | if (user._id === this.user._id) { 107 | this.router.navigate(['/rooms']); 108 | 109 | return; 110 | } 111 | 112 | remove(this.room.members, u => u === user || u._id === user._id); 113 | }); 114 | 115 | this.roomService 116 | .onUpdateEvent() 117 | .pipe(takeUntil(this.destroy$)) 118 | .subscribe(room => (this.room = room)); 119 | 120 | this.roomService 121 | .onDeleteEvent() 122 | .pipe(takeUntil(this.destroy$)) 123 | .subscribe(() => this.router.navigate(['/rooms'])); 124 | 125 | this.authService.user$ 126 | .pipe(takeUntil(this.destroy$)) 127 | .subscribe(user => (this.user = user)); 128 | } 129 | 130 | ngOnDestroy() { 131 | this.destroy$.next(); 132 | this.destroy$.complete(); 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /src/app/features/room/components/room-item/room-item.component.ts: -------------------------------------------------------------------------------- 1 | import { Clipboard } from '@angular/cdk/clipboard'; 2 | import { Component, Input, OnInit } from '@angular/core'; 3 | import { MatDialog } from '@angular/material/dialog'; 4 | import { Router } from '@angular/router'; 5 | import { remove } from 'lodash'; 6 | import { take, tap } from 'rxjs/operators'; 7 | import { ConfirmDialogComponent } from '../../../../shared/components/confirm-dialog/confirm-dialog.component'; 8 | import { updateItem } from '../../../../shared/utils/upsert-item'; 9 | import { User } from '../../../auth/service/auth.service'; 10 | import { Room, RoomService } from '../../service/room.service'; 11 | import { 12 | ActionType, 13 | UpsertRoomDialogComponent, 14 | } from '../upsert-room-dialog/upsert-room-dialog.component'; 15 | 16 | @Component({ 17 | selector: 'app-room-item', 18 | templateUrl: './room-item.component.html', 19 | styleUrls: ['./room-item.component.scss'], 20 | }) 21 | export class RoomItemComponent implements OnInit { 22 | @Input() room: Room; 23 | @Input() user: User; 24 | @Input() publicRooms: Room[] = []; 25 | @Input() userRooms: Room[] = []; 26 | @Input() memberRooms: Room[] = []; 27 | 28 | loading = false; 29 | isOwner = false; 30 | 31 | get isMember() { 32 | return this.memberRooms.some(e => e._id === this.room._id); 33 | } 34 | 35 | constructor( 36 | private roomService: RoomService, 37 | private dialog: MatDialog, 38 | private clipboard: Clipboard, 39 | private router: Router, 40 | ) {} 41 | 42 | ngOnInit() { 43 | this.isOwner = 44 | this.room.owner === this.user._id || 45 | (this.room.owner as User)._id === this.user._id; 46 | } 47 | 48 | openUpdateDialog() { 49 | const dialog = this.dialog.open(UpsertRoomDialogComponent, { 50 | data: { 51 | type: ActionType.Update, 52 | room: this.room, 53 | }, 54 | }); 55 | 56 | dialog 57 | .afterClosed() 58 | .pipe(take(1)) 59 | .subscribe((updatedRoom: Room) => { 60 | updateItem(this.publicRooms, r => r._id === this.room._id, updatedRoom); 61 | updateItem(this.memberRooms, r => r._id === this.room._id, updatedRoom); 62 | updateItem(this.userRooms, r => r._id === this.room._id, updatedRoom); 63 | }); 64 | } 65 | 66 | confirmDelete() { 67 | const dialog = this.dialog.open(ConfirmDialogComponent); 68 | 69 | dialog 70 | .afterClosed() 71 | .pipe(take(1)) 72 | .subscribe(confirm => { 73 | if (confirm) { 74 | this.delete(); 75 | } 76 | }); 77 | } 78 | 79 | delete() { 80 | if (this.loading) { 81 | return; 82 | } 83 | 84 | this.loading = true; 85 | 86 | this.roomService 87 | .deleteRoom(this.room) 88 | .pipe(take(1)) 89 | .subscribe(() => { 90 | this.loading = false; 91 | 92 | remove(this.userRooms, r => r._id === this.room._id); 93 | remove(this.publicRooms, r => r._id === this.room._id); 94 | remove(this.memberRooms, r => r._id === this.room._id); 95 | }); 96 | } 97 | 98 | joinRoom() { 99 | this.loading = true; 100 | 101 | const process = () => (this.loading = false); 102 | 103 | this.roomService 104 | .getRoom(this.room._id) 105 | .pipe(take(1), tap(process, process)) 106 | .subscribe(() => this.router.navigate(['/room', this.room._id])); 107 | } 108 | 109 | confirmLeaveRoom() { 110 | const dialog = this.dialog.open(ConfirmDialogComponent); 111 | 112 | dialog 113 | .afterClosed() 114 | .pipe(take(1)) 115 | .subscribe(confirm => { 116 | if (confirm) { 117 | this.leaveRoom(); 118 | } 119 | }); 120 | } 121 | 122 | leaveRoom() { 123 | this.loading = true; 124 | 125 | const process = () => (this.loading = false); 126 | 127 | this.roomService 128 | .leaveRoom(this.room._id) 129 | .pipe(take(1), tap(process, process)) 130 | .subscribe(() => remove(this.memberRooms, r => r._id === this.room._id)); 131 | } 132 | 133 | copyUrl() { 134 | this.clipboard.copy(`${window.location.origin}/room/${this.room._id}`); 135 | } 136 | 137 | isString(value: T) { 138 | return typeof value === 'string'; 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /src/app/features/user/pages/settings-page/settings-page.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { FormBuilder } from '@angular/forms'; 3 | import { MatDialog } from '@angular/material/dialog'; 4 | import { take } from 'rxjs/operators'; 5 | import { AuthService } from 'src/app/features/auth/service/auth.service'; 6 | import { 7 | UpdatePasswordBody, 8 | UserService, 9 | } from 'src/app/features/user/service/user.service'; 10 | import { 11 | ConfirmDialogComponent, 12 | ConfirmDialogData, 13 | } from 'src/app/shared/components/confirm-dialog/confirm-dialog.component'; 14 | import Swal from 'sweetalert2'; 15 | 16 | @Component({ 17 | templateUrl: './settings-page.component.html', 18 | styleUrls: ['./settings-page.component.scss'], 19 | }) 20 | export class SettingsPageComponent implements OnInit { 21 | settingsForm = this.formBuilder.group({ 22 | username: '', 23 | email: '', 24 | currentPassword: null, 25 | password: null, 26 | confirmPassword: null, 27 | }); 28 | 29 | loading = false; 30 | 31 | get user() { 32 | return this.authService.user; 33 | } 34 | 35 | constructor( 36 | private formBuilder: FormBuilder, 37 | private userService: UserService, 38 | private authService: AuthService, 39 | private dialog: MatDialog, 40 | ) {} 41 | 42 | ngOnInit() { 43 | const { username, email } = this.authService.user; 44 | 45 | this.settingsForm.patchValue({ 46 | username, 47 | email, 48 | }); 49 | } 50 | 51 | updateUsername() { 52 | const { username } = this.settingsForm.value; 53 | 54 | if (this.loading || this.user.username === username) { 55 | return; 56 | } 57 | 58 | this.loading = true; 59 | 60 | this.userService 61 | .updateUsername(username) 62 | .pipe(take(1)) 63 | .subscribe( 64 | () => { 65 | this.authService.user$.next({ 66 | ...this.authService.user, 67 | username, 68 | }); 69 | 70 | this.loading = false; 71 | 72 | Swal.fire({ 73 | title: 'Good job!', 74 | text: 'Your username was sucessfully updated!', 75 | icon: 'success', 76 | }); 77 | }, 78 | () => (this.loading = false), 79 | ); 80 | } 81 | 82 | updateEmail() { 83 | const { email } = this.settingsForm.value; 84 | 85 | if (this.loading || this.user.email === email) { 86 | return; 87 | } 88 | 89 | this.loading = true; 90 | 91 | this.userService 92 | .updateEmail(email) 93 | .pipe(take(1)) 94 | .subscribe( 95 | () => { 96 | this.authService.user$.next({ 97 | ...this.authService.user, 98 | email, 99 | }); 100 | 101 | this.loading = false; 102 | 103 | Swal.fire({ 104 | title: 'Good job!', 105 | text: 'Your email was sucessfully updated!', 106 | icon: 'success', 107 | }); 108 | }, 109 | () => (this.loading = false), 110 | ); 111 | } 112 | 113 | updatePassword() { 114 | if (this.loading) { 115 | return; 116 | } 117 | 118 | this.loading = true; 119 | 120 | const clear = () => { 121 | this.loading = false; 122 | 123 | this.settingsForm.patchValue({ 124 | currentPassword: null, 125 | password: null, 126 | confirmPassword: null, 127 | }); 128 | }; 129 | 130 | const data: UpdatePasswordBody = this.settingsForm.value; 131 | 132 | this.userService 133 | .updatePassword(data) 134 | .pipe(take(1)) 135 | .subscribe(async () => { 136 | clear(); 137 | 138 | await Swal.fire({ 139 | title: 'Good job!', 140 | text: 'Your password was sucessfully updated!', 141 | icon: 'success', 142 | }); 143 | 144 | this.openLogoutDialog(); 145 | }, clear); 146 | } 147 | 148 | private openLogoutDialog() { 149 | const dialog = this.dialog.open(ConfirmDialogComponent, { 150 | data: { 151 | title: 'Global logout', 152 | description: 'Do you want to logout from all of your devices?', 153 | }, 154 | }); 155 | 156 | dialog 157 | .afterClosed() 158 | .pipe(take(1)) 159 | .subscribe(confirm => { 160 | if (confirm) { 161 | this.logoutFromAllDevices(); 162 | } 163 | }); 164 | } 165 | 166 | private logoutFromAllDevices() { 167 | this.authService 168 | .logoutFromAllDevices() 169 | .pipe(take(1)) 170 | .subscribe(() => 171 | Swal.fire({ 172 | title: 'Good job!', 173 | text: 'All of your devices were successfully logged out!', 174 | icon: 'success', 175 | }), 176 | ); 177 | } 178 | } 179 | -------------------------------------------------------------------------------- /angular.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "version": 1, 4 | "newProjectRoot": "projects", 5 | "projects": { 6 | "task": { 7 | "projectType": "application", 8 | "schematics": { 9 | "@schematics/angular:component": { 10 | "style": "scss" 11 | } 12 | }, 13 | "root": "", 14 | "sourceRoot": "src", 15 | "prefix": "app", 16 | "architect": { 17 | "build": { 18 | "builder": "@angular-devkit/build-angular:browser", 19 | "options": { 20 | "allowedCommonJsDependencies": [ 21 | "lodash", 22 | "socket.io-client", 23 | "ngx-socket-io" 24 | ], 25 | "outputPath": "dist/task", 26 | "index": "src/index.html", 27 | "main": "src/main.ts", 28 | "polyfills": "src/polyfills.ts", 29 | "tsConfig": "tsconfig.app.json", 30 | "assets": [ 31 | "src/favicon.ico", 32 | "src/assets", 33 | "src/worker", 34 | "src/ngsw-worker.js", 35 | "src/manifest.webmanifest" 36 | ], 37 | "styles": [ 38 | "./node_modules/bootstrap/scss/bootstrap.scss", 39 | "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css", 40 | "src/styles/styles.scss" 41 | ], 42 | "scripts": [ 43 | "./node_modules/popper.js/dist/umd/popper.min.js", 44 | "./node_modules/bootstrap/dist/js/bootstrap.min.js" 45 | ], 46 | "stylePreprocessorOptions": { 47 | "includePaths": ["src/styles", "./node_modules/bootstrap/scss"] 48 | }, 49 | "vendorChunk": true, 50 | "extractLicenses": false, 51 | "buildOptimizer": false, 52 | "sourceMap": true, 53 | "optimization": false, 54 | "namedChunks": true, 55 | "serviceWorker": true, 56 | "ngswConfigPath": "ngsw-config.json" 57 | }, 58 | "configurations": { 59 | "production": { 60 | "fileReplacements": [ 61 | { 62 | "replace": "src/environments/environment.ts", 63 | "with": "src/environments/environment.prod.ts" 64 | } 65 | ], 66 | "optimization": true, 67 | "outputHashing": "all", 68 | "sourceMap": false, 69 | "namedChunks": false, 70 | "extractLicenses": true, 71 | "vendorChunk": false, 72 | "buildOptimizer": true, 73 | "budgets": [ 74 | { 75 | "type": "initial", 76 | "maximumWarning": "2mb", 77 | "maximumError": "5mb" 78 | }, 79 | { 80 | "type": "anyComponentStyle", 81 | "maximumWarning": "6kb", 82 | "maximumError": "10kb" 83 | } 84 | ] 85 | } 86 | }, 87 | "defaultConfiguration": "" 88 | }, 89 | "serve": { 90 | "builder": "@angular-devkit/build-angular:dev-server", 91 | "options": { 92 | "browserTarget": "task:build" 93 | }, 94 | "configurations": { 95 | "production": { 96 | "browserTarget": "task:build:production" 97 | } 98 | } 99 | }, 100 | "extract-i18n": { 101 | "builder": "@angular-devkit/build-angular:extract-i18n", 102 | "options": { 103 | "browserTarget": "task:build" 104 | } 105 | }, 106 | "test": { 107 | "builder": "@angular-devkit/build-angular:karma", 108 | "options": { 109 | "main": "src/test.ts", 110 | "polyfills": "src/polyfills.ts", 111 | "tsConfig": "tsconfig.spec.json", 112 | "karmaConfig": "karma.conf.js", 113 | "assets": [ 114 | "src/favicon.ico", 115 | "src/assets", 116 | "src/worker", 117 | "src/ngsw-worker.js", 118 | "src/manifest.webmanifest" 119 | ], 120 | "styles": [ 121 | "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css", 122 | "src/styles.scss", 123 | "node_modules/bootstrap/dist/css/bootstrap.min.css" 124 | ], 125 | "scripts": [] 126 | } 127 | }, 128 | "lint": { 129 | "builder": "@angular-devkit/build-angular:tslint", 130 | "options": { 131 | "tsConfig": [ 132 | "tsconfig.app.json", 133 | "tsconfig.spec.json", 134 | "e2e/tsconfig.json" 135 | ], 136 | "exclude": ["**/node_modules/**"] 137 | } 138 | }, 139 | "e2e": { 140 | "builder": "@angular-devkit/build-angular:protractor", 141 | "options": { 142 | "protractorConfig": "e2e/protractor.conf.js", 143 | "devServerTarget": "task:serve" 144 | }, 145 | "configurations": { 146 | "production": { 147 | "devServerTarget": "task:serve:production" 148 | } 149 | } 150 | } 151 | } 152 | } 153 | }, 154 | "defaultProject": "task", 155 | "cli": { 156 | "analytics": false 157 | } 158 | } 159 | -------------------------------------------------------------------------------- /src/app/features/auth/service/auth.service.ts: -------------------------------------------------------------------------------- 1 | import { HttpClient } from '@angular/common/http'; 2 | import { Injectable } from '@angular/core'; 3 | import { Router } from '@angular/router'; 4 | import { 5 | FacebookLoginProvider, 6 | GoogleLoginProvider, 7 | SocialAuthService, 8 | } from 'angularx-social-login'; 9 | import { BehaviorSubject, Observable } from 'rxjs'; 10 | import { mergeMap, take, tap } from 'rxjs/operators'; 11 | import { environment } from 'src/environments/environment'; 12 | import Swal from 'sweetalert2'; 13 | import { ErrorDialogInterceptor } from '../../../core/interceptor/error-dialog.interceptor'; 14 | import { SubscriptionService } from '../../user/service/subscription.service'; 15 | import { AuthTokenInterceptor } from '../interceptor/auth-token.interceptor'; 16 | import { AppleLoginProvider } from '../provider/apple-login.provider'; 17 | 18 | export interface TokenResponse { 19 | access_token: string; 20 | refresh_token: string; 21 | } 22 | 23 | export interface User { 24 | _id: string; 25 | username: string; 26 | password: string; 27 | email: string; 28 | online: boolean; 29 | isSocial: boolean; 30 | } 31 | 32 | const { api } = environment; 33 | 34 | @Injectable({ 35 | providedIn: 'root', 36 | }) 37 | export class AuthService { 38 | user$ = new BehaviorSubject(null); 39 | 40 | get user(): User { 41 | return this.user$.getValue(); 42 | } 43 | 44 | get isAuthenticated(): boolean { 45 | return this.user != null; 46 | } 47 | 48 | constructor( 49 | private http: HttpClient, 50 | private socialService: SocialAuthService, 51 | private router: Router, 52 | private subscriptionService: SubscriptionService, 53 | ) {} 54 | 55 | login(user: Partial) { 56 | return this.http 57 | .post(`${api}/auth/login`, user) 58 | .pipe(mergeMap(response => this.setTokens(response))); 59 | } 60 | 61 | loginWithFacebook() { 62 | return this.loginWith(FacebookLoginProvider.PROVIDER_ID, { 63 | scope: 'email,public_profile', 64 | return_scopes: true, 65 | enable_profile_selector: true, 66 | }); 67 | } 68 | 69 | loginWithGoogle() { 70 | return this.loginWith(GoogleLoginProvider.PROVIDER_ID, { 71 | scope: 'profile email', 72 | }); 73 | } 74 | 75 | loginWithApple() { 76 | return this.loginWith(AppleLoginProvider.PROVIDER_ID, { 77 | scope: 'profile email', 78 | }); 79 | } 80 | 81 | handleSocialLogin(method: () => Promise>) { 82 | return new Promise(async (resolve, reject) => { 83 | try { 84 | const observer = await method(); 85 | 86 | return observer.pipe(take(1)).subscribe( 87 | () => { 88 | resolve(); 89 | 90 | this.redirectToCallback(); 91 | }, 92 | e => reject(e), 93 | ); 94 | } catch (e) { 95 | Swal.fire({ 96 | title: 'Oops...!', 97 | text: 98 | e.message || 99 | e.details || 100 | 'An error occurred completing the authentication', 101 | icon: 'error', 102 | }); 103 | 104 | reject(e); 105 | } 106 | }); 107 | } 108 | 109 | private async loginWith(providerId: string, options?: any) { 110 | const user = await this.socialService.signIn(providerId); 111 | 112 | return this.http 113 | .post( 114 | `${api}/auth/${this.getProviderUri(providerId)}-login`, 115 | { 116 | name: user.name, 117 | accessToken: user.authToken, 118 | authorizationCode: user.authorizationCode, 119 | type: 'web', 120 | }, 121 | ) 122 | .pipe( 123 | take(1), 124 | mergeMap(tokens => this.setTokens(tokens)), 125 | ); 126 | } 127 | 128 | private getProviderUri(providerId: string) { 129 | switch (providerId) { 130 | case FacebookLoginProvider.PROVIDER_ID: 131 | return 'facebook'; 132 | case GoogleLoginProvider.PROVIDER_ID: 133 | return 'google'; 134 | case AppleLoginProvider.PROVIDER_ID: 135 | return 'apple'; 136 | default: 137 | return undefined; 138 | } 139 | } 140 | 141 | register(user: Partial) { 142 | return this.http 143 | .post(`${api}/auth/register`, user) 144 | .pipe(mergeMap(response => this.setTokens(response))); 145 | } 146 | 147 | getProfile() { 148 | return this.http 149 | .get(`${api}/auth/me`, { 150 | headers: { 151 | [ErrorDialogInterceptor.skipHeader]: 'true', 152 | }, 153 | }) 154 | .pipe(tap(user => this.user$.next(user))); 155 | } 156 | 157 | loginWithRefreshToken() { 158 | return this.http 159 | .post( 160 | `${api}/auth/refresh-token`, 161 | { 162 | refreshToken: this.getRefreshToken(), 163 | }, 164 | { 165 | headers: { 166 | [AuthTokenInterceptor.skipHeader]: 'true', 167 | }, 168 | }, 169 | ) 170 | .pipe(mergeMap(response => this.setTokens(response))); 171 | } 172 | 173 | logoutFromAllDevices() { 174 | return this.http 175 | .delete(`${api}/auth/logout-from-all-devices`) 176 | .pipe( 177 | mergeMap(tokens => this.setTokens(tokens)), 178 | tap(() => this.subscriptionService.requestSubscription()), 179 | ); 180 | } 181 | 182 | async setTokens(response: TokenResponse) { 183 | this.setRefreshToken(response.refresh_token); 184 | 185 | return this.setAccessToken(response.access_token); 186 | } 187 | 188 | getAccessToken() { 189 | return localStorage.getItem('accessToken'); 190 | } 191 | 192 | async setAccessToken(token: string) { 193 | localStorage.setItem('accessToken', token); 194 | 195 | return this.getProfile().toPromise(); 196 | } 197 | 198 | getRefreshToken() { 199 | return localStorage.getItem('refreshToken'); 200 | } 201 | 202 | setRefreshToken(token: string) { 203 | localStorage.setItem('refreshToken', token); 204 | } 205 | 206 | getLoginCallbackUrl() { 207 | return localStorage.getItem('loginCallbackUrl'); 208 | } 209 | 210 | setLoginCallbackUrl(url: string) { 211 | localStorage.setItem('loginCallbackUrl', url); 212 | } 213 | 214 | async redirectToCallback() { 215 | const output = await this.router.navigate([ 216 | this.getLoginCallbackUrl() || '/', 217 | ]); 218 | 219 | this.setLoginCallbackUrl(null); 220 | 221 | return output; 222 | } 223 | 224 | logout() { 225 | const callback = () => { 226 | sessionStorage.clear(); 227 | 228 | localStorage.clear(); 229 | 230 | this.user$.next(null); 231 | }; 232 | 233 | this.subscriptionService 234 | .delete() 235 | .pipe(take(1)) 236 | .subscribe(callback, callback); 237 | } 238 | } 239 | -------------------------------------------------------------------------------- /src/app/features/messages/components/messages/messages.component.ts: -------------------------------------------------------------------------------- 1 | import { 2 | ChangeDetectorRef, 3 | Component, 4 | ElementRef, 5 | Input, 6 | OnDestroy, 7 | OnInit, 8 | ViewChild, 9 | } from '@angular/core'; 10 | import { FormBuilder } from '@angular/forms'; 11 | import { MatDialog } from '@angular/material/dialog'; 12 | import { boundMethod } from 'autobind-decorator'; 13 | import { remove } from 'lodash'; 14 | import { Subject, timer } from 'rxjs'; 15 | import { filter, mergeMap, take, takeUntil, tap } from 'rxjs/operators'; 16 | import { Sound, SoundService } from 'src/app/shared/services/sound.service'; 17 | import { HttpError } from '../../../../core/interceptor/error-dialog.interceptor'; 18 | import { MainSocket } from '../../../../core/socket/main-socket'; 19 | import { ConfirmDialogComponent } from '../../../../shared/components/confirm-dialog/confirm-dialog.component'; 20 | import { AuthService, User } from '../../../auth/service/auth.service'; 21 | import { Room } from '../../../room/service/room.service'; 22 | import { Message, MessageService } from '../../service/message.service'; 23 | 24 | export enum MessageType { 25 | Direct = 'direct', 26 | Room = 'room', 27 | } 28 | 29 | interface LocalMessage extends Message { 30 | createdAtDate: Date; 31 | } 32 | 33 | @Component({ 34 | selector: 'app-messages', 35 | templateUrl: './messages.component.html', 36 | styleUrls: ['./messages.component.scss'], 37 | }) 38 | export class MessagesComponent implements OnInit, OnDestroy { 39 | @Input() type: MessageType; 40 | @Input() room?: Room; 41 | @Input() to?: User; 42 | @Input() updateMessages$: Subject; 43 | @Input() messages: LocalMessage[] = []; 44 | 45 | @ViewChild('messagesContainer') messagesContainer: ElementRef; 46 | 47 | messageForm = this.formBuilder.group({ 48 | message: '', 49 | }); 50 | 51 | isConnected = false; 52 | 53 | get messagesElement() { 54 | return this.messagesContainer.nativeElement; 55 | } 56 | 57 | destroy$ = new Subject(); 58 | MessageType = MessageType; 59 | user: User; 60 | firstMessage: Message; 61 | 62 | typing: User[] = []; 63 | 64 | isTyping = false; 65 | 66 | private readonly limit = 30; 67 | private readonly scrollOffset = 200; 68 | private readonly typingTimeout = 5000; 69 | 70 | scrolledToLast = false; 71 | 72 | constructor( 73 | private messageService: MessageService, 74 | private socket: MainSocket, 75 | private formBuilder: FormBuilder, 76 | private soundService: SoundService, 77 | private authService: AuthService, 78 | private dialog: MatDialog, 79 | private changeDetector: ChangeDetectorRef, 80 | ) {} 81 | 82 | get partnerId() { 83 | switch (this.type) { 84 | case MessageType.Room: 85 | return this.room._id; 86 | case MessageType.Direct: 87 | return this.to._id; 88 | default: 89 | return undefined; 90 | } 91 | } 92 | 93 | ngOnInit(): void { 94 | this.socket.connect(); 95 | 96 | this.socket 97 | .onConnect() 98 | .pipe(takeUntil(this.destroy$)) 99 | .subscribe(() => { 100 | this.isConnected = true; 101 | 102 | if (!this.updateMessages$) { 103 | this.getMessages(); 104 | } 105 | }); 106 | 107 | this.socket 108 | .onDisconnect() 109 | .pipe(takeUntil(this.destroy$)) 110 | .subscribe(() => (this.isConnected = false)); 111 | 112 | this.authService.user$ 113 | .pipe(takeUntil(this.destroy$)) 114 | .subscribe(user => (this.user = user)); 115 | 116 | this.updateMessages$ 117 | ?.pipe(takeUntil(this.destroy$)) 118 | .subscribe(this.getMessages); 119 | 120 | this.messageService 121 | .onMessage(this.type) 122 | .pipe( 123 | takeUntil(this.destroy$), 124 | filter( 125 | message => 126 | this.isCurrentSection( 127 | message.to !== this.user._id ? message.to : message.from._id, 128 | message.room, 129 | ) && !this.messages.some(msg => msg._id === message._id), 130 | ), 131 | ) 132 | .subscribe(this.handleMessageEvent); 133 | 134 | this.messageService 135 | .onDeleteMessagesEvent(this.type) 136 | .pipe( 137 | takeUntil(this.destroy$), 138 | filter(id => this.isCurrentSection(id)), 139 | ) 140 | .subscribe(() => remove(this.messages, () => true)); 141 | 142 | this.messageService 143 | .onDeleteMessageEvent(this.type) 144 | .pipe(takeUntil(this.destroy$)) 145 | .subscribe(messageId => { 146 | if (messageId === this.firstMessage?._id) { 147 | if (this.messages.some(message => message._id === messageId)) { 148 | this.firstMessage = this.messages[1]; 149 | } else { 150 | this.updateFirstMessage(); 151 | } 152 | } 153 | 154 | remove(this.messages, message => message._id === messageId); 155 | }); 156 | 157 | this.updateFirstMessage(); 158 | 159 | this.messageService 160 | .onTyping(this.type, this.partnerId) 161 | .pipe( 162 | takeUntil(this.destroy$), 163 | filter( 164 | ({ user, room }) => 165 | this.isCurrentSection(user._id, room?._id) && 166 | this.user._id !== user._id, 167 | ), 168 | tap(({ user }) => { 169 | if (!this.typing.some(u => u._id === user._id)) { 170 | this.typing.push(user); 171 | } 172 | 173 | this.changeDetector.detectChanges(); 174 | 175 | this.scrollToLastIfNecessary(); 176 | }), 177 | mergeMap(({ user }) => 178 | timer(this.typingTimeout).pipe( 179 | takeUntil( 180 | this.messageService 181 | .onTyping(this.type, this.partnerId) 182 | .pipe( 183 | filter( 184 | ({ user: typingUser, room }) => 185 | this.isCurrentSection(user._id, room?._id) && 186 | user._id === typingUser._id, 187 | ), 188 | ), 189 | ), 190 | tap(() => remove(this.typing, u => u._id === user._id)), 191 | ), 192 | ), 193 | ) 194 | .subscribe(); 195 | } 196 | 197 | ngOnDestroy() { 198 | this.socket.disconnect(); 199 | 200 | this.destroy$.next(); 201 | this.destroy$.complete(); 202 | } 203 | 204 | @boundMethod 205 | getMessages() { 206 | this.messageService 207 | .getMessages(this.type, this.partnerId, this.limit) 208 | .pipe(take(1)) 209 | .subscribe(messages => { 210 | remove(this.messages, () => true); 211 | this.messages.push(...messages.map(this.convertToLocalMessage)); 212 | 213 | this.scrollToLastMessages(); 214 | }); 215 | } 216 | 217 | updateFirstMessage() { 218 | this.messageService 219 | .getFirstMessage(this.type, this.partnerId) 220 | .pipe(take(1)) 221 | .subscribe(message => (this.firstMessage = message)); 222 | } 223 | 224 | getPreviousMessages() { 225 | const startingScrollHeight = this.messagesElement.scrollHeight; 226 | 227 | this.messageService 228 | .getMessages( 229 | this.type, 230 | this.partnerId, 231 | this.limit, 232 | this.messages[0].createdAt, 233 | ) 234 | .subscribe(messages => { 235 | this.messages.splice(0, 0, ...messages.map(this.convertToLocalMessage)); 236 | 237 | this.changeDetector.detectChanges(); 238 | 239 | this.messagesElement.scrollTo( 240 | 0, 241 | this.messagesElement.scrollHeight - startingScrollHeight, 242 | ); 243 | }); 244 | } 245 | 246 | @boundMethod 247 | handleMessageEvent(message: Message) { 248 | if (message.from._id === this.user._id) { 249 | this.isTyping = false; 250 | } 251 | 252 | this.messages.push(this.convertToLocalMessage(message)); 253 | 254 | remove(this.typing, user => user._id === message.from._id); 255 | 256 | if (message.from._id !== this.user._id) { 257 | this.soundService.playSound(Sound.Message); 258 | } 259 | 260 | this.scrollToLastIfNecessary(); 261 | 262 | return; 263 | } 264 | 265 | isCurrentSection(...objectIds: string[]) { 266 | return objectIds.some( 267 | id => 268 | (this.room && this.room._id === id) || 269 | (this.to && this.to._id === id) || 270 | this.user._id === id, 271 | ); 272 | } 273 | 274 | scrollToLastIfNecessary() { 275 | const element = this.messagesElement; 276 | 277 | if ( 278 | element.scrollTop > 279 | element.scrollHeight - element.offsetHeight - this.scrollOffset 280 | ) { 281 | this.scrolledToLast = false; 282 | 283 | this.scrollToLastMessages(); 284 | } 285 | } 286 | 287 | scrollToLastMessages() { 288 | this.changeDetector.detectChanges(); 289 | 290 | this.messagesElement.scrollTo({ 291 | top: this.messagesElement.scrollHeight, 292 | behavior: 'smooth', 293 | }); 294 | 295 | timer(1000).subscribe(() => (this.scrolledToLast = true)); 296 | } 297 | 298 | sendTyping() { 299 | if (this.isTyping) { 300 | return; 301 | } 302 | 303 | this.messageService.sendTyping(this.type, this.partnerId); 304 | 305 | this.isTyping = true; 306 | 307 | timer(this.typingTimeout - 1000).subscribe(() => (this.isTyping = false)); 308 | } 309 | 310 | sendMessage() { 311 | const message = this.messageForm.value.message; 312 | 313 | if (!message?.trim()) { 314 | return; 315 | } 316 | 317 | if (!this.isConnected) { 318 | this.handleMessageCallback(); 319 | } 320 | 321 | this.messageService.sendMessage( 322 | this.type, 323 | this.partnerId, 324 | message, 325 | this.handleMessageCallback, 326 | ); 327 | } 328 | 329 | @boundMethod 330 | handleMessageCallback(response?: boolean | HttpError) { 331 | if (typeof response !== 'object') { 332 | this.messageForm.patchValue({ 333 | message: '', 334 | }); 335 | } 336 | } 337 | 338 | onScroll(e: Event) { 339 | if ( 340 | !this.scrolledToLast || 341 | this.messages[0]?._id === this.firstMessage?._id 342 | ) { 343 | return; 344 | } 345 | 346 | const element = e.target as HTMLDivElement; 347 | 348 | if (element.scrollTop <= 5) { 349 | this.getPreviousMessages(); 350 | } 351 | } 352 | 353 | confirmDeleteMessage(message: Message) { 354 | const dialog = this.dialog.open(ConfirmDialogComponent); 355 | 356 | dialog 357 | .afterClosed() 358 | .pipe(take(1)) 359 | .subscribe(confirm => { 360 | if (confirm) { 361 | this.deleteMessage(message); 362 | } 363 | }); 364 | } 365 | 366 | deleteMessage(message: Message) { 367 | this.messageService 368 | .deleteMessage(this.type, message) 369 | .pipe(take(1)) 370 | .subscribe(); 371 | } 372 | 373 | private convertToLocalMessage(message: Message): LocalMessage { 374 | return { 375 | ...message, 376 | createdAtDate: new Date(message.createdAt), 377 | }; 378 | } 379 | } 380 | --------------------------------------------------------------------------------