├── README.md ├── _config.yml ├── frontend ├── .editorconfig ├── .gitignore ├── README.md ├── angular.json ├── browserslist ├── e2e │ ├── protractor.conf.js │ ├── src │ │ ├── app.e2e-spec.ts │ │ └── app.po.ts │ └── tsconfig.json ├── karma.conf.js ├── package-lock.json ├── package.json ├── src │ ├── app │ │ ├── _dtos │ │ │ ├── auth │ │ │ │ ├── SignInRequest.ts │ │ │ │ ├── SignInResponse.ts │ │ │ │ └── SignUpRequest.ts │ │ │ ├── chat │ │ │ │ ├── FriendProfile.ts │ │ │ │ ├── NbMessage.ts │ │ │ │ └── UserMessage.ts │ │ │ ├── common │ │ │ │ └── ApiResponse.ts │ │ │ └── user │ │ │ │ └── UserProfile.ts │ │ ├── _helpers │ │ │ ├── auth.guard.ts │ │ │ └── jwt.interceptor.ts │ │ ├── _services │ │ │ ├── auth.service.spec.ts │ │ │ ├── auth.service.ts │ │ │ ├── chat.service.spec.ts │ │ │ ├── chat.service.ts │ │ │ ├── data.service.spec.ts │ │ │ ├── data.service.ts │ │ │ ├── notification.service.spec.ts │ │ │ ├── notification.service.ts │ │ │ ├── token-storage.service.spec.ts │ │ │ ├── token-storage.service.ts │ │ │ ├── user.service.spec.ts │ │ │ └── user.service.ts │ │ ├── app-routing.module.ts │ │ ├── app.component.html │ │ ├── app.component.scss │ │ ├── app.component.spec.ts │ │ ├── app.component.ts │ │ ├── app.module.ts │ │ ├── auth │ │ │ ├── auth-routing.module.ts │ │ │ ├── auth.component.html │ │ │ ├── auth.component.scss │ │ │ ├── auth.component.spec.ts │ │ │ ├── auth.component.ts │ │ │ ├── auth.module.ts │ │ │ ├── forgot-password │ │ │ │ ├── forgot-password.component.html │ │ │ │ ├── forgot-password.component.scss │ │ │ │ ├── forgot-password.component.spec.ts │ │ │ │ └── forgot-password.component.ts │ │ │ ├── reset-password │ │ │ │ ├── reset-password.component.html │ │ │ │ ├── reset-password.component.scss │ │ │ │ ├── reset-password.component.spec.ts │ │ │ │ └── reset-password.component.ts │ │ │ ├── signin │ │ │ │ ├── signin.component.html │ │ │ │ ├── signin.component.scss │ │ │ │ ├── signin.component.spec.ts │ │ │ │ └── signin.component.ts │ │ │ ├── signup │ │ │ │ ├── signup.component.html │ │ │ │ ├── signup.component.scss │ │ │ │ ├── signup.component.spec.ts │ │ │ │ └── signup.component.ts │ │ │ └── token │ │ │ │ ├── token.component.html │ │ │ │ ├── token.component.scss │ │ │ │ ├── token.component.spec.ts │ │ │ │ └── token.component.ts │ │ ├── home │ │ │ ├── chat-banner │ │ │ │ ├── chat-banner.component.html │ │ │ │ ├── chat-banner.component.scss │ │ │ │ ├── chat-banner.component.spec.ts │ │ │ │ └── chat-banner.component.ts │ │ │ ├── chat-detail │ │ │ │ ├── chat-detail.component.html │ │ │ │ ├── chat-detail.component.scss │ │ │ │ ├── chat-detail.component.spec.ts │ │ │ │ └── chat-detail.component.ts │ │ │ ├── chat-list │ │ │ │ ├── chat-list.component.html │ │ │ │ ├── chat-list.component.scss │ │ │ │ ├── chat-list.component.spec.ts │ │ │ │ ├── chat-list.component.ts │ │ │ │ └── new-chat │ │ │ │ │ └── new-chat.component.ts │ │ │ ├── chat │ │ │ │ ├── chat.component.html │ │ │ │ ├── chat.component.scss │ │ │ │ ├── chat.component.spec.ts │ │ │ │ └── chat.component.ts │ │ │ ├── home-routing.module.ts │ │ │ ├── home.component.html │ │ │ ├── home.component.scss │ │ │ ├── home.component.spec.ts │ │ │ ├── home.component.ts │ │ │ ├── home.module.ts │ │ │ ├── loading │ │ │ │ ├── loading.component.html │ │ │ │ ├── loading.component.scss │ │ │ │ ├── loading.component.spec.ts │ │ │ │ └── loading.component.ts │ │ │ ├── profile │ │ │ │ ├── profile.component.html │ │ │ │ ├── profile.component.scss │ │ │ │ ├── profile.component.spec.ts │ │ │ │ └── profile.component.ts │ │ │ └── settings │ │ │ │ ├── settings.component.html │ │ │ │ ├── settings.component.scss │ │ │ │ ├── settings.component.spec.ts │ │ │ │ └── settings.component.ts │ │ └── shared │ │ │ ├── dialog │ │ │ └── dialog-alert │ │ │ │ ├── dialog-success.component.ts │ │ │ │ └── dialog.common.scss │ │ │ ├── directives │ │ │ └── img-fallback.directive.ts │ │ │ └── shared.module.ts │ ├── assets │ │ ├── .gitkeep │ │ ├── auth.svg │ │ └── friends.jpg │ ├── environments │ │ ├── environment.prod.ts │ │ └── environment.ts │ ├── favicon.ico │ ├── index.html │ ├── main.ts │ ├── polyfills.ts │ ├── styles.scss │ ├── test.ts │ └── themes.scss ├── tsconfig.app.json ├── tsconfig.json ├── tsconfig.spec.json └── tslint.json ├── images ├── add-friend.png ├── chat.png ├── cover.gif ├── edit-profile.png ├── home.png ├── signin.png ├── signup.png ├── theme-2.png ├── theme-3.png └── token.png └── server ├── .gitignore ├── build.gradle.kts ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle.kts └── src ├── main ├── kotlin │ └── com │ │ └── squrlabs │ │ └── sca │ │ ├── ScaApplication.kt │ │ ├── config │ │ ├── ApiConfiguration.kt │ │ ├── AppProperties.kt │ │ ├── SecurityConfigure.kt │ │ ├── WebMvcConfig.kt │ │ ├── WebSocketConfig.kt │ │ └── WebSocketSecurityConfig.kt │ │ ├── data │ │ ├── entity │ │ │ ├── chat │ │ │ │ ├── ChatEntity.kt │ │ │ │ ├── FileEntity.kt │ │ │ │ └── MessageEntity.kt │ │ │ └── user │ │ │ │ └── UserEntity.kt │ │ └── repository │ │ │ ├── chat │ │ │ ├── ChatRepository.kt │ │ │ └── MessageRepository.kt │ │ │ └── user │ │ │ └── UserRepository.kt │ │ ├── domain │ │ ├── model │ │ │ ├── chat │ │ │ │ ├── ChatModel.kt │ │ │ │ ├── ContentType.kt │ │ │ │ ├── FriendProfileModel.kt │ │ │ │ └── MessageModel.kt │ │ │ ├── socket │ │ │ │ ├── SocketModel.kt │ │ │ │ └── SocketType.kt │ │ │ └── user │ │ │ │ ├── AuthProvider.kt │ │ │ │ └── UserModel.kt │ │ └── service │ │ │ ├── auth │ │ │ └── CustomOAuth2UserService.kt │ │ │ ├── chat │ │ │ ├── ChatService.kt │ │ │ └── MessageService.kt │ │ │ ├── file │ │ │ └── FileStorageService.kt │ │ │ └── user │ │ │ └── UserService.kt │ │ ├── util │ │ ├── ApiResponse.kt │ │ ├── CookieUtils.kt │ │ ├── DateTimeUtil.kt │ │ ├── Exceptions.kt │ │ ├── KotlinHelper.kt │ │ └── auth │ │ │ ├── misc │ │ │ ├── CustomChannelInterceptor.kt │ │ │ ├── OAuth2RequestRepository.kt │ │ │ ├── OAuth2ResultHandler.kt │ │ │ ├── RestAuthenticationEntryPoint.kt │ │ │ ├── TokenAuthenticationFilter.kt │ │ │ └── TokenProvider.kt │ │ │ └── util │ │ │ ├── OAuth2UserInfo.kt │ │ │ └── UserPrincipal.kt │ │ └── web │ │ ├── controller │ │ ├── auth │ │ │ └── AccountController.kt │ │ ├── chat │ │ │ └── ChatController.kt │ │ └── user │ │ │ └── UserController.kt │ │ └── dto │ │ ├── auth │ │ ├── AuthResponse.kt │ │ ├── LoginRequest.kt │ │ └── SignUpRequest.kt │ │ ├── chat │ │ ├── FriendProfileResponse.kt │ │ └── MessageResponse.kt │ │ └── user │ │ └── UserProfile.kt └── resources │ ├── application-docker.yaml │ └── application.yaml └── test └── kotlin └── com └── squrlabs └── sca └── ScaApplicationTests.kt /README.md: -------------------------------------------------------------------------------- 1 | # Spring Angular Chat(STOMP) 2 | 3 |  4 | 1-1 instant messaging project designed to demonstrate WebSockets in a load-balanced environment. Users can register, login/logout, see a friendslist, private message all in realtime. WebSocket usages include user presence monitoring, notifications, and chat messages. 5 | 6 | ## Technologies/Design Decisions 7 | 8 | - Backend: Kotlin with Spring Boot 9 | - Frontend: Angular 8 10 | - Message Broker: RabbitMQ (PubSub pattern for multi-server messaging) 11 | - Database: MongoDB 12 | - ORM: Spring Data 13 | - WebSocket messaging protocol: Stomp 14 | - WebSocket handler: Sock.js (with cross-browser fallbacks) 15 | - Security: Spring Security 16 | - Spring Controllers couple REST as well as WebSocket traffic 17 | - Solid Design Principals. 18 | 19 | ## Features 20 | 21 | - OAUTH2 with Google and Facebook. Users can also register via email. 22 | - Multiple color themes available. 23 | - Private Friends list with blocking unwanted users. 24 | - Messages are persisted. Pwa is available provide desktop application features. 25 | - Offline message support and sync when user is online. 26 | - Easy add new friends via email. Like WhatsApp add via Phone number. 27 | - Chat support Images, Audio, Video, Gif's, Map Location. Multiple files with drop in feature. 28 | 29 | ## Themes 30 | 31 | ### Default Theme 32 | 33 |  34 | 35 | ### Dark Theme 36 | 37 |  38 | 39 | ### Light Theme 40 | 41 |  42 | 43 | ## Screenshots 44 | 45 | - [Signin Screen](./images/signin.png) 46 | - [Signup Screen](./images/signin.png) 47 | - [Oauth2 Confirmation](./images/token.png) 48 | - [Home Screen](./images/home.png) 49 | - [Chat](./images/chat.png) 50 | - [Add New Friend](./images/new_friend.png) 51 | - [Edit Profile](./images.edit-profile.png) 52 | 53 | ## Any questions 54 | 55 | If you have any questions, feel free to ask me: 56 | 57 | - **Mail**: deepanshut041@gmail.com 58 | - **Github**: [https://github.com/data-breach/MlAgents](https://github.com/deepanshut041/friends-chat) 59 | - **Website**: [https://data-breach.github.io/MlAgents](https://deepanshut041.github.io/friends-chat) 60 | - **Twitter**: @deepanshut041 61 | 62 | Don't forget to follow me on twitter, github and Medium to be alerted of the new articles that I publish 63 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-cayman 2 | title: Spring Angular Chat 3 | show_downloads: false 4 | description: This Repository contains relatime chat built on spring and angular with Stomp. 5 | plugins: 6 | - jemoji 7 | markdown: kramdown 8 | kramdown: 9 | input: GFM 10 | syntax_highlighter: rouge 11 | -------------------------------------------------------------------------------- /frontend/.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 | [*.md] 12 | max_line_length = off 13 | trim_trailing_whitespace = false 14 | -------------------------------------------------------------------------------- /frontend/.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 | -------------------------------------------------------------------------------- /frontend/README.md: -------------------------------------------------------------------------------- 1 | # Frontend 2 | 3 | This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 9.0.6. 4 | 5 | ## Development server 6 | 7 | Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. 8 | 9 | ## Code scaffolding 10 | 11 | Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`. 12 | 13 | ## Build 14 | 15 | Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build. 16 | 17 | ## Running unit tests 18 | 19 | Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). 20 | 21 | ## Running end-to-end tests 22 | 23 | Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/). 24 | 25 | ## Further help 26 | 27 | To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md). 28 | -------------------------------------------------------------------------------- /frontend/angular.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "version": 1, 4 | "newProjectRoot": "projects", 5 | "projects": { 6 | "frontend": { 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 | "outputPath": "dist/frontend", 21 | "index": "src/index.html", 22 | "main": "src/main.ts", 23 | "polyfills": "src/polyfills.ts", 24 | "tsConfig": "tsconfig.app.json", 25 | "aot": true, 26 | "assets": [ 27 | "src/favicon.ico", 28 | "src/assets" 29 | ], 30 | "styles": [ 31 | "node_modules/bootstrap/dist/css/bootstrap.min.css", 32 | "node_modules/@nebular/theme/styles/prebuilt/dark.scss", 33 | "node_modules/@nebular/theme/styles/prebuilt/corporate.scss", 34 | "node_modules/@nebular/theme/styles/prebuilt/cosmic.scss", 35 | "node_modules/@nebular/theme/styles/prebuilt/default.scss", 36 | "src/styles.scss" 37 | ], 38 | "scripts": [ 39 | "node_modules/jquery/dist/jquery.min.js", 40 | "node_modules/bootstrap/dist/js/bootstrap.min.js" 41 | ] 42 | }, 43 | "configurations": { 44 | "production": { 45 | "fileReplacements": [ 46 | { 47 | "replace": "src/environments/environment.ts", 48 | "with": "src/environments/environment.prod.ts" 49 | } 50 | ], 51 | "optimization": true, 52 | "outputHashing": "all", 53 | "sourceMap": false, 54 | "extractCss": true, 55 | "namedChunks": false, 56 | "extractLicenses": true, 57 | "vendorChunk": false, 58 | "buildOptimizer": true, 59 | "budgets": [ 60 | { 61 | "type": "initial", 62 | "maximumWarning": "2mb", 63 | "maximumError": "5mb" 64 | }, 65 | { 66 | "type": "anyComponentStyle", 67 | "maximumWarning": "6kb", 68 | "maximumError": "10kb" 69 | } 70 | ] 71 | } 72 | } 73 | }, 74 | "serve": { 75 | "builder": "@angular-devkit/build-angular:dev-server", 76 | "options": { 77 | "browserTarget": "frontend:build" 78 | }, 79 | "configurations": { 80 | "production": { 81 | "browserTarget": "frontend:build:production" 82 | } 83 | } 84 | }, 85 | "extract-i18n": { 86 | "builder": "@angular-devkit/build-angular:extract-i18n", 87 | "options": { 88 | "browserTarget": "frontend:build" 89 | } 90 | }, 91 | "test": { 92 | "builder": "@angular-devkit/build-angular:karma", 93 | "options": { 94 | "main": "src/test.ts", 95 | "polyfills": "src/polyfills.ts", 96 | "tsConfig": "tsconfig.spec.json", 97 | "karmaConfig": "karma.conf.js", 98 | "assets": [ 99 | "src/favicon.ico", 100 | "src/assets" 101 | ], 102 | "styles": [ 103 | "src/styles.scss" 104 | ], 105 | "scripts": [] 106 | } 107 | }, 108 | "lint": { 109 | "builder": "@angular-devkit/build-angular:tslint", 110 | "options": { 111 | "tsConfig": [ 112 | "tsconfig.app.json", 113 | "tsconfig.spec.json", 114 | "e2e/tsconfig.json" 115 | ], 116 | "exclude": [ 117 | "**/node_modules/**" 118 | ] 119 | } 120 | }, 121 | "e2e": { 122 | "builder": "@angular-devkit/build-angular:protractor", 123 | "options": { 124 | "protractorConfig": "e2e/protractor.conf.js", 125 | "devServerTarget": "frontend:serve" 126 | }, 127 | "configurations": { 128 | "production": { 129 | "devServerTarget": "frontend:serve:production" 130 | } 131 | } 132 | } 133 | } 134 | } 135 | }, 136 | "defaultProject": "frontend" 137 | } -------------------------------------------------------------------------------- /frontend/browserslist: -------------------------------------------------------------------------------- 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 | # You can see what browsers were selected by your queries by running: 6 | # npx browserslist 7 | 8 | > 0.5% 9 | last 2 versions 10 | Firefox ESR 11 | not dead 12 | not IE 9-11 # For IE 9-11 support, remove 'not'. -------------------------------------------------------------------------------- /frontend/e2e/protractor.conf.js: -------------------------------------------------------------------------------- 1 | // @ts-check 2 | // Protractor configuration file, see link for more information 3 | // https://github.com/angular/protractor/blob/master/lib/config.ts 4 | 5 | const { SpecReporter } = require('jasmine-spec-reporter'); 6 | 7 | /** 8 | * @type { import("protractor").Config } 9 | */ 10 | exports.config = { 11 | allScriptsTimeout: 11000, 12 | specs: [ 13 | './src/**/*.e2e-spec.ts' 14 | ], 15 | capabilities: { 16 | browserName: 'chrome' 17 | }, 18 | directConnect: true, 19 | baseUrl: 'http://localhost:4200/', 20 | framework: 'jasmine', 21 | jasmineNodeOpts: { 22 | showColors: true, 23 | defaultTimeoutInterval: 30000, 24 | print: function() {} 25 | }, 26 | onPrepare() { 27 | require('ts-node').register({ 28 | project: require('path').join(__dirname, './tsconfig.json') 29 | }); 30 | jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); 31 | } 32 | }; -------------------------------------------------------------------------------- /frontend/e2e/src/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { AppPage } from './app.po'; 2 | import { browser, logging } from 'protractor'; 3 | 4 | describe('workspace-project App', () => { 5 | let page: AppPage; 6 | 7 | beforeEach(() => { 8 | page = new AppPage(); 9 | }); 10 | 11 | it('should display welcome message', () => { 12 | page.navigateTo(); 13 | expect(page.getTitleText()).toEqual('frontend app is running!'); 14 | }); 15 | 16 | afterEach(async () => { 17 | // Assert that there are no errors emitted from the browser 18 | const logs = await browser.manage().logs().get(logging.Type.BROWSER); 19 | expect(logs).not.toContain(jasmine.objectContaining({ 20 | level: logging.Level.SEVERE, 21 | } as logging.Entry)); 22 | }); 23 | }); 24 | -------------------------------------------------------------------------------- /frontend/e2e/src/app.po.ts: -------------------------------------------------------------------------------- 1 | import { browser, by, element } from 'protractor'; 2 | 3 | export class AppPage { 4 | navigateTo(): Promise { 5 | return browser.get(browser.baseUrl) as Promise; 6 | } 7 | 8 | getTitleText(): Promise { 9 | return element(by.css('app-root .content span')).getText() as Promise; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /frontend/e2e/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/e2e", 5 | "module": "commonjs", 6 | "target": "es5", 7 | "types": [ 8 | "jasmine", 9 | "jasminewd2", 10 | "node" 11 | ] 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /frontend/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/frontend'), 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 | -------------------------------------------------------------------------------- /frontend/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "frontend", 3 | "version": "0.0.0", 4 | "scripts": { 5 | "ng": "ng", 6 | "start": "ng serve", 7 | "build": "ng build", 8 | "test": "ng test", 9 | "lint": "ng lint", 10 | "e2e": "ng e2e" 11 | }, 12 | "private": true, 13 | "dependencies": { 14 | "@angular/animations": "~9.0.6", 15 | "@angular/cdk": "^9.0.0", 16 | "@angular/common": "~9.0.6", 17 | "@angular/compiler": "~9.0.6", 18 | "@angular/core": "~9.0.6", 19 | "@angular/forms": "~9.0.6", 20 | "@angular/platform-browser": "~9.0.6", 21 | "@angular/platform-browser-dynamic": "~9.0.6", 22 | "@angular/router": "~9.0.6", 23 | "@nebular/eva-icons": "^5.0.0", 24 | "@nebular/theme": "^5.0.0", 25 | "@stomp/stompjs": "^5.4.4", 26 | "bootstrap": "^4.4.1", 27 | "eva-icons": "^1.1.3", 28 | "jquery": "^3.5.0", 29 | "popper.js": "^1.16.1", 30 | "rxjs": "~6.5.4", 31 | "sockjs-client": "^1.4.0", 32 | "tslib": "^1.10.0", 33 | "zone.js": "~0.10.2" 34 | }, 35 | "devDependencies": { 36 | "@angular-devkit/build-angular": "~0.900.6", 37 | "@angular/cli": "~9.0.6", 38 | "@angular/compiler-cli": "~9.0.6", 39 | "@angular/language-service": "~9.0.6", 40 | "@schematics/angular": "~9.0.6", 41 | "@types/jasmine": "~3.5.0", 42 | "@types/jasminewd2": "~2.0.3", 43 | "@types/node": "^12.11.1", 44 | "@types/sockjs-client": "^1.1.1", 45 | "codelyzer": "^5.1.2", 46 | "jasmine-core": "~3.5.0", 47 | "jasmine-spec-reporter": "~4.2.1", 48 | "karma": "~4.3.0", 49 | "karma-chrome-launcher": "~3.1.0", 50 | "karma-coverage-istanbul-reporter": "~2.1.0", 51 | "karma-jasmine": "~2.0.1", 52 | "karma-jasmine-html-reporter": "^1.4.2", 53 | "protractor": "~5.4.3", 54 | "ts-node": "~8.3.0", 55 | "tslint": "~5.18.0", 56 | "typescript": "~3.7.5" 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /frontend/src/app/_dtos/auth/SignInRequest.ts: -------------------------------------------------------------------------------- 1 | export class SignInRequest { 2 | email: string 3 | password: string 4 | 5 | constructor(email: string, password: string){ 6 | this.email = email 7 | this.password = password 8 | } 9 | } -------------------------------------------------------------------------------- /frontend/src/app/_dtos/auth/SignInResponse.ts: -------------------------------------------------------------------------------- 1 | export class SignInResponse { 2 | accessToken: string 3 | tokenType: string 4 | name: string 5 | email: string 6 | imageUrl: string 7 | id: string 8 | } -------------------------------------------------------------------------------- /frontend/src/app/_dtos/auth/SignUpRequest.ts: -------------------------------------------------------------------------------- 1 | export class SignUpRequest { 2 | name: string 3 | email: string 4 | password: string 5 | 6 | constructor(name: string, email: string, password: string){ 7 | this.email = email 8 | this.name = name 9 | this.password = password 10 | } 11 | } -------------------------------------------------------------------------------- /frontend/src/app/_dtos/chat/FriendProfile.ts: -------------------------------------------------------------------------------- 1 | export class FriendProfile { 2 | id: string 3 | email: string 4 | name: string 5 | imgUrl: string 6 | blockedBy: string 7 | lastMsg: string = "" 8 | lastMsgAt: Date 9 | unreadMsgs: number = 0 10 | updatedAt: Date 11 | 12 | constructor(id: string, email: string, name: string, imgUrl: string, blockedBy: string, updatedAt: string) { 13 | this.id = id 14 | this.email = email 15 | this.name = name 16 | this.imgUrl = imgUrl 17 | this.blockedBy = blockedBy 18 | this.updatedAt = new Date(updatedAt) 19 | } 20 | 21 | updateConv(lastMsg: string, lastMsgAt: Date) { 22 | this.lastMsg = lastMsg 23 | this.lastMsgAt = lastMsgAt 24 | } 25 | 26 | update(id: string, email: string, name: string, imgUrl: string, blockedBy: string, updatedAt: Date){ 27 | this.id = id 28 | this.email = email 29 | this.name = name 30 | this.imgUrl = imgUrl 31 | this.blockedBy = blockedBy 32 | this.updatedAt = updatedAt 33 | } 34 | 35 | incrementUnread(){ 36 | this.unreadMsgs += 1 37 | } 38 | } -------------------------------------------------------------------------------- /frontend/src/app/_dtos/chat/NbMessage.ts: -------------------------------------------------------------------------------- 1 | import { UserMessage } from './UserMessage' 2 | 3 | export class NbMessage { 4 | date: Date 5 | files = [] 6 | text: string 7 | quote: string = "" 8 | sender: string 9 | type: string 10 | avatar: string = "" 11 | reply: boolean 12 | latitude: number = 0 13 | longitude: number = 0 14 | 15 | constructor(msg: UserMessage) { 16 | this.date = msg.createdAt 17 | this.text = msg.content 18 | if (msg.contentType == 'FILE') { 19 | this.type = "file" 20 | this.files = msg.files 21 | } else { 22 | this.type = "text" 23 | } 24 | } 25 | 26 | updateUser(name, imgUrl, reply) { 27 | this.reply = reply 28 | this.avatar = imgUrl 29 | this.sender = name 30 | } 31 | } -------------------------------------------------------------------------------- /frontend/src/app/_dtos/chat/UserMessage.ts: -------------------------------------------------------------------------------- 1 | export class UserMessage { 2 | id: string 3 | senderId: string 4 | chatId: string 5 | content: string 6 | files: any[] 7 | contentType: string 8 | createdAt: Date 9 | updatedAt: Date 10 | read: boolean 11 | 12 | constructor(id: string, senderId: string, chatId: string, content: string, files: any[], contentType: string, 13 | createdAt: string, updatedAt: string, read: boolean) { 14 | this.id = id 15 | this.senderId = senderId 16 | this.chatId = chatId 17 | this.content = content 18 | this.files = files 19 | this.contentType = contentType 20 | this.createdAt = new Date(createdAt) 21 | this.updatedAt = new Date(updatedAt) 22 | this.read = read 23 | } 24 | } -------------------------------------------------------------------------------- /frontend/src/app/_dtos/common/ApiResponse.ts: -------------------------------------------------------------------------------- 1 | export class ApiResponse{ 2 | success:boolean 3 | message:string 4 | } -------------------------------------------------------------------------------- /frontend/src/app/_dtos/user/UserProfile.ts: -------------------------------------------------------------------------------- 1 | export class UserProfile { 2 | id: string 3 | email: string 4 | name: string 5 | imgUrl: string 6 | 7 | constructor(id: string, email: string, name: string, imgUrl: string){ 8 | this.email = email 9 | this.name = name 10 | this.imgUrl = imgUrl 11 | this.id = id 12 | } 13 | } -------------------------------------------------------------------------------- /frontend/src/app/_helpers/auth.guard.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; 3 | 4 | import { AuthService } from '../_services/auth.service'; 5 | 6 | @Injectable({ providedIn: 'root' }) 7 | export class AuthGuard implements CanActivate { 8 | constructor( 9 | private router: Router, 10 | private authenticationService: AuthService 11 | ) { } 12 | 13 | canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { 14 | const currentUser = this.authenticationService.getToken(); 15 | if (currentUser) { 16 | // logged in so return true 17 | return true; 18 | } 19 | // not logged in so redirect to login page with the return url 20 | this.router.navigate(['auth', 'signin'], { queryParams: { returnUrl: state.url } }); 21 | return false; 22 | } 23 | } -------------------------------------------------------------------------------- /frontend/src/app/_helpers/jwt.interceptor.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http'; 3 | import { Observable } from 'rxjs'; 4 | 5 | import { environment } from '../../environments/environment'; 6 | import { AuthService } from '../_services/auth.service'; 7 | 8 | @Injectable() 9 | export class JwtInterceptor implements HttpInterceptor { 10 | constructor(private authenticationService: AuthService) { } 11 | 12 | intercept(request: HttpRequest, next: HttpHandler): Observable> { 13 | // add auth header with jwt if user is logged in and request is to the api url 14 | const token = this.authenticationService.getToken(); 15 | const isApiUrl = request.url.startsWith(environment.DOMAIN); 16 | if (token && isApiUrl) { 17 | request = request.clone({ 18 | setHeaders: { 19 | Authorization: `Bearer ${token}` 20 | } 21 | }); 22 | } 23 | 24 | return next.handle(request); 25 | } 26 | } -------------------------------------------------------------------------------- /frontend/src/app/_services/auth.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed } from '@angular/core/testing'; 2 | 3 | import { AuthService } from './auth.service'; 4 | 5 | describe('AuthService', () => { 6 | let service: AuthService; 7 | 8 | beforeEach(() => { 9 | TestBed.configureTestingModule({}); 10 | service = TestBed.inject(AuthService); 11 | }); 12 | 13 | it('should be created', () => { 14 | expect(service).toBeTruthy(); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /frontend/src/app/_services/auth.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpClient, HttpHeaders } from '@angular/common/http'; 3 | import { Observable } from 'rxjs'; 4 | import { TokenStorageService } from './token-storage.service'; 5 | 6 | import { environment } from '../../environments/environment'; 7 | import { map } from 'rxjs/operators'; 8 | import { SignInResponse } from '../_dtos/auth/SignInResponse'; 9 | import { SignInRequest } from '../_dtos/auth/SignInRequest'; 10 | import { SignUpRequest } from '../_dtos/auth/SignUpRequest'; 11 | import { ApiResponse } from '../_dtos/common/ApiResponse'; 12 | import { UserService } from './user.service'; 13 | import { UserProfile } from '../_dtos/user/UserProfile'; 14 | 15 | @Injectable({ 16 | providedIn: 'root' 17 | }) 18 | export class AuthService { 19 | 20 | httpOptions = { 21 | headers: new HttpHeaders({ 'Content-Type': 'application/json' }) 22 | }; 23 | 24 | constructor(private http: HttpClient, private tokenStorage: TokenStorageService) { 25 | 26 | } 27 | 28 | getToken(): string { 29 | return this.tokenStorage.getToken() 30 | } 31 | 32 | setToken(token:string){ 33 | this.tokenStorage.saveToken(token) 34 | } 35 | 36 | login(model: SignInRequest): Observable { 37 | return this.http.post(`${environment.DOMAIN}/api/account/signin`, model, this.httpOptions) 38 | .pipe(map((response: SignInResponse) => { 39 | this.tokenStorage.saveToken(response.accessToken) 40 | this.tokenStorage.saveUser(new UserProfile(response.id, response.email, response.name, response.imageUrl)) 41 | return response 42 | })); 43 | } 44 | 45 | register(model: SignUpRequest): Observable { 46 | return this.http.post(`${environment.DOMAIN}/api/account/signup`, model, this.httpOptions) as Observable; 47 | } 48 | 49 | logout() { 50 | this.tokenStorage.signOut() 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /frontend/src/app/_services/chat.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed } from '@angular/core/testing'; 2 | 3 | import { ChatService } from './chat.service'; 4 | 5 | describe('ChatService', () => { 6 | let service: ChatService; 7 | 8 | beforeEach(() => { 9 | TestBed.configureTestingModule({}); 10 | service = TestBed.inject(ChatService); 11 | }); 12 | 13 | it('should be created', () => { 14 | expect(service).toBeTruthy(); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /frontend/src/app/_services/chat.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpClient, HttpHeaders } from '@angular/common/http'; 3 | import { environment } from '../../environments/environment'; 4 | import { Observable, BehaviorSubject } from 'rxjs'; 5 | import { map, filter } from 'rxjs/operators'; 6 | import { FriendProfile } from '../_dtos/chat/FriendProfile'; 7 | import { DataService } from './data.service'; 8 | import { UserMessage } from '../_dtos/chat/UserMessage'; 9 | 10 | @Injectable() 11 | export class ChatService { 12 | 13 | private _fetch: BehaviorSubject = new BehaviorSubject(0); 14 | public readonly fetch: Observable = this._fetch.asObservable(); 15 | 16 | httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; 17 | fileOptions = { headers: new HttpHeaders({ 'Content-Type': 'multipart/form-data' }) }; 18 | 19 | constructor(private httpClient: HttpClient, private dataService: DataService) { } 20 | 21 | fetchFriends(): Observable { 22 | return this.httpClient.get(`${environment.DOMAIN}/api/chat`, this.httpOptions) 23 | .pipe(map((friends: FriendProfile[]) => { 24 | this.dataService.updateFriends(friends) 25 | })) 26 | } 27 | 28 | updateFetch(value) { 29 | this._fetch.next(value) 30 | } 31 | 32 | fetchAllMessages(): Observable { 33 | return this.httpClient.post(`${environment.DOMAIN}/api/chat/messages`, 34 | Array.from(this.dataService.getAllFriend().keys()), this.httpOptions) 35 | .pipe(map((msgs: UserMessage[]) => { 36 | this.dataService.updateUserMessages(msgs) 37 | })) 38 | } 39 | 40 | fetchMessages(covId: string): Observable { 41 | return this.httpClient.get(`${environment.DOMAIN}/api/chat/${covId}/messages`, this.httpOptions) 42 | .pipe(map((msgs: UserMessage[]) => { 43 | this.dataService.updateUserMessages(msgs) 44 | })) 45 | } 46 | 47 | createFriend(email: String): Observable { 48 | return this.httpClient.post(`${environment.DOMAIN}/api/chat?email=${email}`, this.httpOptions) 49 | .pipe(map((friend: FriendProfile) => { 50 | this.dataService.updateFriends([friend]) 51 | })) 52 | } 53 | 54 | createMessageText(cid: string, content: string): Observable { 55 | return this.httpClient 56 | .post(`${environment.DOMAIN}/api/chat/${cid}/messages/text?content=${content}`,{}, this.httpOptions) 57 | .pipe(map((v: UserMessage) => { 58 | this.dataService.updateUserMessages([v]) 59 | return v 60 | })) 61 | } 62 | 63 | createMessageFile(cid: string, content: string, data:FormData): Observable { 64 | return this.httpClient 65 | .post(`${environment.DOMAIN}/api/chat/${cid}/messages/files?content=${content}`, data) 66 | .pipe(map((v: UserMessage) => { 67 | this.dataService.updateUserMessages([v]) 68 | return v 69 | })) 70 | } 71 | 72 | getFriends(): Observable { 73 | return this.dataService.getFriends() 74 | } 75 | 76 | getFriend(id: string): FriendProfile { 77 | return this.dataService.getAllFriend().get(id) 78 | } 79 | 80 | getMessages(covId: string): Observable { 81 | return this.dataService.getMessages(covId) 82 | } 83 | 84 | } 85 | -------------------------------------------------------------------------------- /frontend/src/app/_services/data.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed } from '@angular/core/testing'; 2 | 3 | import { DataService } from './data.service'; 4 | 5 | describe('DataService', () => { 6 | let service: DataService; 7 | 8 | beforeEach(() => { 9 | TestBed.configureTestingModule({}); 10 | service = TestBed.inject(DataService); 11 | }); 12 | 13 | it('should be created', () => { 14 | expect(service).toBeTruthy(); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /frontend/src/app/_services/data.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { BehaviorSubject, Observable } from 'rxjs'; 3 | import { FriendProfile } from '../_dtos/chat/FriendProfile'; 4 | import { UserMessage } from '../_dtos/chat/UserMessage'; 5 | import { map } from 'rxjs/operators'; 6 | 7 | @Injectable() 8 | export class DataService { 9 | 10 | private _friends: BehaviorSubject> = new BehaviorSubject(new Map()); 11 | public readonly friends: Observable> = this._friends.asObservable(); 12 | 13 | private _userMessages: BehaviorSubject> = new BehaviorSubject(new Map()); 14 | 15 | updateUserMessages(msgs: UserMessage[]) { 16 | let oldMsgs = this._userMessages.value 17 | msgs.map(msg => oldMsgs.set(msg.id, msg)) 18 | this._userMessages.next(oldMsgs) 19 | this.sortFriends() 20 | } 21 | 22 | updateFriends(newFriends: FriendProfile[]) { 23 | let friends = this._friends.value 24 | newFriends.map(v => { 25 | let friend = friends.get(v.id) 26 | if (friend) { 27 | friend.update(v.id, v.email, v.name, v.imgUrl, v.blockedBy, v.updatedAt) 28 | } else { friends.set(v.id, v) } 29 | }) 30 | this._friends.next(friends) 31 | } 32 | 33 | sortFriends() { 34 | let msgs = this._userMessages.value 35 | let friends = this._friends.value 36 | 37 | msgs.forEach((msg, k) => { 38 | let friend = friends.get(msg.chatId) 39 | if (friend.lastMsgAt < msg.createdAt) { friend.updateConv(msg.content, msg.createdAt) } 40 | // if (!msg.readAt) { friend.incrementUnread() } 41 | }) 42 | this._friends.next(friends) 43 | } 44 | 45 | getMessages(chatId: String): Observable { 46 | return this._userMessages.pipe( 47 | map(m => { 48 | let msgs: UserMessage[] = [] 49 | m.forEach((v, k) => { if (v.chatId == chatId) msgs.push(v) }) 50 | // msgs.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime()) 51 | return msgs 52 | }) 53 | ) 54 | } 55 | 56 | getFriends(): Observable { 57 | return this._friends.pipe( 58 | map(m => { 59 | let friends: FriendProfile[] = [] 60 | m.forEach((v, k) => { friends.push(v) }) 61 | // friends.sort((a, b) => a.lastMsgAt.getTime() - b.lastMsgAt.getTime()) 62 | return friends 63 | }) 64 | ) 65 | } 66 | 67 | getAllFriend(): Map { 68 | return this._friends.value 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /frontend/src/app/_services/notification.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed } from '@angular/core/testing'; 2 | 3 | import { NotificationService } from './notification.service'; 4 | 5 | describe('NotificationService', () => { 6 | let service: NotificationService; 7 | 8 | beforeEach(() => { 9 | TestBed.configureTestingModule({}); 10 | service = TestBed.inject(NotificationService); 11 | }); 12 | 13 | it('should be created', () => { 14 | expect(service).toBeTruthy(); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /frontend/src/app/_services/notification.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { DataService } from './data.service'; 3 | import * as SockJS from 'sockjs-client'; 4 | import { Stomp } from '@stomp/stompjs'; 5 | import { environment } from 'src/environments/environment'; 6 | import { UserService } from './user.service'; 7 | import { UserMessage } from '../_dtos/chat/UserMessage'; 8 | import { FriendProfile } from '../_dtos/chat/FriendProfile'; 9 | import { TokenStorageService } from './token-storage.service'; 10 | 11 | @Injectable() 12 | export class NotificationService { 13 | 14 | stompClient: any; 15 | topic: string 16 | 17 | constructor(private dataService: DataService, private userService: UserService, private storageService: TokenStorageService) { 18 | this.topic = `/notifications/${this.userService.getProfile().id}` 19 | } 20 | 21 | suscribe() { 22 | let ws = new SockJS(`${environment.DOMAIN}/ws`); 23 | this.stompClient = Stomp.over(ws); 24 | this.stompClient.debug = () => {}; 25 | const _this = this; 26 | _this.stompClient.connect({ "Authorization": "Bearer " + this.storageService.getToken() }, 27 | function (frame) { 28 | _this.stompClient.subscribe(_this.topic, function (sdkEvent) { 29 | _this.onMessageReceived(sdkEvent); 30 | }); 31 | }, function (error) { setTimeout(() => _this.suscribe(), 5000); }); 32 | } 33 | 34 | onMessageReceived(message) { 35 | let json = JSON.parse(message.body) 36 | if (json['type'] == "USER_MESSAGE_ADDED") { 37 | let data = json['data'] as UserMessage 38 | this.dataService.updateUserMessages([data]) 39 | } else if (json['type'] == "USER_CONVERSATION_UPDATED" || json['type'] == "USER_CONVERSATION_ADDED") { 40 | let data = json['data'] as FriendProfile 41 | this.dataService.updateFriends([data]) 42 | } else { 43 | console.log(json) 44 | } 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /frontend/src/app/_services/token-storage.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed } from '@angular/core/testing'; 2 | 3 | import { TokenStorageService } from './token-storage.service'; 4 | 5 | describe('TokenStorageService', () => { 6 | let service: TokenStorageService; 7 | 8 | beforeEach(() => { 9 | TestBed.configureTestingModule({}); 10 | service = TestBed.inject(TokenStorageService); 11 | }); 12 | 13 | it('should be created', () => { 14 | expect(service).toBeTruthy(); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /frontend/src/app/_services/token-storage.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { UserProfile } from '../_dtos/user/UserProfile'; 3 | 4 | @Injectable({ 5 | providedIn: 'root' 6 | }) 7 | export class TokenStorageService { 8 | TOKEN_KEY = 'auth-token'; 9 | USER_KEY = 'auth-user' 10 | 11 | constructor() { } 12 | 13 | signOut() { 14 | localStorage.clear(); 15 | } 16 | 17 | public saveToken(token: string) { 18 | localStorage.removeItem(this.TOKEN_KEY); 19 | localStorage.setItem(this.TOKEN_KEY, token); 20 | } 21 | 22 | public getToken(): string { 23 | return localStorage.getItem(this.TOKEN_KEY); 24 | } 25 | 26 | public saveUser(user: UserProfile) { 27 | localStorage.removeItem(this.USER_KEY); 28 | localStorage.setItem(this.USER_KEY, JSON.stringify(user)); 29 | } 30 | 31 | public getUser(): UserProfile { 32 | let raw = JSON.parse(localStorage.getItem(this.USER_KEY)); 33 | return (raw != null)? new UserProfile(raw['id'], raw['email'], raw['name'], raw['imgUrl'], ) : null 34 | 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /frontend/src/app/_services/user.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed } from '@angular/core/testing'; 2 | 3 | import { UserService } from './user.service'; 4 | 5 | describe('UserService', () => { 6 | let service: UserService; 7 | 8 | beforeEach(() => { 9 | TestBed.configureTestingModule({}); 10 | service = TestBed.inject(UserService); 11 | }); 12 | 13 | it('should be created', () => { 14 | expect(service).toBeTruthy(); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /frontend/src/app/_services/user.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpClient, HttpHeaders } from '@angular/common/http'; 3 | import { environment } from '../../environments/environment'; 4 | import { TokenStorageService } from './token-storage.service'; 5 | import { map } from 'rxjs/operators'; 6 | import { UserProfile } from '../_dtos/user/UserProfile'; 7 | import { Observable } from 'rxjs'; 8 | 9 | @Injectable() 10 | export class UserService { 11 | 12 | httpOptions = { 13 | headers: new HttpHeaders({ 'Content-Type': 'application/json' }) 14 | }; 15 | 16 | constructor(private httpClient: HttpClient, private storage:TokenStorageService) { 17 | } 18 | 19 | fetchProfile(): Observable{ 20 | return this.httpClient.get(`${environment.DOMAIN}/api/user/me`, this.httpOptions) 21 | .pipe(map((user: UserProfile) =>{ 22 | this.storage.saveUser(user) 23 | return user 24 | })) 25 | } 26 | 27 | getProfile(): UserProfile{ 28 | return this.storage.getUser() 29 | } 30 | 31 | logout(): void{ 32 | this.storage.signOut() 33 | window.location.reload(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /frontend/src/app/app-routing.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | 3 | import { Routes, RouterModule } from '@angular/router'; 4 | 5 | const routes: Routes = [ 6 | {path: '', redirectTo:'loading', pathMatch: 'full'} 7 | ]; 8 | 9 | @NgModule({ 10 | imports: [RouterModule.forRoot(routes)], 11 | exports: [RouterModule], 12 | }) 13 | export class AppRoutingModule { } 14 | -------------------------------------------------------------------------------- /frontend/src/app/app.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /frontend/src/app/app.component.scss: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepanshut041/spring-angular-chat/7b5094c169c82d3eddf2f3aa8c896c8696bc747a/frontend/src/app/app.component.scss -------------------------------------------------------------------------------- /frontend/src/app/app.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed, async } from '@angular/core/testing'; 2 | import { AppComponent } from './app.component'; 3 | 4 | describe('AppComponent', () => { 5 | beforeEach(async(() => { 6 | TestBed.configureTestingModule({ 7 | declarations: [ 8 | AppComponent 9 | ], 10 | }).compileComponents(); 11 | })); 12 | 13 | it('should create the app', () => { 14 | const fixture = TestBed.createComponent(AppComponent); 15 | const app = fixture.componentInstance; 16 | expect(app).toBeTruthy(); 17 | }); 18 | 19 | it(`should have as title 'frontend'`, () => { 20 | const fixture = TestBed.createComponent(AppComponent); 21 | const app = fixture.componentInstance; 22 | expect(app.title).toEqual('frontend'); 23 | }); 24 | 25 | it('should render title', () => { 26 | const fixture = TestBed.createComponent(AppComponent); 27 | fixture.detectChanges(); 28 | const compiled = fixture.nativeElement; 29 | expect(compiled.querySelector('.content span').textContent).toContain('frontend app is running!'); 30 | }); 31 | }); 32 | -------------------------------------------------------------------------------- /frontend/src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-root', 5 | templateUrl: './app.component.html', 6 | styleUrls: ['./app.component.scss'] 7 | }) 8 | export class AppComponent { 9 | title = 'frontend'; 10 | } 11 | -------------------------------------------------------------------------------- /frontend/src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { BrowserModule } from '@angular/platform-browser'; 2 | import { NgModule } from '@angular/core'; 3 | 4 | import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; 5 | import { NbThemeModule, NbLayoutModule, NbMenuModule, NbDialogModule } from '@nebular/theme'; 6 | import { NbEvaIconsModule } from '@nebular/eva-icons'; 7 | 8 | import { AppRoutingModule } from './app-routing.module'; 9 | import { AuthModule } from "./auth/auth.module"; 10 | 11 | import { AppComponent } from './app.component'; 12 | import { HomeModule } from './home/home.module'; 13 | import { HTTP_INTERCEPTORS } from '@angular/common/http'; 14 | import { JwtInterceptor } from './_helpers/jwt.interceptor'; 15 | 16 | @NgModule({ 17 | declarations: [ 18 | AppComponent, 19 | ], 20 | imports: [ 21 | BrowserModule, 22 | BrowserAnimationsModule, 23 | NbThemeModule.forRoot({ name: 'cosmic' }), 24 | NbMenuModule.forRoot(), 25 | NbDialogModule.forRoot(), 26 | NbLayoutModule, 27 | NbEvaIconsModule, 28 | AppRoutingModule, 29 | AuthModule, 30 | HomeModule, 31 | ], 32 | providers: [ 33 | { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true }, 34 | 35 | ], 36 | bootstrap: [AppComponent] 37 | }) 38 | export class AppModule { } 39 | -------------------------------------------------------------------------------- /frontend/src/app/auth/auth-routing.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | 3 | import { Routes, RouterModule } from '@angular/router'; 4 | import { AuthComponent } from './auth.component'; 5 | import { SigninComponent } from './signin/signin.component'; 6 | import { SignupComponent } from './signup/signup.component'; 7 | import { ForgotPasswordComponent } from './forgot-password/forgot-password.component'; 8 | import { ResetPasswordComponent } from './reset-password/reset-password.component'; 9 | import { TokenComponent } from './token/token.component'; 10 | 11 | const routes: Routes = [ 12 | {path: 'auth', component: AuthComponent, children:[ 13 | {path: 'signin', component: SigninComponent}, 14 | {path: 'signup', component: SignupComponent}, 15 | {path: 'forgot', component: ForgotPasswordComponent}, 16 | {path: 'reset', component: ResetPasswordComponent}, 17 | {path: 'token', component: TokenComponent}, 18 | {path: '', redirectTo:'signin', pathMatch: 'full'} 19 | ]} 20 | ]; 21 | 22 | @NgModule({ 23 | imports: [RouterModule.forChild(routes)], 24 | exports: [RouterModule], 25 | }) 26 | export class AuthRoutingModule { } 27 | -------------------------------------------------------------------------------- /frontend/src/app/auth/auth.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | Clean Design with multiple themes 11 | Realtime with sockets 12 | Multimedia message support(Audio, Video, Document, Gif, Images) 13 | Message Encription support 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /frontend/src/app/auth/auth.component.scss: -------------------------------------------------------------------------------- 1 | .row{ 2 | .col-md-6:first-child { 3 | 4 | nb-card{ 5 | height: 100%; 6 | padding-bottom: 0 !important; 7 | } 8 | } 9 | } -------------------------------------------------------------------------------- /frontend/src/app/auth/auth.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { AuthComponent } from './auth.component'; 4 | 5 | describe('AuthComponent', () => { 6 | let component: AuthComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ AuthComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(AuthComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /frontend/src/app/auth/auth.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { AuthService } from '../_services/auth.service'; 3 | import { Router } from '@angular/router'; 4 | 5 | @Component({ 6 | selector: 'app-auth', 7 | templateUrl: './auth.component.html', 8 | styleUrls: ['./auth.component.scss'] 9 | }) 10 | export class AuthComponent implements OnInit { 11 | 12 | constructor(private authService: AuthService, private router: Router) { 13 | if(this.authService.getToken()){ 14 | this.router.navigateByUrl("/") 15 | } 16 | 17 | } 18 | 19 | ngOnInit(): void { 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /frontend/src/app/auth/auth.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { CommonModule } from '@angular/common'; 3 | import { HttpClientModule } from '@angular/common/http'; 4 | import { FormsModule, ReactiveFormsModule } from '@angular/forms'; 5 | 6 | import { AuthRoutingModule } from './auth-routing.module'; 7 | import { SharedModule } from '../shared/shared.module'; 8 | 9 | import { AuthService } from '../_services/auth.service'; 10 | 11 | import { AuthComponent } from './auth.component'; 12 | import { SignupComponent } from './signup/signup.component'; 13 | import { SigninComponent } from './signin/signin.component'; 14 | import { ForgotPasswordComponent } from './forgot-password/forgot-password.component'; 15 | import { ResetPasswordComponent } from './reset-password/reset-password.component'; 16 | import { TokenComponent } from './token/token.component'; 17 | import { UserService } from '../_services/user.service'; 18 | 19 | 20 | @NgModule({ 21 | declarations: [AuthComponent, SignupComponent, SigninComponent, ForgotPasswordComponent, ResetPasswordComponent, TokenComponent], 22 | imports: [ 23 | CommonModule, AuthRoutingModule, SharedModule, HttpClientModule, FormsModule, ReactiveFormsModule 24 | ], 25 | providers: [ 26 | AuthService, UserService 27 | ] 28 | }) 29 | export class AuthModule { } 30 | -------------------------------------------------------------------------------- /frontend/src/app/auth/forgot-password/forgot-password.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Forgot Password 4 | 5 | 6 | 7 | 8 | Email address: 9 | 10 | 11 | 12 | 13 | Submit 14 | 15 | 16 | 17 | 18 | 19 | Don't have an account? Register 20 | 21 | 22 | -------------------------------------------------------------------------------- /frontend/src/app/auth/forgot-password/forgot-password.component.scss: -------------------------------------------------------------------------------- 1 | nb-card{ 2 | height: 100%; 3 | } -------------------------------------------------------------------------------- /frontend/src/app/auth/forgot-password/forgot-password.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { ForgotPasswordComponent } from './forgot-password.component'; 4 | 5 | describe('ForgotPasswordComponent', () => { 6 | let component: ForgotPasswordComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ ForgotPasswordComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(ForgotPasswordComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /frontend/src/app/auth/forgot-password/forgot-password.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-forgot-password', 5 | templateUrl: './forgot-password.component.html', 6 | styleUrls: ['./forgot-password.component.scss'] 7 | }) 8 | export class ForgotPasswordComponent implements OnInit { 9 | 10 | loading: Boolean = false 11 | 12 | constructor() { } 13 | 14 | ngOnInit(): void { 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /frontend/src/app/auth/reset-password/reset-password.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Reset Password 4 | 5 | 6 | 7 | 8 | 9 | Password: 10 | 11 | 12 | 13 | 14 | 15 | 16 | Confirm Password: 17 | 18 | 19 | 20 | 21 | 22 | Reset Password 23 | 24 | 25 | 26 | 27 | 28 | Don't have an account? Register 29 | 30 | 31 | -------------------------------------------------------------------------------- /frontend/src/app/auth/reset-password/reset-password.component.scss: -------------------------------------------------------------------------------- 1 | nb-card{ 2 | height: 100%; 3 | } -------------------------------------------------------------------------------- /frontend/src/app/auth/reset-password/reset-password.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { ResetPasswordComponent } from './reset-password.component'; 4 | 5 | describe('ResetPasswordComponent', () => { 6 | let component: ResetPasswordComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ ResetPasswordComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(ResetPasswordComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /frontend/src/app/auth/reset-password/reset-password.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-reset-password', 5 | templateUrl: './reset-password.component.html', 6 | styleUrls: ['./reset-password.component.scss'] 7 | }) 8 | export class ResetPasswordComponent implements OnInit { 9 | 10 | loading: Boolean = false 11 | 12 | constructor() { } 13 | 14 | ngOnInit(): void { 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /frontend/src/app/auth/signin/signin.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Sign In 4 | 5 | 6 | 7 | 8 | Email address: 9 | 10 | 11 | 12 | 13 | 14 | Password: 15 | 16 | 17 | 18 | Forgot Password? 19 | 20 | 21 | 22 | 23 | Sign In 24 | 25 | 26 | or Continue with 27 | 28 | 29 | Google 30 | 31 | 32 | Facebook 33 | 34 | 35 | 36 | 37 | 38 | Don't have an account? Register 39 | 40 | 41 | -------------------------------------------------------------------------------- /frontend/src/app/auth/signin/signin.component.scss: -------------------------------------------------------------------------------- 1 | nb-card{ 2 | height: 100%; 3 | } -------------------------------------------------------------------------------- /frontend/src/app/auth/signin/signin.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { SigninComponent } from './signin.component'; 4 | 5 | describe('SigninComponent', () => { 6 | let component: SigninComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ SigninComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(SigninComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /frontend/src/app/auth/signin/signin.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { AuthService } from 'src/app/_services/auth.service'; 3 | import { FormBuilder, FormGroup } from '@angular/forms'; 4 | import { SignInRequest } from 'src/app/_dtos/auth/SignInRequest'; 5 | import { SignInResponse } from 'src/app/_dtos/auth/SignInResponse'; 6 | import { Router, ActivatedRoute } from '@angular/router'; 7 | import { environment } from '../../../environments/environment'; 8 | 9 | @Component({ 10 | selector: 'app-signin', 11 | templateUrl: './signin.component.html', 12 | styleUrls: ['./signin.component.scss'] 13 | }) 14 | export class SigninComponent implements OnInit { 15 | 16 | loading: Boolean = false 17 | signInFrom: FormGroup 18 | redirect = "/" 19 | 20 | constructor( private _authService: AuthService, private fb: FormBuilder, private router: Router) { 21 | this.signInFrom = this.fb.group({ 22 | email: [], 23 | password: [] 24 | }) 25 | } 26 | 27 | ngOnInit(): void { 28 | } 29 | 30 | login(){ 31 | if(this.signInFrom.valid){ 32 | let data = this.signInFrom.value 33 | this.loading = true 34 | this._authService.login(new SignInRequest(data['email'], data['password'])).subscribe( 35 | (response: SignInResponse)=>{ 36 | this.router.navigateByUrl(this.redirect) 37 | this.loading = false 38 | },(err:any)=>{ 39 | this.loading = false 40 | console.log(err.error.message) 41 | } 42 | ) 43 | } 44 | } 45 | 46 | facebook(){ 47 | window.location.href=`${environment.DOMAIN}/oauth2/authorization/facebook?redirect_url=http://localhost:4200/auth/token`; 48 | } 49 | 50 | google(){ 51 | window.location.href=`${environment.DOMAIN}/oauth2/authorization/google?redirect_url=http://localhost:4200/auth/token`; 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /frontend/src/app/auth/signup/signup.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Sign Up 4 | 5 | 6 | 7 | 8 | Email address: 9 | 10 | 11 | 12 | 13 | Full Name: 14 | 15 | 16 | 17 | 18 | 19 | Password: 20 | 21 | 22 | 23 | 24 | 25 | 26 | Confirm Password: 27 | 28 | 29 | 30 | 31 | 32 | Sign Up 33 | 34 | 35 | 36 | 37 | 38 | Already have an account? Sigin 39 | 40 | 41 | -------------------------------------------------------------------------------- /frontend/src/app/auth/signup/signup.component.scss: -------------------------------------------------------------------------------- 1 | nb-card{ 2 | height: 100%; 3 | } -------------------------------------------------------------------------------- /frontend/src/app/auth/signup/signup.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { SignupComponent } from './signup.component'; 4 | 5 | describe('SignupComponent', () => { 6 | let component: SignupComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ SignupComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(SignupComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /frontend/src/app/auth/signup/signup.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { FormGroup, FormBuilder } from '@angular/forms'; 3 | import { AuthService } from 'src/app/_services/auth.service'; 4 | import { Router } from '@angular/router'; 5 | import { SignUpRequest } from 'src/app/_dtos/auth/SignUpRequest'; 6 | import { ApiResponse } from 'src/app/_dtos/common/ApiResponse'; 7 | import { NbDialogService } from '@nebular/theme'; 8 | import { DialogSuccessComponent } from 'src/app/shared/dialog/dialog-alert/dialog-success.component'; 9 | 10 | @Component({ 11 | selector: 'app-signup', 12 | templateUrl: './signup.component.html', 13 | styleUrls: ['./signup.component.scss'] 14 | }) 15 | export class SignupComponent implements OnInit { 16 | 17 | loading: Boolean = false 18 | signUpFrom: FormGroup 19 | 20 | constructor(private _authService: AuthService, private fb: FormBuilder, private router: Router, private dialogService: NbDialogService) { 21 | this.signUpFrom = this.fb.group({ 22 | email: [], 23 | password: [], 24 | name: [] 25 | }) 26 | } 27 | 28 | ngOnInit(): void { 29 | 30 | } 31 | 32 | register() { 33 | if (this.signUpFrom.valid) { 34 | let data = this.signUpFrom.value 35 | this.loading = true 36 | this._authService.register(new SignUpRequest(data['name'], data['email'], data['password'])).subscribe( 37 | (response: ApiResponse) => { 38 | this.loading = false 39 | this.dialogService.open(DialogSuccessComponent, { 40 | context: { title: "Congratulation", message: response.message } 41 | }) 42 | }, (err: any) => { 43 | this.loading = false 44 | console.log(err.error.message) 45 | } 46 | ) 47 | } 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /frontend/src/app/auth/token/token.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Profile 4 | 5 | 6 | 7 | 8 | {{profile.name}} 9 | 10 | Continue 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /frontend/src/app/auth/token/token.component.scss: -------------------------------------------------------------------------------- 1 | nb-card{ 2 | height: 100%; 3 | } -------------------------------------------------------------------------------- /frontend/src/app/auth/token/token.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { TokenComponent } from './token.component'; 4 | 5 | describe('TokenComponent', () => { 6 | let component: TokenComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ TokenComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(TokenComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /frontend/src/app/auth/token/token.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { ActivatedRoute, Router } from '@angular/router'; 3 | import { AuthService } from 'src/app/_services/auth.service'; 4 | import { UserService } from 'src/app/_services/user.service'; 5 | import { UserProfile } from 'src/app/_dtos/user/UserProfile'; 6 | import { delay } from 'rxjs/operators'; 7 | 8 | @Component({ 9 | selector: 'app-token', 10 | templateUrl: './token.component.html', 11 | styleUrls: ['./token.component.scss'] 12 | }) 13 | export class TokenComponent implements OnInit { 14 | 15 | loading: Boolean = true 16 | profile: UserProfile 17 | token: string 18 | redirect = "/loading" 19 | 20 | constructor(private route: ActivatedRoute, private authService: AuthService, private userService: UserService, private router: Router) { 21 | this.route.queryParams.subscribe(params => { 22 | this.token = params['token']; 23 | this.authService.setToken(this.token) 24 | }); 25 | } 26 | 27 | ngOnInit(): void { 28 | (async () => { 29 | await delay(5000); 30 | this.userService.fetchProfile().subscribe( 31 | (profile: UserProfile) => { 32 | this.profile = profile 33 | this.loading = false 34 | }, (err) => { 35 | this.router.navigateByUrl("/auth/signin") 36 | }) 37 | })(); 38 | } 39 | 40 | continue() { 41 | this.router.navigateByUrl(this.redirect) 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /frontend/src/app/home/chat-banner/chat-banner.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Friends Chat 6 | 7 | 8 | Clean Design with multiple themes 9 | Group chat with message status 10 | Multimedia message support(Audio, Video, Document, Gif, Images) 11 | Message Encription support 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /frontend/src/app/home/chat-banner/chat-banner.component.scss: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepanshut041/spring-angular-chat/7b5094c169c82d3eddf2f3aa8c896c8696bc747a/frontend/src/app/home/chat-banner/chat-banner.component.scss -------------------------------------------------------------------------------- /frontend/src/app/home/chat-banner/chat-banner.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { ChatBannerComponent } from './chat-banner.component'; 4 | 5 | describe('ChatBannerComponent', () => { 6 | let component: ChatBannerComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ ChatBannerComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(ChatBannerComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /frontend/src/app/home/chat-banner/chat-banner.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-chat-banner', 5 | templateUrl: './chat-banner.component.html', 6 | styleUrls: ['./chat-banner.component.scss'] 7 | }) 8 | export class ChatBannerComponent implements OnInit { 9 | 10 | constructor() { } 11 | 12 | ngOnInit(): void { 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /frontend/src/app/home/chat-detail/chat-detail.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /frontend/src/app/home/chat-detail/chat-detail.component.scss: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepanshut041/spring-angular-chat/7b5094c169c82d3eddf2f3aa8c896c8696bc747a/frontend/src/app/home/chat-detail/chat-detail.component.scss -------------------------------------------------------------------------------- /frontend/src/app/home/chat-detail/chat-detail.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { ChatDetailComponent } from './chat-detail.component'; 4 | 5 | describe('ChatDetailComponent', () => { 6 | let component: ChatDetailComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ ChatDetailComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(ChatDetailComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /frontend/src/app/home/chat-detail/chat-detail.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { ChatService } from 'src/app/_services/chat.service'; 3 | import { Router, ActivatedRoute } from '@angular/router'; 4 | import { FriendProfile } from 'src/app/_dtos/chat/FriendProfile'; 5 | import { UserProfile } from 'src/app/_dtos/user/UserProfile'; 6 | import { UserService } from 'src/app/_services/user.service'; 7 | import { NbMessage } from 'src/app/_dtos/chat/NbMessage'; 8 | import { Observable } from 'rxjs'; 9 | import { UserMessage } from 'src/app/_dtos/chat/UserMessage'; 10 | 11 | @Component({ 12 | selector: 'app-chat-detail', 13 | templateUrl: './chat-detail.component.html', 14 | styleUrls: ['./chat-detail.component.scss'] 15 | }) 16 | export class ChatDetailComponent implements OnInit { 17 | 18 | messages: NbMessage[] = []; 19 | friendId: string; 20 | friendProfile: FriendProfile; 21 | myProfile: UserProfile; 22 | subscription: any; 23 | 24 | constructor(private chatService: ChatService, private router: Router, private route: ActivatedRoute, private userService: UserService) { 25 | 26 | this.route.params.subscribe(params => { 27 | this.friendId = params['id']; 28 | if (this.subscription) this.subscription.unsubscribe(); 29 | this.myProfile = this.userService.getProfile(); 30 | this.friendProfile = this.chatService.getFriend(this.friendId); 31 | this.getChat() 32 | }); 33 | } 34 | 35 | ngOnInit(): void { 36 | } 37 | 38 | getChat() { 39 | this.messages = [] 40 | this.subscription = this.chatService.getMessages(this.friendId).subscribe(msgs => { 41 | let messages = msgs.map(msg => { 42 | let nm = new NbMessage(msg) 43 | if (msg.senderId == this.myProfile.id) nm.updateUser(this.myProfile.name, this.myProfile.imgUrl, true) 44 | else nm.updateUser(this.friendProfile.name, this.friendProfile.imgUrl, false) 45 | return nm 46 | }) 47 | this.messages.push(...messages.slice(this.messages.length, messages.length)) 48 | }) 49 | } 50 | 51 | sendMessage(event) { 52 | const files = !event.files ? [] : event.files; 53 | 54 | let formData = new FormData(); 55 | 56 | if(files.length == 0){ 57 | this.chatService.createMessageText(this.friendId, event.message).subscribe() 58 | } else { 59 | formData.append('files', files); 60 | this.chatService.createMessageFile(this.friendId, event.message, formData).subscribe() 61 | } 62 | } 63 | 64 | 65 | 66 | } 67 | -------------------------------------------------------------------------------- /frontend/src/app/home/chat-list/chat-list.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | {{profile.name}} 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /frontend/src/app/home/chat-list/chat-list.component.scss: -------------------------------------------------------------------------------- 1 | nb-card{ 2 | padding: 0 !important; 3 | height: 100%; 4 | 5 | nb-card-body{ 6 | overflow: unset; 7 | } 8 | nb-list{ 9 | height: 60vh; 10 | 11 | nb-list-item:hover { 12 | background-color:#4C4C4C09; 13 | cursor: pointer; 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /frontend/src/app/home/chat-list/chat-list.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { ChatListComponent } from './chat-list.component'; 4 | 5 | describe('ChatListComponent', () => { 6 | let component: ChatListComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ ChatListComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(ChatListComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /frontend/src/app/home/chat-list/chat-list.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { NbMenuService, NbDialogService } from '@nebular/theme'; 3 | import { filter, map } from 'rxjs/operators'; 4 | import { Router, ActivatedRoute } from '@angular/router'; 5 | import { UserService } from 'src/app/_services/user.service'; 6 | import { UserProfile } from 'src/app/_dtos/user/UserProfile'; 7 | import { ChatService } from 'src/app/_services/chat.service'; 8 | import { Observable } from 'rxjs'; 9 | import { FriendProfile } from 'src/app/_dtos/chat/FriendProfile'; 10 | import { NewChatComponent } from './new-chat/new-chat.component'; 11 | 12 | @Component({ 13 | selector: 'home-chat-list', 14 | templateUrl: './chat-list.component.html', 15 | styleUrls: ['./chat-list.component.scss'] 16 | }) 17 | export class ChatListComponent implements OnInit { 18 | 19 | friends: Observable 20 | menu = [ 21 | { title: 'Profile', icon: 'person-outline' }, 22 | { title: 'New Chat', icon: 'person-add-outline' }, 23 | { title: 'New Group', icon: 'plus-outline' }, 24 | { title: 'Settings', icon: 'settings-outline' }, 25 | { title: 'Log out', icon: 'unlock-outline' }, 26 | ]; 27 | 28 | profile: UserProfile 29 | 30 | constructor(private menuService: NbMenuService, private router: Router, private dialogService: NbDialogService, 31 | private userService: UserService, private chatService: ChatService, private route: ActivatedRoute) { 32 | this.profile = this.userService.getProfile() 33 | this.friends = this.chatService.getFriends() 34 | } 35 | 36 | ngOnInit(): void { 37 | this.menuListener() 38 | } 39 | 40 | menuListener() { 41 | this.menuService.onItemClick() 42 | .pipe( 43 | filter(({ tag }) => tag === 'context-chat-more'), 44 | map(({ item: { title } }) => title), 45 | ) 46 | .subscribe(title => { 47 | switch (title) { 48 | case 'Profile': 49 | this.router.navigateByUrl("/profile") 50 | break; 51 | case 'New Chat': 52 | this.dialogService.open(NewChatComponent).onClose.subscribe((email) => { 53 | this.chatService.createFriend(email).subscribe( 54 | (r) => { console.log(r) }, 55 | (err) => { console.log(err) } 56 | ) 57 | }) 58 | break; 59 | case 'New Group': 60 | 61 | break; 62 | case 'Settings': 63 | this.router.navigateByUrl("/settings") 64 | break; 65 | case 'Log out': 66 | this.userService.logout() 67 | this.router.navigateByUrl("/auth") 68 | break; 69 | default: 70 | break; 71 | } 72 | }) 73 | } 74 | 75 | chatClicked(id: String){ 76 | this.router.navigate([id], { relativeTo: this.route, skipLocationChange:true }) 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /frontend/src/app/home/chat-list/new-chat/new-chat.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, Input } from '@angular/core'; 2 | import { NbDialogRef } from '@nebular/theme'; 3 | 4 | @Component({ 5 | template: ` 6 | 7 | Enter Your Friend Email 8 | 9 | 10 | 11 | 12 | Submit 13 | Close 14 | 15 | 16 | `, 17 | }) 18 | export class NewChatComponent { 19 | 20 | constructor(protected ref: NbDialogRef) { 21 | } 22 | 23 | dismiss() { 24 | this.ref.close(); 25 | } 26 | 27 | submit(email: string){ 28 | this.ref.close(email); 29 | } 30 | } -------------------------------------------------------------------------------- /frontend/src/app/home/chat/chat.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /frontend/src/app/home/chat/chat.component.scss: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepanshut041/spring-angular-chat/7b5094c169c82d3eddf2f3aa8c896c8696bc747a/frontend/src/app/home/chat/chat.component.scss -------------------------------------------------------------------------------- /frontend/src/app/home/chat/chat.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { ChatComponent } from './chat.component'; 4 | 5 | describe('ChatComponent', () => { 6 | let component: ChatComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ ChatComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(ChatComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /frontend/src/app/home/chat/chat.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { NotificationService } from 'src/app/_services/notification.service'; 3 | import { DataService } from 'src/app/_services/data.service'; 4 | import { ChatService } from 'src/app/_services/chat.service'; 5 | import { Router } from '@angular/router'; 6 | 7 | @Component({ 8 | selector: 'home-chat', 9 | templateUrl: './chat.component.html', 10 | styleUrls: ['./chat.component.scss'] 11 | }) 12 | export class ChatComponent implements OnInit { 13 | 14 | constructor(private notificationService: NotificationService, private chatService: ChatService, private router: Router) { } 15 | 16 | ngOnInit(): void { 17 | this.notificationService.suscribe() 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /frontend/src/app/home/home-routing.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | 3 | import { Routes, RouterModule } from '@angular/router'; 4 | import { HomeComponent } from './home.component'; 5 | import { SettingsComponent } from './settings/settings.component'; 6 | import { AuthGuard } from '../_helpers/auth.guard'; 7 | import { LoadingComponent } from './loading/loading.component'; 8 | import { ChatComponent } from './chat/chat.component'; 9 | import { ChatDetailComponent } from './chat-detail/chat-detail.component'; 10 | import { ChatBannerComponent } from './chat-banner/chat-banner.component'; 11 | import { ProfileComponent } from './profile/profile.component'; 12 | 13 | const routes: Routes = [ 14 | { 15 | path: '', component: HomeComponent, canActivate: [AuthGuard], children: [ 16 | { 17 | path: 'chat', component: ChatComponent, children: [ 18 | { path: '', component: ChatBannerComponent }, 19 | { path: ':id', component: ChatDetailComponent }, 20 | ] 21 | }, 22 | { path: 'profile', component: ProfileComponent}, 23 | { path: 'loading', component: LoadingComponent }, 24 | { path: 'settings', component: SettingsComponent } 25 | ] 26 | } 27 | ]; 28 | 29 | @NgModule({ 30 | imports: [RouterModule.forChild(routes)], 31 | exports: [RouterModule], 32 | }) 33 | export class HomeRoutingModule { 34 | 35 | } 36 | -------------------------------------------------------------------------------- /frontend/src/app/home/home.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /frontend/src/app/home/home.component.scss: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepanshut041/spring-angular-chat/7b5094c169c82d3eddf2f3aa8c896c8696bc747a/frontend/src/app/home/home.component.scss -------------------------------------------------------------------------------- /frontend/src/app/home/home.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { HomeComponent } from './home.component'; 4 | 5 | describe('HomeComponent', () => { 6 | let component: HomeComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ HomeComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(HomeComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /frontend/src/app/home/home.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { ChatService } from '../_services/chat.service'; 3 | import { Router } from '@angular/router'; 4 | 5 | @Component({ 6 | selector: 'app-home', 7 | templateUrl: './home.component.html', 8 | styleUrls: ['./home.component.scss'] 9 | }) 10 | export class HomeComponent implements OnInit { 11 | 12 | constructor(private chatService: ChatService, private router: Router) { 13 | this.chatService.fetch.subscribe(v => { 14 | if(v == 0) this.router.navigateByUrl("/loading") 15 | if(v == 100) this.router.navigateByUrl("/chat") 16 | }) 17 | } 18 | 19 | ngOnInit(): void { 20 | 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /frontend/src/app/home/home.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { CommonModule } from '@angular/common'; 3 | import { SharedModule } from '../shared/shared.module'; 4 | 5 | import { HomeComponent } from './home.component'; 6 | import { ChatComponent } from './chat/chat.component'; 7 | import { ProfileComponent } from './profile/profile.component'; 8 | import { SettingsComponent } from './settings/settings.component'; 9 | 10 | import { HomeRoutingModule } from './home-routing.module'; 11 | import { NbSidebarService, NbMenuService } from '@nebular/theme'; 12 | import { ChatListComponent } from './chat-list/chat-list.component'; 13 | import { UserService } from '../_services/user.service'; 14 | import { ChatService } from '../_services/chat.service'; 15 | import { NotificationService } from '../_services/notification.service'; 16 | import { DataService } from '../_services/data.service'; 17 | import { LoadingComponent } from './loading/loading.component'; 18 | import { ChatDetailComponent } from './chat-detail/chat-detail.component'; 19 | import { ChatBannerComponent } from './chat-banner/chat-banner.component'; 20 | import { NewChatComponent } from './chat-list/new-chat/new-chat.component'; 21 | 22 | @NgModule({ 23 | declarations: [ 24 | HomeComponent, 25 | ChatComponent, 26 | ProfileComponent, 27 | SettingsComponent, 28 | ChatListComponent, 29 | LoadingComponent, 30 | ChatDetailComponent, 31 | ChatBannerComponent, 32 | NewChatComponent 33 | ], 34 | imports: [ 35 | CommonModule, HomeRoutingModule, SharedModule, 36 | ], 37 | providers:[ 38 | DataService, NbMenuService, UserService, ChatService, NotificationService 39 | ] 40 | }) 41 | export class HomeModule { } 42 | -------------------------------------------------------------------------------- /frontend/src/app/home/loading/loading.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Friends Chat 6 | 7 | 8 | 9 | Loading your Content... 10 | 11 | 12 | Powered By: Deepanshu Tyagi 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /frontend/src/app/home/loading/loading.component.scss: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepanshut041/spring-angular-chat/7b5094c169c82d3eddf2f3aa8c896c8696bc747a/frontend/src/app/home/loading/loading.component.scss -------------------------------------------------------------------------------- /frontend/src/app/home/loading/loading.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { LoadingComponent } from './loading.component'; 4 | 5 | describe('LoadingComponent', () => { 6 | let component: LoadingComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ LoadingComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(LoadingComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /frontend/src/app/home/loading/loading.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { ChatService } from 'src/app/_services/chat.service'; 3 | import { Router } from '@angular/router'; 4 | import { UserService } from 'src/app/_services/user.service'; 5 | 6 | @Component({ 7 | selector: 'app-loading', 8 | templateUrl: './loading.component.html', 9 | styleUrls: ['./loading.component.scss'] 10 | }) 11 | export class LoadingComponent implements OnInit { 12 | 13 | constructor(private chatService: ChatService, private router: Router, private userService: UserService) { } 14 | 15 | ngOnInit(): void { 16 | this.userService.fetchProfile().subscribe(o =>{ 17 | this.chatService.updateFetch(10) 18 | }) 19 | this.chatService.fetchFriends().subscribe((output)=>{ 20 | this.chatService.updateFetch(20) 21 | this.chatService.fetchAllMessages().subscribe(v =>{ 22 | this.chatService.updateFetch(100) 23 | }) 24 | }) 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /frontend/src/app/home/profile/profile.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Edit your profile 6 | 7 | 8 | 10 | 11 | 12 | 13 | 14 | 15 | {{profile.name}} 16 | 17 | Continue 18 | 19 | 20 | 21 | 22 | Powered By: Deepanshu Tyagi 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /frontend/src/app/home/profile/profile.component.scss: -------------------------------------------------------------------------------- 1 | .profile-image { 2 | height: 200px; 3 | width: 200px; 4 | border-radius: 50%; 5 | margin: auto; 6 | background-size: contain; 7 | background-position: center; 8 | 9 | .top-layer { 10 | background-color:#4c4c4c; 11 | border-radius: 50%; 12 | opacity:0; 13 | 14 | nb-icon{ 15 | margin-top: 70px; 16 | color: #fff; 17 | font-size: 3rem; 18 | opacity: 0; 19 | } 20 | } 21 | 22 | .top-layer:hover{ 23 | opacity:0.6; 24 | cursor: pointer; 25 | 26 | nb-icon{ 27 | opacity: 1; 28 | } 29 | } 30 | 31 | } -------------------------------------------------------------------------------- /frontend/src/app/home/profile/profile.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { ProfileComponent } from './profile.component'; 4 | 5 | describe('ProfileComponent', () => { 6 | let component: ProfileComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ ProfileComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(ProfileComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /frontend/src/app/home/profile/profile.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { Router } from '@angular/router'; 3 | import { UserService } from 'src/app/_services/user.service'; 4 | import { UserProfile } from 'src/app/_dtos/user/UserProfile'; 5 | 6 | @Component({ 7 | selector: 'app-profile', 8 | templateUrl: './profile.component.html', 9 | styleUrls: ['./profile.component.scss'] 10 | }) 11 | export class ProfileComponent implements OnInit { 12 | 13 | profile: UserProfile 14 | 15 | constructor(private userService: UserService, private router: Router) { 16 | this.profile = this.userService.getProfile() 17 | } 18 | 19 | ngOnInit(): void { 20 | } 21 | 22 | continue(): void{ 23 | this.router.navigateByUrl("/chat") 24 | } 25 | 26 | uploadFile(file): void{ 27 | console.log(file) 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /frontend/src/app/home/settings/settings.component.html: -------------------------------------------------------------------------------- 1 | settings works! 2 | -------------------------------------------------------------------------------- /frontend/src/app/home/settings/settings.component.scss: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepanshut041/spring-angular-chat/7b5094c169c82d3eddf2f3aa8c896c8696bc747a/frontend/src/app/home/settings/settings.component.scss -------------------------------------------------------------------------------- /frontend/src/app/home/settings/settings.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { SettingsComponent } from './settings.component'; 4 | 5 | describe('SettingsComponent', () => { 6 | let component: SettingsComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ SettingsComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(SettingsComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /frontend/src/app/home/settings/settings.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-settings', 5 | templateUrl: './settings.component.html', 6 | styleUrls: ['./settings.component.scss'] 7 | }) 8 | export class SettingsComponent implements OnInit { 9 | 10 | constructor() { } 11 | 12 | ngOnInit(): void { 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /frontend/src/app/shared/dialog/dialog-alert/dialog-success.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, Input } from '@angular/core'; 2 | import { NbDialogRef } from '@nebular/theme'; 3 | 4 | @Component({ 5 | template: ` 6 | 7 | {{ title }} 8 | 9 | 10 | 11 | 12 | {{ message }} 13 | 14 | 15 | Close 16 | 17 | 18 | `, 19 | }) 20 | export class DialogSuccessComponent { 21 | 22 | @Input() title: string; 23 | @Input() message: string; 24 | constructor(protected ref: NbDialogRef) { 25 | } 26 | 27 | dismiss() { 28 | this.ref.close(); 29 | } 30 | } -------------------------------------------------------------------------------- /frontend/src/app/shared/dialog/dialog-alert/dialog.common.scss: -------------------------------------------------------------------------------- 1 | ::ng-deep { 2 | nb-layout-column { 3 | height: 80vw; 4 | } 5 | 6 | button + button { 7 | margin-left: 1rem; 8 | } 9 | 10 | .dialog-card { 11 | margin-left: auto; 12 | margin-right: auto; 13 | width: 90%; 14 | } 15 | 16 | @media (min-width: 40rem) { 17 | .dialog-card { 18 | width: 38rem; 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /frontend/src/app/shared/directives/img-fallback.directive.ts: -------------------------------------------------------------------------------- 1 | import { Directive, Input, ElementRef, HostListener } from '@angular/core'; 2 | 3 | @Directive({ 4 | selector: 'img[appImgFallback]' 5 | }) 6 | export class ImgFallbackDirective { 7 | 8 | @Input() appImgFallback: string; 9 | 10 | constructor(private eRef: ElementRef) { } 11 | 12 | @HostListener('error') 13 | loadFallbackOnError() { 14 | const element: HTMLImageElement = this.eRef.nativeElement; 15 | element.src = this.appImgFallback || 'https://via.placeholder.com/200'; 16 | } 17 | 18 | } -------------------------------------------------------------------------------- /frontend/src/app/shared/shared.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { CommonModule } from '@angular/common'; 3 | import { 4 | NbLayoutModule, NbCardModule, NbAlertModule, NbInputModule, NbCheckboxModule, NbFormFieldModule, NbButtonModule, NbIconModule, 5 | NbSpinnerModule, NbUserModule, NbSidebarModule, NbChatModule, NbListModule, NbContextMenuModule, NbDialogModule, NbProgressBarModule 6 | } from '@nebular/theme'; 7 | import { DialogSuccessComponent } from './dialog/dialog-alert/dialog-success.component'; 8 | import { ImgFallbackDirective } from './directives/img-fallback.directive'; 9 | 10 | 11 | 12 | @NgModule({ 13 | declarations: [DialogSuccessComponent, ImgFallbackDirective], 14 | imports: [ 15 | CommonModule, NbLayoutModule, NbCardModule, NbAlertModule, NbInputModule, NbFormFieldModule, NbCheckboxModule, NbProgressBarModule, 16 | NbButtonModule, NbIconModule, NbSpinnerModule, NbUserModule, NbSidebarModule, NbChatModule, NbListModule, NbContextMenuModule, 17 | NbDialogModule 18 | ], 19 | exports: [ 20 | NbLayoutModule, NbCardModule, NbAlertModule, NbInputModule, NbFormFieldModule, NbCheckboxModule, NbButtonModule, NbIconModule, 21 | NbSpinnerModule, NbUserModule, NbSidebarModule, NbChatModule, NbListModule, NbContextMenuModule, NbDialogModule, NbProgressBarModule, 22 | DialogSuccessComponent, 23 | ImgFallbackDirective, 24 | ] 25 | }) 26 | export class SharedModule { } 27 | -------------------------------------------------------------------------------- /frontend/src/assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepanshut041/spring-angular-chat/7b5094c169c82d3eddf2f3aa8c896c8696bc747a/frontend/src/assets/.gitkeep -------------------------------------------------------------------------------- /frontend/src/assets/friends.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepanshut041/spring-angular-chat/7b5094c169c82d3eddf2f3aa8c896c8696bc747a/frontend/src/assets/friends.jpg -------------------------------------------------------------------------------- /frontend/src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true, 3 | DOMAIN: 'http://localhost:8080' 4 | }; -------------------------------------------------------------------------------- /frontend/src/environments/environment.ts: -------------------------------------------------------------------------------- 1 | // This file can be replaced during build by using the `fileReplacements` array. 2 | // `ng build --prod` replaces `environment.ts` with `environment.prod.ts`. 3 | // The list of file replacements can be found in `angular.json`. 4 | 5 | export const environment = { 6 | production: false, 7 | DOMAIN: 'http://localhost:8080' 8 | }; 9 | 10 | /* 11 | * For easier debugging in development mode, you can import the following file 12 | * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`. 13 | * 14 | * This import should be commented out in production mode because it will have a negative impact 15 | * on performance if an error is thrown. 16 | */ 17 | // import 'zone.js/dist/zone-error'; // Included with Angular CLI. 18 | -------------------------------------------------------------------------------- /frontend/src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepanshut041/spring-angular-chat/7b5094c169c82d3eddf2f3aa8c896c8696bc747a/frontend/src/favicon.ico -------------------------------------------------------------------------------- /frontend/src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Frontend 7 | 8 | 9 | 10 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /frontend/src/main.ts: -------------------------------------------------------------------------------- 1 | import { enableProdMode } from '@angular/core'; 2 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; 3 | 4 | import { AppModule } from './app/app.module'; 5 | import { environment } from './environments/environment'; 6 | 7 | if (environment.production) { 8 | enableProdMode(); 9 | } 10 | 11 | platformBrowserDynamic().bootstrapModule(AppModule) 12 | .catch(err => console.error(err)); 13 | -------------------------------------------------------------------------------- /frontend/src/polyfills.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file includes polyfills needed by Angular and is loaded before the app. 3 | * You can add your own extra polyfills to this file. 4 | * 5 | * This file is divided into 2 sections: 6 | * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. 7 | * 2. Application imports. Files imported after ZoneJS that should be loaded before your main 8 | * file. 9 | * 10 | * The current setup is for so-called "evergreen" browsers; the last versions of browsers that 11 | * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), 12 | * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. 13 | * 14 | * Learn more in https://angular.io/guide/browser-support 15 | */ 16 | 17 | /*************************************************************************************************** 18 | * BROWSER POLYFILLS 19 | */ 20 | 21 | /** IE10 and IE11 requires the following for NgClass support on SVG elements */ 22 | // import 'classlist.js'; // Run `npm install --save classlist.js`. 23 | 24 | /** 25 | * Web Animations `@angular/platform-browser/animations` 26 | * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari. 27 | * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0). 28 | */ 29 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`. 30 | 31 | /** 32 | * By default, zone.js will patch all possible macroTask and DomEvents 33 | * user can disable parts of macroTask/DomEvents patch by setting following flags 34 | * because those flags need to be set before `zone.js` being loaded, and webpack 35 | * will put import in the top of bundle, so user need to create a separate file 36 | * in this directory (for example: zone-flags.ts), and put the following flags 37 | * into that file, and then add the following code before importing zone.js. 38 | * import './zone-flags'; 39 | * 40 | * The flags allowed in zone-flags.ts are listed here. 41 | * 42 | * The following flags will work for all browsers. 43 | * 44 | * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame 45 | * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick 46 | * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames 47 | * 48 | * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js 49 | * with the following flag, it will bypass `zone.js` patch for IE/Edge 50 | * 51 | * (window as any).__Zone_enable_cross_context_check = true; 52 | * 53 | */ 54 | 55 | /*************************************************************************************************** 56 | * Zone JS is required by default for Angular itself. 57 | */ 58 | import 'zone.js/dist/zone'; // Included with Angular CLI. 59 | 60 | 61 | /*************************************************************************************************** 62 | * APPLICATION IMPORTS 63 | */ 64 | -------------------------------------------------------------------------------- /frontend/src/styles.scss: -------------------------------------------------------------------------------- 1 | @import 'themes'; 2 | 3 | @import '~@nebular/theme/styles/globals'; 4 | 5 | @include nb-install() { 6 | @include nb-theme-global(); 7 | }; 8 | 9 | body { 10 | font-family: "Roboto", sans-serif; 11 | } -------------------------------------------------------------------------------- /frontend/src/test.ts: -------------------------------------------------------------------------------- 1 | // This file is required by karma.conf.js and loads recursively all the .spec and framework files 2 | 3 | import 'zone.js/dist/zone-testing'; 4 | import { getTestBed } from '@angular/core/testing'; 5 | import { 6 | BrowserDynamicTestingModule, 7 | platformBrowserDynamicTesting 8 | } from '@angular/platform-browser-dynamic/testing'; 9 | 10 | declare const require: { 11 | context(path: string, deep?: boolean, filter?: RegExp): { 12 | keys(): string[]; 13 | (id: string): T; 14 | }; 15 | }; 16 | 17 | // First, initialize the Angular testing environment. 18 | getTestBed().initTestEnvironment( 19 | BrowserDynamicTestingModule, 20 | platformBrowserDynamicTesting() 21 | ); 22 | // Then we find all the tests. 23 | const context = require.context('./', true, /\.spec\.ts$/); 24 | // And load the modules. 25 | context.keys().map(context); 26 | -------------------------------------------------------------------------------- /frontend/src/themes.scss: -------------------------------------------------------------------------------- 1 | @import '~@nebular/theme/styles/theming'; 2 | @import '~@nebular/theme/styles/themes/default'; 3 | 4 | $nb-themes: nb-register-theme(( 5 | 6 | // add your variables here like: 7 | 8 | // color-primary-100: #f2f6ff, 9 | // color-primary-200: #d9e4ff, 10 | // color-primary-300: #a6c1ff, 11 | // color-primary-400: #598bff, 12 | // color-primary-500: #3366ff, 13 | // color-primary-600: #274bdb, 14 | // color-primary-700: #1a34b8, 15 | // color-primary-800: #102694, 16 | // color-primary-900: #091c7a, 17 | 18 | ), default, default); 19 | -------------------------------------------------------------------------------- /frontend/tsconfig.app.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "./out-tsc/app", 5 | "types": [] 6 | }, 7 | "files": [ 8 | "src/main.ts", 9 | "src/polyfills.ts" 10 | ], 11 | "include": [ 12 | "src/**/*.d.ts" 13 | ] 14 | } 15 | -------------------------------------------------------------------------------- /frontend/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": false, 3 | "compilerOptions": { 4 | "baseUrl": "./", 5 | "outDir": "./dist/out-tsc", 6 | "sourceMap": true, 7 | "declaration": false, 8 | "downlevelIteration": true, 9 | "experimentalDecorators": true, 10 | "module": "esnext", 11 | "moduleResolution": "node", 12 | "importHelpers": true, 13 | "target": "es2015", 14 | "lib": [ 15 | "es2018", 16 | "dom" 17 | ] 18 | }, 19 | "angularCompilerOptions": { 20 | "fullTemplateTypeCheck": true, 21 | "strictInjectionParameters": true 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /frontend/tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "./out-tsc/spec", 5 | "types": [ 6 | "jasmine", 7 | "node" 8 | ] 9 | }, 10 | "files": [ 11 | "src/test.ts", 12 | "src/polyfills.ts" 13 | ], 14 | "include": [ 15 | "src/**/*.spec.ts", 16 | "src/**/*.d.ts" 17 | ] 18 | } 19 | -------------------------------------------------------------------------------- /frontend/tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "tslint:recommended", 3 | "rules": { 4 | "array-type": false, 5 | "arrow-parens": false, 6 | "deprecation": { 7 | "severity": "warning" 8 | }, 9 | "component-class-suffix": true, 10 | "contextual-lifecycle": true, 11 | "directive-class-suffix": true, 12 | "directive-selector": [ 13 | true, 14 | "attribute", 15 | "app", 16 | "camelCase" 17 | ], 18 | "component-selector": [ 19 | true, 20 | "element", 21 | "app", 22 | "kebab-case" 23 | ], 24 | "import-blacklist": [ 25 | true, 26 | "rxjs/Rx" 27 | ], 28 | "interface-name": false, 29 | "max-classes-per-file": false, 30 | "max-line-length": [ 31 | true, 32 | 140 33 | ], 34 | "member-access": false, 35 | "member-ordering": [ 36 | true, 37 | { 38 | "order": [ 39 | "static-field", 40 | "instance-field", 41 | "static-method", 42 | "instance-method" 43 | ] 44 | } 45 | ], 46 | "no-consecutive-blank-lines": false, 47 | "no-console": [ 48 | true, 49 | "debug", 50 | "info", 51 | "time", 52 | "timeEnd", 53 | "trace" 54 | ], 55 | "no-empty": false, 56 | "no-inferrable-types": [ 57 | true, 58 | "ignore-params" 59 | ], 60 | "no-non-null-assertion": true, 61 | "no-redundant-jsdoc": true, 62 | "no-switch-case-fall-through": true, 63 | "no-var-requires": false, 64 | "object-literal-key-quotes": [ 65 | true, 66 | "as-needed" 67 | ], 68 | "object-literal-sort-keys": false, 69 | "ordered-imports": false, 70 | "quotemark": [ 71 | true, 72 | "single" 73 | ], 74 | "trailing-comma": false, 75 | "no-conflicting-lifecycle": true, 76 | "no-host-metadata-property": true, 77 | "no-input-rename": true, 78 | "no-inputs-metadata-property": true, 79 | "no-output-native": true, 80 | "no-output-on-prefix": true, 81 | "no-output-rename": true, 82 | "no-outputs-metadata-property": true, 83 | "template-banana-in-box": true, 84 | "template-no-negated-async": true, 85 | "use-lifecycle-interface": true, 86 | "use-pipe-transform-interface": true 87 | }, 88 | "rulesDirectory": [ 89 | "codelyzer" 90 | ] 91 | } -------------------------------------------------------------------------------- /images/add-friend.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepanshut041/spring-angular-chat/7b5094c169c82d3eddf2f3aa8c896c8696bc747a/images/add-friend.png -------------------------------------------------------------------------------- /images/chat.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepanshut041/spring-angular-chat/7b5094c169c82d3eddf2f3aa8c896c8696bc747a/images/chat.png -------------------------------------------------------------------------------- /images/cover.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepanshut041/spring-angular-chat/7b5094c169c82d3eddf2f3aa8c896c8696bc747a/images/cover.gif -------------------------------------------------------------------------------- /images/edit-profile.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepanshut041/spring-angular-chat/7b5094c169c82d3eddf2f3aa8c896c8696bc747a/images/edit-profile.png -------------------------------------------------------------------------------- /images/home.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepanshut041/spring-angular-chat/7b5094c169c82d3eddf2f3aa8c896c8696bc747a/images/home.png -------------------------------------------------------------------------------- /images/signin.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepanshut041/spring-angular-chat/7b5094c169c82d3eddf2f3aa8c896c8696bc747a/images/signin.png -------------------------------------------------------------------------------- /images/signup.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepanshut041/spring-angular-chat/7b5094c169c82d3eddf2f3aa8c896c8696bc747a/images/signup.png -------------------------------------------------------------------------------- /images/theme-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepanshut041/spring-angular-chat/7b5094c169c82d3eddf2f3aa8c896c8696bc747a/images/theme-2.png -------------------------------------------------------------------------------- /images/theme-3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepanshut041/spring-angular-chat/7b5094c169c82d3eddf2f3aa8c896c8696bc747a/images/theme-3.png -------------------------------------------------------------------------------- /images/token.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepanshut041/spring-angular-chat/7b5094c169c82d3eddf2f3aa8c896c8696bc747a/images/token.png -------------------------------------------------------------------------------- /server/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/** 6 | !**/src/test/** 7 | /src/main/resources/application-local.yaml 8 | 9 | ### STS ### 10 | .apt_generated 11 | .classpath 12 | .factorypath 13 | .project 14 | .settings 15 | .springBeans 16 | .sts4-cache 17 | 18 | ### IntelliJ IDEA ### 19 | .idea 20 | *.iws 21 | *.iml 22 | *.ipr 23 | out/ 24 | 25 | ### NetBeans ### 26 | /nbproject/private/ 27 | /nbbuild/ 28 | /dist/ 29 | /nbdist/ 30 | /.nb-gradle/ 31 | 32 | ### VS Code ### 33 | .vscode/ 34 | -------------------------------------------------------------------------------- /server/build.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.jetbrains.kotlin.gradle.tasks.KotlinCompile 2 | 3 | plugins { 4 | id("org.springframework.boot") version "2.2.6.RELEASE" 5 | id("io.spring.dependency-management") version "1.0.9.RELEASE" 6 | kotlin("jvm") version "1.3.71" 7 | kotlin("plugin.spring") version "1.3.71" 8 | } 9 | 10 | group = "com.squrlabs" 11 | version = "0.0.1-SNAPSHOT" 12 | java.sourceCompatibility = JavaVersion.VERSION_1_8 13 | 14 | repositories { 15 | mavenCentral() 16 | } 17 | 18 | dependencies { 19 | implementation("org.springframework.boot:spring-boot-starter-web") 20 | implementation("com.fasterxml.jackson.module:jackson-module-kotlin") 21 | implementation("org.jetbrains.kotlin:kotlin-reflect") 22 | implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") 23 | 24 | // Data 25 | implementation("org.springframework.boot:spring-boot-starter-data-mongodb") 26 | 27 | // Documentation 28 | implementation("org.springdoc:springdoc-openapi-webmvc-core:1.3.2") 29 | implementation("org.springdoc:springdoc-openapi-ui:1.3.2") 30 | implementation("org.springdoc:springdoc-openapi-kotlin:1.3.2") 31 | implementation("org.springdoc:springdoc-openapi-security:1.3.2") 32 | 33 | 34 | // Security 35 | implementation("org.springframework.boot:spring-boot-starter-security") 36 | implementation("io.jsonwebtoken:jjwt:0.9.1") 37 | implementation("org.springframework.security:spring-security-oauth2-client") 38 | implementation("org.springframework.security:spring-security-oauth2-jose") 39 | implementation("org.springframework.security:spring-security-messaging") 40 | 41 | // Websocket 42 | implementation("org.springframework.boot:spring-boot-starter-websocket") 43 | 44 | testImplementation("org.springframework.boot:spring-boot-starter-test") { 45 | exclude(group = "org.junit.vintage", module = "junit-vintage-engine") 46 | } 47 | testImplementation("org.springframework.security:spring-security-test") 48 | 49 | } 50 | 51 | tasks.withType { 52 | useJUnitPlatform() 53 | } 54 | 55 | tasks.withType { 56 | kotlinOptions { 57 | freeCompilerArgs = listOf("-Xjsr305=strict") 58 | jvmTarget = "1.8" 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /server/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepanshut041/spring-angular-chat/7b5094c169c82d3eddf2f3aa8c896c8696bc747a/server/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /server/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /server/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | # Determine the Java command to use to start the JVM. 86 | if [ -n "$JAVA_HOME" ] ; then 87 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 88 | # IBM's JDK on AIX uses strange locations for the executables 89 | JAVACMD="$JAVA_HOME/jre/sh/java" 90 | else 91 | JAVACMD="$JAVA_HOME/bin/java" 92 | fi 93 | if [ ! -x "$JAVACMD" ] ; then 94 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 95 | 96 | Please set the JAVA_HOME variable in your environment to match the 97 | location of your Java installation." 98 | fi 99 | else 100 | JAVACMD="java" 101 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 102 | 103 | Please set the JAVA_HOME variable in your environment to match the 104 | location of your Java installation." 105 | fi 106 | 107 | # Increase the maximum file descriptors if we can. 108 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 109 | MAX_FD_LIMIT=`ulimit -H -n` 110 | if [ $? -eq 0 ] ; then 111 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 112 | MAX_FD="$MAX_FD_LIMIT" 113 | fi 114 | ulimit -n $MAX_FD 115 | if [ $? -ne 0 ] ; then 116 | warn "Could not set maximum file descriptor limit: $MAX_FD" 117 | fi 118 | else 119 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 120 | fi 121 | fi 122 | 123 | # For Darwin, add options to specify how the application appears in the dock 124 | if $darwin; then 125 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 126 | fi 127 | 128 | # For Cygwin or MSYS, switch paths to Windows format before running java 129 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 130 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 131 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 132 | JAVACMD=`cygpath --unix "$JAVACMD"` 133 | 134 | # We build the pattern for arguments to be converted via cygpath 135 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 136 | SEP="" 137 | for dir in $ROOTDIRSRAW ; do 138 | ROOTDIRS="$ROOTDIRS$SEP$dir" 139 | SEP="|" 140 | done 141 | OURCYGPATTERN="(^($ROOTDIRS))" 142 | # Add a user-defined pattern to the cygpath arguments 143 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 144 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 145 | fi 146 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 147 | i=0 148 | for arg in "$@" ; do 149 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 150 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 151 | 152 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 153 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 154 | else 155 | eval `echo args$i`="\"$arg\"" 156 | fi 157 | i=`expr $i + 1` 158 | done 159 | case $i in 160 | 0) set -- ;; 161 | 1) set -- "$args0" ;; 162 | 2) set -- "$args0" "$args1" ;; 163 | 3) set -- "$args0" "$args1" "$args2" ;; 164 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 165 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 166 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 167 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 168 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 169 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 170 | esac 171 | fi 172 | 173 | # Escape application args 174 | save () { 175 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 176 | echo " " 177 | } 178 | APP_ARGS=`save "$@"` 179 | 180 | # Collect all arguments for the java command, following the shell quoting and substitution rules 181 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 182 | 183 | exec "$JAVACMD" "$@" 184 | -------------------------------------------------------------------------------- /server/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto init 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto init 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :init 68 | @rem Get command-line arguments, handling Windows variants 69 | 70 | if not "%OS%" == "Windows_NT" goto win9xME_args 71 | 72 | :win9xME_args 73 | @rem Slurp the command line arguments. 74 | set CMD_LINE_ARGS= 75 | set _SKIP=2 76 | 77 | :win9xME_args_slurp 78 | if "x%~1" == "x" goto execute 79 | 80 | set CMD_LINE_ARGS=%* 81 | 82 | :execute 83 | @rem Setup the command line 84 | 85 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 86 | 87 | @rem Execute Gradle 88 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 89 | 90 | :end 91 | @rem End local scope for the variables with windows NT shell 92 | if "%ERRORLEVEL%"=="0" goto mainEnd 93 | 94 | :fail 95 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 96 | rem the _cmd.exe /c_ return code! 97 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 98 | exit /b 1 99 | 100 | :mainEnd 101 | if "%OS%"=="Windows_NT" endlocal 102 | 103 | :omega 104 | -------------------------------------------------------------------------------- /server/settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "sca" 2 | -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/ScaApplication.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca 2 | 3 | import com.squrlabs.sca.config.AppProperties 4 | import org.springframework.boot.autoconfigure.SpringBootApplication 5 | import org.springframework.boot.context.properties.EnableConfigurationProperties 6 | import org.springframework.boot.runApplication 7 | 8 | @SpringBootApplication 9 | @EnableConfigurationProperties(AppProperties::class) 10 | class ScaApplication 11 | 12 | fun main(args: Array) { 13 | runApplication(*args) 14 | } 15 | -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/config/ApiConfiguration.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.config 2 | 3 | import io.swagger.v3.oas.models.Components 4 | import io.swagger.v3.oas.models.OpenAPI 5 | import io.swagger.v3.oas.models.info.Info 6 | import io.swagger.v3.oas.models.info.License 7 | import io.swagger.v3.oas.models.security.SecurityScheme 8 | import org.springframework.beans.factory.annotation.Value 9 | import org.springframework.context.annotation.Bean 10 | import org.springframework.context.annotation.Configuration 11 | 12 | 13 | @Configuration 14 | class ApiConfiguration { 15 | @Bean 16 | fun customOpenAPI(@Value("\${springdoc.version}") appVersion: String?): OpenAPI? { 17 | return OpenAPI() 18 | .components(Components().addSecuritySchemes("basicScheme", 19 | SecurityScheme().type(SecurityScheme.Type.HTTP).scheme("basic"))) 20 | .info(Info().title("SpringShop API").version(appVersion) 21 | .license(License().name("Apache 2.0").url("http://springdoc.org"))) 22 | } 23 | } -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/config/AppProperties.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.config 2 | 3 | import org.springframework.boot.context.properties.ConfigurationProperties 4 | import java.util.* 5 | 6 | 7 | @ConfigurationProperties(prefix = "app") 8 | object AppProperties{ 9 | val auth = Auth() 10 | 11 | data class Auth(var tokenSecret: String? = null, var tokenExpirationMsec: Long = 0) 12 | 13 | val oauth2 = OAuth2() 14 | 15 | data class OAuth2(var authorizedRedirectUrls: List = ArrayList()){ 16 | fun authorizedRedirectUrls(authorizedRedirectUrls: List): OAuth2 { 17 | println(authorizedRedirectUrls.toString()) 18 | this.authorizedRedirectUrls = authorizedRedirectUrls 19 | return this 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/config/SecurityConfigure.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.config 2 | 3 | import com.squrlabs.sca.domain.service.auth.CustomOAuth2UserService 4 | import com.squrlabs.sca.domain.service.user.UserService 5 | import com.squrlabs.sca.util.auth.misc.* 6 | import org.springframework.beans.factory.annotation.Autowired 7 | import org.springframework.context.annotation.Bean 8 | import org.springframework.context.annotation.Configuration 9 | import org.springframework.security.authentication.AuthenticationManager 10 | import org.springframework.security.config.BeanIds 11 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder 12 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity 13 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 14 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity 15 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter 16 | import org.springframework.security.config.http.SessionCreationPolicy 17 | import org.springframework.security.core.userdetails.UserDetailsService 18 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder 19 | import org.springframework.security.crypto.password.PasswordEncoder 20 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter 21 | 22 | 23 | @Configuration 24 | @EnableWebSecurity 25 | @EnableGlobalMethodSecurity( 26 | securedEnabled = true, 27 | jsr250Enabled = true, 28 | prePostEnabled = true 29 | ) 30 | class SecurityConfigure( 31 | @Autowired val userService: UserService, 32 | @Autowired val tokenAuthenticationFilter: TokenAuthenticationFilter, 33 | @Autowired val customOAuth2UserService: CustomOAuth2UserService, 34 | @Autowired val oAuth2SuccessHandler: OAuth2SuccessHandler, 35 | @Autowired val oAuth2RequestRepository: OAuth2RequestRepository, 36 | @Autowired val oAuth2FailureHandler: OAuth2FailureHandler 37 | ): WebSecurityConfigurerAdapter() { 38 | 39 | @Bean 40 | fun passwordEncoder(): PasswordEncoder? { 41 | return BCryptPasswordEncoder() 42 | } 43 | 44 | @Bean(BeanIds.AUTHENTICATION_MANAGER) 45 | @Throws(Exception::class) 46 | override fun authenticationManagerBean(): AuthenticationManager? { 47 | return super.authenticationManagerBean() 48 | } 49 | 50 | @Throws(java.lang.Exception::class) 51 | override fun configure(authenticationManagerBuilder: AuthenticationManagerBuilder) { 52 | authenticationManagerBuilder 53 | .userDetailsService(userService) 54 | .passwordEncoder(passwordEncoder()) 55 | } 56 | 57 | 58 | override fun configure(http: HttpSecurity) { 59 | http.cors() 60 | .and() 61 | .sessionManagement() 62 | .sessionCreationPolicy(SessionCreationPolicy.STATELESS) 63 | .and().csrf().disable() 64 | .formLogin().disable() 65 | .httpBasic().disable() 66 | .exceptionHandling() 67 | .authenticationEntryPoint(RestAuthenticationEntryPoint()) 68 | .and().authorizeRequests() 69 | .antMatchers("/", "/error", "/favicon.ico", "/**/*.png", "/**/*.gif", "/**/*.svg", "/**/*.jpg", "/**/*.html", "/**/*.css", "/**/*.js").permitAll() 70 | .antMatchers("/api/account/**", "/api/docs", "/login/oauth2/code/**", "/ws/**").permitAll() 71 | .anyRequest() 72 | .authenticated() 73 | .and() 74 | .oauth2Login { oauth2Login -> 75 | oauth2Login.authorizationEndpoint { 76 | it.authorizationRequestRepository(oAuth2RequestRepository) 77 | } 78 | oauth2Login.userInfoEndpoint { 79 | it.userService(customOAuth2UserService) 80 | } 81 | oauth2Login.successHandler(oAuth2SuccessHandler).failureHandler(oAuth2FailureHandler) 82 | } 83 | 84 | http.addFilterBefore(tokenAuthenticationFilter, UsernamePasswordAuthenticationFilter::class.java) 85 | } 86 | 87 | } -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/config/WebMvcConfig.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.config 2 | 3 | import org.springframework.context.annotation.Configuration 4 | import org.springframework.web.servlet.config.annotation.CorsRegistry 5 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer 6 | 7 | 8 | @Configuration 9 | class WebMvcConfig : WebMvcConfigurer { 10 | override fun addCorsMappings(registry: CorsRegistry) { 11 | registry.addMapping("/**") 12 | .allowedOrigins("*") 13 | .allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS") 14 | .allowedHeaders("*") 15 | .allowCredentials(true) 16 | .maxAge(MAX_AGE_SECS) 17 | } 18 | 19 | companion object{ 20 | const val MAX_AGE_SECS: Long = 3600 21 | } 22 | } -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/config/WebSocketConfig.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.config 2 | 3 | import com.squrlabs.sca.domain.service.user.UserService 4 | import com.squrlabs.sca.util.BadRequestException 5 | import com.squrlabs.sca.util.auth.misc.CustomChannelInterceptor 6 | import com.squrlabs.sca.util.auth.misc.TokenProvider 7 | import com.squrlabs.sca.util.auth.util.UserPrincipal 8 | import org.springframework.beans.factory.annotation.Autowired 9 | import org.springframework.context.annotation.Configuration 10 | import org.springframework.messaging.Message 11 | import org.springframework.messaging.MessageChannel 12 | import org.springframework.messaging.simp.SimpMessagingTemplate 13 | import org.springframework.messaging.simp.config.ChannelRegistration 14 | import org.springframework.messaging.simp.config.MessageBrokerRegistry 15 | import org.springframework.messaging.simp.stomp.StompCommand 16 | import org.springframework.messaging.simp.stomp.StompHeaderAccessor 17 | import org.springframework.messaging.support.ChannelInterceptor 18 | import org.springframework.messaging.support.MessageHeaderAccessor 19 | import org.springframework.security.access.AccessDeniedException 20 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken 21 | import org.springframework.security.core.userdetails.UserDetails 22 | import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker 23 | import org.springframework.web.socket.config.annotation.StompEndpointRegistry 24 | import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer 25 | 26 | @Configuration 27 | @EnableWebSocketMessageBroker 28 | class WebSocketConfig( 29 | @Autowired val tokenProvider: TokenProvider, 30 | @Autowired val userService: UserService 31 | ): WebSocketMessageBrokerConfigurer { 32 | 33 | override fun configureMessageBroker(config: MessageBrokerRegistry) { 34 | config.enableSimpleBroker("/notifications") 35 | config.setApplicationDestinationPrefixes("/app") 36 | } 37 | 38 | override fun registerStompEndpoints(registry: StompEndpointRegistry) { 39 | registry.addEndpoint("/ws").setAllowedOrigins("*").withSockJS() 40 | } 41 | 42 | override fun configureClientInboundChannel(registration: ChannelRegistration) { 43 | registration.interceptors(CustomChannelInterceptor(tokenProvider, userService)) 44 | } 45 | 46 | 47 | } -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/config/WebSocketSecurityConfig.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.config 2 | 3 | import org.springframework.context.annotation.Configuration 4 | import org.springframework.messaging.simp.SimpMessageType.*; 5 | 6 | import org.springframework.security.config.annotation.web.messaging.MessageSecurityMetadataSourceRegistry 7 | import org.springframework.security.config.annotation.web.socket.AbstractSecurityWebSocketMessageBrokerConfigurer 8 | 9 | @Configuration 10 | class WebSocketSecurityConfig:AbstractSecurityWebSocketMessageBrokerConfigurer() { 11 | 12 | override fun configureInbound(messages: MessageSecurityMetadataSourceRegistry?) { 13 | messages!!.simpTypeMatchers(CONNECT, UNSUBSCRIBE, DISCONNECT, HEARTBEAT).permitAll() 14 | .simpSubscribeDestMatchers("/notifications/**").authenticated() 15 | .anyMessage().authenticated() 16 | } 17 | 18 | override fun sameOriginDisabled(): Boolean { 19 | return true 20 | } 21 | } -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/data/entity/chat/ChatEntity.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.data.entity.chat 2 | 3 | import org.springframework.data.annotation.Id 4 | import org.springframework.data.mongodb.core.index.CompoundIndex 5 | import org.springframework.data.mongodb.core.index.CompoundIndexes 6 | import org.springframework.data.mongodb.core.index.Indexed 7 | import org.springframework.data.mongodb.core.mapping.Document 8 | import java.util.* 9 | 10 | @Document("chats") 11 | @CompoundIndexes(*[ 12 | CompoundIndex(name = "user1_user2", def = "{'user1' : 1, 'user2': 1}") 13 | ]) 14 | data class ChatEntity( 15 | @Id val id:String?, 16 | @Indexed(unique = false) val user1:String, 17 | @Indexed(unique = false) val user2: String, 18 | val blockedBy: String, 19 | val createdAt: Date, 20 | val updatedAt: Date 21 | ) 22 | -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/data/entity/chat/FileEntity.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.data.entity.chat 2 | 3 | import com.squrlabs.sca.domain.model.chat.FileModel 4 | 5 | data class FileEntity(val url: String, val type: String) 6 | 7 | object FileMapper { 8 | fun to(entity: FileEntity) = FileModel(url = entity.url, type = entity.type) 9 | fun from(model: FileModel) = FileEntity(url = model.url, type = model.type) 10 | } -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/data/entity/chat/MessageEntity.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.data.entity.chat 2 | 3 | import com.squrlabs.sca.domain.model.chat.ContentType 4 | import com.squrlabs.sca.domain.model.chat.MessageModel 5 | import org.springframework.data.annotation.Id 6 | import org.springframework.data.mongodb.core.index.Indexed 7 | import org.springframework.data.mongodb.core.mapping.Document 8 | import java.util.* 9 | 10 | @Document("messages") 11 | data class MessageEntity( 12 | @Id val id:String?, 13 | val senderId: String, 14 | @Indexed(unique = false) val conversationId: String, 15 | val content: String, 16 | val files: List, 17 | val contentType: ContentType, 18 | val createdAt: Date, 19 | val updatedAt: Date, 20 | val read: Boolean 21 | ) 22 | 23 | object MessageMapper { 24 | fun to(entity: MessageEntity) = MessageModel( 25 | id = entity.id!!, 26 | senderId = entity.senderId, 27 | chatId = entity.conversationId, 28 | content = entity.content, 29 | files = entity.files.map { FileMapper.to(it) }, 30 | contentType = entity.contentType, 31 | createdAt = entity.createdAt, 32 | updatedAt = entity.updatedAt, 33 | read = entity.read 34 | ) 35 | } -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/data/entity/user/UserEntity.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.data.entity.user 2 | 3 | import com.squrlabs.sca.domain.model.user.AuthProvider 4 | import com.squrlabs.sca.domain.model.user.UserModel 5 | import org.springframework.data.annotation.Id 6 | import org.springframework.data.mongodb.core.index.Indexed 7 | import org.springframework.data.mongodb.core.mapping.Document 8 | 9 | @Document("users") 10 | data class UserEntity(@Id val id: String = "", 11 | val name: String, 12 | @Indexed(unique = true) val email: String, 13 | val password: String, 14 | val imgUrl: String, 15 | val emailVerified: Boolean = false, 16 | val accountLocked: Boolean = false, 17 | val accountExpired: Boolean = false, 18 | val credentialsExpired: Boolean = false, 19 | val provider: AuthProvider, 20 | val providerId: String, 21 | val roles: List = emptyList()) 22 | 23 | object UserEntityMapper { 24 | fun from(user: UserModel): UserEntity = UserEntity( 25 | id = user.id, 26 | email = user.email, 27 | name = user.name, 28 | password = user.password, 29 | imgUrl = user.imgUrl, 30 | emailVerified = user.emailVerified, 31 | accountLocked = user.accountLocked, 32 | accountExpired = user.accountExpired, 33 | credentialsExpired = user.credentialsExpired, 34 | provider = user.provider, 35 | providerId = user.providerId, 36 | roles = user.roles 37 | ) 38 | 39 | fun to(user: UserEntity): UserModel = UserModel( 40 | id = user.id, 41 | email = user.email, 42 | name = user.name, 43 | password = user.password, 44 | imgUrl = user.imgUrl, 45 | emailVerified = user.emailVerified, 46 | accountLocked = user.accountLocked, 47 | accountExpired = user.accountExpired, 48 | credentialsExpired = user.credentialsExpired, 49 | provider = user.provider, 50 | providerId = user.providerId, 51 | roles = user.roles 52 | ) 53 | } -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/data/repository/chat/ChatRepository.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.data.repository.chat 2 | 3 | import com.squrlabs.sca.data.entity.chat.ChatEntity 4 | import org.springframework.data.mongodb.repository.MongoRepository 5 | import org.springframework.stereotype.Repository 6 | import java.util.* 7 | 8 | @Repository 9 | interface ChatRepository: MongoRepository { 10 | fun findAllByUser1OrUser2AndUpdatedAtAfter(user1: String, user2: String, date: Date): List 11 | fun findByUser1AndUser2OrUser1AndUser2(user1: String, friend2: String, friend1: String, user2: String): Optional 12 | } -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/data/repository/chat/MessageRepository.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.data.repository.chat 2 | 3 | import com.squrlabs.sca.data.entity.chat.MessageEntity 4 | import org.springframework.data.mongodb.repository.MongoRepository 5 | import java.util.* 6 | 7 | interface MessageRepository: MongoRepository { 8 | fun findAllByConversationIdAndUpdatedAtAfter(id: String, date: Date): List 9 | fun findAllByConversationId(id: String): List 10 | } -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/data/repository/user/UserRepository.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.data.repository.user 2 | 3 | import com.squrlabs.sca.data.entity.user.UserEntity 4 | import org.springframework.data.mongodb.repository.MongoRepository 5 | import org.springframework.stereotype.Repository 6 | import java.util.* 7 | 8 | @Repository 9 | interface UserRepository: MongoRepository { 10 | fun findByEmail(email: String): Optional 11 | fun existsByEmail(email: String): Boolean 12 | } -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/domain/model/chat/ChatModel.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.domain.model.chat 2 | 3 | import java.util.* 4 | 5 | data class ChatModel( 6 | val id:String?, 7 | val user1:String, 8 | val user2: String, 9 | val blockedBy: String, 10 | val createdAt: Date, 11 | val updatedAt: Date 12 | ) -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/domain/model/chat/ContentType.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.domain.model.chat 2 | 3 | enum class ContentType{ 4 | TEXT, 5 | FILE, 6 | MAP, 7 | INFO 8 | } -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/domain/model/chat/FriendProfileModel.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.domain.model.chat 2 | 3 | data class FriendProfileModel( 4 | val id: String, 5 | val email: String, 6 | val name: String, 7 | val imgUrl: String, 8 | val blockedBy: String 9 | ) -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/domain/model/chat/MessageModel.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.domain.model.chat 2 | 3 | 4 | import java.util.* 5 | 6 | data class MessageModel( 7 | val id: String?, 8 | val senderId: String, 9 | val chatId: String, 10 | val content: String, 11 | val files: List, 12 | val contentType: ContentType, 13 | val createdAt: Date, 14 | val updatedAt: Date, 15 | val read: Boolean 16 | ) 17 | 18 | data class FileModel(val url: String, val type: String) -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/domain/model/socket/SocketModel.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.domain.model.socket 2 | 3 | data class SocketModel( 4 | val type: SocketType, 5 | val data: T 6 | ) -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/domain/model/socket/SocketType.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.domain.model.socket 2 | 3 | enum class SocketType { 4 | USER_CONVERSATION_UPDATED, 5 | USER_CONVERSATION_ADDED, 6 | USER_MESSAGE_UPDATED, 7 | USER_MESSAGE_ADDED 8 | } 9 | -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/domain/model/user/AuthProvider.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.domain.model.user 2 | 3 | enum class AuthProvider { 4 | local, facebook, google 5 | } -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/domain/model/user/UserModel.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.domain.model.user 2 | 3 | data class UserModel(val id: String = "", 4 | val name: String, 5 | val email: String, 6 | val password: String, 7 | val imgUrl: String, 8 | val emailVerified: Boolean = false, 9 | val accountLocked: Boolean = false, 10 | val accountExpired: Boolean = false, 11 | val credentialsExpired: Boolean = false, 12 | val provider: AuthProvider, 13 | val providerId: String, 14 | val roles: List = emptyList()) -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/domain/service/auth/CustomOAuth2UserService.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.domain.service.auth 2 | 3 | import com.squrlabs.sca.data.entity.user.UserEntity 4 | import com.squrlabs.sca.data.entity.user.UserEntityMapper 5 | import com.squrlabs.sca.data.repository.user.UserRepository 6 | import com.squrlabs.sca.domain.model.user.AuthProvider 7 | import com.squrlabs.sca.domain.model.user.UserModel 8 | import com.squrlabs.sca.domain.service.user.rolesToAuthority 9 | import com.squrlabs.sca.util.OAuth2AuthenticationProcessingException 10 | import com.squrlabs.sca.util.auth.util.OAuth2UserInfo 11 | import com.squrlabs.sca.util.auth.util.OAuth2UserInfoFactory.getOAuth2UserInfo 12 | import com.squrlabs.sca.util.auth.util.UserPrincipal 13 | import com.squrlabs.sca.util.toNullable 14 | import org.springframework.beans.factory.annotation.Autowired 15 | import org.springframework.security.authentication.InternalAuthenticationServiceException 16 | import org.springframework.security.core.AuthenticationException 17 | import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService 18 | import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest 19 | import org.springframework.security.oauth2.core.OAuth2AuthenticationException 20 | import org.springframework.security.oauth2.core.user.OAuth2User 21 | import org.springframework.stereotype.Service 22 | 23 | @Service 24 | class CustomOAuth2UserService(@Autowired private val userRepository: UserRepository) : DefaultOAuth2UserService() { 25 | 26 | @Throws(OAuth2AuthenticationException::class) 27 | override fun loadUser(oAuth2UserRequest: OAuth2UserRequest): OAuth2User { 28 | val oAuth2User = super.loadUser(oAuth2UserRequest) 29 | return try { 30 | processOAuth2User(oAuth2UserRequest, oAuth2User) 31 | } catch (ex: AuthenticationException) { 32 | throw ex 33 | } catch (ex: Exception) { // Throwing an instance of AuthenticationException will trigger the OAuth2AuthenticationFailureHandler 34 | throw InternalAuthenticationServiceException(ex.message, ex.cause) 35 | } 36 | } 37 | 38 | private fun processOAuth2User(oAuth2UserRequest: OAuth2UserRequest, oAuth2User: OAuth2User): OAuth2User { 39 | val oAuth2UserInfo = getOAuth2UserInfo(oAuth2UserRequest.clientRegistration.registrationId, oAuth2User.attributes) 40 | if (oAuth2UserInfo.getEmail().isEmpty()) { 41 | throw OAuth2AuthenticationProcessingException("Email not found from OAuth2 provider") 42 | } 43 | var user: UserModel? = userRepository.findByEmail(oAuth2UserInfo.getEmail()).map(UserEntityMapper::to).toNullable() 44 | 45 | user?.let { 46 | if (it.provider != AuthProvider.valueOf(oAuth2UserRequest.clientRegistration.registrationId)) { 47 | throw OAuth2AuthenticationProcessingException("Looks like you're signed up with " + 48 | it.provider.toString() + " account. Please use your " + it.provider.toString() + 49 | " account to login.") 50 | } 51 | 52 | updateExistingUser(it, oAuth2UserInfo) 53 | } ?: run { 54 | user = registerNewUser(oAuth2UserRequest, oAuth2UserInfo) 55 | } 56 | return UserPrincipal.create(user!!, oAuth2User.attributes, rolesToAuthority(user!!.roles)) 57 | } 58 | 59 | private fun registerNewUser(oAuth2UserRequest: OAuth2UserRequest, oAuth2UserInfo: OAuth2UserInfo): UserModel { 60 | val user = UserEntity( 61 | id = "", 62 | provider = AuthProvider.valueOf(oAuth2UserRequest.clientRegistration.registrationId), 63 | providerId = oAuth2UserInfo.getId(), 64 | name = oAuth2UserInfo.getName(), 65 | email = oAuth2UserInfo.getEmail(), 66 | imgUrl = oAuth2UserInfo.getImageUrl() ?: "", 67 | emailVerified = true, 68 | password = "", 69 | roles = listOf("ROLE_USER") 70 | ) 71 | return UserEntityMapper.to(userRepository.save(user)) 72 | } 73 | 74 | private fun updateExistingUser(existingUser: UserModel, oAuth2UserInfo: OAuth2UserInfo): UserModel { 75 | val user = existingUser.copy( 76 | name = oAuth2UserInfo.getName(), imgUrl = oAuth2UserInfo.getImageUrl() ?: "" 77 | ) 78 | return UserEntityMapper.to(userRepository.save(UserEntityMapper.from(user))) 79 | } 80 | } -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/domain/service/chat/ChatService.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.domain.service.chat 2 | 3 | import com.squrlabs.sca.data.entity.chat.ChatEntity 4 | import com.squrlabs.sca.data.repository.chat.ChatRepository 5 | import com.squrlabs.sca.data.repository.user.UserRepository 6 | import com.squrlabs.sca.domain.model.chat.ChatModel 7 | import com.squrlabs.sca.domain.model.chat.FriendProfileModel 8 | import com.squrlabs.sca.domain.model.socket.SocketModel 9 | import com.squrlabs.sca.domain.model.socket.SocketType 10 | import com.squrlabs.sca.util.BadRequestException 11 | import com.squrlabs.sca.util.ResourceNotFoundException 12 | import com.squrlabs.sca.util.auth.util.UserPrincipal 13 | import com.squrlabs.sca.util.toNullable 14 | import org.springframework.beans.factory.annotation.Autowired 15 | import org.springframework.messaging.simp.SimpMessagingTemplate 16 | import org.springframework.stereotype.Service 17 | import java.util.* 18 | import kotlin.collections.HashMap 19 | 20 | @Service("chatService") 21 | class ChatServiceImpl( 22 | @Autowired val simpMessagingTemplate: SimpMessagingTemplate, 23 | @Autowired val chatRepository: ChatRepository, 24 | @Autowired val userRepository: UserRepository 25 | ) : ChatService { 26 | 27 | override fun newConversation(user: UserPrincipal, email: String): FriendProfileModel { 28 | userRepository.findByEmail(email).toNullable()?.let { friend -> 29 | chatRepository.findByUser1AndUser2OrUser1AndUser2(user.id, friend.id, friend.id, user.id).toNullable()?.let { 30 | throw BadRequestException("User already exist by email:$email") 31 | } ?: run { 32 | val newCov = this.chatRepository.save(ChatEntity(null, user.id, friend.id, "", Date(), Date())) 33 | simpMessagingTemplate.convertAndSend("/notifications/${friend.id}", SocketModel(SocketType.USER_CONVERSATION_ADDED, 34 | FriendProfileModel(newCov.id!!, user.mEmail, user.name, user.mImgUrl, newCov.blockedBy))) 35 | return FriendProfileModel(newCov.id, friend.email, friend.name, friend.imgUrl, newCov.blockedBy) 36 | } 37 | } ?: run { 38 | throw ResourceNotFoundException("User", "email", email) 39 | } 40 | } 41 | 42 | override fun getConversations(id: String, date: Date): List { 43 | val friends = HashMap() 44 | chatRepository.findAllByUser1OrUser2AndUpdatedAtAfter(id, id, date).map { 45 | if (it.user1 == id) 46 | friends[it.user2] = it 47 | if (it.user2 == id) 48 | friends[it.user1] = it 49 | } 50 | val users = userRepository.findAllById(friends.keys) 51 | return users.map { 52 | val profile = friends[it.id]!! 53 | FriendProfileModel(profile.id!!, it.email, it.name, it.imgUrl, profile.blockedBy) 54 | } 55 | } 56 | 57 | override fun blockConversation(id: String, user: UserPrincipal): FriendProfileModel { 58 | chatRepository.findById(id).toNullable()?.let { 59 | if ((it.user1 == user.id|| it.user2 == user.id) && it.blockedBy == ""){ 60 | val newCov = chatRepository.save(it.copy(blockedBy = user.id, updatedAt = Date())) 61 | val friend = userRepository.findById(if (it.user1 == user.id) it.user2 else it.user1).toNullable()!! 62 | simpMessagingTemplate.convertAndSend("/notifications/${friend.id}", SocketModel(SocketType.USER_CONVERSATION_UPDATED, 63 | FriendProfileModel(newCov.id!!, user.mEmail, user.name, user.mImgUrl, newCov.blockedBy))) 64 | return FriendProfileModel(newCov.id, friend.email, friend.name, friend.imgUrl, newCov.blockedBy) 65 | } else{ 66 | throw BadRequestException("Sorry you can block this conversation") 67 | } 68 | }?: run{ 69 | throw ResourceNotFoundException("Conversation", "id", id) 70 | } 71 | } 72 | 73 | override fun unblockConversation(id: String, user: UserPrincipal): FriendProfileModel { 74 | chatRepository.findById(id).toNullable()?.let { 75 | if ((it.user1 == user.id || it.user2 == user.id) && it.blockedBy == user.id){ 76 | val newCov = chatRepository.save(it.copy(blockedBy = "", updatedAt = Date())) 77 | val friendId = if (it.user1 == user.id) it.user2 else it.user1 78 | val friend = userRepository.findById(if (it.user1 == user.id) it.user2 else it.user1).toNullable()!! 79 | simpMessagingTemplate.convertAndSend("/notifications/${friendId}", SocketModel(SocketType.USER_CONVERSATION_UPDATED, 80 | FriendProfileModel(newCov.id!!, user.mEmail, user.name, user.mImgUrl, newCov.blockedBy))) 81 | return FriendProfileModel(newCov.id, friend.email, friend.name, friend.imgUrl, newCov.blockedBy) 82 | } else{ 83 | throw BadRequestException("Sorry you can unblock this conversation") 84 | } 85 | }?: run{ 86 | throw ResourceNotFoundException("Conversation", "id", id) 87 | } 88 | } 89 | 90 | override fun getBlockedConversation(): List { 91 | return emptyList() 92 | } 93 | } 94 | 95 | interface ChatService { 96 | fun newConversation(user: UserPrincipal, email: String): FriendProfileModel 97 | fun getConversations(id: String, date: Date): List 98 | fun blockConversation(id: String, user: UserPrincipal): FriendProfileModel 99 | fun unblockConversation(id: String, user: UserPrincipal): FriendProfileModel 100 | fun getBlockedConversation(): List 101 | } 102 | -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/domain/service/chat/MessageService.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.domain.service.chat 2 | 3 | import com.squrlabs.sca.data.entity.chat.FileMapper 4 | import com.squrlabs.sca.data.entity.chat.MessageEntity 5 | import com.squrlabs.sca.data.entity.chat.MessageMapper 6 | import com.squrlabs.sca.data.repository.chat.ChatRepository 7 | import com.squrlabs.sca.data.repository.chat.MessageRepository 8 | import com.squrlabs.sca.domain.model.chat.ContentType 9 | import com.squrlabs.sca.domain.model.chat.FileModel 10 | import com.squrlabs.sca.domain.model.chat.MessageModel 11 | import com.squrlabs.sca.domain.model.socket.SocketModel 12 | import com.squrlabs.sca.domain.model.socket.SocketType 13 | import com.squrlabs.sca.util.BadRequestException 14 | import com.squrlabs.sca.util.ResourceNotFoundException 15 | import com.squrlabs.sca.util.toNullable 16 | import org.springframework.beans.factory.annotation.Autowired 17 | import org.springframework.messaging.simp.SimpMessagingTemplate 18 | import org.springframework.stereotype.Service 19 | import java.util.* 20 | import kotlin.collections.ArrayList 21 | 22 | @Service("messageService") 23 | class MessageServiceImpl( 24 | @Autowired val simpMessagingTemplate: SimpMessagingTemplate, 25 | @Autowired val chatRepository: ChatRepository, 26 | @Autowired val messageRepository: MessageRepository 27 | ) : MessageService { 28 | 29 | override fun getAllMessages(ids: List, userId: String, updatedAt:Date): List { 30 | val msgs = ArrayList() 31 | chatRepository.findAllById(ids).map { chat -> 32 | if (chat.user1 != userId && chat.user2 != userId) return@map null 33 | messageRepository.findAllByConversationIdAndUpdatedAtAfter(chat.id!!, updatedAt).map { 34 | msgs.add(MessageMapper.to(it)) 35 | } 36 | } 37 | return msgs 38 | } 39 | 40 | override fun getMessagesByChat(id: String, userId: String, updatedAt: Date): List { 41 | chatRepository.findById(id).toNullable()?.let { chat -> 42 | if (chat.user1 == userId || chat.user2 == userId) { 43 | return messageRepository.findAllByConversationIdAndUpdatedAtAfter(id, updatedAt).map { MessageMapper.to(it) } 44 | } 45 | } 46 | return emptyList() 47 | } 48 | 49 | override fun updateMessages(ids: List, chatId: String, userId: String): List { 50 | val updatedMessages = ArrayList() 51 | var friendId: String? = null 52 | chatRepository.findById(chatId).toNullable()?.let { chat -> 53 | if (chat.user1 != userId && chat.user2 != userId) return emptyList() 54 | friendId = if (chat.user1 == userId) chat.user2 else chat.user1 55 | val messages = this.messageRepository.findAllById(ids).filter { it.senderId != userId } 56 | this.messageRepository.saveAll(messages.map { it.copy(read = true, updatedAt = Date()) }) 57 | .map { updatedMessages.add(MessageMapper.to(it)) } 58 | } 59 | 60 | friendId?.let { simpMessagingTemplate.convertAndSend("/notifications/${it}", 61 | SocketModel(SocketType.USER_MESSAGE_UPDATED, updatedMessages)) 62 | } 63 | return updatedMessages 64 | } 65 | 66 | override fun createMessage(chatId: String, userId: String, content: String, files: List, contentType: ContentType): MessageModel { 67 | chatRepository.findById(chatId).toNullable()?.let { 68 | if ((it.user1 == userId || it.user2 == userId) && it.blockedBy == "") { 69 | val msg = messageRepository.save(MessageEntity(null, userId, chatId, content, 70 | files.map{ file -> FileMapper.from(file)}, contentType, Date(), Date(), false)) 71 | simpMessagingTemplate.convertAndSend("/notifications/${if (it.user1 == userId) it.user2 else it.user1}", 72 | SocketModel(SocketType.USER_MESSAGE_ADDED, MessageMapper.to(msg))) 73 | return MessageMapper.to(msg) 74 | } else { 75 | throw BadRequestException("Sorry you're blocked by user") 76 | } 77 | } ?: run { 78 | throw ResourceNotFoundException("Conversation", "id", chatId) 79 | } 80 | } 81 | } 82 | 83 | interface MessageService { 84 | fun getMessagesByChat(id: String, userId: String, updatedAt: Date): List 85 | fun getAllMessages(ids: List, userId: String, updatedAt: Date): List 86 | fun updateMessages(ids: List, chatId: String, userId: String): List 87 | fun createMessage(chatId: String, userId: String, content: String, files: List, contentType: ContentType): MessageModel 88 | } -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/domain/service/file/FileStorageService.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.domain.service.file 2 | 3 | import com.squrlabs.sca.domain.model.chat.FileModel 4 | import org.springframework.stereotype.Service 5 | import org.springframework.web.multipart.MultipartFile 6 | import java.nio.file.Files 7 | import java.nio.file.Path 8 | import java.nio.file.StandardCopyOption 9 | import java.util.* 10 | import kotlin.collections.ArrayList 11 | 12 | @Service 13 | class FileStorageServiceImpl() : FileStorageService { 14 | override fun store(files: List, chatId: String): List { 15 | val uploadedFiles = ArrayList() 16 | files.stream().map { 17 | println("Hello") 18 | val path = Path.of(ROOT_URL, chatId) 19 | Files.copy(it.inputStream, 20 | path.resolve(UUID.randomUUID().toString() + it.originalFilename!!.split(".").last()), 21 | StandardCopyOption.REPLACE_EXISTING) 22 | uploadedFiles.add(FileModel(path.toString(), it.contentType ?: "")) 23 | } 24 | return uploadedFiles 25 | } 26 | 27 | companion object { 28 | const val ROOT_URL = "uploads" 29 | } 30 | 31 | } 32 | 33 | interface FileStorageService { 34 | fun store(files: List, chatId: String): List 35 | } -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/domain/service/user/UserService.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.domain.service.user 2 | 3 | import com.squrlabs.sca.data.entity.user.UserEntityMapper 4 | import com.squrlabs.sca.data.repository.user.UserRepository 5 | import com.squrlabs.sca.domain.model.user.UserModel 6 | import com.squrlabs.sca.util.ResourceNotFoundException 7 | import com.squrlabs.sca.util.auth.util.UserPrincipal 8 | import com.squrlabs.sca.util.toNullable 9 | import com.squrlabs.sca.web.dto.user.UserProfile 10 | import org.springframework.beans.factory.annotation.Autowired 11 | import org.springframework.security.core.GrantedAuthority 12 | import org.springframework.security.core.authority.SimpleGrantedAuthority 13 | import org.springframework.security.core.userdetails.UserDetails 14 | import org.springframework.security.core.userdetails.UserDetailsService 15 | import org.springframework.security.core.userdetails.UsernameNotFoundException 16 | import org.springframework.stereotype.Service 17 | 18 | @Service("userService") 19 | class UserServiceImpl( 20 | @Autowired val userRepository: UserRepository 21 | ): UserService { 22 | 23 | @Throws(UsernameNotFoundException::class) 24 | override fun getUserById(id: String): UserDetails? { 25 | userRepository.findById(id).map(UserEntityMapper::to).toNullable()?.let { 26 | return UserPrincipal.create(it, emptyMap(), rolesToAuthority(it.roles)) 27 | } 28 | throw ResourceNotFoundException("User", "id", id) 29 | } 30 | 31 | 32 | 33 | @Throws(UsernameNotFoundException::class) 34 | override fun getUserByEmail(email: String): UserDetails? { 35 | userRepository.findByEmail(email).map(UserEntityMapper::to).toNullable()?.let { 36 | return UserPrincipal.create(it, emptyMap(), rolesToAuthority(it.roles)) 37 | } 38 | throw ResourceNotFoundException("User", "email", email) 39 | } 40 | 41 | override fun getUserProfile(id: String): UserModel { 42 | userRepository.findById(id).map(UserEntityMapper::to).toNullable()?.let { 43 | return it 44 | }?: run{ 45 | throw ResourceNotFoundException("User", "id", id) 46 | } 47 | } 48 | 49 | override fun saveUser(model: UserModel): UserModel { 50 | return UserEntityMapper.to(userRepository.save(UserEntityMapper.from(model))) 51 | } 52 | 53 | override fun existsByEmail(email: String): Boolean { 54 | return userRepository.existsByEmail(email) 55 | } 56 | 57 | override fun loadUserByUsername(username: String): UserDetails? { 58 | return getUserByEmail(username) 59 | } 60 | 61 | } 62 | 63 | interface UserService: UserDetailsService { 64 | fun getUserById(id: String): UserDetails? 65 | fun getUserByEmail(email: String): UserDetails? 66 | fun saveUser(model: UserModel): UserModel 67 | fun existsByEmail(email: String): Boolean 68 | fun getUserProfile(id: String): UserModel 69 | } 70 | 71 | fun rolesToAuthority(roles: List): Collection{ 72 | val authorises = ArrayList() 73 | 74 | roles.map { 75 | authorises.add(SimpleGrantedAuthority(it)) 76 | } 77 | return authorises 78 | } 79 | -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/util/ApiResponse.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.util 2 | 3 | data class ApiResponse(val success: Boolean, val message: String) -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/util/CookieUtils.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.util 2 | 3 | import org.springframework.util.SerializationUtils 4 | import java.util.* 5 | import javax.servlet.http.Cookie 6 | import javax.servlet.http.HttpServletRequest 7 | import javax.servlet.http.HttpServletResponse 8 | 9 | 10 | object CookieUtils { 11 | fun getCookie(request: HttpServletRequest, name: String?): Cookie? { 12 | val cookies = request.cookies 13 | cookies?.map { 14 | if (it.name == name) 15 | return it 16 | } 17 | return null 18 | } 19 | 20 | fun addCookie(response: HttpServletResponse, name: String?, value: String?, maxAge: Int) { 21 | val cookie = Cookie(name, value) 22 | cookie.path = "/" 23 | cookie.isHttpOnly = true 24 | cookie.maxAge = maxAge 25 | response.addCookie(cookie) 26 | } 27 | 28 | fun deleteCookie(request: HttpServletRequest, response: HttpServletResponse, name: String?) { 29 | val cookies = request.cookies 30 | cookies?.map { 31 | if (it.name == name){ 32 | it.value = "" 33 | it.path = "/" 34 | it.maxAge = 0 35 | response.addCookie(it) 36 | } 37 | } 38 | } 39 | 40 | fun serialize(`object`: Any?): String { 41 | return Base64.getUrlEncoder() 42 | .encodeToString(SerializationUtils.serialize(`object`)) 43 | } 44 | 45 | fun deserialize(cookie: Cookie, cls: Class): T { 46 | return cls.cast(SerializationUtils.deserialize( 47 | Base64.getUrlDecoder().decode(cookie.value))) 48 | } 49 | } -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/util/DateTimeUtil.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.util 2 | 3 | import java.time.ZonedDateTime 4 | import java.time.format.DateTimeFormatter 5 | import java.time.format.DateTimeParseException 6 | import java.util.* 7 | 8 | object DateTimeUtil { 9 | 10 | fun getDateFromString(str: String?): Date { 11 | val parsedStr: String = str?.let { 12 | if (it != "") it else "2000-01-01T00:00:00.000+00:00" 13 | }?: run{ 14 | "2000-01-01T00:00:00.000+00:00" 15 | } 16 | return try { 17 | Date.from(ZonedDateTime.parse( parsedStr, DateTimeFormatter.ISO_DATE_TIME).toInstant()) 18 | } catch (ex: DateTimeParseException){ 19 | throw BadRequestException("Unable to parse date provided") 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/util/Exceptions.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.util 2 | 3 | import org.springframework.http.HttpStatus 4 | import org.springframework.security.core.AuthenticationException 5 | import org.springframework.web.bind.annotation.ResponseStatus 6 | 7 | 8 | @ResponseStatus(HttpStatus.BAD_REQUEST) 9 | class BadRequestException : RuntimeException { 10 | constructor(message: String?) : super(message) {} 11 | constructor(message: String?, cause: Throwable?) : super(message, cause) {} 12 | } 13 | 14 | class OAuth2AuthenticationProcessingException : AuthenticationException { 15 | constructor(msg: String?, t: Throwable?) : super(msg, t) {} 16 | constructor(msg: String?) : super(msg) {} 17 | } 18 | 19 | @ResponseStatus(HttpStatus.NOT_FOUND) 20 | data class ResourceNotFoundException(val resourceName: String, val fieldName: String, val fieldValue: Any) : RuntimeException("$resourceName not found with $fieldName: $fieldValue") -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/util/KotlinHelper.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.util 2 | 3 | import java.util.* 4 | 5 | fun Optional.toNullable(): T? = this.orElse(null) -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/util/auth/misc/CustomChannelInterceptor.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.util.auth.misc 2 | 3 | import com.squrlabs.sca.domain.service.user.UserService 4 | import com.squrlabs.sca.util.auth.util.UserPrincipal 5 | import org.springframework.messaging.Message 6 | import org.springframework.messaging.MessageChannel 7 | import org.springframework.messaging.simp.stomp.StompCommand 8 | import org.springframework.messaging.simp.stomp.StompHeaderAccessor 9 | import org.springframework.messaging.support.ChannelInterceptor 10 | import org.springframework.messaging.support.MessageHeaderAccessor 11 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken 12 | import org.springframework.security.core.userdetails.UserDetails 13 | 14 | class CustomChannelInterceptor( 15 | private val tokenProvider: TokenProvider, 16 | private val userService: UserService 17 | ) : ChannelInterceptor { 18 | 19 | override fun preSend(message: Message<*>, channel: MessageChannel): Message<*>? { 20 | 21 | val accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor::class.java) 22 | if (StompCommand.CONNECT == accessor!!.command) { 23 | val authorization = accessor.getNativeHeader("Authorization") 24 | val accessToken = getJwtFromRequest(authorization!![0]) 25 | if (!accessToken.isNullOrEmpty() && tokenProvider.validateToken(accessToken)) { 26 | val userId: String = tokenProvider.getUserIdFromToken(accessToken) 27 | val userDetails: UserDetails = userService.getUserById(userId)!! 28 | val authentication = UsernamePasswordAuthenticationToken(userDetails, null, userDetails.authorities) 29 | accessor.user = authentication 30 | } 31 | } 32 | if (StompCommand.SUBSCRIBE == accessor.command) { 33 | getDst(accessor.destination!!, "/notifications/")?.let { id -> 34 | accessor.user?.let { if (!verifyUser(it, id)) return null } 35 | } 36 | } 37 | return message 38 | } 39 | 40 | private fun getJwtFromRequest(bearerToken: String?): String? { 41 | bearerToken?.let { 42 | if (it.startsWith("Bearer ")) 43 | return it.substring(7, it.length) 44 | } 45 | return null 46 | } 47 | 48 | private fun getDst(s: String, prefix: String): String? { 49 | if (s.startsWith(prefix)) { 50 | return s.substring(prefix.length, s.length) 51 | } 52 | return null 53 | } 54 | 55 | private fun verifyUser(user: Any, id: String): Boolean { 56 | ((user as UsernamePasswordAuthenticationToken).principal as UserPrincipal).let { 57 | return (it.id == id) 58 | } 59 | } 60 | } -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/util/auth/misc/OAuth2RequestRepository.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.util.auth.misc 2 | 3 | import com.squrlabs.sca.util.CookieUtils 4 | import org.springframework.security.oauth2.client.web.AuthorizationRequestRepository 5 | import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest 6 | import org.springframework.stereotype.Component 7 | import javax.servlet.http.HttpServletRequest 8 | import javax.servlet.http.HttpServletResponse 9 | 10 | @Component 11 | class OAuth2RequestRepository: AuthorizationRequestRepository{ 12 | 13 | override fun loadAuthorizationRequest(request: HttpServletRequest): OAuth2AuthorizationRequest? { 14 | CookieUtils.getCookie(request, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME)?.let { 15 | return CookieUtils.deserialize(it, OAuth2AuthorizationRequest::class.java) 16 | } 17 | return null 18 | } 19 | 20 | fun removeAuthorizationRequestCookies(request: HttpServletRequest, response: HttpServletResponse) { 21 | CookieUtils.deleteCookie(request, response, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME); 22 | CookieUtils.deleteCookie(request, response, REDIRECT_URL_PARAM_COOKIE_NAME); 23 | } 24 | 25 | override fun saveAuthorizationRequest(authorizationRequest: OAuth2AuthorizationRequest?, request: HttpServletRequest, response: HttpServletResponse) { 26 | authorizationRequest?.let { 27 | CookieUtils.addCookie(response, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME, CookieUtils.serialize(authorizationRequest), cookieExpireSeconds) 28 | request.getParameter(REDIRECT_URL_PARAM_COOKIE_NAME)?.let { uri -> 29 | if (uri.isNotBlank()) 30 | CookieUtils.addCookie(response, REDIRECT_URL_PARAM_COOKIE_NAME, uri, cookieExpireSeconds) 31 | } 32 | 33 | }?: run{ 34 | removeAuthorizationRequestCookies(request, response) 35 | } 36 | } 37 | 38 | override fun removeAuthorizationRequest(request: HttpServletRequest): OAuth2AuthorizationRequest? { 39 | return this.loadAuthorizationRequest(request) 40 | } 41 | 42 | companion object { 43 | const val OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME = "oauth2_auth_request" 44 | const val REDIRECT_URL_PARAM_COOKIE_NAME = "redirect_url" 45 | private const val cookieExpireSeconds = 180 46 | } 47 | } -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/util/auth/misc/OAuth2ResultHandler.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.util.auth.misc 2 | 3 | import com.squrlabs.sca.config.AppProperties 4 | import com.squrlabs.sca.util.BadRequestException 5 | import com.squrlabs.sca.util.CookieUtils.getCookie 6 | import com.squrlabs.sca.util.auth.misc.OAuth2RequestRepository.Companion.REDIRECT_URL_PARAM_COOKIE_NAME 7 | import com.squrlabs.sca.util.auth.util.UserPrincipal 8 | import org.springframework.beans.factory.annotation.Autowired 9 | import org.springframework.security.core.Authentication 10 | import org.springframework.security.core.AuthenticationException 11 | import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler 12 | import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler 13 | import org.springframework.stereotype.Component 14 | import org.springframework.web.util.UriComponentsBuilder 15 | import java.io.IOException 16 | import java.net.URI 17 | import javax.servlet.ServletException 18 | import javax.servlet.http.HttpServletRequest 19 | import javax.servlet.http.HttpServletResponse 20 | 21 | @Component 22 | class OAuth2SuccessHandler(@Autowired val tokenProvider: TokenProvider, 23 | @Autowired private val appProperties: AppProperties, 24 | @Autowired val oAuth2RequestRepository: OAuth2RequestRepository) 25 | : SimpleUrlAuthenticationSuccessHandler() { 26 | 27 | override fun onAuthenticationSuccess(request: HttpServletRequest, response: HttpServletResponse, authentication: Authentication) { 28 | val targetUrl = determineTargetUrl(request, response, authentication) 29 | 30 | if (response.isCommitted) { 31 | return 32 | } 33 | clearAuthenticationAttributes(request, response) 34 | redirectStrategy.sendRedirect(request, response, targetUrl) 35 | } 36 | 37 | override fun determineTargetUrl(request: HttpServletRequest?, response: HttpServletResponse?, authentication: Authentication): String { 38 | 39 | val redirectUrl: String = getCookie(request!!, REDIRECT_URL_PARAM_COOKIE_NAME)?.let { return@let it.value }?:"" 40 | 41 | if (redirectUrl.isEmpty() && !isAuthorizedRedirectUrl(redirectUrl)) { 42 | throw BadRequestException("Sorry! We've got an Unauthorized Redirect URL and can't proceed with the authentication") 43 | } 44 | 45 | return UriComponentsBuilder.fromUriString(redirectUrl) 46 | .queryParam("token", tokenProvider.createToken(authentication)) 47 | .build().toUriString() 48 | } 49 | 50 | private fun clearAuthenticationAttributes(request: HttpServletRequest, response: HttpServletResponse) { 51 | super.clearAuthenticationAttributes(request) 52 | oAuth2RequestRepository.removeAuthorizationRequestCookies(request, response) 53 | } 54 | 55 | private fun isAuthorizedRedirectUrl(uri:String): Boolean { 56 | 57 | val clientRedirectUri = URI.create(uri) 58 | appProperties.oauth2.authorizedRedirectUrls.map{ 59 | val authorizedURL = URI.create(it) 60 | if(authorizedURL.host.toUpperCase() == clientRedirectUri.host.toUpperCase()) { 61 | return true 62 | } 63 | } 64 | return false 65 | } 66 | 67 | } 68 | 69 | @Component 70 | class OAuth2FailureHandler(@Autowired val oAuth2RequestRepository: OAuth2RequestRepository) 71 | : SimpleUrlAuthenticationFailureHandler() { 72 | 73 | 74 | @Throws(IOException::class, ServletException::class) 75 | override fun onAuthenticationFailure(request: HttpServletRequest, response: HttpServletResponse, exception: AuthenticationException) { 76 | var targetUrl: String = getCookie(request, REDIRECT_URL_PARAM_COOKIE_NAME)?.value ?: "/" 77 | targetUrl = UriComponentsBuilder.fromUriString(targetUrl) 78 | .queryParam("error", exception.localizedMessage) 79 | .build().toUriString() 80 | oAuth2RequestRepository.removeAuthorizationRequestCookies(request, response) 81 | redirectStrategy.sendRedirect(request, response, targetUrl) 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/util/auth/misc/RestAuthenticationEntryPoint.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.util.auth.misc 2 | 3 | import org.springframework.security.core.AuthenticationException 4 | import org.springframework.security.web.AuthenticationEntryPoint 5 | import javax.servlet.http.HttpServletRequest 6 | import javax.servlet.http.HttpServletResponse 7 | 8 | class RestAuthenticationEntryPoint: AuthenticationEntryPoint { 9 | 10 | override fun commence(request: HttpServletRequest?, response: HttpServletResponse?, authException: AuthenticationException?) { 11 | response!!.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException!!.localizedMessage) 12 | } 13 | } -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/util/auth/misc/TokenAuthenticationFilter.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.util.auth.misc 2 | 3 | import com.squrlabs.sca.domain.service.user.UserService 4 | import org.springframework.beans.factory.annotation.Autowired 5 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken 6 | import org.springframework.security.core.context.SecurityContextHolder 7 | import org.springframework.security.core.userdetails.UserDetails 8 | import org.springframework.security.web.authentication.WebAuthenticationDetailsSource 9 | import org.springframework.stereotype.Component 10 | import org.springframework.web.filter.OncePerRequestFilter 11 | import java.io.IOException 12 | import javax.servlet.FilterChain 13 | import javax.servlet.ServletException 14 | import javax.servlet.http.HttpServletRequest 15 | import javax.servlet.http.HttpServletResponse 16 | 17 | 18 | @Component 19 | class TokenAuthenticationFilter( 20 | @Autowired val tokenProvider: TokenProvider, 21 | @Autowired val userService: UserService 22 | ): OncePerRequestFilter(){ 23 | @Throws(ServletException::class, IOException::class) 24 | override fun doFilterInternal(request: HttpServletRequest, response: HttpServletResponse, filterChain: FilterChain) { 25 | try { 26 | val jwt = getJwtFromRequest(request) 27 | if (!jwt.isNullOrEmpty() && tokenProvider.validateToken(jwt)) { 28 | val userId: String = tokenProvider.getUserIdFromToken(jwt) 29 | val userDetails: UserDetails = userService.getUserById(userId)!! 30 | val authentication = UsernamePasswordAuthenticationToken(userDetails, null, userDetails.authorities) 31 | authentication.details = WebAuthenticationDetailsSource().buildDetails(request) 32 | SecurityContextHolder.getContext().authentication = authentication 33 | } 34 | } catch (ex: Exception) { 35 | logger.error("Could not set user authentication in security context", ex) 36 | } 37 | filterChain.doFilter(request, response) 38 | } 39 | 40 | private fun getJwtFromRequest(request: HttpServletRequest): String? { 41 | val bearerToken: String? = request.getHeader("Authorization") 42 | bearerToken?.let{ 43 | if (it.startsWith("Bearer ")) 44 | return it.substring(7, it.length) 45 | } 46 | return null 47 | } 48 | 49 | } -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/util/auth/misc/TokenProvider.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.util.auth.misc 2 | 3 | import com.squrlabs.sca.config.AppProperties 4 | import com.squrlabs.sca.util.auth.util.UserPrincipal 5 | import io.jsonwebtoken.* 6 | import org.springframework.security.core.Authentication 7 | import org.springframework.stereotype.Service 8 | import java.util.* 9 | 10 | @Service 11 | class TokenProvider(private val appProperties: AppProperties) { 12 | 13 | fun createToken(authentication: Authentication): String { 14 | val userPrincipal: UserPrincipal = authentication.principal as UserPrincipal 15 | return generateToken(userPrincipal) 16 | } 17 | 18 | fun generateToken(userPrincipal: UserPrincipal): String { 19 | val now = Date() 20 | val expiryDate = Date(now.time + appProperties.auth.tokenExpirationMsec) 21 | return Jwts.builder() 22 | .setSubject(userPrincipal.id) 23 | .setIssuedAt(Date()) 24 | .setExpiration(expiryDate) 25 | .signWith(SignatureAlgorithm.HS512, appProperties.auth.tokenSecret) 26 | .compact() 27 | } 28 | 29 | fun getUserIdFromToken(token: String?): String { 30 | return Jwts.parser().setSigningKey(appProperties.auth.tokenSecret).parseClaimsJws(token).body.subject 31 | } 32 | 33 | fun validateToken(authToken: String?): Boolean { 34 | return try { 35 | Jwts.parser().setSigningKey(appProperties.auth.tokenSecret).parseClaimsJws(authToken) 36 | true 37 | } catch (ex: Exception) { 38 | false 39 | } 40 | 41 | } 42 | 43 | 44 | } 45 | -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/util/auth/util/OAuth2UserInfo.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.util.auth.util 2 | 3 | import com.squrlabs.sca.domain.model.user.AuthProvider 4 | import com.squrlabs.sca.util.OAuth2AuthenticationProcessingException 5 | 6 | 7 | abstract class OAuth2UserInfo(val attributes: Map) { 8 | abstract fun getId(): String 9 | abstract fun getName(): String 10 | abstract fun getEmail(): String 11 | abstract fun getImageUrl(): String? 12 | } 13 | 14 | class FacebookOAuth2UserInfo(attributes: Map): OAuth2UserInfo(attributes){ 15 | override fun getId(): String = attributes["id"] as String 16 | override fun getName(): String = attributes["name"] as String 17 | override fun getEmail(): String = attributes["email"] as String 18 | override fun getImageUrl(): String? { 19 | if (attributes.containsKey("picture")) { 20 | val pictureObj = attributes["picture"] as Map? 21 | if (pictureObj!!.containsKey("data")) { 22 | val dataObj = pictureObj["data"] as Map? 23 | if (dataObj!!.containsKey("url")) { 24 | return (dataObj["url"] as String?)!! 25 | } 26 | } 27 | } 28 | return null 29 | } 30 | 31 | } 32 | 33 | class GoogleOAuth2UserInfo(attributes: Map): OAuth2UserInfo(attributes){ 34 | override fun getId(): String = attributes["sub"] as String 35 | override fun getName(): String = attributes["name"] as String 36 | override fun getEmail(): String = attributes["email"] as String 37 | override fun getImageUrl(): String? = attributes["picture"] as String 38 | 39 | } 40 | 41 | object OAuth2UserInfoFactory { 42 | fun getOAuth2UserInfo(registrationId: String, attributes: Map): OAuth2UserInfo { 43 | return if (registrationId.equals(AuthProvider.google.toString(), ignoreCase = true)) { 44 | GoogleOAuth2UserInfo(attributes) 45 | } else if (registrationId.equals(AuthProvider.facebook.toString(), ignoreCase = true)) { 46 | FacebookOAuth2UserInfo(attributes) 47 | } else { 48 | throw OAuth2AuthenticationProcessingException("Sorry! Login with $registrationId is not supported yet.") 49 | } 50 | } 51 | } -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/util/auth/util/UserPrincipal.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.util.auth.util 2 | 3 | import com.squrlabs.sca.domain.model.user.UserModel 4 | import org.springframework.security.core.GrantedAuthority 5 | import org.springframework.security.core.userdetails.UserDetails 6 | import org.springframework.security.oauth2.core.user.OAuth2User 7 | 8 | class UserPrincipal(val id: String, val mEmail: String, val mPassword: String, val mAuthorities: Collection, 9 | val mAttributes: Map, val mName: String, val mImgUrl: String) : OAuth2User, UserDetails { 10 | 11 | companion object { 12 | fun create(userModel: UserModel, attributes: Map, authorities: Collection): UserPrincipal { 13 | return UserPrincipal(id = userModel.id, mEmail = userModel.email, mPassword = userModel.password, 14 | mAttributes = attributes, mAuthorities = authorities, mName = userModel.name, mImgUrl = userModel.imgUrl) 15 | } 16 | } 17 | 18 | 19 | override fun isEnabled(): Boolean { 20 | return true 21 | } 22 | 23 | override fun getUsername(): String { 24 | return mEmail 25 | } 26 | 27 | override fun isCredentialsNonExpired(): Boolean { 28 | return true 29 | } 30 | 31 | override fun getPassword(): String { 32 | return mPassword 33 | } 34 | 35 | override fun isAccountNonExpired(): Boolean { 36 | return true 37 | } 38 | 39 | override fun isAccountNonLocked(): Boolean { 40 | return true 41 | } 42 | 43 | override fun getAuthorities(): Collection { 44 | return mAuthorities 45 | } 46 | 47 | override fun getName(): String { 48 | return mName 49 | } 50 | 51 | override fun getAttributes(): Map { 52 | return mAttributes 53 | } 54 | } -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/web/controller/auth/AccountController.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.web.controller.auth 2 | 3 | import com.squrlabs.sca.domain.model.user.AuthProvider 4 | import com.squrlabs.sca.domain.model.user.UserModel 5 | import com.squrlabs.sca.domain.service.user.UserService 6 | import com.squrlabs.sca.util.ApiResponse 7 | import com.squrlabs.sca.util.BadRequestException 8 | import com.squrlabs.sca.util.auth.misc.TokenProvider 9 | import com.squrlabs.sca.util.auth.util.UserPrincipal 10 | import com.squrlabs.sca.web.dto.auth.AuthResponse 11 | import com.squrlabs.sca.web.dto.auth.LoginRequest 12 | import com.squrlabs.sca.web.dto.auth.SignUpRequest 13 | import io.swagger.v3.oas.annotations.Operation 14 | import io.swagger.v3.oas.annotations.tags.Tag 15 | import org.springframework.beans.factory.annotation.Autowired 16 | import org.springframework.http.ResponseEntity 17 | import org.springframework.security.authentication.AuthenticationManager 18 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken 19 | import org.springframework.security.core.Authentication 20 | import org.springframework.security.core.context.SecurityContextHolder 21 | import org.springframework.security.crypto.password.PasswordEncoder 22 | import org.springframework.web.bind.annotation.PostMapping 23 | import org.springframework.web.bind.annotation.RequestBody 24 | import org.springframework.web.bind.annotation.RequestMapping 25 | import org.springframework.web.bind.annotation.RestController 26 | import javax.validation.Valid 27 | 28 | 29 | @RestController 30 | @RequestMapping(AccountController.AUTH_BASE_URI, consumes = ["application/json"]) 31 | @Tag(name = "Account Api", description = " This contains url related to login account") 32 | class AccountController( 33 | @Autowired private val authenticationManager: AuthenticationManager, 34 | @Autowired private val userService: UserService, 35 | @Autowired private val passwordEncoder: PasswordEncoder, 36 | @Autowired private val tokenProvider: TokenProvider 37 | ) { 38 | 39 | @PostMapping("/signin") 40 | fun authenticateUser(@Valid @RequestBody loginRequest: LoginRequest): ResponseEntity? { 41 | val authentication: Authentication = authenticationManager.authenticate( 42 | UsernamePasswordAuthenticationToken( 43 | loginRequest.email, 44 | loginRequest.password 45 | ) 46 | ) 47 | SecurityContextHolder.getContext().authentication = authentication 48 | val token = tokenProvider.createToken(authentication) 49 | val userPrincipal = authentication.principal as UserPrincipal 50 | 51 | return ResponseEntity.ok(AuthResponse(accessToken = token, name = userPrincipal.mName, email = userPrincipal.mEmail, imageUrl = userPrincipal.mImgUrl, id = userPrincipal.id)) 52 | } 53 | 54 | @PostMapping("/signup") 55 | fun registerUser(@Valid @RequestBody signUpRequest: SignUpRequest): ResponseEntity? { 56 | if (userService.existsByEmail(signUpRequest.email)) { 57 | throw BadRequestException("Email address already in use.") 58 | } 59 | // Creating user's account 60 | val user = UserModel( 61 | name = signUpRequest.name, 62 | email = signUpRequest.email, 63 | password = passwordEncoder.encode(signUpRequest.password), 64 | imgUrl = "", 65 | roles = listOf("USER_ROLE"), 66 | providerId = "", 67 | provider = AuthProvider.local 68 | ) 69 | 70 | val result = userService.saveUser(user) 71 | return ResponseEntity.ok(ApiResponse(true, "User registered successfully@")) 72 | } 73 | 74 | 75 | companion object { 76 | const val AUTH_BASE_URI = "/api/account" 77 | } 78 | } -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/web/controller/chat/ChatController.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.web.controller.chat 2 | 3 | import com.squrlabs.sca.domain.model.chat.ContentType 4 | import com.squrlabs.sca.domain.model.chat.FileModel 5 | import com.squrlabs.sca.domain.service.chat.ChatService 6 | import com.squrlabs.sca.domain.service.chat.MessageService 7 | import com.squrlabs.sca.domain.service.file.FileStorageService 8 | import com.squrlabs.sca.util.BadRequestException 9 | import com.squrlabs.sca.util.DateTimeUtil 10 | import com.squrlabs.sca.util.auth.util.UserPrincipal 11 | import com.squrlabs.sca.web.controller.chat.ChatController.Companion.USER_CHAT_BASE_URI 12 | import com.squrlabs.sca.web.dto.chat.FriendProfileResponse 13 | import com.squrlabs.sca.web.dto.chat.MessageResponse 14 | import com.squrlabs.sca.web.dto.chat.MessageResponseMapper 15 | import io.swagger.v3.oas.annotations.tags.Tag 16 | import org.springframework.beans.factory.annotation.Autowired 17 | import org.springframework.http.ResponseEntity 18 | import org.springframework.security.core.context.SecurityContextHolder 19 | import org.springframework.web.bind.annotation.* 20 | import org.springframework.web.multipart.MultipartFile 21 | import java.io.IOException 22 | import java.nio.file.Files 23 | import java.nio.file.Path 24 | import java.nio.file.StandardCopyOption 25 | 26 | @RestController 27 | @RequestMapping(USER_CHAT_BASE_URI) 28 | @Tag(name = "User Chat", description = "This contains url related user Conversations") 29 | class ChatController( 30 | @Autowired val messageService: MessageService, 31 | @Autowired val chatService: ChatService, 32 | @Autowired val fileStorageService: FileStorageService 33 | ) { 34 | 35 | @GetMapping 36 | fun getFriends(@RequestParam("from", required = false) from: String?): ResponseEntity> { 37 | val user = getCurrentUser() 38 | val updatedAfter = DateTimeUtil.getDateFromString(from) 39 | val friends = chatService.getConversations(user.id, updatedAfter) 40 | return ResponseEntity.ok(friends.map { FriendProfileResponse(it.id, it.email, it.name, it.imgUrl, it.blockedBy) }) 41 | } 42 | 43 | @PostMapping 44 | fun startConversation(@RequestParam("email", required = true) email: String?): ResponseEntity{ 45 | val user = getCurrentUser() 46 | email?.let { 47 | val friend = chatService.newConversation(user, it) 48 | return ResponseEntity.ok( FriendProfileResponse(friend.id, friend.email, friend.name, friend.imgUrl, friend.blockedBy)) 49 | }?: run{ 50 | throw BadRequestException("Sorry no email provides") 51 | } 52 | } 53 | 54 | @PostMapping("/messages") 55 | fun getAllMessages( 56 | @RequestBody ids: List, 57 | @RequestParam("from", required = false) from: String? 58 | ): ResponseEntity> { 59 | val user = getCurrentUser() 60 | val updatedAfter = DateTimeUtil.getDateFromString(from) 61 | val messages = messageService.getAllMessages(ids, user.id, updatedAfter) 62 | 63 | return ResponseEntity.ok(messages.map { MessageResponseMapper.from(it) }) 64 | } 65 | 66 | @PutMapping("/{cid}/block") 67 | fun blockUser(@PathVariable("cid") id: String): ResponseEntity{ 68 | val user = getCurrentUser() 69 | val friend = chatService.blockConversation(id, user) 70 | return ResponseEntity.ok( FriendProfileResponse(friend.id, friend.email, friend.name, friend.imgUrl, friend.blockedBy)) 71 | } 72 | 73 | @PutMapping("/{cid}/unblock") 74 | fun unblockUser(@PathVariable("cid") id: String): ResponseEntity{ 75 | val user = getCurrentUser() 76 | val friend = chatService.unblockConversation(id, user) 77 | return ResponseEntity.ok( FriendProfileResponse(friend.id, friend.email, friend.name, friend.imgUrl, friend.blockedBy)) 78 | } 79 | 80 | @GetMapping("/{cid}/messages") 81 | fun getMessages( 82 | @PathVariable("cid") id: String, 83 | @RequestParam("from", required = false) from: String? 84 | ): ResponseEntity>{ 85 | val user = getCurrentUser() 86 | val updatedAfter = DateTimeUtil.getDateFromString(from) 87 | val messages = messageService.getMessagesByChat(id, user.id, updatedAfter) 88 | 89 | return ResponseEntity.ok(messages.map { MessageResponseMapper.from(it) }) 90 | } 91 | 92 | @PostMapping("/{cid}/messages/text") 93 | fun createMessageText( 94 | @PathVariable("cid") id: String, 95 | @RequestParam("content", required = false) content: String = "" 96 | ): ResponseEntity{ 97 | val user = getCurrentUser() 98 | val msg = messageService.createMessage(id, user.id, content, emptyList(), ContentType.TEXT) 99 | return ResponseEntity.ok( MessageResponseMapper.from(msg) ) 100 | } 101 | 102 | @PostMapping("/{cid}/messages/files", consumes = ["multipart/form-data"]) 103 | fun createMessageFile( 104 | @PathVariable("cid") id: String, 105 | @RequestParam("content", required = false) content: String = "", 106 | @RequestParam("files") files: Array 107 | ): ResponseEntity{ 108 | val user = getCurrentUser() 109 | val uploadedFiles = fileStorageService.store(files.toList(), id) 110 | val msg = messageService.createMessage(id, user.id, content, uploadedFiles, ContentType.FILE) 111 | return ResponseEntity.ok(MessageResponseMapper.from(msg)) 112 | 113 | } 114 | 115 | @PutMapping("/{cid}/messages/read") 116 | fun readMessage( 117 | @RequestBody ids: List, 118 | @PathVariable("cid") convId: String 119 | ): ResponseEntity>{ 120 | val user = getCurrentUser() 121 | val messages = messageService.updateMessages(ids, convId, user.id) 122 | return ResponseEntity.ok(messages.map { MessageResponseMapper.from(it) }) 123 | } 124 | 125 | 126 | fun getCurrentUser(): UserPrincipal { 127 | return SecurityContextHolder.getContext().authentication.principal as UserPrincipal 128 | } 129 | 130 | companion object{ 131 | const val USER_CHAT_BASE_URI = "/api/chat" 132 | } 133 | } -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/web/controller/user/UserController.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.web.controller.user 2 | 3 | import com.squrlabs.sca.domain.service.user.UserService 4 | import com.squrlabs.sca.util.auth.util.UserPrincipal 5 | import com.squrlabs.sca.web.controller.user.UserController.Companion.USER_BASE_URI 6 | import com.squrlabs.sca.web.dto.user.UserProfile 7 | import io.swagger.v3.oas.annotations.tags.Tag 8 | import org.springframework.beans.factory.annotation.Autowired 9 | import org.springframework.security.core.context.SecurityContextHolder 10 | import org.springframework.web.bind.annotation.GetMapping 11 | import org.springframework.web.bind.annotation.RequestMapping 12 | import org.springframework.web.bind.annotation.RestController 13 | 14 | @RestController 15 | @RequestMapping(USER_BASE_URI, consumes = ["application/json"]) 16 | @Tag(name = "User Api", description = " This contains url related to login account") 17 | class UserController( 18 | @Autowired val userService: UserService 19 | ) { 20 | 21 | @GetMapping("/me") 22 | fun getMyProfile(): UserProfile{ 23 | val user = SecurityContextHolder.getContext().authentication.principal as UserPrincipal 24 | return this.userService.getUserProfile(user.id).let { UserProfile(it.id, it.email, it.name, it.imgUrl) } 25 | } 26 | 27 | companion object{ 28 | const val USER_BASE_URI = "/api/user" 29 | } 30 | } -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/web/dto/auth/AuthResponse.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.web.dto.auth 2 | 3 | data class AuthResponse( 4 | val accessToken: String, 5 | val tokenType: String = "Bearer ", 6 | val name: String, 7 | val email: String, 8 | val imageUrl: String, 9 | val id: String 10 | ) -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/web/dto/auth/LoginRequest.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.web.dto.auth 2 | 3 | import javax.validation.constraints.Email 4 | import javax.validation.constraints.NotBlank 5 | 6 | data class LoginRequest( 7 | @NotBlank @Email val email: String, 8 | @NotBlank val password: String) -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/web/dto/auth/SignUpRequest.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.web.dto.auth 2 | 3 | import javax.validation.constraints.Email 4 | import javax.validation.constraints.NotBlank 5 | 6 | data class SignUpRequest( 7 | @NotBlank val name:String, 8 | @NotBlank @Email val email:String, 9 | @NotBlank val password: String 10 | ) -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/web/dto/chat/FriendProfileResponse.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.web.dto.chat 2 | 3 | data class FriendProfileResponse( 4 | val id: String, 5 | val email: String, 6 | val name: String, 7 | val imgUrl: String, 8 | val blockedBy: String 9 | ) -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/web/dto/chat/MessageResponse.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.web.dto.chat 2 | 3 | import com.squrlabs.sca.domain.model.chat.ContentType 4 | import com.squrlabs.sca.domain.model.chat.FileModel 5 | import com.squrlabs.sca.domain.model.chat.MessageModel 6 | import java.util.* 7 | 8 | data class MessageResponse(val id:String, 9 | val senderId: String, 10 | val chatId: String, 11 | val content: String, 12 | val files: List, 13 | val contentType: ContentType, 14 | val createdAt: Date, 15 | val updatedAt: Date, 16 | val read: Boolean) 17 | 18 | data class FileResponse( 19 | val url: String, 20 | val type: String 21 | ) 22 | 23 | object MessageResponseMapper{ 24 | fun from(model: MessageModel) = MessageResponse( 25 | id = model.id!!, 26 | senderId = model.senderId, 27 | chatId = model.chatId, 28 | content = model.content, 29 | files = model.files.map { FileResponse(it.url, it.type) }, 30 | contentType = model.contentType, 31 | createdAt = model.createdAt, 32 | updatedAt = model.updatedAt, 33 | read = model.read 34 | ) 35 | } -------------------------------------------------------------------------------- /server/src/main/kotlin/com/squrlabs/sca/web/dto/user/UserProfile.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca.web.dto.user 2 | 3 | data class UserProfile( 4 | val id: String, 5 | val email: String, 6 | val name: String, 7 | val imgUrl: String 8 | ) -------------------------------------------------------------------------------- /server/src/main/resources/application-docker.yaml: -------------------------------------------------------------------------------- 1 | spring: 2 | data: 3 | mongodb: 4 | uri: ${MONGO_DB_URL} 5 | 6 | security: 7 | oauth2: 8 | client: 9 | registration: 10 | google: 11 | clientId: ${OAUTH_GOOGLE_ID} 12 | clientSecret: ${OAUTH_GOOGLE_SECRET} 13 | scope: 14 | - email 15 | - profile 16 | facebook: 17 | clientId: ${OAUTH_FACEBOOK_ID} 18 | clientSecret: ${OAUTH_FACEBOOK_SECRET} 19 | scope: 20 | - email 21 | - public_profile 22 | servlet: 23 | multipart: 24 | enabled: true 25 | max-file-size: 10MB 26 | max-request-size: 10MB 27 | 28 | #logging 29 | logging: 30 | level: 31 | org: 32 | springframework: 33 | data: debug 34 | error: trace 35 | 36 | #docs 37 | springdoc: 38 | version: '1.0.0' 39 | api-docs: 40 | path: /api/docs 41 | 42 | app: 43 | auth: 44 | tokenSecret: ${OAUTH_EMAIL_SECRET} 45 | tokenExpirationMsec: ${OAUTH_EMAIL_EXPIRATION} 46 | oauth2: 47 | authorizedRedirectUrls: 48 | - ${OAUTH_URI_WEB} 49 | - ${OAUTH_URI_ANDROID} 50 | - ${OAUTH_URI_IOS} -------------------------------------------------------------------------------- /server/src/main/resources/application.yaml: -------------------------------------------------------------------------------- 1 | spring: 2 | profiles: 3 | active: local -------------------------------------------------------------------------------- /server/src/test/kotlin/com/squrlabs/sca/ScaApplicationTests.kt: -------------------------------------------------------------------------------- 1 | package com.squrlabs.sca 2 | 3 | import org.junit.jupiter.api.Test 4 | import org.springframework.boot.test.context.SpringBootTest 5 | 6 | @SpringBootTest 7 | class ScaApplicationTests { 8 | 9 | @Test 10 | fun contextLoads() { 11 | } 12 | 13 | } 14 | --------------------------------------------------------------------------------
19 | Don't have an account? Register 20 |
28 | Don't have an account? Register 29 |
18 | Forgot Password? 19 |
or Continue with
38 | Don't have an account? Register 39 |
38 | Already have an account? Sigin 39 |
Powered By: Deepanshu Tyagi
settings works!
10 | 11 |
{{ message }}