├── .github └── workflows │ └── digitalocean.yml ├── LICENSE ├── README.md ├── angular-11-social-login ├── .browserslistrc ├── .dockerignore ├── .editorconfig ├── .gitignore ├── Dockerfile ├── README.md ├── angular.json ├── e2e │ ├── protractor.conf.js │ ├── src │ │ ├── app.e2e-spec.ts │ │ └── app.po.ts │ └── tsconfig.json ├── karma.conf.js ├── nginx-custom.conf ├── package-lock.json ├── package.json ├── src │ ├── app │ │ ├── _helpers │ │ │ └── auth.interceptor.ts │ │ ├── _services │ │ │ ├── auth.service.spec.ts │ │ │ ├── auth.service.ts │ │ │ ├── order.service.ts │ │ │ ├── token-storage.service.spec.ts │ │ │ ├── token-storage.service.ts │ │ │ ├── user.service.spec.ts │ │ │ └── user.service.ts │ │ ├── app-routing.module.ts │ │ ├── app.component.css │ │ ├── app.component.html │ │ ├── app.component.spec.ts │ │ ├── app.component.ts │ │ ├── app.module.ts │ │ ├── board-admin │ │ │ ├── board-admin.component.css │ │ │ ├── board-admin.component.html │ │ │ ├── board-admin.component.spec.ts │ │ │ └── board-admin.component.ts │ │ ├── board-moderator │ │ │ ├── board-moderator.component.css │ │ │ ├── board-moderator.component.html │ │ │ ├── board-moderator.component.spec.ts │ │ │ └── board-moderator.component.ts │ │ ├── board-user │ │ │ ├── board-user.component.css │ │ │ ├── board-user.component.html │ │ │ ├── board-user.component.spec.ts │ │ │ └── board-user.component.ts │ │ ├── common │ │ │ └── app.constants.ts │ │ ├── home │ │ │ ├── home.component.css │ │ │ ├── home.component.html │ │ │ ├── home.component.spec.ts │ │ │ └── home.component.ts │ │ ├── login │ │ │ ├── login.component.css │ │ │ ├── login.component.html │ │ │ ├── login.component.spec.ts │ │ │ └── login.component.ts │ │ ├── order │ │ │ ├── order.component.css │ │ │ ├── order.component.html │ │ │ └── order.component.ts │ │ ├── profile │ │ │ ├── profile.component.css │ │ │ ├── profile.component.html │ │ │ ├── profile.component.spec.ts │ │ │ └── profile.component.ts │ │ ├── register │ │ │ ├── register.component.css │ │ │ ├── register.component.html │ │ │ ├── register.component.spec.ts │ │ │ └── register.component.ts │ │ └── totp │ │ │ ├── totp.component.css │ │ │ ├── totp.component.html │ │ │ └── totp.component.ts │ ├── assets │ │ ├── .gitkeep │ │ └── img │ │ │ ├── facebook.png │ │ │ ├── github.png │ │ │ ├── google.png │ │ │ ├── linkedin.png │ │ │ └── logo.png │ ├── environments │ │ ├── environment.prod.ts │ │ └── environment.ts │ ├── favicon.ico │ ├── index.html │ ├── main.ts │ ├── polyfills.ts │ ├── styles.css │ └── test.ts ├── tsconfig.app.json ├── tsconfig.base.json ├── tsconfig.json ├── tsconfig.spec.json └── tslint.json ├── docker-compose.yml ├── k8s ├── app-client.yml ├── app-server.yml ├── ingress-nginx-https.yml ├── ingress-nginx.yml ├── mysql.yml ├── prod-issuer.yml └── staging-issuer.yml └── spring-boot-oauth2-social-login ├── .mvn └── wrapper │ ├── MavenWrapperDownloader.java │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── Dockerfile ├── mvnw ├── mvnw.cmd ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── javachinna │ │ ├── DemoApplication.java │ │ ├── config │ │ ├── AppProperties.java │ │ ├── CurrentUser.java │ │ ├── RazorPayClientConfig.java │ │ ├── RestAuthenticationEntryPoint.java │ │ ├── SetupDataLoader.java │ │ ├── WebConfig.java │ │ └── WebSecurityConfig.java │ │ ├── controller │ │ ├── AuthController.java │ │ ├── OrderController.java │ │ └── UserController.java │ │ ├── dto │ │ ├── ApiResponse.java │ │ ├── JwtAuthenticationResponse.java │ │ ├── LocalUser.java │ │ ├── LoginRequest.java │ │ ├── SignUpRequest.java │ │ ├── SignUpResponse.java │ │ ├── SocialProvider.java │ │ ├── UserInfo.java │ │ └── payment │ │ │ ├── OrderRequest.java │ │ │ ├── OrderResponse.java │ │ │ └── PaymentResponse.java │ │ ├── exception │ │ ├── BadRequestException.java │ │ ├── OAuth2AuthenticationProcessingException.java │ │ ├── ResourceNotFoundException.java │ │ ├── UserAlreadyExistAuthenticationException.java │ │ └── handler │ │ │ └── RestResponseEntityExceptionHandler.java │ │ ├── model │ │ ├── Order.java │ │ ├── Role.java │ │ └── User.java │ │ ├── repo │ │ ├── OrderRepository.java │ │ ├── RoleRepository.java │ │ └── UserRepository.java │ │ ├── security │ │ ├── jwt │ │ │ ├── TokenAuthenticationFilter.java │ │ │ └── TokenProvider.java │ │ └── oauth2 │ │ │ ├── CustomOAuth2UserService.java │ │ │ ├── CustomOidcUserService.java │ │ │ ├── HttpCookieOAuth2AuthorizationRequestRepository.java │ │ │ ├── OAuth2AccessTokenResponseConverterWithDefaults.java │ │ │ ├── OAuth2AuthenticationFailureHandler.java │ │ │ ├── OAuth2AuthenticationSuccessHandler.java │ │ │ └── user │ │ │ ├── FacebookOAuth2UserInfo.java │ │ │ ├── GithubOAuth2UserInfo.java │ │ │ ├── GoogleOAuth2UserInfo.java │ │ │ ├── LinkedinOAuth2UserInfo.java │ │ │ ├── OAuth2UserInfo.java │ │ │ └── OAuth2UserInfoFactory.java │ │ ├── service │ │ ├── LocalUserDetailService.java │ │ ├── OrderService.java │ │ ├── UserService.java │ │ └── UserServiceImpl.java │ │ ├── util │ │ ├── CookieUtils.java │ │ ├── GeneralUtils.java │ │ └── Signature.java │ │ └── validator │ │ ├── PasswordMatches.java │ │ └── PasswordMatchesValidator.java └── resources │ ├── application.properties │ └── messages_en.properties └── test └── java └── com └── javachinna ├── config ├── MockUserUtils.java ├── TestSecurityConfig.java ├── WithMockCustomUser.java └── WithMockCustomUserSecurityContextFactory.java └── controller ├── AuthControllerTest.java ├── AuthControllerTest2.java └── OrderControllerTest.java /.github/workflows/digitalocean.yml: -------------------------------------------------------------------------------- 1 | on: 2 | push: 3 | branches: 4 | - main 5 | pull_request: 6 | branches: 7 | - main 8 | # Environment variables available to all jobs and steps in this workflow 9 | env: 10 | ANGULAR_IMAGE_NAME: social-login-app-client 11 | ANGULAR_CONTAINER_NAME: social-login-app-client 12 | ANGULAR_DEPLOYMENT_NAME: social-login-app-client 13 | SPRING_BOOT_IMAGE_NAME: social-login-app-server 14 | SPRING_BOOT_CONTAINER_NAME: social-login-app-server 15 | SPRING_BOOT_DEPLOYMENT_NAME: social-login-app-server 16 | jobs: 17 | 18 | build: 19 | name: Build, push, and deploy 20 | runs-on: ubuntu-latest 21 | steps: 22 | 23 | - name: Checkout main 24 | uses: actions/checkout@main 25 | 26 | - name: Login to Docker Hub 27 | uses: docker/login-action@v1 28 | with: 29 | username: ${{ secrets.DOCKER_HUB_USERNAME }} 30 | password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }} 31 | 32 | - name: Provide permission to run mvnw 33 | run: chmod +x ./spring-boot-oauth2-social-login/mvnw 34 | 35 | - name: Build and push Angular Image 36 | id: angular_docker_build 37 | uses: docker/build-push-action@v2 38 | with: 39 | context: ./angular-11-social-login 40 | file: ./angular-11-social-login/Dockerfile 41 | push: true 42 | tags: ${{ secrets.DOCKER_HUB_USERNAME }}/${{ env.ANGULAR_IMAGE_NAME }}:${{ github.sha }} 43 | 44 | - name: Build and push Spring Boot Image 45 | id: spring-boot-docker_build 46 | uses: docker/build-push-action@v2 47 | with: 48 | context: ./spring-boot-oauth2-social-login 49 | file: ./spring-boot-oauth2-social-login/Dockerfile 50 | push: true 51 | tags: ${{ secrets.DOCKER_HUB_USERNAME }}/${{ env.SPRING_BOOT_IMAGE_NAME }}:${{ github.sha }} 52 | 53 | - name: Install doctl 54 | uses: digitalocean/action-doctl@v2 55 | with: 56 | token: ${{ secrets.DIGITALOCEAN_ACCESS_TOKEN }} 57 | 58 | - name: Save DigitalOcean kubeconfig with short-lived credentials 59 | run: doctl kubernetes cluster kubeconfig save --expiry-seconds 600 k8s-1-20-2-do-0-blr1-1619022201280 60 | 61 | # Deploy Angular & Spring Boot Docker image to the DigitalOcean kubernetes cluster 62 | - name: Deploy 63 | run: |- 64 | kubectl set image deployment/${{env.ANGULAR_DEPLOYMENT_NAME}} ${{env.ANGULAR_CONTAINER_NAME}}=${{ secrets.DOCKER_HUB_USERNAME }}/${{ env.ANGULAR_IMAGE_NAME }}:${{ github.sha }} 65 | kubectl set image deployment/${{env.SPRING_BOOT_DEPLOYMENT_NAME}} ${{ env.SPRING_BOOT_CONTAINER_NAME}}=${{ secrets.DOCKER_HUB_USERNAME }}/${{ env.SPRING_BOOT_IMAGE_NAME }}:${{ github.sha }} 66 | kubectl rollout status deployment/${{env.ANGULAR_DEPLOYMENT_NAME}} 67 | kubectl rollout status deployment/${{env.SPRING_BOOT_DEPLOYMENT_NAME}} 68 | kubectl get services -o wide 69 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Chinna 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Integrate Payment Gateway with Angular and Spring Boot Application 2 | 3 | [Creating Backend - Spring REST API - Part 1](https://www.javachinna.com/spring-boot-angular-two-factor-authentication/) 4 | 5 | [Creating Backend - Spring REST API - Part 2](https://www.javachinna.com/2020/10/23/spring-boot-angular-10-user-registration-oauth2-social-login-part-2/) 6 | 7 | [Creating Angular 10 Client Application - Part 3](https://www.javachinna.com/2020/10/28/spring-boot-angular-10-user-registration-oauth2-social-login-part-3/) 8 | 9 | [Secure Spring Boot Angular Application with Two Factor Authentication](https://www.javachinna.com/spring-boot-angular-two-factor-authentication/) 10 | 11 | [Dockerize Angular with NGINX and Spring Boot with MySQL using Docker Compose](https://www.javachinna.com/angular-nginx-spring-boot-mysql-docker-compose/) 12 | 13 | [Deploy Angular, Spring Boot, and MySQL Application to DigitalOcean Kubernetes in 30 mins](https://www.javachinna.com/deploy-angular-spring-boot-mysql-digitalocean-kubernetes/) 14 | 15 | [Create CI/CD pipeline using GitHub Actions to Build and Deploy Angular Spring Boot App on Kubernetes in 15 mins 16 | ](https://www.javachinna.com/spring-boot-angular-ci-cd-pipeline-github-actions-kubernetes/) 17 | 18 | [Integrate Razorpay Payment Gateway with Angular and Spring Boot Application in 14 Simple Steps 19 | ](https://www.javachinna.com/integrate-razorpay-payment-gateway-angular-spring-boot-mysql/) 20 | 21 | [How to Write Junit 5 Test Cases for Spring REST Controller using Mockito](https://www.javachinna.com/spring-boot-rest-controller-junit-tests-mockito/) 22 | 23 | [4 Methods to Disable Spring Security or Test with Mock Authentication in JUnit Tests](https://www.javachinna.com/disable-spring-security-or-mock-authentication-junit-tests/) 24 | -------------------------------------------------------------------------------- /angular-11-social-login/.browserslistrc: -------------------------------------------------------------------------------- 1 | # This file is used by the build system to adjust CSS and JS output to support the specified browsers below. 2 | # For additional information regarding the format and rule options, please see: 3 | # https://github.com/browserslist/browserslist#queries 4 | 5 | # For the full list of supported browsers by the Angular framework, please see: 6 | # https://angular.io/guide/browser-support 7 | 8 | # You can see what browsers were selected by your queries by running: 9 | # npx browserslist 10 | 11 | last 1 Chrome version 12 | last 1 Firefox version 13 | last 2 Edge major versions 14 | last 2 Safari major version 15 | last 2 iOS major versions 16 | Firefox ESR 17 | not IE 9-11 # For IE 9-11 support, remove 'not'. 18 | -------------------------------------------------------------------------------- /angular-11-social-login/.dockerignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .git 3 | .gitignore -------------------------------------------------------------------------------- /angular-11-social-login/.editorconfig: -------------------------------------------------------------------------------- 1 | # Editor configuration, see https://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | indent_style = space 7 | indent_size = 2 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | 11 | [*.ts] 12 | quote_type = single 13 | 14 | [*.md] 15 | max_line_length = off 16 | trim_trailing_whitespace = false 17 | -------------------------------------------------------------------------------- /angular-11-social-login/.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 | -------------------------------------------------------------------------------- /angular-11-social-login/Dockerfile: -------------------------------------------------------------------------------- 1 | #### Stage 1: Build the angular application 2 | FROM node as build 3 | 4 | # Configure the main working directory inside the docker image. 5 | # This is the base directory used in any further RUN, COPY, and ENTRYPOINT 6 | # commands. 7 | WORKDIR /app 8 | 9 | # Copy the package.json as well as the package-lock.json and install 10 | # the dependencies. This is a separate step so the dependencies 11 | # will be cached unless changes to one of those two files 12 | # are made. 13 | COPY package*.json ./ 14 | RUN npm install 15 | 16 | # Copy the main application 17 | COPY . ./ 18 | 19 | # Arguments 20 | ARG configuration=production 21 | 22 | # Build the application 23 | RUN npm run build -- --outputPath=./dist/out --configuration $configuration 24 | 25 | #### Stage 2, use the compiled app, ready for production with Nginx 26 | FROM nginx 27 | 28 | # Copy the angular build from Stage 1 29 | COPY --from=build /app/dist/out/ /usr/share/nginx/html 30 | 31 | # Copy our custom nginx config 32 | COPY /nginx-custom.conf /etc/nginx/conf.d/default.conf 33 | 34 | 35 | # Expose port 80 to the Docker host, so we can access it 36 | # from the outside. 37 | EXPOSE 80 38 | 39 | ENTRYPOINT ["nginx","-g","daemon off;"] -------------------------------------------------------------------------------- /angular-11-social-login/README.md: -------------------------------------------------------------------------------- 1 | # Spring Boot 2 + Angular 10: User Registration and Login using JWT Authentication, OAuth2 Social Login with Facebook, Google, LinkedIn, and Github using Spring Security 5 and Two Factor Authentication (2FA) 2 | 3 | [Creating Backend - Spring REST API - Part 1](https://www.javachinna.com/spring-boot-angular-two-factor-authentication/) 4 | 5 | [Creating Backend - Spring REST API - Part 2](https://www.javachinna.com/2020/10/23/spring-boot-angular-10-user-registration-oauth2-social-login-part-2/) 6 | 7 | [Creating Angular 10 Client Application - Part 3](https://www.javachinna.com/2020/10/28/spring-boot-angular-10-user-registration-oauth2-social-login-part-3/) 8 | 9 | [Secure Spring Boot Angular Application with Two Factor Authentication](https://www.javachinna.com/spring-boot-angular-two-factor-authentication/) -------------------------------------------------------------------------------- /angular-11-social-login/e2e/protractor.conf.js: -------------------------------------------------------------------------------- 1 | // @ts-check 2 | // Protractor configuration file, see link for more information 3 | // https://github.com/angular/protractor/blob/master/lib/config.ts 4 | 5 | const { SpecReporter, StacktraceOption } = require('jasmine-spec-reporter'); 6 | 7 | /** 8 | * @type { import("protractor").Config } 9 | */ 10 | exports.config = { 11 | allScriptsTimeout: 11000, 12 | specs: [ 13 | './src/**/*.e2e-spec.ts' 14 | ], 15 | capabilities: { 16 | browserName: 'chrome' 17 | }, 18 | directConnect: true, 19 | baseUrl: 'http://localhost:4200/', 20 | framework: 'jasmine', 21 | jasmineNodeOpts: { 22 | showColors: true, 23 | defaultTimeoutInterval: 30000, 24 | print: function() {} 25 | }, 26 | onPrepare() { 27 | require('ts-node').register({ 28 | project: require('path').join(__dirname, './tsconfig.json') 29 | }); 30 | jasmine.getEnv().addReporter(new SpecReporter({ 31 | spec: { 32 | displayStacktrace: StacktraceOption.PRETTY 33 | } 34 | })); 35 | } 36 | }; -------------------------------------------------------------------------------- /angular-11-social-login/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('Angular10SocialLogin 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 | -------------------------------------------------------------------------------- /angular-11-social-login/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 | -------------------------------------------------------------------------------- /angular-11-social-login/e2e/tsconfig.json: -------------------------------------------------------------------------------- 1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */ 2 | { 3 | "extends": "../tsconfig.json", 4 | "compilerOptions": { 5 | "outDir": "../out-tsc/e2e", 6 | "module": "commonjs", 7 | "target": "es2018", 8 | "types": [ 9 | "jasmine", 10 | "jasminewd2", 11 | "node" 12 | ] 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /angular-11-social-login/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/Angular10SocialLogin'), 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 | -------------------------------------------------------------------------------- /angular-11-social-login/nginx-custom.conf: -------------------------------------------------------------------------------- 1 | server { 2 | listen 80; 3 | location / { 4 | root /usr/share/nginx/html; 5 | index index.html index.htm; 6 | try_files $uri $uri/ /index.html =404; 7 | } 8 | } -------------------------------------------------------------------------------- /angular-11-social-login/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "angular10-jwt-auth", 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": "~11.0.2", 15 | "@angular/common": "~11.0.2", 16 | "@angular/compiler": "~11.0.2", 17 | "@angular/core": "~11.0.2", 18 | "@angular/forms": "~11.0.2", 19 | "@angular/platform-browser": "~11.0.2", 20 | "@angular/platform-browser-dynamic": "~11.0.2", 21 | "@angular/router": "~11.0.2", 22 | "rxjs": "~6.5.5", 23 | "tslib": "^2.0.0", 24 | "zone.js": "~0.10.3" 25 | }, 26 | "devDependencies": { 27 | "@angular-devkit/build-angular": "^0.1100.2", 28 | "@angular/cli": "~11.0.2", 29 | "@angular/compiler-cli": "~11.0.2", 30 | "@types/jasmine": "~3.6.0", 31 | "@types/jasminewd2": "~2.0.3", 32 | "@types/node": "^12.11.1", 33 | "codelyzer": "^6.0.0", 34 | "jasmine-core": "~3.6.0", 35 | "jasmine-spec-reporter": "~5.0.0", 36 | "karma": "~5.1.1", 37 | "karma-chrome-launcher": "~3.1.0", 38 | "karma-coverage-istanbul-reporter": "~3.0.2", 39 | "karma-jasmine": "~4.0.0", 40 | "karma-jasmine-html-reporter": "^1.5.0", 41 | "protractor": "~7.0.0", 42 | "ts-node": "~8.3.0", 43 | "tslint": "~6.1.0", 44 | "typescript": "~4.0.5" 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/_helpers/auth.interceptor.ts: -------------------------------------------------------------------------------- 1 | import { HTTP_INTERCEPTORS, HttpEvent } from '@angular/common/http'; 2 | import { Injectable } from '@angular/core'; 3 | import { HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse } from '@angular/common/http'; 4 | import { Router } from '@angular/router'; 5 | import { TokenStorageService } from '../_services/token-storage.service'; 6 | import {tap} from 'rxjs/operators'; 7 | import { Observable } from 'rxjs'; 8 | 9 | const TOKEN_HEADER_KEY = 'Authorization'; 10 | 11 | @Injectable() 12 | export class AuthInterceptor implements HttpInterceptor { 13 | constructor(private token: TokenStorageService, private router: Router) { 14 | 15 | } 16 | 17 | intercept(req: HttpRequest, next: HttpHandler): Observable> { 18 | let authReq = req; 19 | const loginPath = '/login'; 20 | const token = this.token.getToken(); 21 | if (token != null) { 22 | authReq = req.clone({ headers: req.headers.set(TOKEN_HEADER_KEY, 'Bearer ' + token) }); 23 | } 24 | return next.handle(authReq).pipe( tap(() => {}, 25 | (err: any) => { 26 | if (err instanceof HttpErrorResponse) { 27 | if (err.status !== 401 || window.location.pathname === loginPath) { 28 | return; 29 | } 30 | this.token.signOut(); 31 | window.location.href = loginPath; 32 | } 33 | } 34 | )); 35 | } 36 | } 37 | 38 | export const authInterceptorProviders = [ 39 | { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true } 40 | ]; 41 | -------------------------------------------------------------------------------- /angular-11-social-login/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 | -------------------------------------------------------------------------------- /angular-11-social-login/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 { AppConstants } from '../common/app.constants'; 5 | 6 | const httpOptions = { 7 | headers: new HttpHeaders({ 'Content-Type': 'application/json' }) 8 | }; 9 | 10 | @Injectable({ 11 | providedIn: 'root' 12 | }) 13 | export class AuthService { 14 | constructor(private http: HttpClient) { } 15 | 16 | login(credentials): Observable { 17 | return this.http.post(AppConstants.AUTH_API + 'signin', { 18 | email: credentials.username, 19 | password: credentials.password 20 | }, httpOptions); 21 | } 22 | 23 | register(user): Observable { 24 | return this.http.post(AppConstants.AUTH_API + 'signup', { 25 | displayName: user.displayName, 26 | email: user.email, 27 | password: user.password, 28 | matchingPassword: user.matchingPassword, 29 | socialProvider: 'LOCAL', 30 | using2FA: user.using2FA 31 | }, httpOptions); 32 | } 33 | 34 | verify(credentials): Observable { 35 | return this.http.post(AppConstants.AUTH_API + 'verify', credentials.code, { 36 | headers: new HttpHeaders({ 'Content-Type': 'text/plain' }) 37 | }); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/_services/order.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpClient, HttpHeaders } from '@angular/common/http'; 3 | import { Observable } from 'rxjs'; 4 | import { AppConstants } from '../common/app.constants'; 5 | 6 | const httpOptions = { 7 | headers: new HttpHeaders({ 'Content-Type': 'application/json' }) 8 | }; 9 | declare var Razorpay: any; 10 | 11 | @Injectable({ 12 | providedIn: 'root' 13 | }) 14 | export class OrderService { 15 | 16 | constructor(private http: HttpClient) { 17 | 18 | } 19 | 20 | createOrder(order): Observable { 21 | return this.http.post(AppConstants.API_URL + 'order', { 22 | customerName: order.name, 23 | email: order.email, 24 | phoneNumber: order.phone, 25 | amount: order.amount 26 | }, httpOptions); 27 | } 28 | 29 | updateOrder(order): Observable { 30 | return this.http.put(AppConstants.API_URL + 'order', { 31 | razorpayOrderId: order.razorpay_order_id, 32 | razorpayPaymentId: order.razorpay_payment_id, 33 | razorpaySignature: order.razorpay_signature 34 | }, httpOptions); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /angular-11-social-login/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 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/_services/token-storage.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | 3 | const TOKEN_KEY = 'auth-token'; 4 | const USER_KEY = 'auth-user'; 5 | 6 | @Injectable({ 7 | providedIn: 'root' 8 | }) 9 | export class TokenStorageService { 10 | 11 | constructor() { } 12 | 13 | signOut(): void { 14 | window.sessionStorage.clear(); 15 | } 16 | 17 | public saveToken(token: string): void { 18 | window.sessionStorage.removeItem(TOKEN_KEY); 19 | window.sessionStorage.setItem(TOKEN_KEY, token); 20 | } 21 | 22 | public getToken(): string { 23 | return sessionStorage.getItem(TOKEN_KEY); 24 | } 25 | 26 | public saveUser(user): void { 27 | window.sessionStorage.removeItem(USER_KEY); 28 | window.sessionStorage.setItem(USER_KEY, JSON.stringify(user)); 29 | } 30 | 31 | public getUser(): any { 32 | return JSON.parse(sessionStorage.getItem(USER_KEY)); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /angular-11-social-login/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 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/_services/user.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpClient, HttpHeaders } from '@angular/common/http'; 3 | import { Observable } from 'rxjs'; 4 | import { AppConstants } from '../common/app.constants'; 5 | 6 | const httpOptions = { 7 | headers: new HttpHeaders({ 'Content-Type': 'application/json' }) 8 | }; 9 | 10 | 11 | @Injectable({ 12 | providedIn: 'root' 13 | }) 14 | export class UserService { 15 | 16 | constructor(private http: HttpClient) { } 17 | 18 | getPublicContent(): Observable { 19 | return this.http.get(AppConstants.API_URL + 'all', { responseType: 'text' }); 20 | } 21 | 22 | getUserBoard(): Observable { 23 | return this.http.get(AppConstants.API_URL + 'user', { responseType: 'text' }); 24 | } 25 | 26 | getModeratorBoard(): Observable { 27 | return this.http.get(AppConstants.API_URL + 'mod', { responseType: 'text' }); 28 | } 29 | 30 | getAdminBoard(): Observable { 31 | return this.http.get(AppConstants.API_URL + 'admin', { responseType: 'text' }); 32 | } 33 | 34 | getCurrentUser(): Observable { 35 | return this.http.get(AppConstants.API_URL + 'user/me', httpOptions); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/app-routing.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { Routes, RouterModule } from '@angular/router'; 3 | 4 | import { RegisterComponent } from './register/register.component'; 5 | import { LoginComponent } from './login/login.component'; 6 | import { HomeComponent } from './home/home.component'; 7 | import { ProfileComponent } from './profile/profile.component'; 8 | import { BoardUserComponent } from './board-user/board-user.component'; 9 | import { BoardModeratorComponent } from './board-moderator/board-moderator.component'; 10 | import { BoardAdminComponent } from './board-admin/board-admin.component'; 11 | import { TotpComponent } from './totp/totp.component'; 12 | import { OrderComponent } from './order/order.component'; 13 | 14 | const routes: Routes = [ 15 | { path: 'home', component: HomeComponent }, 16 | { path: 'login', component: LoginComponent }, 17 | { path: 'register', component: RegisterComponent }, 18 | { path: 'profile', component: ProfileComponent }, 19 | { path: 'user', component: BoardUserComponent }, 20 | { path: 'mod', component: BoardModeratorComponent }, 21 | { path: 'admin', component: BoardAdminComponent }, 22 | { path: 'totp', component: TotpComponent }, 23 | { path: 'order', component: OrderComponent }, 24 | { path: '', redirectTo: 'home', pathMatch: 'full' } 25 | ]; 26 | 27 | @NgModule({ 28 | imports: [RouterModule.forRoot(routes, { relativeLinkResolution: 'legacy' })], 29 | exports: [RouterModule] 30 | }) 31 | export class AppRoutingModule { } 32 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/app.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaChinna/angular-spring-boot-razorpay-integration/68b6ec7b500294c1d25a645e271ce2c7954d20ce/angular-11-social-login/src/app/app.component.css -------------------------------------------------------------------------------- /angular-11-social-login/src/app/app.component.html: -------------------------------------------------------------------------------- 1 |
2 | 22 |
23 | 24 |
25 |
-------------------------------------------------------------------------------- /angular-11-social-login/src/app/app.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed, waitForAsync } from '@angular/core/testing'; 2 | import { RouterTestingModule } from '@angular/router/testing'; 3 | import { AppComponent } from './app.component'; 4 | 5 | describe('AppComponent', () => { 6 | beforeEach(waitForAsync(() => { 7 | TestBed.configureTestingModule({ 8 | imports: [ 9 | RouterTestingModule 10 | ], 11 | declarations: [ 12 | AppComponent 13 | ], 14 | }).compileComponents(); 15 | })); 16 | 17 | it('should create the app', () => { 18 | const fixture = TestBed.createComponent(AppComponent); 19 | const app = fixture.componentInstance; 20 | expect(app).toBeTruthy(); 21 | }); 22 | 23 | it(`should have as title 'Angular10SocialLogin'`, () => { 24 | const fixture = TestBed.createComponent(AppComponent); 25 | const app = fixture.componentInstance; 26 | expect(app.title).toEqual('Angular10SocialLogin'); 27 | }); 28 | 29 | it('should render title', () => { 30 | const fixture = TestBed.createComponent(AppComponent); 31 | fixture.detectChanges(); 32 | const compiled = fixture.nativeElement; 33 | expect(compiled.querySelector('.content span').textContent).toContain('Angular10SocialLogin app is running!'); 34 | }); 35 | }); 36 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { TokenStorageService } from './_services/token-storage.service'; 3 | 4 | @Component({ 5 | selector: 'app-root', 6 | templateUrl: './app.component.html', 7 | styleUrls: ['./app.component.css'] 8 | }) 9 | export class AppComponent implements OnInit { 10 | private roles: string[]; 11 | isLoggedIn = false; 12 | showAdminBoard = false; 13 | showModeratorBoard = false; 14 | username: string; 15 | 16 | constructor(private tokenStorageService: TokenStorageService) { } 17 | 18 | ngOnInit(): void { 19 | this.isLoggedIn = !!this.tokenStorageService.getUser(); 20 | 21 | if (this.isLoggedIn) { 22 | const user = this.tokenStorageService.getUser(); 23 | this.roles = user.roles; 24 | 25 | this.showAdminBoard = this.roles.includes('ROLE_ADMIN'); 26 | this.showModeratorBoard = this.roles.includes('ROLE_MODERATOR'); 27 | 28 | this.username = user.displayName; 29 | } 30 | } 31 | 32 | logout(): void { 33 | this.tokenStorageService.signOut(); 34 | window.location.reload(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { BrowserModule } from '@angular/platform-browser'; 2 | import { NgModule } from '@angular/core'; 3 | 4 | import { AppRoutingModule } from './app-routing.module'; 5 | import { FormsModule } from '@angular/forms'; 6 | import { HttpClientModule } from '@angular/common/http'; 7 | 8 | import { AppComponent } from './app.component'; 9 | import { LoginComponent } from './login/login.component'; 10 | import { RegisterComponent } from './register/register.component'; 11 | import { HomeComponent } from './home/home.component'; 12 | import { ProfileComponent } from './profile/profile.component'; 13 | import { BoardAdminComponent } from './board-admin/board-admin.component'; 14 | import { BoardModeratorComponent } from './board-moderator/board-moderator.component'; 15 | import { BoardUserComponent } from './board-user/board-user.component'; 16 | import { TotpComponent } from './totp/totp.component'; 17 | import { OrderComponent } from './order/order.component'; 18 | 19 | import { authInterceptorProviders } from './_helpers/auth.interceptor'; 20 | 21 | @NgModule({ 22 | declarations: [ 23 | AppComponent, 24 | LoginComponent, 25 | RegisterComponent, 26 | HomeComponent, 27 | ProfileComponent, 28 | BoardAdminComponent, 29 | BoardModeratorComponent, 30 | BoardUserComponent, 31 | TotpComponent, 32 | OrderComponent 33 | ], 34 | imports: [ 35 | BrowserModule, 36 | AppRoutingModule, 37 | FormsModule, 38 | HttpClientModule 39 | ], 40 | providers: [authInterceptorProviders], 41 | bootstrap: [AppComponent] 42 | }) 43 | export class AppModule { } 44 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/board-admin/board-admin.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaChinna/angular-spring-boot-razorpay-integration/68b6ec7b500294c1d25a645e271ce2c7954d20ce/angular-11-social-login/src/app/board-admin/board-admin.component.css -------------------------------------------------------------------------------- /angular-11-social-login/src/app/board-admin/board-admin.component.html: -------------------------------------------------------------------------------- 1 |
2 |
{{ content }}
3 |
4 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/board-admin/board-admin.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; 2 | 3 | import { BoardAdminComponent } from './board-admin.component'; 4 | 5 | describe('BoardAdminComponent', () => { 6 | let component: BoardAdminComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(waitForAsync(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ BoardAdminComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(BoardAdminComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/board-admin/board-admin.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { UserService } from '../_services/user.service'; 3 | 4 | @Component({ 5 | selector: 'app-board-admin', 6 | templateUrl: './board-admin.component.html', 7 | styleUrls: ['./board-admin.component.css'] 8 | }) 9 | export class BoardAdminComponent implements OnInit { 10 | 11 | content: string; 12 | 13 | constructor(private userService: UserService) { } 14 | 15 | ngOnInit(): void { 16 | this.userService.getAdminBoard().subscribe( 17 | data => { 18 | this.content = data; 19 | }, 20 | err => { 21 | this.content = JSON.parse(err.error).message; 22 | } 23 | ); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/board-moderator/board-moderator.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaChinna/angular-spring-boot-razorpay-integration/68b6ec7b500294c1d25a645e271ce2c7954d20ce/angular-11-social-login/src/app/board-moderator/board-moderator.component.css -------------------------------------------------------------------------------- /angular-11-social-login/src/app/board-moderator/board-moderator.component.html: -------------------------------------------------------------------------------- 1 |
2 |
{{ content }}
3 |
4 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/board-moderator/board-moderator.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; 2 | 3 | import { BoardModeratorComponent } from './board-moderator.component'; 4 | 5 | describe('BoardModeratorComponent', () => { 6 | let component: BoardModeratorComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(waitForAsync(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ BoardModeratorComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(BoardModeratorComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/board-moderator/board-moderator.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { UserService } from '../_services/user.service'; 3 | 4 | @Component({ 5 | selector: 'app-board-moderator', 6 | templateUrl: './board-moderator.component.html', 7 | styleUrls: ['./board-moderator.component.css'] 8 | }) 9 | export class BoardModeratorComponent implements OnInit { 10 | 11 | content: string; 12 | 13 | constructor(private userService: UserService) { } 14 | 15 | ngOnInit(): void { 16 | this.userService.getModeratorBoard().subscribe( 17 | data => { 18 | this.content = data; 19 | }, 20 | err => { 21 | this.content = JSON.parse(err.error).message; 22 | } 23 | ); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/board-user/board-user.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaChinna/angular-spring-boot-razorpay-integration/68b6ec7b500294c1d25a645e271ce2c7954d20ce/angular-11-social-login/src/app/board-user/board-user.component.css -------------------------------------------------------------------------------- /angular-11-social-login/src/app/board-user/board-user.component.html: -------------------------------------------------------------------------------- 1 |
2 |
{{ content }}
3 |
4 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/board-user/board-user.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; 2 | 3 | import { BoardUserComponent } from './board-user.component'; 4 | 5 | describe('BoardUserComponent', () => { 6 | let component: BoardUserComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(waitForAsync(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ BoardUserComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(BoardUserComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/board-user/board-user.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { UserService } from '../_services/user.service'; 3 | 4 | @Component({ 5 | selector: 'app-board-user', 6 | templateUrl: './board-user.component.html', 7 | styleUrls: ['./board-user.component.css'] 8 | }) 9 | export class BoardUserComponent implements OnInit { 10 | 11 | content: string; 12 | 13 | constructor(private userService: UserService) { } 14 | 15 | ngOnInit(): void { 16 | this.userService.getUserBoard().subscribe( 17 | data => { 18 | this.content = data; 19 | }, 20 | err => { 21 | this.content = JSON.parse(err.error).message; 22 | } 23 | ); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/common/app.constants.ts: -------------------------------------------------------------------------------- 1 | import { environment } from '../../environments/environment'; 2 | 3 | export class AppConstants { 4 | private static API_BASE_URL = environment.apiBaseUrl; 5 | private static OAUTH2_URL = AppConstants.API_BASE_URL + "oauth2/authorization/"; 6 | private static REDIRECT_URL = environment.clientUrl; 7 | public static API_URL = AppConstants.API_BASE_URL + "api/"; 8 | public static AUTH_API = AppConstants.API_URL + "auth/"; 9 | public static GOOGLE_AUTH_URL = AppConstants.OAUTH2_URL + "google" + AppConstants.REDIRECT_URL; 10 | public static FACEBOOK_AUTH_URL = AppConstants.OAUTH2_URL + "facebook" + AppConstants.REDIRECT_URL; 11 | public static GITHUB_AUTH_URL = AppConstants.OAUTH2_URL + "github" + AppConstants.REDIRECT_URL; 12 | public static LINKEDIN_AUTH_URL = AppConstants.OAUTH2_URL + "linkedin" + AppConstants.REDIRECT_URL; 13 | } -------------------------------------------------------------------------------- /angular-11-social-login/src/app/home/home.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaChinna/angular-spring-boot-razorpay-integration/68b6ec7b500294c1d25a645e271ce2c7954d20ce/angular-11-social-login/src/app/home/home.component.css -------------------------------------------------------------------------------- /angular-11-social-login/src/app/home/home.component.html: -------------------------------------------------------------------------------- 1 |
2 |
{{ content }}
3 |
4 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/home/home.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { ComponentFixture, TestBed, waitForAsync } 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(waitForAsync(() => { 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 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/home/home.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { UserService } from '../_services/user.service'; 3 | 4 | @Component({ 5 | selector: 'app-home', 6 | templateUrl: './home.component.html', 7 | styleUrls: ['./home.component.css'] 8 | }) 9 | export class HomeComponent implements OnInit { 10 | 11 | content: string; 12 | 13 | constructor(private userService: UserService) { } 14 | 15 | ngOnInit(): void { 16 | this.userService.getPublicContent().subscribe( 17 | data => { 18 | this.content = data; 19 | }, 20 | err => { 21 | this.content = JSON.parse(err.error).message; 22 | } 23 | ); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/login/login.component.css: -------------------------------------------------------------------------------- 1 | label { 2 | display: block; 3 | margin-top: 10px; 4 | } 5 | 6 | .card-container.card { 7 | max-width: 400px !important; 8 | padding: 40px 40px; 9 | } 10 | 11 | .card { 12 | background-color: #f7f7f7; 13 | padding: 20px 25px 30px; 14 | margin: 0 auto 25px; 15 | margin-top: 50px; 16 | -moz-border-radius: 2px; 17 | -webkit-border-radius: 2px; 18 | border-radius: 2px; 19 | -moz-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); 20 | -webkit-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); 21 | box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); 22 | } 23 | 24 | .profile-img-card { 25 | width: 96px; 26 | height: 96px; 27 | margin: 0 auto 10px; 28 | display: block; 29 | -moz-border-radius: 50%; 30 | -webkit-border-radius: 50%; 31 | border-radius: 50%; 32 | } 33 | 34 | .content-divider.center { 35 | text-align: center; 36 | } 37 | 38 | .content-divider { 39 | position: relative; 40 | z-index: 1; 41 | } 42 | 43 | .content-divider>span, .content-divider>a { 44 | background-color: #fff; 45 | color: #000; 46 | display: inline-block; 47 | padding: 2px 12px; 48 | border-radius: 3px; 49 | text-transform: uppercase; 50 | font-weight: 500; 51 | } 52 | 53 | .content-divider>span:before, .content-divider>a:before { 54 | content: ""; 55 | position: absolute; 56 | top: 50%; 57 | left: 0; 58 | height: 1px; 59 | background-color: #ddd; 60 | width: 100%; 61 | z-index: -1; 62 | } 63 | 64 | .social-login .btn-img { 65 | width: 30px; 66 | height: auto; 67 | padding: 0.6rem 0; 68 | margin-right: 15px; 69 | } 70 | 71 | .btn-img-linkedin { 72 | width: auto; 73 | height: 50px; 74 | padding: 0.6rem 0; 75 | margin-right: 10px; 76 | } 77 | 78 | .form-group .has-error { 79 | color: red; 80 | } -------------------------------------------------------------------------------- /angular-11-social-login/src/app/login/login.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 | 4 |
5 |
6 | 7 | 8 |
9 |
10 | 12 | 16 |
17 |
18 | 19 |
20 |
21 | 22 |
23 |
24 |

25 | or 26 |

27 | 42 |
43 |
44 |
Welcome {{currentUser.displayName}}
Logged in as {{ currentUser.roles }}.
45 |
46 |
47 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/login/login.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; 2 | 3 | import { LoginComponent } from './login.component'; 4 | 5 | describe('LoginComponent', () => { 6 | let component: LoginComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(waitForAsync(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ LoginComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(LoginComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/login/login.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { AuthService } from '../_services/auth.service'; 3 | import { UserService } from '../_services/user.service'; 4 | import { TokenStorageService } from '../_services/token-storage.service'; 5 | import { Router, ActivatedRoute } from '@angular/router'; 6 | import { AppConstants } from '../common/app.constants'; 7 | 8 | 9 | @Component({ 10 | selector: 'app-login', 11 | templateUrl: './login.component.html', 12 | styleUrls: ['./login.component.css'] 13 | }) 14 | export class LoginComponent implements OnInit { 15 | 16 | form: any = {}; 17 | isLoggedIn = false; 18 | isLoginFailed = false; 19 | errorMessage = ''; 20 | currentUser: any; 21 | googleURL = AppConstants.GOOGLE_AUTH_URL; 22 | facebookURL = AppConstants.FACEBOOK_AUTH_URL; 23 | githubURL = AppConstants.GITHUB_AUTH_URL; 24 | linkedinURL = AppConstants.LINKEDIN_AUTH_URL; 25 | 26 | constructor(private authService: AuthService, private tokenStorage: TokenStorageService, private route: ActivatedRoute, private userService: UserService, private router: Router) {} 27 | 28 | ngOnInit(): void { 29 | const token: string = this.route.snapshot.queryParamMap.get('token'); 30 | const error: string = this.route.snapshot.queryParamMap.get('error'); 31 | if (this.tokenStorage.getUser()) { 32 | this.isLoggedIn = true; 33 | this.currentUser = this.tokenStorage.getUser(); 34 | } 35 | else if(token){ 36 | this.tokenStorage.saveToken(token); 37 | this.userService.getCurrentUser().subscribe( 38 | data => { 39 | this.login(data); 40 | }, 41 | err => { 42 | this.errorMessage = err.error.message; 43 | this.isLoginFailed = true; 44 | } 45 | ); 46 | } 47 | else if(error){ 48 | this.errorMessage = error; 49 | this.isLoginFailed = true; 50 | } 51 | } 52 | 53 | onSubmit(): void { 54 | this.authService.login(this.form).subscribe( 55 | data => { 56 | this.tokenStorage.saveToken(data.accessToken); 57 | if(data.authenticated){ 58 | this.login(data.user); 59 | } else { 60 | this.router.navigate(['/totp']); 61 | } 62 | }, 63 | err => { 64 | this.errorMessage = err.error.message; 65 | this.isLoginFailed = true; 66 | } 67 | ); 68 | } 69 | 70 | login(user): void { 71 | this.tokenStorage.saveUser(user); 72 | this.isLoginFailed = false; 73 | this.isLoggedIn = true; 74 | this.currentUser = this.tokenStorage.getUser(); 75 | window.location.reload(); 76 | } 77 | 78 | } 79 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/order/order.component.css: -------------------------------------------------------------------------------- 1 | label { 2 | display: block; 3 | margin-top: 10px; 4 | } 5 | 6 | .card-container.card { 7 | max-width: 400px !important; 8 | padding: 40px 40px; 9 | } 10 | 11 | .card { 12 | background-color: #f7f7f7; 13 | padding: 20px 25px 30px; 14 | margin: 0 auto 25px; 15 | margin-top: 50px; 16 | -moz-border-radius: 2px; 17 | -webkit-border-radius: 2px; 18 | border-radius: 2px; 19 | -moz-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); 20 | -webkit-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); 21 | box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); 22 | } -------------------------------------------------------------------------------- /angular-11-social-login/src/app/order/order.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 |
5 | 6 | 7 |
8 |
9 | 10 |
11 |
Name is required
12 |
Name must be at least 3 characters
13 |
Name must be at most 20 characters
14 |
15 |
16 |
17 | 18 | 19 |
20 |
21 | 23 | 27 |
28 |
29 | 30 | 33 |
34 |
35 | 36 |
37 |
38 |
39 |
40 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/order/order.component.ts: -------------------------------------------------------------------------------- 1 | import { HostListener, Component } from '@angular/core'; 2 | import { OrderService } from '../_services/order.service'; 3 | 4 | declare var Razorpay: any; 5 | 6 | @Component({ 7 | selector: 'app-order', 8 | templateUrl: './order.component.html', 9 | styleUrls: ['./order.component.css'] 10 | }) 11 | export class OrderComponent { 12 | 13 | form: any = {}; 14 | paymentId: string; 15 | error: string; 16 | 17 | constructor(private orderService: OrderService) { 18 | 19 | } 20 | 21 | options = { 22 | "key": "", 23 | "amount": "", 24 | "name": "Java Chinna", 25 | "description": "Web Development", 26 | "image": "https://www.javachinna.com/wp-content/uploads/2020/02/android-chrome-512x512-1.png", 27 | "order_id":"", 28 | "handler": function (response){ 29 | var event = new CustomEvent("payment.success", 30 | { 31 | detail: response, 32 | bubbles: true, 33 | cancelable: true 34 | } 35 | ); 36 | window.dispatchEvent(event); 37 | } 38 | , 39 | "prefill": { 40 | "name": "", 41 | "email": "", 42 | "contact": "" 43 | }, 44 | "notes": { 45 | "address": "" 46 | }, 47 | "theme": { 48 | "color": "#3399cc" 49 | } 50 | }; 51 | 52 | onSubmit(): void { 53 | this.paymentId = ''; 54 | this.error = ''; 55 | this.orderService.createOrder(this.form).subscribe( 56 | data => { 57 | this.options.key = data.secretKey; 58 | this.options.order_id = data.razorpayOrderId; 59 | this.options.amount = data.applicationFee; //paise 60 | this.options.prefill.name = this.form.name; 61 | this.options.prefill.email = this.form.email; 62 | this.options.prefill.contact = this.form.phone; 63 | var rzp1 = new Razorpay(this.options); 64 | rzp1.open(); 65 | 66 | rzp1.on('payment.failed', function (response){ 67 | // Todo - store this information in the server 68 | console.log(response.error.code); 69 | console.log(response.error.description); 70 | console.log(response.error.source); 71 | console.log(response.error.step); 72 | console.log(response.error.reason); 73 | console.log(response.error.metadata.order_id); 74 | console.log(response.error.metadata.payment_id); 75 | this.error = response.error.reason; 76 | } 77 | ); 78 | } 79 | , 80 | err => { 81 | this.error = err.error.message; 82 | } 83 | ); 84 | } 85 | 86 | @HostListener('window:payment.success', ['$event']) 87 | onPaymentSuccess(event): void { 88 | this.orderService.updateOrder(event.detail).subscribe( 89 | data => { 90 | this.paymentId = data.message; 91 | } 92 | , 93 | err => { 94 | this.error = err.error.message; 95 | } 96 | ); 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/profile/profile.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaChinna/angular-spring-boot-razorpay-integration/68b6ec7b500294c1d25a645e271ce2c7954d20ce/angular-11-social-login/src/app/profile/profile.component.css -------------------------------------------------------------------------------- /angular-11-social-login/src/app/profile/profile.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 | {{ currentUser.displayName }} Profile 5 |
6 |
7 |

8 | Email: {{ currentUser.email }} 9 |

10 | Roles: 11 |
    12 |
  • {{ role }}
  • 13 |
14 |
15 | Please login. 16 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/profile/profile.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { ComponentFixture, TestBed, waitForAsync } 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(waitForAsync(() => { 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 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/profile/profile.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { TokenStorageService } from '../_services/token-storage.service'; 3 | 4 | @Component({ 5 | selector: 'app-profile', 6 | templateUrl: './profile.component.html', 7 | styleUrls: ['./profile.component.css'] 8 | }) 9 | export class ProfileComponent implements OnInit { 10 | 11 | currentUser: any; 12 | 13 | constructor(private token: TokenStorageService) { } 14 | 15 | ngOnInit(): void { 16 | this.currentUser = this.token.getUser(); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/register/register.component.css: -------------------------------------------------------------------------------- 1 | label { 2 | display: block; 3 | margin-top: 10px; 4 | } 5 | 6 | .card-container.card { 7 | max-width: 400px !important; 8 | padding: 40px 40px; 9 | } 10 | 11 | .card { 12 | background-color: #f7f7f7; 13 | padding: 20px 25px 30px; 14 | margin: 0 auto 25px; 15 | margin-top: 50px; 16 | -moz-border-radius: 2px; 17 | -webkit-border-radius: 2px; 18 | border-radius: 2px; 19 | -moz-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); 20 | -webkit-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); 21 | box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); 22 | } 23 | 24 | .profile-img-card { 25 | width: 96px; 26 | height: 96px; 27 | margin: 0 auto 10px; 28 | display: block; 29 | -moz-border-radius: 50%; 30 | -webkit-border-radius: 50%; 31 | border-radius: 50%; 32 | } -------------------------------------------------------------------------------- /angular-11-social-login/src/app/register/register.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 | 4 |
5 |
6 | 8 |
9 |
Display Name is required
10 |
Display Name must be at least 3 characters
11 |
Display Name must be at most 20 characters
12 |
13 |
14 |
15 | 16 |
17 |
Email is required
18 |
Email must be a valid email address
19 |
20 |
21 |
22 | 24 |
25 |
Password is required
26 |
Password must be at least 6 characters
27 |
28 |
29 |
30 | 32 |
33 |
Confirm Password is required
34 |
Confirm Password must be at least 6 characters
35 |
36 |
37 |
38 | 40 |
41 |
42 | 43 |
44 |
45 | Signup failed!
{{ errorMessage }} 46 |
47 |
48 |
49 | Your registration is successful! 50 |
51 |

Scan this QR code using Google Authenticator app on your phone to use it later to login

52 | 53 |
54 |
55 |
56 |
57 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/register/register.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; 2 | 3 | import { RegisterComponent } from './register.component'; 4 | 5 | describe('RegisterComponent', () => { 6 | let component: RegisterComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(waitForAsync(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ RegisterComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(RegisterComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/register/register.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { AuthService } from '../_services/auth.service'; 3 | 4 | @Component({ 5 | selector: 'app-register', 6 | templateUrl: './register.component.html', 7 | styleUrls: ['./register.component.css'] 8 | }) 9 | export class RegisterComponent implements OnInit { 10 | 11 | form: any = {}; 12 | isSuccessful = false; 13 | isSignUpFailed = false; 14 | isUsing2FA = false; 15 | errorMessage = ''; 16 | qrCodeImage = ''; 17 | 18 | constructor(private authService: AuthService) { } 19 | 20 | ngOnInit(): void { 21 | } 22 | 23 | onSubmit(): void { 24 | this.authService.register(this.form).subscribe( 25 | data => { 26 | console.log(data); 27 | if(data.using2FA){ 28 | this.isUsing2FA = true; 29 | this.qrCodeImage = data.qrCodeImage; 30 | } 31 | this.isSuccessful = true; 32 | this.isSignUpFailed = false; 33 | }, 34 | err => { 35 | this.errorMessage = err.error.message; 36 | this.isSignUpFailed = true; 37 | } 38 | ); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/totp/totp.component.css: -------------------------------------------------------------------------------- 1 | .card-container.card { 2 | max-width: 400px !important; 3 | padding: 40px 40px; 4 | } 5 | 6 | .card { 7 | background-color: #f7f7f7; 8 | padding: 20px 25px 30px; 9 | margin: 0 auto 25px; 10 | margin-top: 50px; 11 | -moz-border-radius: 2px; 12 | -webkit-border-radius: 2px; 13 | border-radius: 2px; 14 | -moz-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); 15 | -webkit-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); 16 | box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); 17 | } 18 | 19 | .profile-img-card { 20 | width: 96px; 21 | height: 96px; 22 | margin: 0 auto 10px; 23 | display: block; 24 | -moz-border-radius: 50%; 25 | -webkit-border-radius: 50%; 26 | border-radius: 50%; 27 | } -------------------------------------------------------------------------------- /angular-11-social-login/src/app/totp/totp.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 | 4 |
5 |
6 | 7 | 11 |
12 |
13 | 14 |
15 |
16 | 17 |
18 |
19 |
Welcome {{currentUser.displayName}}
Logged in as {{ currentUser.roles }}.
20 |
21 |
22 | -------------------------------------------------------------------------------- /angular-11-social-login/src/app/totp/totp.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { AuthService } from '../_services/auth.service'; 3 | import { TokenStorageService } from '../_services/token-storage.service'; 4 | 5 | 6 | @Component({ 7 | selector: 'app-totp', 8 | templateUrl: './totp.component.html', 9 | styleUrls: ['./totp.component.css'] 10 | }) 11 | export class TotpComponent implements OnInit { 12 | 13 | form: any = {}; 14 | isLoggedIn = false; 15 | isLoginFailed = false; 16 | errorMessage = ''; 17 | currentUser: any; 18 | 19 | constructor(private authService: AuthService, private tokenStorage: TokenStorageService) {} 20 | 21 | ngOnInit(): void { 22 | if (this.tokenStorage.getUser()) { 23 | this.isLoggedIn = true; 24 | this.currentUser = this.tokenStorage.getUser(); 25 | } 26 | } 27 | 28 | onSubmit(): void { 29 | this.authService.verify(this.form).subscribe( 30 | data => { 31 | this.tokenStorage.saveToken(data.accessToken); 32 | this.login(data.user); 33 | }, 34 | err => { 35 | this.errorMessage = err.error.message; 36 | this.isLoginFailed = true; 37 | } 38 | ); 39 | } 40 | 41 | login(user): void { 42 | this.tokenStorage.saveUser(user); 43 | this.isLoginFailed = false; 44 | this.isLoggedIn = true; 45 | this.currentUser = this.tokenStorage.getUser(); 46 | window.location.reload(); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /angular-11-social-login/src/assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaChinna/angular-spring-boot-razorpay-integration/68b6ec7b500294c1d25a645e271ce2c7954d20ce/angular-11-social-login/src/assets/.gitkeep -------------------------------------------------------------------------------- /angular-11-social-login/src/assets/img/facebook.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaChinna/angular-spring-boot-razorpay-integration/68b6ec7b500294c1d25a645e271ce2c7954d20ce/angular-11-social-login/src/assets/img/facebook.png -------------------------------------------------------------------------------- /angular-11-social-login/src/assets/img/github.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaChinna/angular-spring-boot-razorpay-integration/68b6ec7b500294c1d25a645e271ce2c7954d20ce/angular-11-social-login/src/assets/img/github.png -------------------------------------------------------------------------------- /angular-11-social-login/src/assets/img/google.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaChinna/angular-spring-boot-razorpay-integration/68b6ec7b500294c1d25a645e271ce2c7954d20ce/angular-11-social-login/src/assets/img/google.png -------------------------------------------------------------------------------- /angular-11-social-login/src/assets/img/linkedin.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaChinna/angular-spring-boot-razorpay-integration/68b6ec7b500294c1d25a645e271ce2c7954d20ce/angular-11-social-login/src/assets/img/linkedin.png -------------------------------------------------------------------------------- /angular-11-social-login/src/assets/img/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaChinna/angular-spring-boot-razorpay-integration/68b6ec7b500294c1d25a645e271ce2c7954d20ce/angular-11-social-login/src/assets/img/logo.png -------------------------------------------------------------------------------- /angular-11-social-login/src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true, 3 | apiBaseUrl: 'https://server.javachinna.xyz/', 4 | clientUrl: '?redirect_uri=https://client.javachinna.xyz/login' 5 | }; 6 | -------------------------------------------------------------------------------- /angular-11-social-login/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 | apiBaseUrl: 'http://localhost:8080/', 8 | clientUrl: '?redirect_uri=http://localhost:8081/login' 9 | }; 10 | 11 | /* 12 | * For easier debugging in development mode, you can import the following file 13 | * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`. 14 | * 15 | * This import should be commented out in production mode because it will have a negative impact 16 | * on performance if an error is thrown. 17 | */ 18 | // import 'zone.js/dist/zone-error'; // Included with Angular CLI. 19 | -------------------------------------------------------------------------------- /angular-11-social-login/src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaChinna/angular-spring-boot-razorpay-integration/68b6ec7b500294c1d25a645e271ce2c7954d20ce/angular-11-social-login/src/favicon.ico -------------------------------------------------------------------------------- /angular-11-social-login/src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Angular11SocialLogin 6 | 7 | 8 | 9 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /angular-11-social-login/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 | -------------------------------------------------------------------------------- /angular-11-social-login/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 | -------------------------------------------------------------------------------- /angular-11-social-login/src/styles.css: -------------------------------------------------------------------------------- 1 | /* You can add global styles to this file, and also import other style files */ 2 | -------------------------------------------------------------------------------- /angular-11-social-login/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 | -------------------------------------------------------------------------------- /angular-11-social-login/tsconfig.app.json: -------------------------------------------------------------------------------- 1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */ 2 | { 3 | "extends": "./tsconfig.json", 4 | "compilerOptions": { 5 | "outDir": "./out-tsc/app", 6 | "types": [] 7 | }, 8 | "files": [ 9 | "src/main.ts", 10 | "src/polyfills.ts" 11 | ], 12 | "include": [ 13 | "src/**/*.d.ts" 14 | ] 15 | } 16 | -------------------------------------------------------------------------------- /angular-11-social-login/tsconfig.base.json: -------------------------------------------------------------------------------- 1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */ 2 | { 3 | "compileOnSave": false, 4 | "compilerOptions": { 5 | "baseUrl": "./", 6 | "outDir": "./dist/out-tsc", 7 | "sourceMap": true, 8 | "declaration": false, 9 | "downlevelIteration": true, 10 | "experimentalDecorators": true, 11 | "moduleResolution": "node", 12 | "importHelpers": true, 13 | "target": "es2015", 14 | "module": "es2020", 15 | "lib": [ 16 | "es2018", 17 | "dom" 18 | ] 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /angular-11-social-login/tsconfig.json: -------------------------------------------------------------------------------- 1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */ 2 | { 3 | "compileOnSave": false, 4 | "compilerOptions": { 5 | "baseUrl": "./", 6 | "outDir": "./dist/out-tsc", 7 | "sourceMap": true, 8 | "declaration": false, 9 | "downlevelIteration": true, 10 | "experimentalDecorators": true, 11 | "moduleResolution": "node", 12 | "importHelpers": true, 13 | "target": "es2015", 14 | "module": "es2020", 15 | "lib": [ 16 | "es2018", 17 | "dom" 18 | ] 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /angular-11-social-login/tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */ 2 | { 3 | "extends": "./tsconfig.json", 4 | "compilerOptions": { 5 | "outDir": "./out-tsc/spec", 6 | "types": [ 7 | "jasmine" 8 | ] 9 | }, 10 | "files": [ 11 | "src/test.ts", 12 | "src/polyfills.ts" 13 | ], 14 | "include": [ 15 | "src/**/*.spec.ts", 16 | "src/**/*.d.ts" 17 | ] 18 | } 19 | -------------------------------------------------------------------------------- /angular-11-social-login/tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "tslint:recommended", 3 | "rules": { 4 | "align": { 5 | "options": [ 6 | "parameters", 7 | "statements" 8 | ] 9 | }, 10 | "array-type": false, 11 | "arrow-return-shorthand": true, 12 | "curly": true, 13 | "deprecation": { 14 | "severity": "warning" 15 | }, 16 | "component-class-suffix": true, 17 | "contextual-lifecycle": true, 18 | "directive-class-suffix": true, 19 | "directive-selector": [ 20 | true, 21 | "attribute", 22 | "app", 23 | "camelCase" 24 | ], 25 | "component-selector": [ 26 | true, 27 | "element", 28 | "app", 29 | "kebab-case" 30 | ], 31 | "eofline": true, 32 | "import-blacklist": [ 33 | true, 34 | "rxjs/Rx" 35 | ], 36 | "import-spacing": true, 37 | "indent": { 38 | "options": [ 39 | "spaces" 40 | ] 41 | }, 42 | "max-classes-per-file": false, 43 | "max-line-length": [ 44 | true, 45 | 140 46 | ], 47 | "member-ordering": [ 48 | true, 49 | { 50 | "order": [ 51 | "static-field", 52 | "instance-field", 53 | "static-method", 54 | "instance-method" 55 | ] 56 | } 57 | ], 58 | "no-console": [ 59 | true, 60 | "debug", 61 | "info", 62 | "time", 63 | "timeEnd", 64 | "trace" 65 | ], 66 | "no-empty": false, 67 | "no-inferrable-types": [ 68 | true, 69 | "ignore-params" 70 | ], 71 | "no-non-null-assertion": true, 72 | "no-redundant-jsdoc": true, 73 | "no-switch-case-fall-through": true, 74 | "no-var-requires": false, 75 | "object-literal-key-quotes": [ 76 | true, 77 | "as-needed" 78 | ], 79 | "quotemark": [ 80 | true, 81 | "single" 82 | ], 83 | "semicolon": { 84 | "options": [ 85 | "always" 86 | ] 87 | }, 88 | "space-before-function-paren": { 89 | "options": { 90 | "anonymous": "never", 91 | "asyncArrow": "always", 92 | "constructor": "never", 93 | "method": "never", 94 | "named": "never" 95 | } 96 | }, 97 | "typedef": [ 98 | true, 99 | "call-signature" 100 | ], 101 | "typedef-whitespace": { 102 | "options": [ 103 | { 104 | "call-signature": "nospace", 105 | "index-signature": "nospace", 106 | "parameter": "nospace", 107 | "property-declaration": "nospace", 108 | "variable-declaration": "nospace" 109 | }, 110 | { 111 | "call-signature": "onespace", 112 | "index-signature": "onespace", 113 | "parameter": "onespace", 114 | "property-declaration": "onespace", 115 | "variable-declaration": "onespace" 116 | } 117 | ] 118 | }, 119 | "variable-name": { 120 | "options": [ 121 | "ban-keywords", 122 | "check-format", 123 | "allow-pascal-case" 124 | ] 125 | }, 126 | "whitespace": { 127 | "options": [ 128 | "check-branch", 129 | "check-decl", 130 | "check-operator", 131 | "check-separator", 132 | "check-type", 133 | "check-typecast" 134 | ] 135 | }, 136 | "no-conflicting-lifecycle": true, 137 | "no-host-metadata-property": true, 138 | "no-input-rename": true, 139 | "no-inputs-metadata-property": true, 140 | "no-output-native": true, 141 | "no-output-on-prefix": true, 142 | "no-output-rename": true, 143 | "no-outputs-metadata-property": true, 144 | "template-banana-in-box": true, 145 | "template-no-negated-async": true, 146 | "use-lifecycle-interface": true, 147 | "use-pipe-transform-interface": true 148 | }, 149 | "rulesDirectory": [ 150 | "codelyzer" 151 | ] 152 | } -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | # Docker Compose file Reference (https://docs.docker.com/compose/compose-file/) 2 | version: '3.7' 3 | 4 | # Define services 5 | services: 6 | # App backend service 7 | app-server: 8 | # Configuration for building the docker image for the backend service 9 | build: 10 | context: spring-boot-oauth2-social-login # Use an image built from the specified dockerfile in the `spring-boot-oauth2-social-login` directory. 11 | dockerfile: Dockerfile 12 | ports: 13 | - "8080:8080" # Forward the exposed port 8080 on the container to port 8080 on the host machine 14 | restart: always 15 | depends_on: 16 | - db # This service depends on mysql. Start that first. 17 | environment: # Pass environment variables to the service 18 | SPRING_DATASOURCE_URL: jdbc:mysql://db:3306/demo?useSSL=false&serverTimezone=UTC&useLegacyDatetimeCode=false&allowPublicKeyRetrieval=true 19 | SPRING_DATASOURCE_USERNAME: javachinna 20 | SPRING_DATASOURCE_PASSWORD: javachinna 21 | networks: # Networks to join (Services on the same network can communicate with each other using their name) 22 | - backend 23 | - frontend 24 | 25 | # Frontend Service 26 | app-client: 27 | build: 28 | context: angular-11-social-login # Use an image built from the specified dockerfile in the `angular-11-social-login` directory. 29 | dockerfile: Dockerfile 30 | ports: 31 | - "8081:80" # Map the exposed port 80 on the container to port 8081 on the host machine 32 | restart: always 33 | depends_on: 34 | - app-server 35 | networks: 36 | - frontend 37 | 38 | # Database Service (Mysql) 39 | db: 40 | image: mysql:8.0 41 | ports: 42 | - "3306:3306" 43 | restart: always 44 | environment: 45 | MYSQL_DATABASE: demo 46 | MYSQL_USER: javachinna 47 | MYSQL_PASSWORD: javachinna 48 | MYSQL_ROOT_PASSWORD: root 49 | networks: 50 | - backend 51 | 52 | # Networks to be created to facilitate communication between containers 53 | networks: 54 | backend: 55 | frontend: -------------------------------------------------------------------------------- /k8s/app-client.yml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 # API version 2 | kind: Deployment # Type of kubernetes resource 3 | metadata: 4 | name: social-login-app-client # Name of the kubernetes resource 5 | spec: 6 | replicas: 1 # No of replicas/pods to run 7 | selector: 8 | matchLabels: # This deployment applies to Pods matching the specified labels 9 | app: social-login-app-client 10 | template: # Template for creating the Pods in this deployment 11 | metadata: 12 | labels: # Labels that will be applied to all the Pods in this deployment 13 | app: social-login-app-client 14 | spec: # Spec for the containers that will run inside the Pods 15 | containers: 16 | - name: social-login-app-client 17 | image: javachinna/social-login-app-client:1.0.0 18 | imagePullPolicy: Always 19 | ports: 20 | - name: http 21 | containerPort: 80 # Should match the Port that the container listens on 22 | resources: 23 | limits: 24 | cpu: 0.2 25 | memory: "10Mi" 26 | --- 27 | apiVersion: v1 # API version 28 | kind: Service # Type of kubernetes resource 29 | metadata: 30 | name: social-login-app-client # Name of the kubernetes resource 31 | spec: 32 | type: NodePort # Exposes the service by opening a port on each node 33 | selector: 34 | app: social-login-app-client # Any Pod matching the label `app=social-login-app-client` will be picked up by this service 35 | ports: # Forward incoming connections on port 8081 to the target port 80 in the Pod 36 | - name: http 37 | port: 8081 38 | targetPort: 80 -------------------------------------------------------------------------------- /k8s/app-server.yml: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: apps/v1 # API version 3 | kind: Deployment # Type of kubernetes resource 4 | metadata: 5 | name: social-login-app-server # Name of the kubernetes resource 6 | labels: # Labels that will be applied to this resource 7 | app: social-login-app-server 8 | spec: 9 | replicas: 1 # No. of replicas/pods to run in this deployment 10 | selector: 11 | matchLabels: # The deployment applies to any pods mayching the specified labels 12 | app: social-login-app-server 13 | template: # Template for creating the pods in this deployment 14 | metadata: 15 | labels: # Labels that will be applied to each Pod in this deployment 16 | app: social-login-app-server 17 | spec: # Spec for the containers that will be run in the Pods 18 | containers: 19 | - name: social-login-app-server 20 | image: javachinna/social-login-app-server:1.0.0 21 | imagePullPolicy: Always 22 | ports: 23 | - name: http 24 | containerPort: 8080 # The port that the container exposes 25 | resources: 26 | limits: 27 | cpu: 0.2 28 | memory: "200Mi" 29 | env: # Environment variables supplied to the Pod 30 | - name: SPRING_DATASOURCE_USERNAME # Name of the environment variable 31 | valueFrom: # Get the value of environment variable from kubernetes secrets 32 | secretKeyRef: 33 | name: mysql-user-pass 34 | key: username 35 | - name: SPRING_DATASOURCE_PASSWORD 36 | valueFrom: 37 | secretKeyRef: 38 | name: mysql-user-pass 39 | key: password 40 | - name: SPRING_DATASOURCE_URL 41 | valueFrom: 42 | secretKeyRef: 43 | name: mysql-db-url 44 | key: url 45 | --- 46 | apiVersion: v1 # API version 47 | kind: Service # Type of the kubernetes resource 48 | metadata: 49 | name: social-login-app-server # Name of the kubernetes resource 50 | labels: # Labels that will be applied to this resource 51 | app: social-login-app-server 52 | spec: 53 | type: NodePort # The service will be exposed by opening a Port on each node and proxying it. 54 | selector: 55 | app: social-login-app-server # The service exposes Pods with label `app=social-login-app-server` 56 | ports: # Forward incoming connections on port 8080 to the target port 8080 57 | - name: http 58 | port: 8080 59 | targetPort: 8080 -------------------------------------------------------------------------------- /k8s/ingress-nginx-https.yml: -------------------------------------------------------------------------------- 1 | apiVersion: networking.k8s.io/v1 2 | kind: Ingress 3 | metadata: 4 | name: social-login-app-ingress 5 | annotations: 6 | kubernetes.io/ingress.class: nginx 7 | cert-manager.io/cluster-issuer: letsencrypt-prod 8 | spec: 9 | tls: 10 | - hosts: 11 | - client.javachinna.xyz 12 | - server.javachinna.xyz 13 | secretName: social-login-app-tls 14 | rules: 15 | - host: "client.javachinna.xyz" 16 | http: 17 | paths: 18 | - pathType: Prefix 19 | path: / 20 | backend: 21 | service: 22 | name: social-login-app-client 23 | port: 24 | number: 80 25 | - host: "server.javachinna.xyz" 26 | http: 27 | paths: 28 | - pathType: Prefix 29 | path: /api/ 30 | backend: 31 | service: 32 | name: social-login-app-server 33 | port: 34 | number: 8080 35 | - pathType: Prefix 36 | path: /oauth2/ 37 | backend: 38 | service: 39 | name: social-login-app-server 40 | port: 41 | number: 8080 -------------------------------------------------------------------------------- /k8s/ingress-nginx.yml: -------------------------------------------------------------------------------- 1 | apiVersion: networking.k8s.io/v1 2 | kind: Ingress 3 | metadata: 4 | name: social-login-app-ingress 5 | annotations: 6 | kubernetes.io/ingress.class: nginx 7 | spec: 8 | rules: 9 | - host: "client.javachinna.xyz" 10 | http: 11 | paths: 12 | - pathType: Prefix 13 | path: / 14 | backend: 15 | service: 16 | name: social-login-app-client 17 | port: 18 | number: 80 19 | - host: "server.javachinna.xyz" 20 | http: 21 | paths: 22 | - pathType: Prefix 23 | path: /api/ 24 | backend: 25 | service: 26 | name: social-login-app-server 27 | port: 28 | number: 8080 29 | - pathType: Prefix 30 | path: /oauth2/ 31 | backend: 32 | service: 33 | name: social-login-app-server 34 | port: 35 | number: 8080 -------------------------------------------------------------------------------- /k8s/mysql.yml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: PersistentVolume # Create a PersistentVolume 3 | metadata: 4 | name: mysql-pv 5 | labels: 6 | type: local 7 | spec: 8 | storageClassName: standard # Storage class. A PV Claim requesting the same storageClass can be bound to this volume. 9 | capacity: 10 | storage: 250Mi 11 | accessModes: 12 | - ReadWriteOnce 13 | hostPath: # hostPath PersistentVolume is used for development and testing. It uses a file/directory on the Node to emulate network-attached storage 14 | path: "/mnt/data" 15 | persistentVolumeReclaimPolicy: Retain # Retain the PersistentVolume even after PersistentVolumeClaim is deleted. The volume is considered “released”. But it is not yet available for another claim because the previous claimant’s data remains on the volume. 16 | --- 17 | apiVersion: v1 18 | kind: PersistentVolumeClaim # Create a PersistentVolumeClaim to request a PersistentVolume storage 19 | metadata: # Claim name and labels 20 | name: mysql-pv-claim 21 | labels: 22 | app: social-login-app 23 | spec: # Access mode and resource limits 24 | storageClassName: standard # Request a certain storage class 25 | accessModes: 26 | - ReadWriteOnce # ReadWriteOnce means the volume can be mounted as read-write by a single Node 27 | resources: 28 | requests: 29 | storage: 250Mi 30 | --- 31 | apiVersion: v1 # API version 32 | kind: Service # Type of kubernetes resource 33 | metadata: 34 | name: social-login-app-mysql # Name of the resource 35 | labels: # Labels that will be applied to the resource 36 | app: social-login-app 37 | spec: 38 | ports: 39 | - port: 3306 40 | selector: # Selects any Pod with labels `app=social-login-app,tier=mysql` 41 | app: social-login-app 42 | tier: mysql 43 | clusterIP: None 44 | --- 45 | apiVersion: apps/v1 46 | kind: Deployment # Type of the kubernetes resource 47 | metadata: 48 | name: social-login-app-mysql # Name of the deployment 49 | labels: # Labels applied to this deployment 50 | app: social-login-app 51 | spec: 52 | selector: 53 | matchLabels: # This deployment applies to the Pods matching the specified labels 54 | app: social-login-app 55 | tier: mysql 56 | strategy: 57 | type: Recreate 58 | template: # Template for the Pods in this deployment 59 | metadata: 60 | labels: # Labels to be applied to the Pods in this deployment 61 | app: social-login-app 62 | tier: mysql 63 | spec: # The spec for the containers that will be run inside the Pods in this deployment 64 | containers: 65 | - image: mysql:8.0 # The container image 66 | name: mysql 67 | env: # Environment variables passed to the container 68 | - name: MYSQL_ROOT_PASSWORD 69 | valueFrom: # Read environment variables from kubernetes secrets 70 | secretKeyRef: 71 | name: mysql-root-pass 72 | key: password 73 | - name: MYSQL_DATABASE 74 | valueFrom: 75 | secretKeyRef: 76 | name: mysql-db-url 77 | key: database 78 | - name: MYSQL_USER 79 | valueFrom: 80 | secretKeyRef: 81 | name: mysql-user-pass 82 | key: username 83 | - name: MYSQL_PASSWORD 84 | valueFrom: 85 | secretKeyRef: 86 | name: mysql-user-pass 87 | key: password 88 | ports: 89 | - containerPort: 3306 # The port that the container exposes 90 | name: mysql 91 | volumeMounts: 92 | - name: mysql-persistent-storage # This name should match the name specified in `volumes.name` 93 | mountPath: /var/lib/mysql 94 | volumes: # A PersistentVolume is mounted as a volume to the Pod 95 | - name: mysql-persistent-storage 96 | persistentVolumeClaim: 97 | claimName: mysql-pv-claim -------------------------------------------------------------------------------- /k8s/prod-issuer.yml: -------------------------------------------------------------------------------- 1 | apiVersion: cert-manager.io/v1 2 | kind: ClusterIssuer 3 | metadata: 4 | name: letsencrypt-prod 5 | spec: 6 | acme: 7 | # Email address used for ACME registration 8 | email: java4chinna@gmail.com 9 | server: https://acme-v02.api.letsencrypt.org/directory 10 | privateKeySecretRef: 11 | # Name of a secret used to store the ACME account private key 12 | name: letsencrypt-prod-private-key 13 | # Add a single challenge solver, HTTP01 using nginx 14 | solvers: 15 | - http01: 16 | ingress: 17 | class: nginx -------------------------------------------------------------------------------- /k8s/staging-issuer.yml: -------------------------------------------------------------------------------- 1 | apiVersion: cert-manager.io/v1 2 | kind: ClusterIssuer 3 | metadata: 4 | name: letsencrypt-staging 5 | spec: 6 | acme: 7 | # Email address used for ACME registration 8 | email: java4chinna@gmail.com 9 | server: https://acme-staging-v02.api.letsencrypt.org/directory 10 | privateKeySecretRef: 11 | # Name of a secret used to store the ACME account private key 12 | name: letsencrypt-staging-private-key 13 | # Add a single challenge solver, HTTP01 using nginx 14 | solvers: 15 | - http01: 16 | ingress: 17 | class: nginx -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/.mvn/wrapper/MavenWrapperDownloader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2007-present the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | import java.net.*; 17 | import java.io.*; 18 | import java.nio.channels.*; 19 | import java.util.Properties; 20 | 21 | public class MavenWrapperDownloader { 22 | 23 | private static final String WRAPPER_VERSION = "0.5.6"; 24 | /** 25 | * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. 26 | */ 27 | private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" 28 | + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; 29 | 30 | /** 31 | * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to 32 | * use instead of the default one. 33 | */ 34 | private static final String MAVEN_WRAPPER_PROPERTIES_PATH = 35 | ".mvn/wrapper/maven-wrapper.properties"; 36 | 37 | /** 38 | * Path where the maven-wrapper.jar will be saved to. 39 | */ 40 | private static final String MAVEN_WRAPPER_JAR_PATH = 41 | ".mvn/wrapper/maven-wrapper.jar"; 42 | 43 | /** 44 | * Name of the property which should be used to override the default download url for the wrapper. 45 | */ 46 | private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; 47 | 48 | public static void main(String args[]) { 49 | System.out.println("- Downloader started"); 50 | File baseDirectory = new File(args[0]); 51 | System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); 52 | 53 | // If the maven-wrapper.properties exists, read it and check if it contains a custom 54 | // wrapperUrl parameter. 55 | File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); 56 | String url = DEFAULT_DOWNLOAD_URL; 57 | if(mavenWrapperPropertyFile.exists()) { 58 | FileInputStream mavenWrapperPropertyFileInputStream = null; 59 | try { 60 | mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); 61 | Properties mavenWrapperProperties = new Properties(); 62 | mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); 63 | url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); 64 | } catch (IOException e) { 65 | System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); 66 | } finally { 67 | try { 68 | if(mavenWrapperPropertyFileInputStream != null) { 69 | mavenWrapperPropertyFileInputStream.close(); 70 | } 71 | } catch (IOException e) { 72 | // Ignore ... 73 | } 74 | } 75 | } 76 | System.out.println("- Downloading from: " + url); 77 | 78 | File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); 79 | if(!outputFile.getParentFile().exists()) { 80 | if(!outputFile.getParentFile().mkdirs()) { 81 | System.out.println( 82 | "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); 83 | } 84 | } 85 | System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); 86 | try { 87 | downloadFileFromURL(url, outputFile); 88 | System.out.println("Done"); 89 | System.exit(0); 90 | } catch (Throwable e) { 91 | System.out.println("- Error downloading"); 92 | e.printStackTrace(); 93 | System.exit(1); 94 | } 95 | } 96 | 97 | private static void downloadFileFromURL(String urlString, File destination) throws Exception { 98 | if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { 99 | String username = System.getenv("MVNW_USERNAME"); 100 | char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); 101 | Authenticator.setDefault(new Authenticator() { 102 | @Override 103 | protected PasswordAuthentication getPasswordAuthentication() { 104 | return new PasswordAuthentication(username, password); 105 | } 106 | }); 107 | } 108 | URL website = new URL(urlString); 109 | ReadableByteChannel rbc; 110 | rbc = Channels.newChannel(website.openStream()); 111 | FileOutputStream fos = new FileOutputStream(destination); 112 | fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); 113 | fos.close(); 114 | rbc.close(); 115 | } 116 | 117 | } 118 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaChinna/angular-spring-boot-razorpay-integration/68b6ec7b500294c1d25a645e271ce2c7954d20ce/spring-boot-oauth2-social-login/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip 2 | wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar 3 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/Dockerfile: -------------------------------------------------------------------------------- 1 | #### Stage 1: Build the application 2 | FROM openjdk:11-jdk-slim as build 3 | 4 | # Set the current working directory inside the image 5 | WORKDIR /app 6 | 7 | # Copy maven executable to the image 8 | COPY mvnw . 9 | COPY .mvn .mvn 10 | 11 | # Copy the pom.xml file 12 | COPY pom.xml . 13 | 14 | # Build all the dependencies in preparation to go offline. 15 | # This is a separate step so the dependencies will be cached unless 16 | # the pom.xml file has changed. 17 | RUN ./mvnw dependency:go-offline -B 18 | 19 | # Copy the project source 20 | COPY src src 21 | 22 | # Package the application 23 | RUN ./mvnw package -DskipTests 24 | RUN mkdir -p target/dependency && (cd target/dependency; jar -xf ../*.jar) 25 | 26 | #### Stage 2: A minimal docker image with command to run the app 27 | FROM openjdk:11-jre-slim 28 | 29 | ARG DEPENDENCY=/app/target/dependency 30 | 31 | # Copy project dependencies from the build stage 32 | COPY --from=build ${DEPENDENCY}/BOOT-INF/lib /app/lib 33 | COPY --from=build ${DEPENDENCY}/META-INF /app/META-INF 34 | COPY --from=build ${DEPENDENCY}/BOOT-INF/classes /app 35 | 36 | ENTRYPOINT ["java","-cp","app:app/lib/*","com.javachinna.DemoApplication"] -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.4.0 9 | 10 | 11 | com.javachinna 12 | demo 13 | 1.1.0 14 | demo 15 | Demo project for Spring Boot 16 | 17 | 18 | 11 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-data-jpa 25 | 26 | 27 | org.springframework.boot 28 | spring-boot-starter-oauth2-client 29 | 30 | 31 | org.springframework.boot 32 | spring-boot-starter-web 33 | 34 | 35 | org.springframework.boot 36 | spring-boot-starter-validation 37 | 38 | 39 | io.jsonwebtoken 40 | jjwt 41 | 0.9.1 42 | 43 | 44 | 45 | mysql 46 | mysql-connector-java 47 | 48 | 49 | org.springframework.boot 50 | spring-boot-starter-test 51 | test 52 | 53 | 54 | org.springframework.security 55 | spring-security-test 56 | test 57 | 58 | 59 | org.springframework.boot 60 | spring-boot-devtools 61 | 62 | 63 | org.projectlombok 64 | lombok 65 | 66 | 67 | org.springframework.boot 68 | spring-boot-configuration-processor 69 | true 70 | 71 | 72 | dev.samstevens.totp 73 | totp-spring-boot-starter 74 | 1.7.1 75 | 76 | 77 | com.razorpay 78 | razorpay-java 79 | 1.3.9 80 | 81 | 82 | 83 | 84 | 85 | org.springframework.boot 86 | spring-boot-maven-plugin 87 | 88 | 89 | 90 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/DemoApplication.java: -------------------------------------------------------------------------------- 1 | package com.javachinna; 2 | 3 | import org.springframework.boot.autoconfigure.SpringBootApplication; 4 | import org.springframework.boot.builder.SpringApplicationBuilder; 5 | import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; 6 | import org.springframework.data.jpa.repository.config.EnableJpaRepositories; 7 | import org.springframework.transaction.annotation.EnableTransactionManagement; 8 | 9 | @SpringBootApplication(scanBasePackages = "com.javachinna") 10 | @EnableJpaRepositories 11 | @EnableTransactionManagement 12 | public class DemoApplication extends SpringBootServletInitializer { 13 | 14 | public static void main(String[] args) { 15 | SpringApplicationBuilder app = new SpringApplicationBuilder(DemoApplication.class); 16 | app.run(); 17 | } 18 | 19 | @Override 20 | protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { 21 | return application.sources(DemoApplication.class); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/config/AppProperties.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.config; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import org.springframework.boot.context.properties.ConfigurationProperties; 7 | import org.springframework.stereotype.Component; 8 | 9 | @Component 10 | @ConfigurationProperties(prefix = "app") 11 | public class AppProperties { 12 | private final Auth auth = new Auth(); 13 | private final OAuth2 oauth2 = new OAuth2(); 14 | 15 | public static class Auth { 16 | private String tokenSecret; 17 | private long tokenExpirationMsec; 18 | 19 | public String getTokenSecret() { 20 | return tokenSecret; 21 | } 22 | 23 | public void setTokenSecret(String tokenSecret) { 24 | this.tokenSecret = tokenSecret; 25 | } 26 | 27 | public long getTokenExpirationMsec() { 28 | return tokenExpirationMsec; 29 | } 30 | 31 | public void setTokenExpirationMsec(long tokenExpirationMsec) { 32 | this.tokenExpirationMsec = tokenExpirationMsec; 33 | } 34 | } 35 | 36 | public static final class OAuth2 { 37 | private List authorizedRedirectUris = new ArrayList<>(); 38 | 39 | public List getAuthorizedRedirectUris() { 40 | return authorizedRedirectUris; 41 | } 42 | 43 | public OAuth2 authorizedRedirectUris(List authorizedRedirectUris) { 44 | this.authorizedRedirectUris = authorizedRedirectUris; 45 | return this; 46 | } 47 | } 48 | 49 | public Auth getAuth() { 50 | return auth; 51 | } 52 | 53 | public OAuth2 getOauth2() { 54 | return oauth2; 55 | } 56 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/config/CurrentUser.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.config; 2 | 3 | import java.lang.annotation.Documented; 4 | import java.lang.annotation.ElementType; 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import java.lang.annotation.Target; 8 | 9 | import org.springframework.security.core.annotation.AuthenticationPrincipal; 10 | 11 | @Target({ ElementType.PARAMETER, ElementType.TYPE }) 12 | @Retention(RetentionPolicy.RUNTIME) 13 | @Documented 14 | @AuthenticationPrincipal 15 | public @interface CurrentUser { 16 | 17 | } 18 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/config/RazorPayClientConfig.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.config; 2 | 3 | import org.springframework.boot.context.properties.ConfigurationProperties; 4 | import org.springframework.stereotype.Component; 5 | 6 | import lombok.Data; 7 | 8 | @Data 9 | @Component 10 | @ConfigurationProperties(prefix = "razorpay") 11 | public class RazorPayClientConfig { 12 | private String key; 13 | private String secret; 14 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/config/RestAuthenticationEntryPoint.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.config; 2 | 3 | import java.io.IOException; 4 | 5 | import javax.servlet.ServletException; 6 | import javax.servlet.http.HttpServletRequest; 7 | import javax.servlet.http.HttpServletResponse; 8 | 9 | import org.slf4j.Logger; 10 | import org.slf4j.LoggerFactory; 11 | import org.springframework.security.core.AuthenticationException; 12 | import org.springframework.security.web.AuthenticationEntryPoint; 13 | 14 | public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint { 15 | 16 | private static final Logger logger = LoggerFactory.getLogger(RestAuthenticationEntryPoint.class); 17 | 18 | @Override 19 | public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException { 20 | logger.error("Responding with unauthorized error. Message - {}", e.getMessage()); 21 | httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getLocalizedMessage()); 22 | } 23 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/config/SetupDataLoader.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.config; 2 | 3 | import java.util.Calendar; 4 | import java.util.Date; 5 | import java.util.Set; 6 | 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.context.ApplicationListener; 9 | import org.springframework.context.event.ContextRefreshedEvent; 10 | import org.springframework.security.crypto.password.PasswordEncoder; 11 | import org.springframework.stereotype.Component; 12 | import org.springframework.transaction.annotation.Transactional; 13 | 14 | import com.javachinna.dto.SocialProvider; 15 | import com.javachinna.model.Role; 16 | import com.javachinna.model.User; 17 | import com.javachinna.repo.RoleRepository; 18 | import com.javachinna.repo.UserRepository; 19 | 20 | @Component 21 | public class SetupDataLoader implements ApplicationListener { 22 | 23 | private boolean alreadySetup = false; 24 | 25 | @Autowired 26 | private UserRepository userRepository; 27 | 28 | @Autowired 29 | private RoleRepository roleRepository; 30 | 31 | @Autowired 32 | private PasswordEncoder passwordEncoder; 33 | 34 | @Override 35 | @Transactional 36 | public void onApplicationEvent(final ContextRefreshedEvent event) { 37 | if (alreadySetup) { 38 | return; 39 | } 40 | // Create initial roles 41 | Role userRole = createRoleIfNotFound(Role.ROLE_USER); 42 | Role adminRole = createRoleIfNotFound(Role.ROLE_ADMIN); 43 | Role modRole = createRoleIfNotFound(Role.ROLE_MODERATOR); 44 | createUserIfNotFound("admin@javachinna.com", Set.of(userRole, adminRole, modRole)); 45 | alreadySetup = true; 46 | } 47 | 48 | @Transactional 49 | private final User createUserIfNotFound(final String email, Set roles) { 50 | User user = userRepository.findByEmail(email); 51 | if (user == null) { 52 | user = new User(); 53 | user.setDisplayName("Admin"); 54 | user.setEmail(email); 55 | user.setPassword(passwordEncoder.encode("admin@")); 56 | user.setRoles(roles); 57 | user.setProvider(SocialProvider.LOCAL.getProviderType()); 58 | user.setEnabled(true); 59 | Date now = Calendar.getInstance().getTime(); 60 | user.setCreatedDate(now); 61 | user.setModifiedDate(now); 62 | user = userRepository.save(user); 63 | } 64 | return user; 65 | } 66 | 67 | @Transactional 68 | private final Role createRoleIfNotFound(final String name) { 69 | Role role = roleRepository.findByName(name); 70 | if (role == null) { 71 | role = roleRepository.save(new Role(name)); 72 | } 73 | return role; 74 | } 75 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/config/WebConfig.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.config; 2 | 3 | import java.util.Locale; 4 | 5 | import org.springframework.context.MessageSource; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.context.support.ReloadableResourceBundleMessageSource; 9 | import org.springframework.validation.Validator; 10 | import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; 11 | import org.springframework.web.servlet.LocaleResolver; 12 | import org.springframework.web.servlet.config.annotation.CorsRegistry; 13 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 14 | import org.springframework.web.servlet.i18n.CookieLocaleResolver; 15 | 16 | @Configuration 17 | public class WebConfig implements WebMvcConfigurer { 18 | 19 | private final long MAX_AGE_SECS = 3600; 20 | 21 | @Override 22 | public void addCorsMappings(CorsRegistry registry) { 23 | registry.addMapping("/**").allowedOrigins("*").allowedMethods("HEAD", "OPTIONS", "GET", "POST", "PUT", "PATCH", "DELETE").maxAge(MAX_AGE_SECS); 24 | } 25 | 26 | @Bean 27 | public MessageSource messageSource() { 28 | ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); 29 | messageSource.setBasename("classpath:messages"); 30 | messageSource.setDefaultEncoding("UTF-8"); 31 | return messageSource; 32 | } 33 | 34 | @Bean 35 | public LocaleResolver localeResolver() { 36 | final CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver(); 37 | cookieLocaleResolver.setDefaultLocale(Locale.ENGLISH); 38 | return cookieLocaleResolver; 39 | } 40 | 41 | @Override 42 | public Validator getValidator() { 43 | LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); 44 | validator.setValidationMessageSource(messageSource()); 45 | return validator; 46 | } 47 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/controller/AuthController.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.controller; 2 | 3 | import static dev.samstevens.totp.util.Utils.getDataUriForImage; 4 | 5 | import javax.validation.Valid; 6 | import javax.validation.constraints.NotEmpty; 7 | 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.http.HttpStatus; 10 | import org.springframework.http.ResponseEntity; 11 | import org.springframework.security.access.prepost.PreAuthorize; 12 | import org.springframework.security.authentication.AuthenticationManager; 13 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 14 | import org.springframework.security.core.Authentication; 15 | import org.springframework.security.core.context.SecurityContextHolder; 16 | import org.springframework.web.bind.annotation.PostMapping; 17 | import org.springframework.web.bind.annotation.RequestBody; 18 | import org.springframework.web.bind.annotation.RequestMapping; 19 | import org.springframework.web.bind.annotation.RestController; 20 | 21 | import com.javachinna.config.CurrentUser; 22 | import com.javachinna.dto.ApiResponse; 23 | import com.javachinna.dto.JwtAuthenticationResponse; 24 | import com.javachinna.dto.LocalUser; 25 | import com.javachinna.dto.LoginRequest; 26 | import com.javachinna.dto.SignUpRequest; 27 | import com.javachinna.dto.SignUpResponse; 28 | import com.javachinna.exception.UserAlreadyExistAuthenticationException; 29 | import com.javachinna.model.User; 30 | import com.javachinna.security.jwt.TokenProvider; 31 | import com.javachinna.service.UserService; 32 | import com.javachinna.util.GeneralUtils; 33 | 34 | import dev.samstevens.totp.code.CodeVerifier; 35 | import dev.samstevens.totp.exceptions.QrGenerationException; 36 | import dev.samstevens.totp.qr.QrData; 37 | import dev.samstevens.totp.qr.QrDataFactory; 38 | import dev.samstevens.totp.qr.QrGenerator; 39 | import lombok.extern.slf4j.Slf4j; 40 | 41 | @Slf4j 42 | @RestController 43 | @RequestMapping("/api/auth") 44 | public class AuthController { 45 | 46 | @Autowired 47 | AuthenticationManager authenticationManager; 48 | 49 | @Autowired 50 | UserService userService; 51 | 52 | @Autowired 53 | TokenProvider tokenProvider; 54 | 55 | @Autowired 56 | private QrDataFactory qrDataFactory; 57 | 58 | @Autowired 59 | private QrGenerator qrGenerator; 60 | 61 | @Autowired 62 | private CodeVerifier verifier; 63 | 64 | @PostMapping("/signin") 65 | public ResponseEntity authenticateUser(@Valid @RequestBody LoginRequest loginRequest) { 66 | Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getEmail(), loginRequest.getPassword())); 67 | SecurityContextHolder.getContext().setAuthentication(authentication); 68 | LocalUser localUser = (LocalUser) authentication.getPrincipal(); 69 | boolean authenticated = !localUser.getUser().isUsing2FA(); 70 | String jwt = tokenProvider.createToken(localUser, authenticated); 71 | return ResponseEntity.ok(new JwtAuthenticationResponse(jwt, authenticated, authenticated ? GeneralUtils.buildUserInfo(localUser) : null)); 72 | } 73 | 74 | @PostMapping("/signup") 75 | public ResponseEntity registerUser(@Valid @RequestBody SignUpRequest signUpRequest) { 76 | try { 77 | User user = userService.registerNewUser(signUpRequest); 78 | if (signUpRequest.isUsing2FA()) { 79 | QrData data = qrDataFactory.newBuilder().label(user.getEmail()).secret(user.getSecret()).issuer("JavaChinna").build(); 80 | // Generate the QR code image data as a base64 string which can 81 | // be used in an tag: 82 | String qrCodeImage = getDataUriForImage(qrGenerator.generate(data), qrGenerator.getImageMimeType()); 83 | return ResponseEntity.ok().body(new SignUpResponse(true, qrCodeImage)); 84 | } 85 | } catch (UserAlreadyExistAuthenticationException e) { 86 | log.error("Exception Ocurred", e); 87 | return new ResponseEntity<>(new ApiResponse(false, "Email Address already in use!"), HttpStatus.BAD_REQUEST); 88 | } catch (QrGenerationException e) { 89 | log.error("QR Generation Exception Ocurred", e); 90 | return new ResponseEntity<>(new ApiResponse(false, "Unable to generate QR code!"), HttpStatus.BAD_REQUEST); 91 | } 92 | return ResponseEntity.ok().body(new ApiResponse(true, "User registered successfully")); 93 | } 94 | 95 | @PostMapping("/verify") 96 | @PreAuthorize("hasRole('PRE_VERIFICATION_USER')") 97 | public ResponseEntity verifyCode(@NotEmpty @RequestBody String code, @CurrentUser LocalUser user) { 98 | if (!verifier.isValidCode(user.getUser().getSecret(), code)) { 99 | return new ResponseEntity<>(new ApiResponse(false, "Invalid Code!"), HttpStatus.BAD_REQUEST); 100 | } 101 | String jwt = tokenProvider.createToken(user, true); 102 | return ResponseEntity.ok(new JwtAuthenticationResponse(jwt, true, GeneralUtils.buildUserInfo(user))); 103 | } 104 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/controller/OrderController.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.controller; 2 | 3 | import java.math.BigDecimal; 4 | import java.math.RoundingMode; 5 | 6 | import org.json.JSONObject; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.http.HttpStatus; 9 | import org.springframework.http.ResponseEntity; 10 | import org.springframework.web.bind.annotation.PostMapping; 11 | import org.springframework.web.bind.annotation.PutMapping; 12 | import org.springframework.web.bind.annotation.RequestBody; 13 | import org.springframework.web.bind.annotation.RequestMapping; 14 | import org.springframework.web.bind.annotation.RestController; 15 | 16 | import com.javachinna.config.CurrentUser; 17 | import com.javachinna.config.RazorPayClientConfig; 18 | import com.javachinna.dto.ApiResponse; 19 | import com.javachinna.dto.LocalUser; 20 | import com.javachinna.dto.payment.OrderRequest; 21 | import com.javachinna.dto.payment.OrderResponse; 22 | import com.javachinna.dto.payment.PaymentResponse; 23 | import com.javachinna.service.OrderService; 24 | import com.razorpay.Order; 25 | import com.razorpay.RazorpayClient; 26 | import com.razorpay.RazorpayException; 27 | 28 | import lombok.extern.slf4j.Slf4j; 29 | 30 | /** 31 | * 32 | * @author Chinna 33 | */ 34 | @Slf4j 35 | @RestController 36 | @RequestMapping("/api") 37 | public class OrderController { 38 | 39 | private RazorpayClient client; 40 | 41 | private RazorPayClientConfig razorPayClientConfig; 42 | 43 | @Autowired 44 | private OrderService orderService; 45 | 46 | @Autowired 47 | public OrderController(RazorPayClientConfig razorpayClientConfig) throws RazorpayException { 48 | this.razorPayClientConfig = razorpayClientConfig; 49 | this.client = new RazorpayClient(razorpayClientConfig.getKey(), razorpayClientConfig.getSecret()); 50 | } 51 | 52 | @PostMapping("/order") 53 | public ResponseEntity createOrder(@RequestBody OrderRequest orderRequest, @CurrentUser LocalUser user) { 54 | OrderResponse razorPay = null; 55 | try { 56 | // The transaction amount is expressed in the currency subunit, such 57 | // as paise (in case of INR) 58 | String amountInPaise = convertRupeeToPaise(orderRequest.getAmount()); 59 | // Create an order in RazorPay and get the order id 60 | Order order = createRazorPayOrder(amountInPaise); 61 | razorPay = getOrderResponse((String) order.get("id"), amountInPaise); 62 | // Save order in the database 63 | orderService.saveOrder(razorPay.getRazorpayOrderId(), user.getUser().getId()); 64 | } catch (RazorpayException e) { 65 | log.error("Exception while create payment order", e); 66 | return new ResponseEntity<>(new ApiResponse(false, "Error while create payment order: " + e.getMessage()), HttpStatus.EXPECTATION_FAILED); 67 | } 68 | return ResponseEntity.ok(razorPay); 69 | } 70 | 71 | @PutMapping("/order") 72 | public ResponseEntity updateOrder(@RequestBody PaymentResponse paymentResponse) { 73 | String errorMsg = orderService.validateAndUpdateOrder(paymentResponse.getRazorpayOrderId(), paymentResponse.getRazorpayPaymentId(), paymentResponse.getRazorpaySignature(), 74 | razorPayClientConfig.getSecret()); 75 | if (errorMsg != null) { 76 | return new ResponseEntity<>(new ApiResponse(false, errorMsg), HttpStatus.BAD_REQUEST); 77 | } 78 | return ResponseEntity.ok(new ApiResponse(true, paymentResponse.getRazorpayPaymentId())); 79 | } 80 | 81 | private OrderResponse getOrderResponse(String orderId, String amountInPaise) { 82 | OrderResponse razorPay = new OrderResponse(); 83 | razorPay.setApplicationFee(amountInPaise); 84 | razorPay.setRazorpayOrderId(orderId); 85 | razorPay.setSecretKey(razorPayClientConfig.getKey()); 86 | return razorPay; 87 | } 88 | 89 | private Order createRazorPayOrder(String amount) throws RazorpayException { 90 | JSONObject options = new JSONObject(); 91 | options.put("amount", amount); 92 | options.put("currency", "INR"); 93 | options.put("receipt", "txn_123456"); 94 | return client.Orders.create(options); 95 | } 96 | 97 | private String convertRupeeToPaise(String paise) { 98 | BigDecimal b = new BigDecimal(paise); 99 | BigDecimal value = b.multiply(new BigDecimal("100")); 100 | return value.setScale(0, RoundingMode.UP).toString(); 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.controller; 2 | 3 | import org.springframework.http.ResponseEntity; 4 | import org.springframework.security.access.prepost.PreAuthorize; 5 | import org.springframework.web.bind.annotation.GetMapping; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | import com.javachinna.config.CurrentUser; 10 | import com.javachinna.dto.LocalUser; 11 | import com.javachinna.util.GeneralUtils; 12 | 13 | @RestController 14 | @RequestMapping("/api") 15 | public class UserController { 16 | 17 | @GetMapping("/user/me") 18 | @PreAuthorize("hasRole('USER')") 19 | public ResponseEntity getCurrentUser(@CurrentUser LocalUser user) { 20 | return ResponseEntity.ok(GeneralUtils.buildUserInfo(user)); 21 | } 22 | 23 | @GetMapping("/all") 24 | public ResponseEntity getContent() { 25 | return ResponseEntity.ok("Public content goes here"); 26 | } 27 | 28 | @GetMapping("/user") 29 | @PreAuthorize("hasRole('USER')") 30 | public ResponseEntity getUserContent() { 31 | return ResponseEntity.ok("User content goes here"); 32 | } 33 | 34 | @GetMapping("/admin") 35 | @PreAuthorize("hasRole('ADMIN')") 36 | public ResponseEntity getAdminContent() { 37 | return ResponseEntity.ok("Admin content goes here"); 38 | } 39 | 40 | @GetMapping("/mod") 41 | @PreAuthorize("hasRole('MODERATOR')") 42 | public ResponseEntity getModeratorContent() { 43 | return ResponseEntity.ok("Moderator content goes here"); 44 | } 45 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/dto/ApiResponse.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.dto; 2 | 3 | import lombok.Value; 4 | 5 | @Value 6 | public class ApiResponse { 7 | private Boolean success; 8 | private String message; 9 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/dto/JwtAuthenticationResponse.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.dto; 2 | 3 | import lombok.Value; 4 | 5 | @Value 6 | public class JwtAuthenticationResponse { 7 | private String accessToken; 8 | private boolean authenticated; 9 | private UserInfo user; 10 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/dto/LocalUser.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.dto; 2 | 3 | import java.util.Collection; 4 | import java.util.Map; 5 | 6 | import org.springframework.security.core.GrantedAuthority; 7 | import org.springframework.security.core.userdetails.User; 8 | import org.springframework.security.oauth2.core.oidc.OidcIdToken; 9 | import org.springframework.security.oauth2.core.oidc.OidcUserInfo; 10 | import org.springframework.security.oauth2.core.oidc.user.OidcUser; 11 | import org.springframework.security.oauth2.core.user.OAuth2User; 12 | 13 | import com.javachinna.util.GeneralUtils; 14 | 15 | /** 16 | * 17 | * @author Chinna 18 | * 19 | */ 20 | public class LocalUser extends User implements OAuth2User, OidcUser { 21 | 22 | /** 23 | * 24 | */ 25 | private static final long serialVersionUID = -2845160792248762779L; 26 | private final OidcIdToken idToken; 27 | private final OidcUserInfo userInfo; 28 | private Map attributes; 29 | private com.javachinna.model.User user; 30 | 31 | public LocalUser(final String userID, final String password, final boolean enabled, final boolean accountNonExpired, final boolean credentialsNonExpired, 32 | final boolean accountNonLocked, final Collection authorities, final com.javachinna.model.User user) { 33 | this(userID, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities, user, null, null); 34 | } 35 | 36 | public LocalUser(final String userID, final String password, final boolean enabled, final boolean accountNonExpired, final boolean credentialsNonExpired, 37 | final boolean accountNonLocked, final Collection authorities, final com.javachinna.model.User user, OidcIdToken idToken, 38 | OidcUserInfo userInfo) { 39 | super(userID, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); 40 | this.user = user; 41 | this.idToken = idToken; 42 | this.userInfo = userInfo; 43 | } 44 | 45 | public static LocalUser create(com.javachinna.model.User user, Map attributes, OidcIdToken idToken, OidcUserInfo userInfo) { 46 | LocalUser localUser = new LocalUser(user.getEmail(), user.getPassword(), user.isEnabled(), true, true, true, GeneralUtils.buildSimpleGrantedAuthorities(user.getRoles()), 47 | user, idToken, userInfo); 48 | localUser.setAttributes(attributes); 49 | return localUser; 50 | } 51 | 52 | public void setAttributes(Map attributes) { 53 | this.attributes = attributes; 54 | } 55 | 56 | @Override 57 | public String getName() { 58 | return this.user.getDisplayName(); 59 | } 60 | 61 | @Override 62 | public Map getAttributes() { 63 | return this.attributes; 64 | } 65 | 66 | @Override 67 | public Map getClaims() { 68 | return this.attributes; 69 | } 70 | 71 | @Override 72 | public OidcUserInfo getUserInfo() { 73 | return this.userInfo; 74 | } 75 | 76 | @Override 77 | public OidcIdToken getIdToken() { 78 | return this.idToken; 79 | } 80 | 81 | public com.javachinna.model.User getUser() { 82 | return user; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/dto/LoginRequest.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.dto; 2 | 3 | import javax.validation.constraints.NotBlank; 4 | 5 | import lombok.AllArgsConstructor; 6 | import lombok.Data; 7 | 8 | @Data 9 | @AllArgsConstructor 10 | public class LoginRequest { 11 | @NotBlank 12 | private String email; 13 | 14 | @NotBlank 15 | private String password; 16 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/dto/SignUpRequest.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.dto; 2 | 3 | import javax.validation.constraints.NotEmpty; 4 | import javax.validation.constraints.Size; 5 | 6 | import com.javachinna.validator.PasswordMatches; 7 | 8 | import lombok.Data; 9 | 10 | /** 11 | * @author Chinna 12 | * @since 26/3/18 13 | */ 14 | @Data 15 | @PasswordMatches 16 | public class SignUpRequest { 17 | 18 | private Long userID; 19 | 20 | private String providerUserId; 21 | 22 | @NotEmpty 23 | private String displayName; 24 | 25 | @NotEmpty 26 | private String email; 27 | 28 | private SocialProvider socialProvider; 29 | 30 | @Size(min = 6, message = "{Size.userDto.password}") 31 | private String password; 32 | 33 | @NotEmpty 34 | private String matchingPassword; 35 | 36 | private boolean using2FA; 37 | 38 | public SignUpRequest(String providerUserId, String displayName, String email, String password, String matchingPassword, SocialProvider socialProvider) { 39 | this.providerUserId = providerUserId; 40 | this.displayName = displayName; 41 | this.email = email; 42 | this.password = password; 43 | this.matchingPassword = matchingPassword; 44 | this.socialProvider = socialProvider; 45 | } 46 | 47 | public static Builder getBuilder() { 48 | return new Builder(); 49 | } 50 | 51 | public static class Builder { 52 | private String providerUserID; 53 | private String displayName; 54 | private String email; 55 | private String password; 56 | private String matchingPassword; 57 | private SocialProvider socialProvider; 58 | 59 | public Builder addProviderUserID(final String userID) { 60 | this.providerUserID = userID; 61 | return this; 62 | } 63 | 64 | public Builder addDisplayName(final String displayName) { 65 | this.displayName = displayName; 66 | return this; 67 | } 68 | 69 | public Builder addEmail(final String email) { 70 | this.email = email; 71 | return this; 72 | } 73 | 74 | public Builder addPassword(final String password) { 75 | this.password = password; 76 | return this; 77 | } 78 | 79 | public Builder addMatchingPassword(final String matchingPassword) { 80 | this.matchingPassword = matchingPassword; 81 | return this; 82 | } 83 | 84 | public Builder addSocialProvider(final SocialProvider socialProvider) { 85 | this.socialProvider = socialProvider; 86 | return this; 87 | } 88 | 89 | public SignUpRequest build() { 90 | return new SignUpRequest(providerUserID, displayName, email, password, matchingPassword, socialProvider); 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/dto/SignUpResponse.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.dto; 2 | 3 | import lombok.Value; 4 | 5 | @Value 6 | public class SignUpResponse { 7 | private boolean using2FA; 8 | private String qrCodeImage; 9 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/dto/SocialProvider.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.dto; 2 | 3 | /** 4 | * @author Chinna 5 | * @since 26/3/18 6 | */ 7 | public enum SocialProvider { 8 | 9 | FACEBOOK("facebook"), TWITTER("twitter"), LINKEDIN("linkedin"), GOOGLE("google"), GITHUB("github"), LOCAL("local"); 10 | 11 | private String providerType; 12 | 13 | public String getProviderType() { 14 | return providerType; 15 | } 16 | 17 | SocialProvider(final String providerType) { 18 | this.providerType = providerType; 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/dto/UserInfo.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.dto; 2 | 3 | import java.util.List; 4 | 5 | import lombok.Value; 6 | 7 | @Value 8 | public class UserInfo { 9 | private String id, displayName, email; 10 | private List roles; 11 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/dto/payment/OrderRequest.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.dto.payment; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class OrderRequest { 7 | private String customerName; 8 | private String email; 9 | private String phoneNumber; 10 | private String amount; 11 | } 12 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/dto/payment/OrderResponse.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.dto.payment; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class OrderResponse { 7 | private String applicationFee; 8 | private String razorpayOrderId; 9 | private String secretKey; 10 | } 11 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/dto/payment/PaymentResponse.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.dto.payment; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class PaymentResponse { 7 | private String razorpayOrderId; 8 | private String razorpayPaymentId; 9 | private String razorpaySignature; 10 | } 11 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/exception/BadRequestException.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.exception; 2 | 3 | import org.springframework.http.HttpStatus; 4 | import org.springframework.web.bind.annotation.ResponseStatus; 5 | 6 | @ResponseStatus(HttpStatus.BAD_REQUEST) 7 | public class BadRequestException extends RuntimeException { 8 | /** 9 | * 10 | */ 11 | private static final long serialVersionUID = 752858877580882829L; 12 | 13 | public BadRequestException(String message) { 14 | super(message); 15 | } 16 | 17 | public BadRequestException(String message, Throwable cause) { 18 | super(message, cause); 19 | } 20 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/exception/OAuth2AuthenticationProcessingException.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.exception; 2 | 3 | import org.springframework.security.core.AuthenticationException; 4 | 5 | public class OAuth2AuthenticationProcessingException extends AuthenticationException { 6 | /** 7 | * 8 | */ 9 | private static final long serialVersionUID = 3392450042101522832L; 10 | 11 | public OAuth2AuthenticationProcessingException(String msg, Throwable t) { 12 | super(msg, t); 13 | } 14 | 15 | public OAuth2AuthenticationProcessingException(String msg) { 16 | super(msg); 17 | } 18 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/exception/ResourceNotFoundException.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.exception; 2 | 3 | import org.springframework.http.HttpStatus; 4 | import org.springframework.web.bind.annotation.ResponseStatus; 5 | 6 | import lombok.Getter; 7 | 8 | @Getter 9 | @ResponseStatus(HttpStatus.NOT_FOUND) 10 | public class ResourceNotFoundException extends RuntimeException { 11 | private static final long serialVersionUID = 7004203416628447047L; 12 | private String resourceName; 13 | private String fieldName; 14 | private Object fieldValue; 15 | 16 | public ResourceNotFoundException(String resourceName, String fieldName, Object fieldValue) { 17 | super(String.format("%s not found with %s : '%s'", resourceName, fieldName, fieldValue)); 18 | this.resourceName = resourceName; 19 | this.fieldName = fieldName; 20 | this.fieldValue = fieldValue; 21 | } 22 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/exception/UserAlreadyExistAuthenticationException.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.exception; 2 | 3 | import org.springframework.security.core.AuthenticationException; 4 | 5 | /** 6 | * 7 | * @author Chinna 8 | * 9 | */ 10 | public class UserAlreadyExistAuthenticationException extends AuthenticationException { 11 | 12 | /** 13 | * 14 | */ 15 | private static final long serialVersionUID = 5570981880007077317L; 16 | 17 | public UserAlreadyExistAuthenticationException(final String msg) { 18 | super(msg); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/exception/handler/RestResponseEntityExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.exception.handler; 2 | 3 | import java.util.stream.Collectors; 4 | 5 | import org.springframework.http.HttpHeaders; 6 | import org.springframework.http.HttpStatus; 7 | import org.springframework.http.ResponseEntity; 8 | import org.springframework.validation.BindingResult; 9 | import org.springframework.validation.FieldError; 10 | import org.springframework.web.bind.MethodArgumentNotValidException; 11 | import org.springframework.web.bind.annotation.ControllerAdvice; 12 | import org.springframework.web.context.request.WebRequest; 13 | import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; 14 | 15 | import com.javachinna.dto.ApiResponse; 16 | 17 | @ControllerAdvice 18 | public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler { 19 | 20 | public RestResponseEntityExceptionHandler() { 21 | super(); 22 | } 23 | 24 | @Override 25 | protected ResponseEntity handleMethodArgumentNotValid(final MethodArgumentNotValidException ex, final HttpHeaders headers, final HttpStatus status, 26 | final WebRequest request) { 27 | logger.error("400 Status Code", ex); 28 | final BindingResult result = ex.getBindingResult(); 29 | 30 | String error = result.getAllErrors().stream().map(e -> { 31 | if (e instanceof FieldError) { 32 | return ((FieldError) e).getField() + " : " + e.getDefaultMessage(); 33 | } else { 34 | return e.getObjectName() + " : " + e.getDefaultMessage(); 35 | } 36 | }).collect(Collectors.joining(", ")); 37 | return handleExceptionInternal(ex, new ApiResponse(false, error), new HttpHeaders(), HttpStatus.BAD_REQUEST, request); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/model/Order.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.model; 2 | 3 | import java.io.Serializable; 4 | 5 | import javax.persistence.Entity; 6 | import javax.persistence.GeneratedValue; 7 | import javax.persistence.GenerationType; 8 | import javax.persistence.Id; 9 | import javax.persistence.Table; 10 | 11 | import lombok.Getter; 12 | import lombok.NoArgsConstructor; 13 | import lombok.Setter; 14 | 15 | /** 16 | * The persistent class for the user_order database table. 17 | * 18 | */ 19 | @Entity 20 | @Table(name = "user_order") 21 | @NoArgsConstructor 22 | @Getter 23 | @Setter 24 | public class Order implements Serializable { 25 | 26 | /** 27 | * 28 | */ 29 | private static final long serialVersionUID = 65981149772133526L; 30 | 31 | @Id 32 | @GeneratedValue(strategy = GenerationType.IDENTITY) 33 | private Long id; 34 | 35 | private Long userId; 36 | 37 | private String razorpayPaymentId; 38 | 39 | private String razorpayOrderId; 40 | 41 | private String razorpaySignature; 42 | 43 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/model/Role.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.model; 2 | 3 | import java.io.Serializable; 4 | import java.util.Set; 5 | 6 | import javax.persistence.Column; 7 | import javax.persistence.Entity; 8 | import javax.persistence.GeneratedValue; 9 | import javax.persistence.GenerationType; 10 | import javax.persistence.Id; 11 | import javax.persistence.ManyToMany; 12 | 13 | import lombok.Getter; 14 | import lombok.NoArgsConstructor; 15 | import lombok.Setter; 16 | 17 | /** 18 | * The persistent class for the role database table. 19 | * 20 | */ 21 | @Entity 22 | @Getter 23 | @Setter 24 | @NoArgsConstructor 25 | public class Role implements Serializable { 26 | private static final long serialVersionUID = 1L; 27 | public static final String USER = "USER"; 28 | public static final String ROLE_USER = "ROLE_USER"; 29 | public static final String ROLE_ADMIN = "ROLE_ADMIN"; 30 | public static final String ROLE_MODERATOR = "ROLE_MODERATOR"; 31 | public static final String ROLE_PRE_VERIFICATION_USER = "ROLE_PRE_VERIFICATION_USER"; 32 | 33 | @Id 34 | @GeneratedValue(strategy = GenerationType.IDENTITY) 35 | @Column(name = "ROLE_ID") 36 | private Long roleId; 37 | 38 | private String name; 39 | 40 | // bi-directional many-to-many association to User 41 | @ManyToMany(mappedBy = "roles") 42 | private Set users; 43 | 44 | public Role(String name) { 45 | this.name = name; 46 | } 47 | 48 | @Override 49 | public int hashCode() { 50 | final int prime = 31; 51 | int result = 1; 52 | result = prime * result + ((name == null) ? 0 : name.hashCode()); 53 | return result; 54 | } 55 | 56 | @Override 57 | public boolean equals(final Object obj) { 58 | if (this == obj) { 59 | return true; 60 | } 61 | if (obj == null) { 62 | return false; 63 | } 64 | if (getClass() != obj.getClass()) { 65 | return false; 66 | } 67 | final Role role = (Role) obj; 68 | if (!role.equals(role.name)) { 69 | return false; 70 | } 71 | return true; 72 | } 73 | 74 | @Override 75 | public String toString() { 76 | final StringBuilder builder = new StringBuilder(); 77 | builder.append("Role [name=").append(name).append("]").append("[id=").append(roleId).append("]"); 78 | return builder.toString(); 79 | } 80 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/model/User.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.model; 2 | 3 | import java.io.Serializable; 4 | import java.util.Date; 5 | import java.util.Set; 6 | 7 | import javax.persistence.Column; 8 | import javax.persistence.Entity; 9 | import javax.persistence.GeneratedValue; 10 | import javax.persistence.GenerationType; 11 | import javax.persistence.Id; 12 | import javax.persistence.JoinColumn; 13 | import javax.persistence.JoinTable; 14 | import javax.persistence.ManyToMany; 15 | import javax.persistence.Temporal; 16 | import javax.persistence.TemporalType; 17 | 18 | import com.fasterxml.jackson.annotation.JsonIgnore; 19 | 20 | import lombok.Getter; 21 | import lombok.NoArgsConstructor; 22 | import lombok.Setter; 23 | 24 | /** 25 | * The persistent class for the user database table. 26 | * 27 | */ 28 | @Entity 29 | @NoArgsConstructor 30 | @Getter 31 | @Setter 32 | public class User implements Serializable { 33 | 34 | /** 35 | * 36 | */ 37 | private static final long serialVersionUID = 65981149772133526L; 38 | 39 | @Id 40 | @GeneratedValue(strategy = GenerationType.IDENTITY) 41 | @Column(name = "USER_ID") 42 | private Long id; 43 | 44 | @Column(name = "PROVIDER_USER_ID") 45 | private String providerUserId; 46 | 47 | private String email; 48 | 49 | @Column(name = "enabled", columnDefinition = "BIT", length = 1) 50 | private boolean enabled; 51 | 52 | @Column(name = "DISPLAY_NAME") 53 | private String displayName; 54 | 55 | @Column(name = "created_date", nullable = false, updatable = false) 56 | @Temporal(TemporalType.TIMESTAMP) 57 | protected Date createdDate; 58 | 59 | @Temporal(TemporalType.TIMESTAMP) 60 | protected Date modifiedDate; 61 | 62 | private String password; 63 | 64 | private String provider; 65 | 66 | @Column(name = "USING_2FA") 67 | private boolean using2FA; 68 | 69 | private String secret; 70 | 71 | // bi-directional many-to-many association to Role 72 | @JsonIgnore 73 | @ManyToMany 74 | @JoinTable(name = "user_role", joinColumns = {@JoinColumn(name = "USER_ID")}, inverseJoinColumns = {@JoinColumn(name = "ROLE_ID")}) 75 | private Set roles; 76 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/repo/OrderRepository.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.repo; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | import org.springframework.stereotype.Repository; 5 | 6 | import com.javachinna.model.Order; 7 | 8 | @Repository 9 | public interface OrderRepository extends JpaRepository { 10 | 11 | Order findByRazorpayOrderId(String orderId); 12 | } 13 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/repo/RoleRepository.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.repo; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | import org.springframework.stereotype.Repository; 5 | 6 | import com.javachinna.model.Role; 7 | 8 | @Repository 9 | public interface RoleRepository extends JpaRepository { 10 | 11 | Role findByName(String name); 12 | } 13 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/repo/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.repo; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | import org.springframework.stereotype.Repository; 5 | 6 | import com.javachinna.model.User; 7 | 8 | @Repository 9 | public interface UserRepository extends JpaRepository { 10 | 11 | User findByEmail(String email); 12 | 13 | boolean existsByEmail(String email); 14 | 15 | } 16 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/security/jwt/TokenAuthenticationFilter.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.security.jwt; 2 | 3 | import java.io.IOException; 4 | import java.util.Collection; 5 | import java.util.List; 6 | 7 | import javax.servlet.FilterChain; 8 | import javax.servlet.ServletException; 9 | import javax.servlet.http.HttpServletRequest; 10 | import javax.servlet.http.HttpServletResponse; 11 | 12 | import org.slf4j.Logger; 13 | import org.slf4j.LoggerFactory; 14 | import org.springframework.beans.factory.annotation.Autowired; 15 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 16 | import org.springframework.security.core.GrantedAuthority; 17 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 18 | import org.springframework.security.core.context.SecurityContextHolder; 19 | import org.springframework.security.core.userdetails.UserDetails; 20 | import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; 21 | import org.springframework.util.StringUtils; 22 | import org.springframework.web.filter.OncePerRequestFilter; 23 | 24 | import com.javachinna.model.Role; 25 | import com.javachinna.service.LocalUserDetailService; 26 | 27 | public class TokenAuthenticationFilter extends OncePerRequestFilter { 28 | 29 | @Autowired 30 | private TokenProvider tokenProvider; 31 | 32 | @Autowired 33 | private LocalUserDetailService customUserDetailsService; 34 | 35 | private static final Logger logger = LoggerFactory.getLogger(TokenAuthenticationFilter.class); 36 | 37 | @Override 38 | protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { 39 | try { 40 | String jwt = getJwtFromRequest(request); 41 | 42 | if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)) { 43 | Long userId = tokenProvider.getUserIdFromToken(jwt); 44 | 45 | UserDetails userDetails = customUserDetailsService.loadUserById(userId); 46 | Collection authorities = tokenProvider.isAuthenticated(jwt) 47 | ? userDetails.getAuthorities() 48 | : List.of(new SimpleGrantedAuthority(Role.ROLE_PRE_VERIFICATION_USER)); 49 | UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, authorities); 50 | authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); 51 | 52 | SecurityContextHolder.getContext().setAuthentication(authentication); 53 | } 54 | } catch (Exception ex) { 55 | logger.error("Could not set user authentication in security context", ex); 56 | } 57 | 58 | filterChain.doFilter(request, response); 59 | } 60 | 61 | private String getJwtFromRequest(HttpServletRequest request) { 62 | String bearerToken = request.getHeader("Authorization"); 63 | if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) { 64 | return bearerToken.substring(7, bearerToken.length()); 65 | } 66 | return null; 67 | } 68 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/security/jwt/TokenProvider.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.security.jwt; 2 | 3 | import java.util.Date; 4 | 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.stereotype.Service; 8 | 9 | import com.javachinna.config.AppProperties; 10 | import com.javachinna.dto.LocalUser; 11 | 12 | import io.jsonwebtoken.Claims; 13 | import io.jsonwebtoken.ExpiredJwtException; 14 | import io.jsonwebtoken.Jwts; 15 | import io.jsonwebtoken.MalformedJwtException; 16 | import io.jsonwebtoken.SignatureAlgorithm; 17 | import io.jsonwebtoken.SignatureException; 18 | import io.jsonwebtoken.UnsupportedJwtException; 19 | 20 | @Service 21 | public class TokenProvider { 22 | 23 | private static final String AUTHENTICATED = "authenticated"; 24 | 25 | private static final Logger logger = LoggerFactory.getLogger(TokenProvider.class); 26 | 27 | public static final long TEMP_TOKEN_VALIDITY_IN_MILLIS = 300000; 28 | 29 | private AppProperties appProperties; 30 | 31 | public TokenProvider(AppProperties appProperties) { 32 | this.appProperties = appProperties; 33 | } 34 | 35 | public String createToken(LocalUser userPrincipal, boolean authenticated) { 36 | Date now = new Date(); 37 | Date expiryDate = new Date(now.getTime() + (authenticated ? appProperties.getAuth().getTokenExpirationMsec() : TEMP_TOKEN_VALIDITY_IN_MILLIS)); 38 | 39 | return Jwts.builder().setSubject(Long.toString(userPrincipal.getUser().getId())).claim(AUTHENTICATED, authenticated).setIssuedAt(new Date()).setExpiration(expiryDate) 40 | .signWith(SignatureAlgorithm.HS512, appProperties.getAuth().getTokenSecret()).compact(); 41 | } 42 | 43 | public Long getUserIdFromToken(String token) { 44 | Claims claims = Jwts.parser().setSigningKey(appProperties.getAuth().getTokenSecret()).parseClaimsJws(token).getBody(); 45 | 46 | return Long.parseLong(claims.getSubject()); 47 | } 48 | 49 | public Boolean isAuthenticated(String token) { 50 | Claims claims = Jwts.parser().setSigningKey(appProperties.getAuth().getTokenSecret()).parseClaimsJws(token).getBody(); 51 | return claims.get(AUTHENTICATED, Boolean.class); 52 | } 53 | 54 | public boolean validateToken(String authToken) { 55 | try { 56 | Jwts.parser().setSigningKey(appProperties.getAuth().getTokenSecret()).parseClaimsJws(authToken); 57 | return true; 58 | } catch (SignatureException ex) { 59 | logger.error("Invalid JWT signature"); 60 | } catch (MalformedJwtException ex) { 61 | logger.error("Invalid JWT token"); 62 | } catch (ExpiredJwtException ex) { 63 | logger.error("Expired JWT token"); 64 | } catch (UnsupportedJwtException ex) { 65 | logger.error("Unsupported JWT token"); 66 | } catch (IllegalArgumentException ex) { 67 | logger.error("JWT claims string is empty."); 68 | } 69 | return false; 70 | } 71 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/security/oauth2/CustomOAuth2UserService.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.security.oauth2; 2 | 3 | import java.util.HashMap; 4 | import java.util.List; 5 | import java.util.Map; 6 | 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.core.env.Environment; 9 | import org.springframework.http.HttpEntity; 10 | import org.springframework.http.HttpHeaders; 11 | import org.springframework.http.HttpMethod; 12 | import org.springframework.http.ResponseEntity; 13 | import org.springframework.security.core.AuthenticationException; 14 | import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService; 15 | import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest; 16 | import org.springframework.security.oauth2.core.OAuth2AuthenticationException; 17 | import org.springframework.security.oauth2.core.user.OAuth2User; 18 | import org.springframework.stereotype.Service; 19 | import org.springframework.util.Assert; 20 | import org.springframework.web.client.RestTemplate; 21 | 22 | import com.javachinna.dto.SocialProvider; 23 | import com.javachinna.exception.OAuth2AuthenticationProcessingException; 24 | import com.javachinna.service.UserService; 25 | 26 | @Service 27 | public class CustomOAuth2UserService extends DefaultOAuth2UserService { 28 | 29 | @Autowired 30 | private UserService userService; 31 | 32 | @Autowired 33 | private Environment env; 34 | 35 | @Override 36 | public OAuth2User loadUser(OAuth2UserRequest oAuth2UserRequest) throws OAuth2AuthenticationException { 37 | OAuth2User oAuth2User = super.loadUser(oAuth2UserRequest); 38 | try { 39 | Map attributes = new HashMap<>(oAuth2User.getAttributes()); 40 | String provider = oAuth2UserRequest.getClientRegistration().getRegistrationId(); 41 | if (provider.equals(SocialProvider.LINKEDIN.getProviderType())) { 42 | populateEmailAddressFromLinkedIn(oAuth2UserRequest, attributes); 43 | } 44 | return userService.processUserRegistration(provider, attributes, null, null); 45 | } catch (AuthenticationException ex) { 46 | throw ex; 47 | } catch (Exception ex) { 48 | ex.printStackTrace(); 49 | // Throwing an instance of AuthenticationException will trigger the 50 | // OAuth2AuthenticationFailureHandler 51 | throw new OAuth2AuthenticationProcessingException(ex.getMessage(), ex.getCause()); 52 | } 53 | } 54 | 55 | @SuppressWarnings({ "rawtypes", "unchecked" }) 56 | public void populateEmailAddressFromLinkedIn(OAuth2UserRequest oAuth2UserRequest, Map attributes) throws OAuth2AuthenticationException { 57 | String emailEndpointUri = env.getProperty("linkedin.email-address-uri"); 58 | Assert.notNull(emailEndpointUri, "LinkedIn email address end point required"); 59 | RestTemplate restTemplate = new RestTemplate(); 60 | HttpHeaders headers = new HttpHeaders(); 61 | headers.add(HttpHeaders.AUTHORIZATION, "Bearer " + oAuth2UserRequest.getAccessToken().getTokenValue()); 62 | HttpEntity entity = new HttpEntity<>("", headers); 63 | ResponseEntity response = restTemplate.exchange(emailEndpointUri, HttpMethod.GET, entity, Map.class); 64 | List list = (List) response.getBody().get("elements"); 65 | Map map = (Map) ((Map) list.get(0)).get("handle~"); 66 | attributes.putAll(map); 67 | } 68 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/security/oauth2/CustomOidcUserService.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.security.oauth2; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.security.core.AuthenticationException; 5 | import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest; 6 | import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserService; 7 | import org.springframework.security.oauth2.core.OAuth2AuthenticationException; 8 | import org.springframework.security.oauth2.core.oidc.user.OidcUser; 9 | import org.springframework.stereotype.Service; 10 | 11 | import com.javachinna.exception.OAuth2AuthenticationProcessingException; 12 | import com.javachinna.service.UserService; 13 | 14 | @Service 15 | public class CustomOidcUserService extends OidcUserService { 16 | 17 | @Autowired 18 | private UserService userService; 19 | 20 | @Override 21 | public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException { 22 | OidcUser oidcUser = super.loadUser(userRequest); 23 | try { 24 | return userService.processUserRegistration(userRequest.getClientRegistration().getRegistrationId(), oidcUser.getAttributes(), oidcUser.getIdToken(), 25 | oidcUser.getUserInfo()); 26 | } catch (AuthenticationException ex) { 27 | throw ex; 28 | } catch (Exception ex) { 29 | ex.printStackTrace(); 30 | // Throwing an instance of AuthenticationException will trigger the 31 | // OAuth2AuthenticationFailureHandler 32 | throw new OAuth2AuthenticationProcessingException(ex.getMessage(), ex.getCause()); 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/security/oauth2/HttpCookieOAuth2AuthorizationRequestRepository.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.security.oauth2; 2 | 3 | import javax.servlet.http.HttpServletRequest; 4 | import javax.servlet.http.HttpServletResponse; 5 | 6 | import org.springframework.security.oauth2.client.web.AuthorizationRequestRepository; 7 | import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; 8 | import org.springframework.stereotype.Component; 9 | 10 | import com.javachinna.util.CookieUtils; 11 | import com.nimbusds.oauth2.sdk.util.StringUtils; 12 | 13 | @Component 14 | public class HttpCookieOAuth2AuthorizationRequestRepository implements AuthorizationRequestRepository { 15 | public static final String OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME = "oauth2_auth_request"; 16 | public static final String REDIRECT_URI_PARAM_COOKIE_NAME = "redirect_uri"; 17 | private static final int cookieExpireSeconds = 180; 18 | 19 | @Override 20 | public OAuth2AuthorizationRequest loadAuthorizationRequest(HttpServletRequest request) { 21 | return CookieUtils.getCookie(request, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME).map(cookie -> CookieUtils.deserialize(cookie, OAuth2AuthorizationRequest.class)) 22 | .orElse(null); 23 | } 24 | 25 | @Override 26 | public void saveAuthorizationRequest(OAuth2AuthorizationRequest authorizationRequest, HttpServletRequest request, HttpServletResponse response) { 27 | if (authorizationRequest == null) { 28 | CookieUtils.deleteCookie(request, response, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME); 29 | CookieUtils.deleteCookie(request, response, REDIRECT_URI_PARAM_COOKIE_NAME); 30 | return; 31 | } 32 | 33 | CookieUtils.addCookie(response, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME, CookieUtils.serialize(authorizationRequest), cookieExpireSeconds); 34 | String redirectUriAfterLogin = request.getParameter(REDIRECT_URI_PARAM_COOKIE_NAME); 35 | if (StringUtils.isNotBlank(redirectUriAfterLogin)) { 36 | CookieUtils.addCookie(response, REDIRECT_URI_PARAM_COOKIE_NAME, redirectUriAfterLogin, cookieExpireSeconds); 37 | } 38 | } 39 | 40 | @Override 41 | public OAuth2AuthorizationRequest removeAuthorizationRequest(HttpServletRequest request) { 42 | return this.loadAuthorizationRequest(request); 43 | } 44 | 45 | public void removeAuthorizationRequestCookies(HttpServletRequest request, HttpServletResponse response) { 46 | CookieUtils.deleteCookie(request, response, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME); 47 | CookieUtils.deleteCookie(request, response, REDIRECT_URI_PARAM_COOKIE_NAME); 48 | } 49 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/security/oauth2/OAuth2AccessTokenResponseConverterWithDefaults.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.security.oauth2; 2 | 3 | import java.util.Arrays; 4 | import java.util.Collections; 5 | import java.util.LinkedHashMap; 6 | import java.util.Map; 7 | import java.util.Set; 8 | import java.util.stream.Collectors; 9 | import java.util.stream.Stream; 10 | 11 | import org.springframework.core.convert.converter.Converter; 12 | import org.springframework.security.oauth2.core.OAuth2AccessToken; 13 | import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse; 14 | import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; 15 | import org.springframework.util.Assert; 16 | import org.springframework.util.StringUtils; 17 | 18 | /** 19 | * @author Joe Grandja 20 | */ 21 | public class OAuth2AccessTokenResponseConverterWithDefaults implements Converter, OAuth2AccessTokenResponse> { 22 | private static final Set TOKEN_RESPONSE_PARAMETER_NAMES = Stream 23 | .of(OAuth2ParameterNames.ACCESS_TOKEN, OAuth2ParameterNames.TOKEN_TYPE, OAuth2ParameterNames.EXPIRES_IN, OAuth2ParameterNames.REFRESH_TOKEN, OAuth2ParameterNames.SCOPE) 24 | .collect(Collectors.toSet()); 25 | 26 | private OAuth2AccessToken.TokenType defaultAccessTokenType = OAuth2AccessToken.TokenType.BEARER; 27 | 28 | @Override 29 | public OAuth2AccessTokenResponse convert(Map tokenResponseParameters) { 30 | String accessToken = tokenResponseParameters.get(OAuth2ParameterNames.ACCESS_TOKEN); 31 | 32 | OAuth2AccessToken.TokenType accessTokenType = this.defaultAccessTokenType; 33 | if (OAuth2AccessToken.TokenType.BEARER.getValue().equalsIgnoreCase(tokenResponseParameters.get(OAuth2ParameterNames.TOKEN_TYPE))) { 34 | accessTokenType = OAuth2AccessToken.TokenType.BEARER; 35 | } 36 | 37 | long expiresIn = 0; 38 | if (tokenResponseParameters.containsKey(OAuth2ParameterNames.EXPIRES_IN)) { 39 | try { 40 | expiresIn = Long.valueOf(tokenResponseParameters.get(OAuth2ParameterNames.EXPIRES_IN)); 41 | } catch (NumberFormatException ex) { 42 | } 43 | } 44 | 45 | Set scopes = Collections.emptySet(); 46 | if (tokenResponseParameters.containsKey(OAuth2ParameterNames.SCOPE)) { 47 | String scope = tokenResponseParameters.get(OAuth2ParameterNames.SCOPE); 48 | scopes = Arrays.stream(StringUtils.delimitedListToStringArray(scope, " ")).collect(Collectors.toSet()); 49 | } 50 | 51 | Map additionalParameters = new LinkedHashMap<>(); 52 | tokenResponseParameters.entrySet().stream().filter(e -> !TOKEN_RESPONSE_PARAMETER_NAMES.contains(e.getKey())) 53 | .forEach(e -> additionalParameters.put(e.getKey(), e.getValue())); 54 | 55 | return OAuth2AccessTokenResponse.withToken(accessToken).tokenType(accessTokenType).expiresIn(expiresIn).scopes(scopes).additionalParameters(additionalParameters).build(); 56 | } 57 | 58 | public final void setDefaultAccessTokenType(OAuth2AccessToken.TokenType defaultAccessTokenType) { 59 | Assert.notNull(defaultAccessTokenType, "defaultAccessTokenType cannot be null"); 60 | this.defaultAccessTokenType = defaultAccessTokenType; 61 | } 62 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/security/oauth2/OAuth2AuthenticationFailureHandler.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.security.oauth2; 2 | 3 | import static com.javachinna.security.oauth2.HttpCookieOAuth2AuthorizationRequestRepository.REDIRECT_URI_PARAM_COOKIE_NAME; 4 | 5 | import java.io.IOException; 6 | 7 | import javax.servlet.ServletException; 8 | import javax.servlet.http.Cookie; 9 | import javax.servlet.http.HttpServletRequest; 10 | import javax.servlet.http.HttpServletResponse; 11 | 12 | import org.springframework.beans.factory.annotation.Autowired; 13 | import org.springframework.security.core.AuthenticationException; 14 | import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler; 15 | import org.springframework.stereotype.Component; 16 | import org.springframework.web.util.UriComponentsBuilder; 17 | 18 | import com.javachinna.util.CookieUtils; 19 | 20 | @Component 21 | public class OAuth2AuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler { 22 | 23 | @Autowired 24 | HttpCookieOAuth2AuthorizationRequestRepository httpCookieOAuth2AuthorizationRequestRepository; 25 | 26 | @Override 27 | public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { 28 | String targetUrl = CookieUtils.getCookie(request, REDIRECT_URI_PARAM_COOKIE_NAME).map(Cookie::getValue).orElse(("/")); 29 | 30 | targetUrl = UriComponentsBuilder.fromUriString(targetUrl).queryParam("error", exception.getLocalizedMessage()).build().toUriString(); 31 | 32 | httpCookieOAuth2AuthorizationRequestRepository.removeAuthorizationRequestCookies(request, response); 33 | 34 | getRedirectStrategy().sendRedirect(request, response, targetUrl); 35 | } 36 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/security/oauth2/OAuth2AuthenticationSuccessHandler.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.security.oauth2; 2 | 3 | import static com.javachinna.security.oauth2.HttpCookieOAuth2AuthorizationRequestRepository.REDIRECT_URI_PARAM_COOKIE_NAME; 4 | 5 | import java.io.IOException; 6 | import java.net.URI; 7 | import java.util.Optional; 8 | 9 | import javax.servlet.ServletException; 10 | import javax.servlet.http.Cookie; 11 | import javax.servlet.http.HttpServletRequest; 12 | import javax.servlet.http.HttpServletResponse; 13 | 14 | import org.springframework.beans.factory.annotation.Autowired; 15 | import org.springframework.security.core.Authentication; 16 | import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler; 17 | import org.springframework.stereotype.Component; 18 | import org.springframework.web.util.UriComponentsBuilder; 19 | 20 | import com.javachinna.config.AppProperties; 21 | import com.javachinna.dto.LocalUser; 22 | import com.javachinna.exception.BadRequestException; 23 | import com.javachinna.security.jwt.TokenProvider; 24 | import com.javachinna.util.CookieUtils; 25 | 26 | @Component 27 | public class OAuth2AuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler { 28 | 29 | private TokenProvider tokenProvider; 30 | 31 | private AppProperties appProperties; 32 | 33 | private HttpCookieOAuth2AuthorizationRequestRepository httpCookieOAuth2AuthorizationRequestRepository; 34 | 35 | @Autowired 36 | OAuth2AuthenticationSuccessHandler(TokenProvider tokenProvider, AppProperties appProperties, 37 | HttpCookieOAuth2AuthorizationRequestRepository httpCookieOAuth2AuthorizationRequestRepository) { 38 | this.tokenProvider = tokenProvider; 39 | this.appProperties = appProperties; 40 | this.httpCookieOAuth2AuthorizationRequestRepository = httpCookieOAuth2AuthorizationRequestRepository; 41 | } 42 | 43 | @Override 44 | public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { 45 | String targetUrl = determineTargetUrl(request, response, authentication); 46 | 47 | if (response.isCommitted()) { 48 | logger.debug("Response has already been committed. Unable to redirect to " + targetUrl); 49 | return; 50 | } 51 | 52 | clearAuthenticationAttributes(request, response); 53 | getRedirectStrategy().sendRedirect(request, response, targetUrl); 54 | } 55 | 56 | @Override 57 | protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { 58 | Optional redirectUri = CookieUtils.getCookie(request, REDIRECT_URI_PARAM_COOKIE_NAME).map(Cookie::getValue); 59 | 60 | if (redirectUri.isPresent() && !isAuthorizedRedirectUri(redirectUri.get())) { 61 | throw new BadRequestException("Sorry! We've got an Unauthorized Redirect URI and can't proceed with the authentication"); 62 | } 63 | 64 | String targetUrl = redirectUri.orElse(getDefaultTargetUrl()); 65 | LocalUser user = (LocalUser) authentication.getPrincipal(); 66 | String token = tokenProvider.createToken(user, true); 67 | 68 | return UriComponentsBuilder.fromUriString(targetUrl).queryParam("token", token).build().toUriString(); 69 | } 70 | 71 | protected void clearAuthenticationAttributes(HttpServletRequest request, HttpServletResponse response) { 72 | super.clearAuthenticationAttributes(request); 73 | httpCookieOAuth2AuthorizationRequestRepository.removeAuthorizationRequestCookies(request, response); 74 | } 75 | 76 | private boolean isAuthorizedRedirectUri(String uri) { 77 | URI clientRedirectUri = URI.create(uri); 78 | 79 | return appProperties.getOauth2().getAuthorizedRedirectUris().stream().anyMatch(authorizedRedirectUri -> { 80 | // Only validate host and port. Let the clients use different paths 81 | // if they want 82 | // to 83 | URI authorizedURI = URI.create(authorizedRedirectUri); 84 | if (authorizedURI.getHost().equalsIgnoreCase(clientRedirectUri.getHost()) && authorizedURI.getPort() == clientRedirectUri.getPort()) { 85 | return true; 86 | } 87 | return false; 88 | }); 89 | } 90 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/security/oauth2/user/FacebookOAuth2UserInfo.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.security.oauth2.user; 2 | 3 | import java.util.Map; 4 | 5 | public class FacebookOAuth2UserInfo extends OAuth2UserInfo { 6 | public FacebookOAuth2UserInfo(Map attributes) { 7 | super(attributes); 8 | } 9 | 10 | @Override 11 | public String getId() { 12 | return (String) attributes.get("id"); 13 | } 14 | 15 | @Override 16 | public String getName() { 17 | return (String) attributes.get("name"); 18 | } 19 | 20 | @Override 21 | public String getEmail() { 22 | return (String) attributes.get("email"); 23 | } 24 | 25 | @Override 26 | @SuppressWarnings("unchecked") 27 | public String getImageUrl() { 28 | if (attributes.containsKey("picture")) { 29 | Map pictureObj = (Map) attributes.get("picture"); 30 | if (pictureObj.containsKey("data")) { 31 | Map dataObj = (Map) pictureObj.get("data"); 32 | if (dataObj.containsKey("url")) { 33 | return (String) dataObj.get("url"); 34 | } 35 | } 36 | } 37 | return null; 38 | } 39 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/security/oauth2/user/GithubOAuth2UserInfo.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.security.oauth2.user; 2 | 3 | import java.util.Map; 4 | 5 | public class GithubOAuth2UserInfo extends OAuth2UserInfo { 6 | 7 | public GithubOAuth2UserInfo(Map attributes) { 8 | super(attributes); 9 | } 10 | 11 | @Override 12 | public String getId() { 13 | return ((Integer) attributes.get("id")).toString(); 14 | } 15 | 16 | @Override 17 | public String getName() { 18 | return (String) attributes.get("name"); 19 | } 20 | 21 | @Override 22 | public String getEmail() { 23 | return (String) attributes.get("email"); 24 | } 25 | 26 | @Override 27 | public String getImageUrl() { 28 | return (String) attributes.get("avatar_url"); 29 | } 30 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/security/oauth2/user/GoogleOAuth2UserInfo.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.security.oauth2.user; 2 | 3 | import java.util.Map; 4 | 5 | public class GoogleOAuth2UserInfo extends OAuth2UserInfo { 6 | 7 | public GoogleOAuth2UserInfo(Map attributes) { 8 | super(attributes); 9 | } 10 | 11 | @Override 12 | public String getId() { 13 | return (String) attributes.get("sub"); 14 | } 15 | 16 | @Override 17 | public String getName() { 18 | return (String) attributes.get("name"); 19 | } 20 | 21 | @Override 22 | public String getEmail() { 23 | return (String) attributes.get("email"); 24 | } 25 | 26 | @Override 27 | public String getImageUrl() { 28 | return (String) attributes.get("picture"); 29 | } 30 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/security/oauth2/user/LinkedinOAuth2UserInfo.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.security.oauth2.user; 2 | 3 | import java.util.Map; 4 | 5 | public class LinkedinOAuth2UserInfo extends OAuth2UserInfo { 6 | 7 | public LinkedinOAuth2UserInfo(Map attributes) { 8 | super(attributes); 9 | } 10 | 11 | @Override 12 | public String getId() { 13 | return (String) attributes.get("id"); 14 | } 15 | 16 | @Override 17 | public String getName() { 18 | return ((String) attributes.get("localizedFirstName")).concat(" ").concat((String) attributes.get("localizedLastName")); 19 | } 20 | 21 | @Override 22 | public String getEmail() { 23 | return (String) attributes.get("emailAddress"); 24 | } 25 | 26 | @Override 27 | public String getImageUrl() { 28 | return (String) attributes.get("pictureUrl"); 29 | } 30 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/security/oauth2/user/OAuth2UserInfo.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.security.oauth2.user; 2 | 3 | import java.util.Map; 4 | 5 | public abstract class OAuth2UserInfo { 6 | protected Map attributes; 7 | 8 | public OAuth2UserInfo(Map attributes) { 9 | this.attributes = attributes; 10 | } 11 | 12 | public Map getAttributes() { 13 | return attributes; 14 | } 15 | 16 | public abstract String getId(); 17 | 18 | public abstract String getName(); 19 | 20 | public abstract String getEmail(); 21 | 22 | public abstract String getImageUrl(); 23 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/security/oauth2/user/OAuth2UserInfoFactory.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.security.oauth2.user; 2 | 3 | import java.util.Map; 4 | 5 | import com.javachinna.dto.SocialProvider; 6 | import com.javachinna.exception.OAuth2AuthenticationProcessingException; 7 | 8 | public class OAuth2UserInfoFactory { 9 | public static OAuth2UserInfo getOAuth2UserInfo(String registrationId, Map attributes) { 10 | if (registrationId.equalsIgnoreCase(SocialProvider.GOOGLE.getProviderType())) { 11 | return new GoogleOAuth2UserInfo(attributes); 12 | } else if (registrationId.equalsIgnoreCase(SocialProvider.FACEBOOK.getProviderType())) { 13 | return new FacebookOAuth2UserInfo(attributes); 14 | } else if (registrationId.equalsIgnoreCase(SocialProvider.GITHUB.getProviderType())) { 15 | return new GithubOAuth2UserInfo(attributes); 16 | } else if (registrationId.equalsIgnoreCase(SocialProvider.LINKEDIN.getProviderType())) { 17 | return new LinkedinOAuth2UserInfo(attributes); 18 | } else if (registrationId.equalsIgnoreCase(SocialProvider.TWITTER.getProviderType())) { 19 | return new GithubOAuth2UserInfo(attributes); 20 | } else { 21 | throw new OAuth2AuthenticationProcessingException("Sorry! Login with " + registrationId + " is not supported yet."); 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/service/LocalUserDetailService.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.service; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.security.core.userdetails.UserDetailsService; 5 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 6 | import org.springframework.stereotype.Service; 7 | import org.springframework.transaction.annotation.Transactional; 8 | 9 | import com.javachinna.dto.LocalUser; 10 | import com.javachinna.exception.ResourceNotFoundException; 11 | import com.javachinna.model.User; 12 | import com.javachinna.util.GeneralUtils; 13 | 14 | /** 15 | * 16 | * @author Chinna 17 | * 18 | */ 19 | @Service("localUserDetailService") 20 | public class LocalUserDetailService implements UserDetailsService { 21 | 22 | @Autowired 23 | private UserService userService; 24 | 25 | @Override 26 | @Transactional 27 | public LocalUser loadUserByUsername(final String email) throws UsernameNotFoundException { 28 | User user = userService.findUserByEmail(email); 29 | if (user == null) { 30 | throw new UsernameNotFoundException("User " + email + " was not found in the database"); 31 | } 32 | return createLocalUser(user); 33 | } 34 | 35 | @Transactional 36 | public LocalUser loadUserById(Long id) { 37 | User user = userService.findUserById(id).orElseThrow(() -> new ResourceNotFoundException("User", "id", id)); 38 | return createLocalUser(user); 39 | } 40 | 41 | /** 42 | * @param user 43 | * @return 44 | */ 45 | private LocalUser createLocalUser(User user) { 46 | return new LocalUser(user.getEmail(), user.getPassword(), user.isEnabled(), true, true, true, GeneralUtils.buildSimpleGrantedAuthorities(user.getRoles()), user); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/service/OrderService.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.service; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.stereotype.Service; 5 | import org.springframework.transaction.annotation.Transactional; 6 | 7 | import com.javachinna.model.Order; 8 | import com.javachinna.repo.OrderRepository; 9 | import com.javachinna.util.Signature; 10 | 11 | import lombok.extern.slf4j.Slf4j; 12 | 13 | /** 14 | * 15 | * @author Chinna 16 | * 17 | */ 18 | @Slf4j 19 | @Service 20 | public class OrderService { 21 | 22 | @Autowired 23 | private OrderRepository orderRepository; 24 | 25 | @Transactional 26 | public Order saveOrder(final String razorpayOrderId, final Long userId) { 27 | Order order = new Order(); 28 | order.setRazorpayOrderId(razorpayOrderId); 29 | order.setUserId(userId); 30 | return orderRepository.save(order); 31 | } 32 | 33 | @Transactional 34 | public String validateAndUpdateOrder(final String razorpayOrderId, final String razorpayPaymentId, final String razorpaySignature, final String secret) { 35 | String errorMsg = null; 36 | try { 37 | Order order = orderRepository.findByRazorpayOrderId(razorpayOrderId); 38 | // Verify if the razorpay signature matches the generated one to 39 | // confirm the authenticity of the details returned 40 | String generatedSignature = Signature.calculateRFC2104HMAC(order.getRazorpayOrderId() + "|" + razorpayPaymentId, secret); 41 | if (generatedSignature.equals(razorpaySignature)) { 42 | order.setRazorpayOrderId(razorpayOrderId); 43 | order.setRazorpayPaymentId(razorpayPaymentId); 44 | order.setRazorpaySignature(razorpaySignature); 45 | orderRepository.save(order); 46 | } else { 47 | errorMsg = "Payment validation failed: Signature doesn't match"; 48 | } 49 | } catch (Exception e) { 50 | log.error("Payment validation failed", e); 51 | errorMsg = e.getMessage(); 52 | } 53 | return errorMsg; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.service; 2 | 3 | import java.util.Map; 4 | import java.util.Optional; 5 | 6 | import org.springframework.security.oauth2.core.oidc.OidcIdToken; 7 | import org.springframework.security.oauth2.core.oidc.OidcUserInfo; 8 | 9 | import com.javachinna.dto.LocalUser; 10 | import com.javachinna.dto.SignUpRequest; 11 | import com.javachinna.exception.UserAlreadyExistAuthenticationException; 12 | import com.javachinna.model.User; 13 | 14 | /** 15 | * @author Chinna 16 | * @since 26/3/18 17 | */ 18 | public interface UserService { 19 | 20 | public User registerNewUser(SignUpRequest signUpRequest) throws UserAlreadyExistAuthenticationException; 21 | 22 | User findUserByEmail(String email); 23 | 24 | Optional findUserById(Long id); 25 | 26 | LocalUser processUserRegistration(String registrationId, Map attributes, OidcIdToken idToken, OidcUserInfo userInfo); 27 | } 28 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/service/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.service; 2 | 3 | import java.util.Calendar; 4 | import java.util.Date; 5 | import java.util.HashSet; 6 | import java.util.Map; 7 | import java.util.Optional; 8 | 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.security.crypto.password.PasswordEncoder; 11 | import org.springframework.security.oauth2.core.oidc.OidcIdToken; 12 | import org.springframework.security.oauth2.core.oidc.OidcUserInfo; 13 | import org.springframework.stereotype.Service; 14 | import org.springframework.transaction.annotation.Transactional; 15 | import org.springframework.util.StringUtils; 16 | 17 | import com.javachinna.dto.LocalUser; 18 | import com.javachinna.dto.SignUpRequest; 19 | import com.javachinna.dto.SocialProvider; 20 | import com.javachinna.exception.OAuth2AuthenticationProcessingException; 21 | import com.javachinna.exception.UserAlreadyExistAuthenticationException; 22 | import com.javachinna.model.Role; 23 | import com.javachinna.model.User; 24 | import com.javachinna.repo.RoleRepository; 25 | import com.javachinna.repo.UserRepository; 26 | import com.javachinna.security.oauth2.user.OAuth2UserInfo; 27 | import com.javachinna.security.oauth2.user.OAuth2UserInfoFactory; 28 | import com.javachinna.util.GeneralUtils; 29 | 30 | import dev.samstevens.totp.secret.SecretGenerator; 31 | 32 | /** 33 | * @author Chinna 34 | * @since 26/3/18 35 | */ 36 | @Service 37 | public class UserServiceImpl implements UserService { 38 | 39 | @Autowired 40 | private UserRepository userRepository; 41 | 42 | @Autowired 43 | private RoleRepository roleRepository; 44 | 45 | @Autowired 46 | private PasswordEncoder passwordEncoder; 47 | 48 | @Autowired 49 | private SecretGenerator secretGenerator; 50 | 51 | @Override 52 | @Transactional(value = "transactionManager") 53 | public User registerNewUser(final SignUpRequest signUpRequest) throws UserAlreadyExistAuthenticationException { 54 | if (signUpRequest.getUserID() != null && userRepository.existsById(signUpRequest.getUserID())) { 55 | throw new UserAlreadyExistAuthenticationException("User with User id " + signUpRequest.getUserID() + " already exist"); 56 | } else if (userRepository.existsByEmail(signUpRequest.getEmail())) { 57 | throw new UserAlreadyExistAuthenticationException("User with email id " + signUpRequest.getEmail() + " already exist"); 58 | } 59 | User user = buildUser(signUpRequest); 60 | Date now = Calendar.getInstance().getTime(); 61 | user.setCreatedDate(now); 62 | user.setModifiedDate(now); 63 | user = userRepository.save(user); 64 | userRepository.flush(); 65 | return user; 66 | } 67 | 68 | private User buildUser(final SignUpRequest formDTO) { 69 | User user = new User(); 70 | user.setDisplayName(formDTO.getDisplayName()); 71 | user.setEmail(formDTO.getEmail()); 72 | user.setPassword(passwordEncoder.encode(formDTO.getPassword())); 73 | final HashSet roles = new HashSet(); 74 | roles.add(roleRepository.findByName(Role.ROLE_USER)); 75 | user.setRoles(roles); 76 | user.setProvider(formDTO.getSocialProvider().getProviderType()); 77 | user.setEnabled(true); 78 | user.setProviderUserId(formDTO.getProviderUserId()); 79 | if (formDTO.isUsing2FA()) { 80 | user.setUsing2FA(true); 81 | user.setSecret(secretGenerator.generate()); 82 | } 83 | return user; 84 | } 85 | 86 | @Override 87 | public User findUserByEmail(final String email) { 88 | return userRepository.findByEmail(email); 89 | } 90 | 91 | @Override 92 | @Transactional 93 | public LocalUser processUserRegistration(String registrationId, Map attributes, OidcIdToken idToken, OidcUserInfo userInfo) { 94 | OAuth2UserInfo oAuth2UserInfo = OAuth2UserInfoFactory.getOAuth2UserInfo(registrationId, attributes); 95 | if (StringUtils.isEmpty(oAuth2UserInfo.getName())) { 96 | throw new OAuth2AuthenticationProcessingException("Name not found from OAuth2 provider"); 97 | } else if (StringUtils.isEmpty(oAuth2UserInfo.getEmail())) { 98 | throw new OAuth2AuthenticationProcessingException("Email not found from OAuth2 provider"); 99 | } 100 | SignUpRequest userDetails = toUserRegistrationObject(registrationId, oAuth2UserInfo); 101 | User user = findUserByEmail(oAuth2UserInfo.getEmail()); 102 | if (user != null) { 103 | if (!user.getProvider().equals(registrationId) && !user.getProvider().equals(SocialProvider.LOCAL.getProviderType())) { 104 | throw new OAuth2AuthenticationProcessingException( 105 | "Looks like you're signed up with " + user.getProvider() + " account. Please use your " + user.getProvider() + " account to login."); 106 | } 107 | user = updateExistingUser(user, oAuth2UserInfo); 108 | } else { 109 | user = registerNewUser(userDetails); 110 | } 111 | 112 | return LocalUser.create(user, attributes, idToken, userInfo); 113 | } 114 | 115 | private User updateExistingUser(User existingUser, OAuth2UserInfo oAuth2UserInfo) { 116 | existingUser.setDisplayName(oAuth2UserInfo.getName()); 117 | return userRepository.save(existingUser); 118 | } 119 | 120 | private SignUpRequest toUserRegistrationObject(String registrationId, OAuth2UserInfo oAuth2UserInfo) { 121 | return SignUpRequest.getBuilder().addProviderUserID(oAuth2UserInfo.getId()).addDisplayName(oAuth2UserInfo.getName()).addEmail(oAuth2UserInfo.getEmail()) 122 | .addSocialProvider(GeneralUtils.toSocialProvider(registrationId)).addPassword("changeit").build(); 123 | } 124 | 125 | @Override 126 | public Optional findUserById(Long id) { 127 | return userRepository.findById(id); 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/util/CookieUtils.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.util; 2 | 3 | import java.util.Base64; 4 | import java.util.Optional; 5 | 6 | import javax.servlet.http.Cookie; 7 | import javax.servlet.http.HttpServletRequest; 8 | import javax.servlet.http.HttpServletResponse; 9 | 10 | import org.springframework.util.SerializationUtils; 11 | 12 | public class CookieUtils { 13 | 14 | public static Optional getCookie(HttpServletRequest request, String name) { 15 | Cookie[] cookies = request.getCookies(); 16 | 17 | if (cookies != null && cookies.length > 0) { 18 | for (Cookie cookie : cookies) { 19 | if (cookie.getName().equals(name)) { 20 | return Optional.of(cookie); 21 | } 22 | } 23 | } 24 | 25 | return Optional.empty(); 26 | } 27 | 28 | public static void addCookie(HttpServletResponse response, String name, String value, int maxAge) { 29 | Cookie cookie = new Cookie(name, value); 30 | cookie.setPath("/"); 31 | cookie.setHttpOnly(true); 32 | cookie.setMaxAge(maxAge); 33 | response.addCookie(cookie); 34 | } 35 | 36 | public static void deleteCookie(HttpServletRequest request, HttpServletResponse response, String name) { 37 | Cookie[] cookies = request.getCookies(); 38 | if (cookies != null && cookies.length > 0) { 39 | for (Cookie cookie : cookies) { 40 | if (cookie.getName().equals(name)) { 41 | cookie.setValue(""); 42 | cookie.setPath("/"); 43 | cookie.setMaxAge(0); 44 | response.addCookie(cookie); 45 | } 46 | } 47 | } 48 | } 49 | 50 | public static String serialize(Object object) { 51 | return Base64.getUrlEncoder().encodeToString(SerializationUtils.serialize(object)); 52 | } 53 | 54 | public static T deserialize(Cookie cookie, Class cls) { 55 | return cls.cast(SerializationUtils.deserialize(Base64.getUrlDecoder().decode(cookie.getValue()))); 56 | } 57 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/util/GeneralUtils.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.util; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.Set; 6 | import java.util.stream.Collectors; 7 | 8 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 9 | 10 | import com.javachinna.dto.LocalUser; 11 | import com.javachinna.dto.SocialProvider; 12 | import com.javachinna.dto.UserInfo; 13 | import com.javachinna.model.Role; 14 | import com.javachinna.model.User; 15 | 16 | /** 17 | * 18 | * @author Chinna 19 | * 20 | */ 21 | public class GeneralUtils { 22 | 23 | public static List buildSimpleGrantedAuthorities(final Set roles) { 24 | List authorities = new ArrayList<>(); 25 | for (Role role : roles) { 26 | authorities.add(new SimpleGrantedAuthority(role.getName())); 27 | } 28 | return authorities; 29 | } 30 | 31 | public static SocialProvider toSocialProvider(String providerId) { 32 | for (SocialProvider socialProvider : SocialProvider.values()) { 33 | if (socialProvider.getProviderType().equals(providerId)) { 34 | return socialProvider; 35 | } 36 | } 37 | return SocialProvider.LOCAL; 38 | } 39 | 40 | public static UserInfo buildUserInfo(LocalUser localUser) { 41 | List roles = localUser.getAuthorities().stream().map(item -> item.getAuthority()).collect(Collectors.toList()); 42 | User user = localUser.getUser(); 43 | return new UserInfo(user.getId().toString(), user.getDisplayName(), user.getEmail(), roles); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/util/Signature.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.util; 2 | 3 | import java.security.SignatureException; 4 | 5 | import javax.crypto.Mac; 6 | import javax.crypto.spec.SecretKeySpec; 7 | import javax.xml.bind.DatatypeConverter; 8 | 9 | /** 10 | * This class defines common routines for generating authentication signatures 11 | * for Razorpay Webhook requests. 12 | */ 13 | public class Signature { 14 | private static final String HMAC_SHA256_ALGORITHM = "HmacSHA256"; 15 | /** 16 | * Computes RFC 2104-compliant HMAC signature. * @param data The data to be 17 | * signed. 18 | * 19 | * @param key 20 | * The signing key. 21 | * @return The Base64-encoded RFC 2104-compliant HMAC signature. 22 | * @throws java.security.SignatureException 23 | * when signature generation fails 24 | */ 25 | public static String calculateRFC2104HMAC(String data, String secret) throws java.security.SignatureException { 26 | String result; 27 | try { 28 | 29 | // get an hmac_sha256 key from the raw secret bytes 30 | SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes(), HMAC_SHA256_ALGORITHM); 31 | 32 | // get an hmac_sha256 Mac instance and initialize with the signing 33 | // key 34 | Mac mac = Mac.getInstance(HMAC_SHA256_ALGORITHM); 35 | mac.init(signingKey); 36 | 37 | // compute the hmac on input data bytes 38 | byte[] rawHmac = mac.doFinal(data.getBytes()); 39 | 40 | // base64-encode the hmac 41 | result = DatatypeConverter.printHexBinary(rawHmac).toLowerCase(); 42 | 43 | } catch (Exception e) { 44 | throw new SignatureException("Failed to generate HMAC : " + e.getMessage()); 45 | } 46 | return result; 47 | } 48 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/validator/PasswordMatches.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.validator; 2 | 3 | import static java.lang.annotation.ElementType.ANNOTATION_TYPE; 4 | import static java.lang.annotation.ElementType.TYPE; 5 | import static java.lang.annotation.RetentionPolicy.RUNTIME; 6 | 7 | import java.lang.annotation.Documented; 8 | import java.lang.annotation.Retention; 9 | import java.lang.annotation.Target; 10 | 11 | import javax.validation.Constraint; 12 | import javax.validation.Payload; 13 | 14 | @Target({ TYPE, ANNOTATION_TYPE }) 15 | @Retention(RUNTIME) 16 | @Constraint(validatedBy = PasswordMatchesValidator.class) 17 | @Documented 18 | public @interface PasswordMatches { 19 | 20 | String message() default "Passwords don't match"; 21 | 22 | Class[] groups() default {}; 23 | 24 | Class[] payload() default {}; 25 | 26 | } 27 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/java/com/javachinna/validator/PasswordMatchesValidator.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.validator; 2 | 3 | import javax.validation.ConstraintValidator; 4 | import javax.validation.ConstraintValidatorContext; 5 | 6 | import com.javachinna.dto.SignUpRequest; 7 | 8 | public class PasswordMatchesValidator implements ConstraintValidator { 9 | 10 | @Override 11 | public boolean isValid(final SignUpRequest user, final ConstraintValidatorContext context) { 12 | return user.getPassword().equals(user.getMatchingPassword()); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | # Database configuration props 2 | spring.datasource.url=jdbc:mysql://localhost:3306/demo?createDatabaseIfNotExist=true 3 | spring.datasource.username=root 4 | spring.datasource.password=secret 5 | spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver 6 | 7 | # Hibernate props 8 | spring.jpa.show-sql=true 9 | #spring.jpa.hibernate.ddl-auto=none 10 | spring.jpa.hibernate.ddl-auto=create 11 | spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect 12 | 13 | # Social login provider props 14 | spring.security.oauth2.client.registration.google.clientId= 15 | spring.security.oauth2.client.registration.google.clientSecret= 16 | spring.security.oauth2.client.registration.facebook.clientId= 17 | spring.security.oauth2.client.registration.facebook.clientSecret= 18 | spring.security.oauth2.client.provider.facebook.user-info-uri=https://graph.facebook.com/me?fields=id,name,email,picture 19 | spring.security.oauth2.client.registration.github.clientId= 20 | spring.security.oauth2.client.registration.github.clientSecret= 21 | spring.security.oauth2.client.registration.linkedin.clientId= 22 | spring.security.oauth2.client.registration.linkedin.clientSecret= 23 | spring.security.oauth2.client.registration.linkedin.client-authentication-method=post 24 | spring.security.oauth2.client.registration.linkedin.authorization-grant-type=authorization_code 25 | spring.security.oauth2.client.registration.linkedin.scope=r_liteprofile, r_emailaddress 26 | spring.security.oauth2.client.registration.linkedin.redirect-uri={baseUrl}/login/oauth2/code/{registrationId} 27 | spring.security.oauth2.client.registration.linkedin.client-name=Linkedin 28 | spring.security.oauth2.client.registration.linkedin.provider=linkedin 29 | spring.security.oauth2.client.provider.linkedin.authorization-uri=https://www.linkedin.com/oauth/v2/authorization 30 | spring.security.oauth2.client.provider.linkedin.token-uri=https://www.linkedin.com/oauth/v2/accessToken 31 | spring.security.oauth2.client.provider.linkedin.user-info-uri=https://api.linkedin.com/v2/me 32 | spring.security.oauth2.client.provider.linkedin.user-name-attribute=id 33 | linkedin.email-address-uri=https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~)) 34 | 35 | app.auth.tokenSecret=926D96C90030DD58429D2751AC1BDBBC 36 | app.auth.tokenExpirationMsec=864000000 37 | # After successfully authenticating with the OAuth2 Provider, 38 | # we'll be generating an auth token for the user and sending the token to the 39 | # redirectUri mentioned by the frontend client in the /oauth2/authorization request. 40 | # We're not using cookies because they won't work well in mobile clients. 41 | app.oauth2.authorizedRedirectUris=https://client.javachinna.xyz/oauth2/redirect,myandroidapp://oauth2/redirect,myiosapp://oauth2/redirect 42 | # For detailed logging during development 43 | #logging.level.com=TRACE 44 | logging.level.org.springframework=INFO 45 | #logging.level.org.hibernate.SQL=TRACE 46 | #logging.level.org.hibernate.type=TRACE 47 | razorpay.key=rzp_test_tF42jI563EUWQE 48 | razorpay.secret=eGakMHimSEH7Lzb1f002golU -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/main/resources/messages_en.properties: -------------------------------------------------------------------------------- 1 | NotEmpty=This field is required. 2 | Size.userDto.password=Try one with at least 6 characters. 3 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/test/java/com/javachinna/config/MockUserUtils.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.config; 2 | 3 | import java.util.Set; 4 | 5 | import com.javachinna.model.Role; 6 | import com.javachinna.model.User; 7 | 8 | public class MockUserUtils { 9 | 10 | private MockUserUtils() { 11 | } 12 | /** 13 | * 14 | */ 15 | public static User getMockUser(String username) { 16 | User user = new User(); 17 | user.setId(1L); 18 | user.setEmail(username); 19 | user.setPassword("secret"); 20 | Role role = new Role(); 21 | role.setName(Role.ROLE_PRE_VERIFICATION_USER); 22 | user.setRoles(Set.of(role)); 23 | user.setEnabled(true); 24 | user.setSecret("secret"); 25 | return user; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/test/java/com/javachinna/config/TestSecurityConfig.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.config; 2 | 3 | import org.springframework.boot.test.context.TestConfiguration; 4 | import org.springframework.core.annotation.Order; 5 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 6 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 7 | 8 | @TestConfiguration 9 | @Order(1) 10 | public class TestSecurityConfig extends WebSecurityConfigurerAdapter { 11 | @Override 12 | protected void configure(HttpSecurity httpSecurity) throws Exception { 13 | // Disable CSRF 14 | httpSecurity.csrf().disable() 15 | // Permit all requests without authentication 16 | .authorizeRequests().anyRequest().permitAll(); 17 | } 18 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/test/java/com/javachinna/config/WithMockCustomUser.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.config; 2 | 3 | import java.lang.annotation.Retention; 4 | import java.lang.annotation.RetentionPolicy; 5 | 6 | import org.springframework.security.test.context.support.WithSecurityContext; 7 | 8 | @Retention(RetentionPolicy.RUNTIME) 9 | @WithSecurityContext(factory = WithMockCustomUserSecurityContextFactory.class) 10 | public @interface WithMockCustomUser { 11 | 12 | String username() default "JavaChinna"; 13 | 14 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/test/java/com/javachinna/config/WithMockCustomUserSecurityContextFactory.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.config; 2 | 3 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 4 | import org.springframework.security.core.Authentication; 5 | import org.springframework.security.core.context.SecurityContext; 6 | import org.springframework.security.core.context.SecurityContextHolder; 7 | import org.springframework.security.test.context.support.WithSecurityContextFactory; 8 | 9 | import com.javachinna.dto.LocalUser; 10 | import com.javachinna.model.User; 11 | 12 | public class WithMockCustomUserSecurityContextFactory implements WithSecurityContextFactory { 13 | @Override 14 | public SecurityContext createSecurityContext(WithMockCustomUser customUser) { 15 | SecurityContext context = SecurityContextHolder.createEmptyContext(); 16 | User user = MockUserUtils.getMockUser(customUser.username()); 17 | LocalUser localUser = LocalUser.create(user, null, null, null); 18 | Authentication auth = new UsernamePasswordAuthenticationToken(localUser, user.getPassword(), localUser.getAuthorities()); 19 | context.setAuthentication(auth); 20 | return context; 21 | } 22 | } -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/test/java/com/javachinna/controller/AuthControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.controller; 2 | 3 | import static org.mockito.ArgumentMatchers.any; 4 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; 5 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; 6 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 7 | 8 | import org.junit.jupiter.api.Test; 9 | import org.mockito.Mockito; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; 12 | import org.springframework.boot.test.context.SpringBootTest; 13 | import org.springframework.boot.test.mock.mockito.MockBean; 14 | import org.springframework.http.MediaType; 15 | import org.springframework.security.authentication.AuthenticationManager; 16 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 17 | import org.springframework.test.web.servlet.MockMvc; 18 | 19 | import com.fasterxml.jackson.databind.ObjectMapper; 20 | import com.javachinna.config.MockUserUtils; 21 | import com.javachinna.config.WithMockCustomUser; 22 | import com.javachinna.dto.LocalUser; 23 | import com.javachinna.dto.LoginRequest; 24 | import com.javachinna.dto.SignUpRequest; 25 | import com.javachinna.dto.SocialProvider; 26 | import com.javachinna.exception.UserAlreadyExistAuthenticationException; 27 | import com.javachinna.model.User; 28 | import com.javachinna.service.UserService; 29 | 30 | import dev.samstevens.totp.code.CodeVerifier;; 31 | 32 | @SpringBootTest 33 | @AutoConfigureMockMvc 34 | class AuthControllerTest { 35 | 36 | @Autowired 37 | private MockMvc mockMvc; 38 | 39 | @MockBean 40 | private UserService userService; 41 | 42 | @MockBean 43 | private CodeVerifier verifier; 44 | 45 | @MockBean 46 | private AuthenticationManager authenticationManager; 47 | 48 | private static User user = MockUserUtils.getMockUser("JavaChinna"); 49 | 50 | private static ObjectMapper mapper = new ObjectMapper(); 51 | 52 | @Test 53 | public void testAuthenticateUser() throws Exception { 54 | LocalUser localUser = LocalUser.create(user, null, null, null); 55 | LoginRequest loginRequest = new LoginRequest(user.getEmail(), user.getPassword()); 56 | UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(localUser, null); 57 | Mockito.when(authenticationManager.authenticate(Mockito.any(UsernamePasswordAuthenticationToken.class))).thenReturn(authentication); 58 | String json = mapper.writeValueAsString(loginRequest); 59 | mockMvc.perform(post("/api/auth/signin").contentType(MediaType.APPLICATION_JSON).characterEncoding("utf-8").content(json).accept(MediaType.APPLICATION_JSON)) 60 | .andExpect(status().isOk()).andExpect(jsonPath("$.authenticated").value("true")).andExpect(jsonPath("$.accessToken").isNotEmpty()); 61 | 62 | // Test when user 2fa is enabled 63 | user.setUsing2FA(true); 64 | mockMvc.perform(post("/api/auth/signin").contentType(MediaType.APPLICATION_JSON).characterEncoding("utf-8").content(json).accept(MediaType.APPLICATION_JSON)) 65 | .andExpect(status().isOk()).andExpect(jsonPath("$.authenticated").value("false")).andExpect(jsonPath("$.user").doesNotExist()); 66 | } 67 | 68 | @Test 69 | public void testRegisterUser() throws Exception { 70 | SignUpRequest signUpRequest = new SignUpRequest("1234", "JavaChinna", user.getEmail(), user.getPassword(), user.getPassword(), SocialProvider.FACEBOOK); 71 | Mockito.when(userService.registerNewUser(any(SignUpRequest.class))).thenReturn(user); 72 | String json = mapper.writeValueAsString(signUpRequest); 73 | mockMvc.perform(post("/api/auth/signup").contentType(MediaType.APPLICATION_JSON).characterEncoding("utf-8").content(json).accept(MediaType.APPLICATION_JSON)) 74 | .andExpect(status().isOk()).andExpect(jsonPath("$.success").value("true")).andExpect(jsonPath("$.message").value("User registered successfully")); 75 | 76 | // Test when user provided email already exists in the database 77 | Mockito.when(userService.registerNewUser(any(SignUpRequest.class))).thenThrow(new UserAlreadyExistAuthenticationException("exists")); 78 | json = mapper.writeValueAsString(signUpRequest); 79 | mockMvc.perform(post("/api/auth/signup").contentType(MediaType.APPLICATION_JSON).characterEncoding("utf-8").content(json).accept(MediaType.APPLICATION_JSON)) 80 | .andExpect(status().isBadRequest()).andExpect(jsonPath("$.success").value("false")).andExpect(jsonPath("$.message").value("Email Address already in use!")); 81 | } 82 | 83 | @Test 84 | @WithMockCustomUser 85 | public void testVerifyCodeWhenCodeIsNotValid() throws Exception { 86 | Mockito.when(verifier.isValidCode(Mockito.anyString(), Mockito.anyString())).thenReturn(false); 87 | String json = mapper.writeValueAsString("443322"); 88 | mockMvc.perform(post("/api/auth/verify").contentType(MediaType.APPLICATION_JSON).characterEncoding("utf-8").content(json).accept(MediaType.APPLICATION_JSON)) 89 | .andExpect(status().isBadRequest()).andExpect(jsonPath("$.success").value("false")).andExpect(jsonPath("$.message").value("Invalid Code!")); 90 | } 91 | 92 | @Test 93 | @WithMockCustomUser 94 | public void testVerifyCodeWhenCodeIsValid() throws Exception { 95 | Mockito.when(verifier.isValidCode(Mockito.anyString(), Mockito.anyString())).thenReturn(true); 96 | String json = mapper.writeValueAsString("443322"); 97 | mockMvc.perform(post("/api/auth/verify").contentType(MediaType.APPLICATION_JSON).characterEncoding("utf-8").content(json).accept(MediaType.APPLICATION_JSON)) 98 | .andExpect(status().isOk()).andExpect(jsonPath("$.authenticated").value("true")).andExpect(jsonPath("$.accessToken").isNotEmpty()) 99 | .andExpect(jsonPath("$.user").exists()); 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/test/java/com/javachinna/controller/AuthControllerTest2.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.controller; 2 | 3 | import static org.mockito.ArgumentMatchers.any; 4 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; 5 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; 6 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 7 | 8 | import org.junit.jupiter.api.BeforeEach; 9 | import org.junit.jupiter.api.Test; 10 | import org.junit.jupiter.api.TestInstance; 11 | import org.junit.jupiter.api.TestInstance.Lifecycle; 12 | import org.mockito.Mockito; 13 | import org.springframework.beans.factory.annotation.Autowired; 14 | import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; 15 | import org.springframework.boot.test.context.SpringBootTest; 16 | import org.springframework.boot.test.mock.mockito.MockBean; 17 | import org.springframework.http.MediaType; 18 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 19 | import org.springframework.security.core.context.SecurityContextHolder; 20 | import org.springframework.security.crypto.password.PasswordEncoder; 21 | import org.springframework.test.web.servlet.MockMvc; 22 | 23 | import com.fasterxml.jackson.databind.ObjectMapper; 24 | import com.javachinna.config.MockUserUtils; 25 | import com.javachinna.dto.LocalUser; 26 | import com.javachinna.dto.LoginRequest; 27 | import com.javachinna.dto.SignUpRequest; 28 | import com.javachinna.dto.SocialProvider; 29 | import com.javachinna.exception.UserAlreadyExistAuthenticationException; 30 | import com.javachinna.model.User; 31 | import com.javachinna.service.UserService; 32 | 33 | import dev.samstevens.totp.code.CodeVerifier; 34 | 35 | @SpringBootTest 36 | @TestInstance(Lifecycle.PER_CLASS) 37 | @AutoConfigureMockMvc 38 | class AuthControllerTest2 { 39 | 40 | @Autowired 41 | private MockMvc mockMvc; 42 | 43 | @MockBean 44 | private UserService userService; 45 | 46 | @MockBean 47 | private CodeVerifier verifier; 48 | 49 | @MockBean 50 | private PasswordEncoder passwordEncoder; 51 | 52 | private static User user = MockUserUtils.getMockUser("JavaChinna"); 53 | 54 | private static ObjectMapper mapper = new ObjectMapper(); 55 | 56 | @BeforeEach 57 | public void init() { 58 | LocalUser localUser = LocalUser.create(user, null, null, null); 59 | SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(localUser, "secret")); 60 | Mockito.when(userService.findUserByEmail(Mockito.anyString())).thenReturn(user); 61 | Mockito.when(passwordEncoder.matches(Mockito.anyString(), Mockito.anyString())).thenReturn(true); 62 | } 63 | 64 | @Test 65 | public void testAuthenticateUser() throws Exception { 66 | LoginRequest loginRequest = new LoginRequest(user.getEmail(), user.getPassword()); 67 | String json = mapper.writeValueAsString(loginRequest); 68 | mockMvc.perform(post("/api/auth/signin").contentType(MediaType.APPLICATION_JSON).characterEncoding("utf-8").content(json).accept(MediaType.APPLICATION_JSON)) 69 | .andExpect(status().isOk()).andExpect(jsonPath("$.authenticated").value("true")).andExpect(jsonPath("$.accessToken").isNotEmpty()); 70 | 71 | // Test when user 2fa is enabled 72 | user.setUsing2FA(true); 73 | mockMvc.perform(post("/api/auth/signin").contentType(MediaType.APPLICATION_JSON).characterEncoding("utf-8").content(json).accept(MediaType.APPLICATION_JSON)) 74 | .andExpect(status().isOk()).andExpect(jsonPath("$.authenticated").value("false")).andExpect(jsonPath("$.user").doesNotExist()); 75 | } 76 | 77 | @Test 78 | public void testRegisterUser() throws Exception { 79 | SignUpRequest signUpRequest = new SignUpRequest("1234", "JavaChinna", user.getEmail(), user.getPassword(), user.getPassword(), SocialProvider.FACEBOOK); 80 | // Test when user provided email already exists in the database 81 | Mockito.when(userService.registerNewUser(any(SignUpRequest.class))).thenReturn(user); 82 | String json = mapper.writeValueAsString(signUpRequest); 83 | mockMvc.perform(post("/api/auth/signup").contentType(MediaType.APPLICATION_JSON).characterEncoding("utf-8").content(json).accept(MediaType.APPLICATION_JSON)) 84 | .andExpect(status().isOk()).andExpect(jsonPath("$.success").value("true")).andExpect(jsonPath("$.message").value("User registered successfully")); 85 | 86 | // Test when user provided email already exists in the database 87 | Mockito.when(userService.registerNewUser(any(SignUpRequest.class))).thenThrow(new UserAlreadyExistAuthenticationException("exists")); 88 | json = mapper.writeValueAsString(signUpRequest); 89 | mockMvc.perform(post("/api/auth/signup").contentType(MediaType.APPLICATION_JSON).characterEncoding("utf-8").content(json).accept(MediaType.APPLICATION_JSON)) 90 | .andExpect(status().isBadRequest()).andExpect(jsonPath("$.success").value("false")).andExpect(jsonPath("$.message").value("Email Address already in use!")); 91 | } 92 | 93 | @Test 94 | public void testVerifyCodeWhenCodeIsNotValid() throws Exception { 95 | Mockito.when(verifier.isValidCode(Mockito.anyString(), Mockito.anyString())).thenReturn(false); 96 | String json = mapper.writeValueAsString("443322"); 97 | mockMvc.perform(post("/api/auth/verify").contentType(MediaType.APPLICATION_JSON).characterEncoding("utf-8").content(json).accept(MediaType.APPLICATION_JSON)) 98 | .andExpect(status().isBadRequest()).andExpect(jsonPath("$.success").value("false")).andExpect(jsonPath("$.message").value("Invalid Code!")); 99 | } 100 | 101 | @Test 102 | public void testVerifyCodeWhenCodeIsValid() throws Exception { 103 | Mockito.when(verifier.isValidCode(Mockito.anyString(), Mockito.anyString())).thenReturn(true); 104 | String json = mapper.writeValueAsString("443322"); 105 | mockMvc.perform(post("/api/auth/verify").contentType(MediaType.APPLICATION_JSON).characterEncoding("utf-8").content(json).accept(MediaType.APPLICATION_JSON)) 106 | .andExpect(status().isOk()).andExpect(jsonPath("$.authenticated").value("true")).andExpect(jsonPath("$.accessToken").isNotEmpty()) 107 | .andExpect(jsonPath("$.user").exists()); 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /spring-boot-oauth2-social-login/src/test/java/com/javachinna/controller/OrderControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.controller; 2 | 3 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; 4 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; 5 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 6 | 7 | import org.junit.jupiter.api.Test; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; 10 | import org.springframework.boot.test.context.SpringBootTest; 11 | import org.springframework.boot.test.mock.mockito.MockBean; 12 | import org.springframework.http.MediaType; 13 | import org.springframework.security.crypto.password.PasswordEncoder; 14 | import org.springframework.test.web.servlet.MockMvc; 15 | 16 | import com.fasterxml.jackson.databind.ObjectMapper; 17 | import com.javachinna.config.TestSecurityConfig; 18 | import com.javachinna.dto.payment.PaymentResponse; 19 | import com.javachinna.service.OrderService; 20 | 21 | @SpringBootTest(classes = TestSecurityConfig.class) 22 | @AutoConfigureMockMvc 23 | class OrderControllerTest { 24 | 25 | @Autowired 26 | private MockMvc mockMvc; 27 | 28 | @MockBean 29 | private OrderService orderService; 30 | 31 | @MockBean 32 | private PasswordEncoder passwordEncoder; 33 | 34 | private static ObjectMapper mapper = new ObjectMapper(); 35 | 36 | @Test 37 | public void testUpdateOrder() throws Exception { 38 | PaymentResponse paymentResponse = new PaymentResponse(); 39 | paymentResponse.setRazorpayPaymentId("22445566"); 40 | String json = mapper.writeValueAsString(paymentResponse); 41 | mockMvc.perform(put("/api/order").contentType(MediaType.APPLICATION_JSON).characterEncoding("utf-8").content(json).accept(MediaType.APPLICATION_JSON)) 42 | .andExpect(status().isOk()).andExpect(jsonPath("$.success").value("true")).andExpect(jsonPath("$.message").isNotEmpty()); 43 | } 44 | } 45 | --------------------------------------------------------------------------------