├── two-factor-auth-client
├── src
│ ├── signup
│ │ ├── Signup.css
│ │ └── Signup.js
│ ├── App.css
│ ├── verifycode
│ │ ├── VerifyCode.css
│ │ └── VerifyCode.js
│ ├── setupTests.js
│ ├── App.test.js
│ ├── qrcode
│ │ ├── QrCode.css
│ │ └── QrCode.js
│ ├── index.css
│ ├── profile
│ │ ├── Profile.css
│ │ └── Profile.js
│ ├── index.js
│ ├── signin
│ │ ├── Signin.css
│ │ └── Signin.js
│ ├── App.js
│ ├── util
│ │ └── ApiUtil.js
│ ├── logo.svg
│ └── serviceWorker.js
├── public
│ ├── robots.txt
│ ├── favicon.ico
│ ├── logo192.png
│ ├── logo512.png
│ ├── manifest.json
│ └── index.html
├── .gitignore
├── package.json
└── README.md
├── thumbnail.png
├── auth-service
├── .mvn
│ └── wrapper
│ │ ├── maven-wrapper.jar
│ │ └── maven-wrapper.properties
├── src
│ ├── main
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── clone
│ │ │ │ └── instagram
│ │ │ │ └── authservice
│ │ │ │ ├── payload
│ │ │ │ ├── VerifyCodeRequest.java
│ │ │ │ ├── ApiResponse.java
│ │ │ │ ├── SignupResponse.java
│ │ │ │ ├── LoginRequest.java
│ │ │ │ ├── UserSummary.java
│ │ │ │ ├── JwtAuthenticationResponse.java
│ │ │ │ └── SignUpRequest.java
│ │ │ │ ├── exception
│ │ │ │ ├── EmailAlreadyExistsException.java
│ │ │ │ ├── UsernameAlreadyExistsException.java
│ │ │ │ ├── BadRequestException.java
│ │ │ │ ├── InternalServerException.java
│ │ │ │ └── ResourceNotFoundException.java
│ │ │ │ ├── model
│ │ │ │ ├── Role.java
│ │ │ │ ├── Address.java
│ │ │ │ ├── Profile.java
│ │ │ │ ├── InstaUserDetails.java
│ │ │ │ └── User.java
│ │ │ │ ├── repository
│ │ │ │ └── UserRepository.java
│ │ │ │ ├── AuthServiceApplication.java
│ │ │ │ ├── config
│ │ │ │ ├── JwtConfig.java
│ │ │ │ ├── JwtTokenAuthenticationFilter.java
│ │ │ │ └── SecurityCredentialsConfig.java
│ │ │ │ ├── service
│ │ │ │ ├── InstaUserDetailsService.java
│ │ │ │ ├── TotpManager.java
│ │ │ │ ├── JwtTokenManager.java
│ │ │ │ └── UserService.java
│ │ │ │ └── endpoint
│ │ │ │ ├── UserEndpoint.java
│ │ │ │ └── AuthEndpoint.java
│ │ └── resources
│ │ │ ├── banner.txt
│ │ │ ├── bootstrap.yml
│ │ │ └── application.yml
│ └── test
│ │ └── java
│ │ └── com
│ │ └── clone
│ │ └── instagram
│ │ └── authservice
│ │ └── AuthServiceApplicationTests.java
├── Dockerfile
├── .gitignore
├── pom.xml
├── mvnw.cmd
└── mvnw
└── README.md
/two-factor-auth-client/src/signup/Signup.css:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/thumbnail.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/amrkhaledccd/two-factor-authentication/HEAD/thumbnail.png
--------------------------------------------------------------------------------
/two-factor-auth-client/public/robots.txt:
--------------------------------------------------------------------------------
1 | # https://www.robotstxt.org/robotstxt.html
2 | User-agent: *
3 | Disallow:
4 |
--------------------------------------------------------------------------------
/two-factor-auth-client/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/amrkhaledccd/two-factor-authentication/HEAD/two-factor-auth-client/public/favicon.ico
--------------------------------------------------------------------------------
/two-factor-auth-client/public/logo192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/amrkhaledccd/two-factor-authentication/HEAD/two-factor-auth-client/public/logo192.png
--------------------------------------------------------------------------------
/two-factor-auth-client/public/logo512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/amrkhaledccd/two-factor-authentication/HEAD/two-factor-auth-client/public/logo512.png
--------------------------------------------------------------------------------
/auth-service/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/amrkhaledccd/two-factor-authentication/HEAD/auth-service/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/auth-service/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.5.4/apache-maven-3.5.4-bin.zip
2 |
--------------------------------------------------------------------------------
/two-factor-auth-client/src/App.css:
--------------------------------------------------------------------------------
1 | @import "~antd/dist/antd.css";
2 |
3 | body {
4 | background-color: #fafafa;
5 | }
6 |
7 | .App {
8 | padding-top: 50px;
9 | }
10 |
--------------------------------------------------------------------------------
/two-factor-auth-client/src/verifycode/VerifyCode.css:
--------------------------------------------------------------------------------
1 | .verify-form-button {
2 | margin-left: 10px;
3 | background-color: rebeccapurple !important;
4 | color: white !important;
5 | font-weight: 700 !important;
6 | }
7 |
--------------------------------------------------------------------------------
/auth-service/src/main/java/com/clone/instagram/authservice/payload/VerifyCodeRequest.java:
--------------------------------------------------------------------------------
1 | package com.clone.instagram.authservice.payload;
2 |
3 | import lombok.Data;
4 |
5 | @Data
6 | public class VerifyCodeRequest {
7 | private String username;
8 | private String code;
9 | }
10 |
--------------------------------------------------------------------------------
/two-factor-auth-client/src/setupTests.js:
--------------------------------------------------------------------------------
1 | // jest-dom adds custom jest matchers for asserting on DOM nodes.
2 | // allows you to do things like:
3 | // expect(element).toHaveTextContent(/react/i)
4 | // learn more: https://github.com/testing-library/jest-dom
5 | import '@testing-library/jest-dom/extend-expect';
6 |
--------------------------------------------------------------------------------
/auth-service/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM openjdk:10-jre-slim
2 |
3 | LABEL maintainer="amrkhaledccd@hotmail.com"
4 | VOLUME /tmp
5 |
6 | EXPOSE 8080
7 |
8 | ARG JAR_FILE=target/auth-service-0.0.1-SNAPSHOT.jar
9 |
10 | ADD ${JAR_FILE} app.jar
11 |
12 | ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"]
--------------------------------------------------------------------------------
/auth-service/src/main/java/com/clone/instagram/authservice/exception/EmailAlreadyExistsException.java:
--------------------------------------------------------------------------------
1 | package com.clone.instagram.authservice.exception;
2 |
3 |
4 | public class EmailAlreadyExistsException extends RuntimeException {
5 |
6 | public EmailAlreadyExistsException(String message) {
7 | super(message);
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/auth-service/src/main/java/com/clone/instagram/authservice/payload/ApiResponse.java:
--------------------------------------------------------------------------------
1 | package com.clone.instagram.authservice.payload;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Data;
5 |
6 | @Data
7 | @AllArgsConstructor
8 | public class ApiResponse {
9 |
10 | private Boolean success;
11 | private String message;
12 | }
13 |
--------------------------------------------------------------------------------
/auth-service/src/main/java/com/clone/instagram/authservice/exception/UsernameAlreadyExistsException.java:
--------------------------------------------------------------------------------
1 | package com.clone.instagram.authservice.exception;
2 |
3 |
4 | public class UsernameAlreadyExistsException extends RuntimeException {
5 |
6 | public UsernameAlreadyExistsException(String message) {
7 | super(message);
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/auth-service/src/main/java/com/clone/instagram/authservice/payload/SignupResponse.java:
--------------------------------------------------------------------------------
1 | package com.clone.instagram.authservice.payload;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Data;
5 |
6 | @Data
7 | @AllArgsConstructor
8 | public class SignupResponse {
9 | private boolean mfa;
10 | private String secretImageUri;
11 | }
12 |
--------------------------------------------------------------------------------
/two-factor-auth-client/src/App.test.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { render } from '@testing-library/react';
3 | import App from './App';
4 |
5 | test('renders learn react link', () => {
6 | const { getByText } = render();
7 | const linkElement = getByText(/learn react/i);
8 | expect(linkElement).toBeInTheDocument();
9 | });
10 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Tutorial
2 | [Spring Boot Two-Factor Authentication (JWT and Authenticator App)](https://medium.com/javarevisited/spring-boot-two-factor-authentication-78e00aa10176)
3 |
4 | # Video overview
5 | [](https://www.youtube.com/watch?v=4EictjTARpY)
6 |
--------------------------------------------------------------------------------
/auth-service/src/main/resources/banner.txt:
--------------------------------------------------------------------------------
1 |
2 | _____ _ _ _
3 | |_ _| | | | | | |
4 | | | _ __ ___| |_ __ _ __ _ _ _| |_| |__
5 | | | | '_ \/ __| __/ _` | / _` | | | | __| '_ \
6 | _| |_| | | \__ \ || (_| | | (_| | |_| | |_| | | |
7 | |_____|_| |_|___/\__\__,_| \__,_|\__,_|\__|_| |_|
8 |
9 |
--------------------------------------------------------------------------------
/two-factor-auth-client/src/qrcode/QrCode.css:
--------------------------------------------------------------------------------
1 | .qrcode-container {
2 | max-width: 480px;
3 | margin: 0 auto;
4 | margin: 0 auto;
5 | margin-top: 40px;
6 | padding: 30px 50px 10px 50px;
7 | border: 1px solid #e1e0e0;
8 | background-color: #fff;
9 | font-size: 32px;
10 | font-weight: 700;
11 | border-radius: 10px;
12 | text-align: center;
13 | }
14 |
--------------------------------------------------------------------------------
/auth-service/src/main/java/com/clone/instagram/authservice/payload/LoginRequest.java:
--------------------------------------------------------------------------------
1 | package com.clone.instagram.authservice.payload;
2 |
3 | import lombok.Data;
4 |
5 | import javax.validation.constraints.NotBlank;
6 |
7 | @Data
8 | public class LoginRequest {
9 |
10 | @NotBlank
11 | private String username;
12 |
13 | @NotBlank
14 | private String password;
15 | }
16 |
--------------------------------------------------------------------------------
/auth-service/src/main/java/com/clone/instagram/authservice/payload/UserSummary.java:
--------------------------------------------------------------------------------
1 | package com.clone.instagram.authservice.payload;
2 |
3 | import lombok.Builder;
4 | import lombok.Data;
5 |
6 | @Data
7 | @Builder
8 | public class UserSummary {
9 |
10 | private String id;
11 | private String username;
12 | private String name;
13 | private String profilePicture;
14 | }
15 |
--------------------------------------------------------------------------------
/auth-service/.gitignore:
--------------------------------------------------------------------------------
1 | /target/
2 | !.mvn/wrapper/maven-wrapper.jar
3 |
4 | ### STS ###
5 | .apt_generated
6 | .classpath
7 | .factorypath
8 | .project
9 | .settings
10 | .springBeans
11 | .sts4-cache
12 | .DS_Store
13 |
14 | ### IntelliJ IDEA ###
15 | .idea
16 | *.iws
17 | *.iml
18 | *.ipr
19 |
20 | ### NetBeans ###
21 | /nbproject/private/
22 | /build/
23 | /nbbuild/
24 | /dist/
25 | /nbdist/
26 | /.nb-gradle/
27 |
--------------------------------------------------------------------------------
/auth-service/src/main/java/com/clone/instagram/authservice/model/Role.java:
--------------------------------------------------------------------------------
1 | package com.clone.instagram.authservice.model;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Data;
5 | import lombok.NoArgsConstructor;
6 |
7 |
8 | @Data
9 | @NoArgsConstructor
10 | @AllArgsConstructor
11 | public class Role {
12 |
13 | public final static Role USER = new Role("USER");
14 |
15 | private String name;
16 | }
17 |
18 |
--------------------------------------------------------------------------------
/two-factor-auth-client/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | /node_modules
5 | /.pnp
6 | .pnp.js
7 |
8 | # testing
9 | /coverage
10 |
11 | # production
12 | /build
13 |
14 | # misc
15 | .DS_Store
16 | .env.local
17 | .env.development.local
18 | .env.test.local
19 | .env.production.local
20 |
21 | npm-debug.log*
22 | yarn-debug.log*
23 | yarn-error.log*
24 |
--------------------------------------------------------------------------------
/auth-service/src/main/resources/bootstrap.yml:
--------------------------------------------------------------------------------
1 | spring:
2 | application:
3 | name: insta-auth
4 |
5 | cloud:
6 | kubernetes:
7 | reload:
8 | period: 1000
9 | enabled: true
10 | config:
11 | enabled: true
12 | name: insta-configs
13 | namespace: default
14 | sources:
15 | - name: insta-configs
16 |
17 | management:
18 | endpoint:
19 | restart:
20 | enabled: true
--------------------------------------------------------------------------------
/two-factor-auth-client/src/index.css:
--------------------------------------------------------------------------------
1 | body {
2 | margin: 0;
3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
5 | sans-serif;
6 | -webkit-font-smoothing: antialiased;
7 | -moz-osx-font-smoothing: grayscale;
8 | }
9 |
10 | code {
11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
12 | monospace;
13 | }
14 |
--------------------------------------------------------------------------------
/auth-service/src/main/java/com/clone/instagram/authservice/model/Address.java:
--------------------------------------------------------------------------------
1 | package com.clone.instagram.authservice.model;
2 |
3 | import lombok.Data;
4 | import lombok.NoArgsConstructor;
5 |
6 |
7 | @Data
8 | @NoArgsConstructor
9 | public class Address {
10 |
11 | private String id;
12 | private String country;
13 | private String city;
14 | private String zipCode;
15 | private String streetName;
16 | private int buildingNumber;
17 | }
18 |
19 |
--------------------------------------------------------------------------------
/auth-service/src/main/java/com/clone/instagram/authservice/model/Profile.java:
--------------------------------------------------------------------------------
1 | package com.clone.instagram.authservice.model;
2 |
3 | import lombok.*;
4 | import java.util.Date;
5 | import java.util.Set;
6 |
7 |
8 | @Data
9 | @Builder
10 | @NoArgsConstructor
11 | @AllArgsConstructor
12 | public class Profile {
13 |
14 | private String displayName;
15 | private String profilePictureUrl;
16 | private Date birthday;
17 | private Set
addresses;
18 | }
19 |
--------------------------------------------------------------------------------
/auth-service/src/main/java/com/clone/instagram/authservice/exception/BadRequestException.java:
--------------------------------------------------------------------------------
1 | package com.clone.instagram.authservice.exception;
2 |
3 |
4 | import org.springframework.http.HttpStatus;
5 | import org.springframework.web.bind.annotation.ResponseStatus;
6 |
7 | @ResponseStatus(HttpStatus.BAD_REQUEST)
8 | public class BadRequestException extends RuntimeException {
9 |
10 | public BadRequestException(String message) {
11 | super(message);
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/auth-service/src/main/java/com/clone/instagram/authservice/payload/JwtAuthenticationResponse.java:
--------------------------------------------------------------------------------
1 | package com.clone.instagram.authservice.payload;
2 |
3 |
4 | import lombok.AllArgsConstructor;
5 | import lombok.Data;
6 | import lombok.NonNull;
7 | import lombok.RequiredArgsConstructor;
8 |
9 | @Data
10 | @RequiredArgsConstructor
11 | @AllArgsConstructor
12 | public class JwtAuthenticationResponse {
13 |
14 | @NonNull
15 | private String accessToken;
16 | private boolean mfa;
17 | }
18 |
--------------------------------------------------------------------------------
/auth-service/src/main/java/com/clone/instagram/authservice/exception/InternalServerException.java:
--------------------------------------------------------------------------------
1 | package com.clone.instagram.authservice.exception;
2 |
3 |
4 | import org.springframework.http.HttpStatus;
5 | import org.springframework.web.bind.annotation.ResponseStatus;
6 |
7 | @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
8 | public class InternalServerException extends RuntimeException {
9 |
10 | public InternalServerException(String message) {
11 | super(message);
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/auth-service/src/test/java/com/clone/instagram/authservice/AuthServiceApplicationTests.java:
--------------------------------------------------------------------------------
1 | package com.clone.instagram.authservice;
2 |
3 | import org.junit.Test;
4 | import org.junit.runner.RunWith;
5 | import org.springframework.boot.test.context.SpringBootTest;
6 | import org.springframework.test.context.junit4.SpringRunner;
7 |
8 | @RunWith(SpringRunner.class)
9 | @SpringBootTest
10 | public class AuthServiceApplicationTests {
11 |
12 | @Test
13 | public void contextLoads() {
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/auth-service/src/main/resources/application.yml:
--------------------------------------------------------------------------------
1 | spring:
2 | data:
3 | mongodb:
4 | database: instaclone_auth
5 |
6 | server:
7 | port: 8081
8 |
9 | security:
10 | basic:
11 | enable: false
12 |
13 | jwt:
14 | uri: /auth/**
15 | header: Authorization
16 | prefix: Bearer
17 | expiration: 86400
18 | secret: JwtSecretKey
19 |
20 | feign:
21 | client:
22 | config:
23 | default:
24 | connectTimeout: 5000
25 | readTimeout: 5000
26 | loggerLevel: basic
--------------------------------------------------------------------------------
/two-factor-auth-client/src/profile/Profile.css:
--------------------------------------------------------------------------------
1 | .profile-container {
2 | max-width: 420px;
3 | margin: 0 auto;
4 | margin: 0 auto;
5 | margin-top: 40px;
6 | /* border: 1px solid #e1e0e0;
7 | background-color: #fff;
8 | border-radius: 10px; */
9 | }
10 |
11 | .user-avatar-circle {
12 | width: 150px !important;
13 | height: 150px !important;
14 | cursor: pointer;
15 | }
16 |
17 | .ant-card-meta-title {
18 | font-size: 28px !important;
19 | }
20 |
21 | .ant-card-meta-description {
22 | font-size: 14px;
23 | }
24 |
--------------------------------------------------------------------------------
/auth-service/src/main/java/com/clone/instagram/authservice/exception/ResourceNotFoundException.java:
--------------------------------------------------------------------------------
1 | package com.clone.instagram.authservice.exception;
2 |
3 | import org.springframework.http.HttpStatus;
4 | import org.springframework.web.bind.annotation.ResponseStatus;
5 |
6 |
7 | @ResponseStatus(HttpStatus.NOT_FOUND)
8 | public class ResourceNotFoundException extends RuntimeException {
9 |
10 | public ResourceNotFoundException(String resource) {
11 | super(String.format("Resource %s not found", resource));
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/auth-service/src/main/java/com/clone/instagram/authservice/repository/UserRepository.java:
--------------------------------------------------------------------------------
1 | package com.clone.instagram.authservice.repository;
2 |
3 | import com.clone.instagram.authservice.model.User;
4 | import org.springframework.data.mongodb.repository.MongoRepository;
5 | import java.util.Optional;
6 |
7 |
8 | public interface UserRepository extends MongoRepository {
9 |
10 | Optional findByUsername(String username);
11 | Boolean existsByUsername(String username);
12 | Boolean existsByEmail(String email);
13 | }
14 |
--------------------------------------------------------------------------------
/two-factor-auth-client/src/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import './index.css';
4 | import App from './App';
5 | import * as serviceWorker from './serviceWorker';
6 |
7 | ReactDOM.render(
8 |
9 |
10 | ,
11 | document.getElementById('root')
12 | );
13 |
14 | // If you want your app to work offline and load faster, you can change
15 | // unregister() to register() below. Note this comes with some pitfalls.
16 | // Learn more about service workers: https://bit.ly/CRA-PWA
17 | serviceWorker.unregister();
18 |
--------------------------------------------------------------------------------
/auth-service/src/main/java/com/clone/instagram/authservice/AuthServiceApplication.java:
--------------------------------------------------------------------------------
1 | package com.clone.instagram.authservice;
2 |
3 | import lombok.extern.slf4j.Slf4j;
4 | import org.springframework.boot.SpringApplication;
5 | import org.springframework.boot.autoconfigure.SpringBootApplication;
6 | import org.springframework.data.mongodb.config.EnableMongoAuditing;
7 |
8 | @SpringBootApplication
9 | @EnableMongoAuditing
10 | @Slf4j
11 | public class AuthServiceApplication {
12 |
13 | public static void main(String[] args) {
14 | SpringApplication.run(AuthServiceApplication.class, args);
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/two-factor-auth-client/public/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "short_name": "React App",
3 | "name": "Create React App Sample",
4 | "icons": [
5 | {
6 | "src": "favicon.ico",
7 | "sizes": "64x64 32x32 24x24 16x16",
8 | "type": "image/x-icon"
9 | },
10 | {
11 | "src": "logo192.png",
12 | "type": "image/png",
13 | "sizes": "192x192"
14 | },
15 | {
16 | "src": "logo512.png",
17 | "type": "image/png",
18 | "sizes": "512x512"
19 | }
20 | ],
21 | "start_url": ".",
22 | "display": "standalone",
23 | "theme_color": "#000000",
24 | "background_color": "#ffffff"
25 | }
26 |
--------------------------------------------------------------------------------
/two-factor-auth-client/src/signin/Signin.css:
--------------------------------------------------------------------------------
1 | .login-container {
2 | max-width: 420px;
3 | margin: 0 auto;
4 | margin: 0 auto;
5 | margin-top: 40px;
6 | padding: 30px 50px 10px 50px;
7 | border: 1px solid #e1e0e0;
8 | background-color: #fff;
9 | font-size: 32px;
10 | font-weight: 700;
11 | border-radius: 10px;
12 | text-align: center;
13 | }
14 |
15 | .login-form-button {
16 | width: 100%;
17 | background-color: rebeccapurple !important;
18 | color: white !important;
19 | font-weight: 700 !important;
20 | }
21 |
22 | .login-with-facebook {
23 | width: 100%;
24 | background-color: #1877f2 !important;
25 | color: white !important;
26 | font-weight: 700 !important;
27 | }
28 |
--------------------------------------------------------------------------------
/auth-service/src/main/java/com/clone/instagram/authservice/payload/SignUpRequest.java:
--------------------------------------------------------------------------------
1 | package com.clone.instagram.authservice.payload;
2 |
3 | import lombok.Data;
4 |
5 | import javax.validation.constraints.Email;
6 | import javax.validation.constraints.NotBlank;
7 | import javax.validation.constraints.Size;
8 |
9 | @Data
10 | public class SignUpRequest {
11 |
12 | @NotBlank
13 | @Size(min = 3, max = 40)
14 | private String name;
15 |
16 | @NotBlank
17 | @Size(min = 3, max = 15)
18 | private String username;
19 |
20 | @NotBlank
21 | @Size(max = 40)
22 | @Email
23 | private String email;
24 |
25 | @NotBlank
26 | @Size(min = 6, max = 20)
27 | private String password;
28 |
29 | private boolean mfa;
30 | }
31 |
--------------------------------------------------------------------------------
/auth-service/src/main/java/com/clone/instagram/authservice/config/JwtConfig.java:
--------------------------------------------------------------------------------
1 | package com.clone.instagram.authservice.config;
2 |
3 | import lombok.Data;
4 | import lombok.NoArgsConstructor;
5 | import org.springframework.beans.factory.annotation.Value;
6 | import org.springframework.stereotype.Component;
7 |
8 |
9 | @Data
10 | @NoArgsConstructor
11 | @Component
12 | public class JwtConfig {
13 |
14 | @Value("${security.jwt.uri:}")
15 | private String Uri;
16 |
17 | @Value("${security.jwt.header:}")
18 | private String header;
19 |
20 | @Value("${security.jwt.prefix:}")
21 | private String prefix;
22 |
23 | @Value("${security.jwt.expiration:1234}")
24 | private int expiration;
25 |
26 | @Value("${security.jwt.secret:}")
27 | private String secret;
28 | }
29 |
--------------------------------------------------------------------------------
/two-factor-auth-client/src/qrcode/QrCode.js:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import { Button, Typography } from "antd";
3 | import { DingtalkOutlined } from "@ant-design/icons";
4 | import "./QrCode.css";
5 |
6 | const QrCode = (props) => {
7 | const { Title } = Typography;
8 |
9 | return (
10 |
11 |
12 |
Scan the QrCode using authenticator app
13 |

14 |
22 |
23 | );
24 | };
25 |
26 | export default QrCode;
27 |
--------------------------------------------------------------------------------
/two-factor-auth-client/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "two-factor-auth-client",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "@ant-design/icons": "^4.2.1",
7 | "@testing-library/jest-dom": "^4.2.4",
8 | "@testing-library/react": "^9.5.0",
9 | "@testing-library/user-event": "^7.2.1",
10 | "antd": "^4.4.0",
11 | "react": "^16.13.1",
12 | "react-dom": "^16.13.1",
13 | "react-router": "^5.2.0",
14 | "react-router-dom": "^5.2.0",
15 | "react-scripts": "3.4.1"
16 | },
17 | "scripts": {
18 | "start": "react-scripts start",
19 | "build": "react-scripts build",
20 | "test": "react-scripts test",
21 | "eject": "react-scripts eject"
22 | },
23 | "eslintConfig": {
24 | "extends": "react-app"
25 | },
26 | "browserslist": {
27 | "production": [
28 | ">0.2%",
29 | "not dead",
30 | "not op_mini all"
31 | ],
32 | "development": [
33 | "last 1 chrome version",
34 | "last 1 firefox version",
35 | "last 1 safari version"
36 | ]
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/auth-service/src/main/java/com/clone/instagram/authservice/service/InstaUserDetailsService.java:
--------------------------------------------------------------------------------
1 | package com.clone.instagram.authservice.service;
2 |
3 | import com.clone.instagram.authservice.model.InstaUserDetails;
4 | import org.springframework.beans.factory.annotation.Autowired;
5 | import org.springframework.security.core.userdetails.UserDetails;
6 | import org.springframework.security.core.userdetails.UserDetailsService;
7 | import org.springframework.security.core.userdetails.UsernameNotFoundException;
8 | import org.springframework.stereotype.Service;
9 |
10 | @Service
11 | public class InstaUserDetailsService implements UserDetailsService {
12 |
13 | @Autowired
14 | private UserService userService;
15 |
16 | @Override
17 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
18 |
19 | return userService
20 | .findByUsername(username)
21 | .map(InstaUserDetails::new)
22 | .orElseThrow(() -> new UsernameNotFoundException("Username not found"));
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/two-factor-auth-client/src/App.js:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import { BrowserRouter, Route, Switch } from "react-router-dom";
3 | import Signin from "./signin/Signin";
4 | import Signup from "./signup/Signup";
5 | import Profile from "./profile/Profile";
6 | import QrCode from "./qrcode/QrCode";
7 | import VerifyCode from "./verifycode/VerifyCode";
8 |
9 | import "./App.css";
10 |
11 | const App = (props) => {
12 | return (
13 |
14 |
15 |
16 | } />
17 | }
21 | />
22 | }
26 | />
27 | }
31 | />
32 | }
36 | />
37 |
38 |
39 |
40 | );
41 | };
42 |
43 | export default App;
44 |
--------------------------------------------------------------------------------
/auth-service/src/main/java/com/clone/instagram/authservice/model/InstaUserDetails.java:
--------------------------------------------------------------------------------
1 | package com.clone.instagram.authservice.model;
2 |
3 | import org.springframework.security.core.GrantedAuthority;
4 | import org.springframework.security.core.authority.SimpleGrantedAuthority;
5 | import org.springframework.security.core.userdetails.UserDetails;
6 | import java.util.Collection;
7 | import java.util.stream.Collectors;
8 |
9 |
10 | public class InstaUserDetails extends User implements UserDetails {
11 |
12 | public InstaUserDetails(final User user) {
13 | super(user);
14 | }
15 |
16 | @Override
17 | public Collection extends GrantedAuthority> getAuthorities() {
18 |
19 | return getRoles()
20 | .stream()
21 | .map(role -> new SimpleGrantedAuthority("ROLE_" +role.getName()))
22 | .collect(Collectors.toSet());
23 | }
24 |
25 | @Override
26 | public boolean isAccountNonExpired() {
27 | return isActive();
28 | }
29 |
30 | @Override
31 | public boolean isAccountNonLocked() {
32 | return isActive();
33 | }
34 |
35 | @Override
36 | public boolean isCredentialsNonExpired() {
37 | return isActive();
38 | }
39 |
40 | @Override
41 | public boolean isEnabled() {
42 | return isActive();
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/two-factor-auth-client/src/profile/Profile.js:
--------------------------------------------------------------------------------
1 | import React, { useEffect, useState } from "react";
2 | import { Button, Card, Avatar } from "antd";
3 | import { LogoutOutlined } from "@ant-design/icons";
4 | import { getCurrentUser } from "../util/ApiUtil";
5 | import "./Profile.css";
6 |
7 | const { Meta } = Card;
8 |
9 | const Profile = (props) => {
10 | const [currentUser, setCurrentUser] = useState({});
11 | useEffect(() => {
12 | if (localStorage.getItem("accessToken") === null) {
13 | props.history.push("/login");
14 | }
15 | loadCurrentUser();
16 | }, []);
17 |
18 | const loadCurrentUser = () => {
19 | getCurrentUser()
20 | .then((response) => {
21 | console.log(response);
22 | setCurrentUser(response);
23 | })
24 | .catch((error) => {
25 | // logout();
26 | console.log(error);
27 | });
28 | };
29 |
30 | const logout = () => {
31 | localStorage.removeItem("accessToken");
32 | props.history.push("/login");
33 | };
34 |
35 | return (
36 |
37 | ]}
40 | >
41 |
47 | }
48 | title={currentUser.name}
49 | description={"@" + currentUser.username}
50 | />
51 |
52 |
53 | );
54 | };
55 |
56 | export default Profile;
57 |
--------------------------------------------------------------------------------
/two-factor-auth-client/src/util/ApiUtil.js:
--------------------------------------------------------------------------------
1 | const request = (options) => {
2 | const headers = new Headers();
3 |
4 | if (options.setContentType !== false) {
5 | headers.append("Content-Type", "application/json");
6 | }
7 |
8 | if (localStorage.getItem("accessToken")) {
9 | headers.append(
10 | "Authorization",
11 | "Bearer " + localStorage.getItem("accessToken")
12 | );
13 | }
14 |
15 | const defaults = { headers: headers };
16 | options = Object.assign({}, defaults, options);
17 |
18 | return fetch(options.url, options).then((response) =>
19 | response.json().then((json) => {
20 | if (!response.ok) {
21 | return Promise.reject(json);
22 | }
23 | return json;
24 | })
25 | );
26 | };
27 |
28 | export function login(loginRequest) {
29 | return request({
30 | url: "http://localhost:8081/signin",
31 | method: "POST",
32 | body: JSON.stringify(loginRequest),
33 | });
34 | }
35 |
36 | export function verify(verifyRequest) {
37 | return request({
38 | url: "http://localhost:8081/verify",
39 | method: "POST",
40 | body: JSON.stringify(verifyRequest),
41 | });
42 | }
43 |
44 | export function signup(signupRequest) {
45 | return request({
46 | url: "http://localhost:8081/users",
47 | method: "POST",
48 | body: JSON.stringify(signupRequest),
49 | });
50 | }
51 |
52 | export function getCurrentUser() {
53 | if (!localStorage.getItem("accessToken")) {
54 | return Promise.reject("No access token set.");
55 | }
56 |
57 | return request({
58 | url: "http://localhost:8081/users/me",
59 | method: "GET",
60 | });
61 | }
62 |
--------------------------------------------------------------------------------
/two-factor-auth-client/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
12 |
13 |
17 |
18 |
27 | React App
28 |
29 |
30 |
31 |
32 |
38 |
39 |
40 |
50 |
51 |
52 |
--------------------------------------------------------------------------------
/auth-service/src/main/java/com/clone/instagram/authservice/service/TotpManager.java:
--------------------------------------------------------------------------------
1 | package com.clone.instagram.authservice.service;
2 |
3 | import dev.samstevens.totp.code.*;
4 | import dev.samstevens.totp.exceptions.QrGenerationException;
5 | import dev.samstevens.totp.qr.QrData;
6 | import dev.samstevens.totp.qr.QrGenerator;
7 | import dev.samstevens.totp.qr.ZxingPngQrGenerator;
8 | import dev.samstevens.totp.secret.DefaultSecretGenerator;
9 | import dev.samstevens.totp.secret.SecretGenerator;
10 | import dev.samstevens.totp.time.SystemTimeProvider;
11 | import dev.samstevens.totp.time.TimeProvider;
12 | import lombok.extern.slf4j.Slf4j;
13 | import org.springframework.stereotype.Service;
14 | import static dev.samstevens.totp.util.Utils.getDataUriForImage;
15 |
16 | @Service
17 | @Slf4j
18 | public class TotpManager {
19 |
20 | public String generateSecret() {
21 | SecretGenerator generator = new DefaultSecretGenerator();
22 | return generator.generate();
23 | }
24 |
25 | public String getUriForImage(String secret) {
26 | QrData data = new QrData.Builder()
27 | .label("Two-factor-auth-test")
28 | .secret(secret)
29 | .issuer("exampleTwoFactor")
30 | .algorithm(HashingAlgorithm.SHA1)
31 | .digits(6)
32 | .period(30)
33 | .build();
34 |
35 | QrGenerator generator = new ZxingPngQrGenerator();
36 | byte[] imageData = new byte[0];
37 |
38 | try {
39 | imageData = generator.generate(data);
40 | } catch (QrGenerationException e) {
41 | log.error("unable to generate QrCode");
42 | }
43 |
44 | String mimeType = generator.getImageMimeType();
45 |
46 | return getDataUriForImage(imageData, mimeType);
47 | }
48 |
49 | public boolean verifyCode(String code, String secret) {
50 | TimeProvider timeProvider = new SystemTimeProvider();
51 | CodeGenerator codeGenerator = new DefaultCodeGenerator();
52 | CodeVerifier verifier = new DefaultCodeVerifier(codeGenerator, timeProvider);
53 | return verifier.isValidCode(secret, code);
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/auth-service/src/main/java/com/clone/instagram/authservice/model/User.java:
--------------------------------------------------------------------------------
1 | package com.clone.instagram.authservice.model;
2 |
3 | import com.fasterxml.jackson.annotation.JsonIgnore;
4 | import lombok.AllArgsConstructor;
5 | import lombok.Builder;
6 | import lombok.Data;
7 | import lombok.NoArgsConstructor;
8 | import org.springframework.data.annotation.CreatedDate;
9 | import org.springframework.data.annotation.Id;
10 | import org.springframework.data.annotation.LastModifiedDate;
11 | import org.springframework.data.mongodb.core.mapping.Document;
12 |
13 | import javax.validation.constraints.Email;
14 | import javax.validation.constraints.NotBlank;
15 | import javax.validation.constraints.Size;
16 | import java.time.Instant;
17 | import java.util.HashSet;
18 | import java.util.Set;
19 |
20 |
21 | @Data
22 | @Builder
23 | @NoArgsConstructor
24 | @AllArgsConstructor
25 | @Document
26 | public class User {
27 |
28 | public User(User user) {
29 | this.id = user.id;
30 | this.username = user.username;
31 | this.password = user.password;
32 | this.email = user.email;
33 | this.createdAt = user.getCreatedAt();
34 | this.updatedAt = user.getUpdatedAt();
35 | this.active = user.active;
36 | this.userProfile = user.userProfile;
37 | this.roles = user.roles;
38 | }
39 |
40 | public User(String username, String password, String email) {
41 | this.username = username;
42 | this.password = password;
43 | this.email = email;
44 | this.active = true;
45 | this.roles = new HashSet<>() {{ new Role("USER"); }};
46 | }
47 |
48 | @Id
49 | private String id;
50 |
51 | @NotBlank
52 | @Size(max = 15)
53 | private String username;
54 |
55 | @NotBlank
56 | @Size(max = 100)
57 | @JsonIgnore
58 | private String password;
59 |
60 | @NotBlank
61 | @Size(max = 40)
62 | @Email
63 | private String email;
64 |
65 | @CreatedDate
66 | private Instant createdAt;
67 |
68 | @LastModifiedDate
69 | private Instant updatedAt;
70 |
71 | private boolean active;
72 | private Profile userProfile;
73 | private Set roles;
74 | private boolean mfa;
75 | private String secret;
76 | }
77 |
--------------------------------------------------------------------------------
/two-factor-auth-client/src/verifycode/VerifyCode.js:
--------------------------------------------------------------------------------
1 | import React, { useEffect, useState } from "react";
2 | import { Form, Input, Button, notification } from "antd";
3 | import { DingtalkOutlined } from "@ant-design/icons";
4 | import { verify } from "../util/ApiUtil";
5 | import "./VerifyCode.css";
6 |
7 | const VerifyCode = (props) => {
8 | const [loading, setLoading] = useState(false);
9 |
10 | const onFinish = (values) => {
11 | setLoading(true);
12 |
13 | const verifyRequest = {
14 | code: values.code,
15 | username: props.location.state.username,
16 | };
17 |
18 | console.log(verifyRequest);
19 | verify(verifyRequest)
20 | .then((response) => {
21 | localStorage.setItem("accessToken", response.accessToken);
22 | props.history.push("/");
23 | setLoading(false);
24 | })
25 | .catch((error) => {
26 | if (error.status === 400) {
27 | notification.error({
28 | message: "Error",
29 | description: "Code is incorrect",
30 | });
31 | } else {
32 | notification.error({
33 | message: "Error",
34 | description: "Sorry! Something went wrong. Please try again!",
35 | });
36 | }
37 | setLoading(false);
38 | });
39 | };
40 |
41 | return (
42 |
43 |
44 |
54 |
55 |
56 |
57 |
64 |
73 |
74 |
75 |
76 | );
77 | };
78 |
79 | export default VerifyCode;
80 |
--------------------------------------------------------------------------------
/auth-service/src/main/java/com/clone/instagram/authservice/service/JwtTokenManager.java:
--------------------------------------------------------------------------------
1 | package com.clone.instagram.authservice.service;
2 |
3 | import com.clone.instagram.authservice.config.JwtConfig;
4 | import io.jsonwebtoken.*;
5 | import lombok.extern.slf4j.Slf4j;
6 | import org.springframework.security.core.Authentication;
7 | import org.springframework.security.core.GrantedAuthority;
8 | import org.springframework.stereotype.Service;
9 | import java.util.Date;
10 | import java.util.stream.Collectors;
11 |
12 |
13 | @Service
14 | @Slf4j
15 | public class JwtTokenManager {
16 |
17 | private final JwtConfig jwtConfig;
18 |
19 | public JwtTokenManager(JwtConfig jwtConfig) {
20 | this.jwtConfig = jwtConfig;
21 | }
22 |
23 | public String generateToken(Authentication authentication) {
24 |
25 | Long now = System.currentTimeMillis();
26 | return Jwts.builder()
27 | .setSubject(authentication.getName())
28 | .claim("authorities", authentication.getAuthorities().stream()
29 | .map(GrantedAuthority::getAuthority).collect(Collectors.toList()))
30 | .setIssuedAt(new Date(now))
31 | .setExpiration(new Date(now + jwtConfig.getExpiration() * 1000)) // in milliseconds
32 | .signWith(SignatureAlgorithm.HS512, jwtConfig.getSecret().getBytes())
33 | .compact();
34 | }
35 |
36 | public Claims getClaimsFromJWT(String token) {
37 | return Jwts.parser()
38 | .setSigningKey(jwtConfig.getSecret().getBytes())
39 | .parseClaimsJws(token)
40 | .getBody();
41 | }
42 |
43 | public boolean validateToken(String authToken) {
44 | try {
45 | Jwts.parser()
46 | .setSigningKey(jwtConfig.getSecret().getBytes())
47 | .parseClaimsJws(authToken);
48 |
49 | return true;
50 | } catch (SignatureException ex) {
51 | log.error("Invalid JWT signature");
52 | } catch (MalformedJwtException ex) {
53 | log.error("Invalid JWT token");
54 | } catch (ExpiredJwtException ex) {
55 | log.error("Expired JWT token");
56 | } catch (UnsupportedJwtException ex) {
57 | log.error("Unsupported JWT token");
58 | } catch (IllegalArgumentException ex) {
59 | log.error("JWT claims string is empty.");
60 | }
61 | return false;
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/two-factor-auth-client/src/logo.svg:
--------------------------------------------------------------------------------
1 |
8 |
--------------------------------------------------------------------------------
/two-factor-auth-client/README.md:
--------------------------------------------------------------------------------
1 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
2 |
3 | ## Available Scripts
4 |
5 | In the project directory, you can run:
6 |
7 | ### `npm start`
8 |
9 | Runs the app in the development mode.
10 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
11 |
12 | The page will reload if you make edits.
13 | You will also see any lint errors in the console.
14 |
15 | ### `npm test`
16 |
17 | Launches the test runner in the interactive watch mode.
18 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
19 |
20 | ### `npm run build`
21 |
22 | Builds the app for production to the `build` folder.
23 | It correctly bundles React in production mode and optimizes the build for the best performance.
24 |
25 | The build is minified and the filenames include the hashes.
26 | Your app is ready to be deployed!
27 |
28 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
29 |
30 | ### `npm run eject`
31 |
32 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!**
33 |
34 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
35 |
36 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
37 |
38 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
39 |
40 | ## Learn More
41 |
42 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
43 |
44 | To learn React, check out the [React documentation](https://reactjs.org/).
45 |
46 | ### Code Splitting
47 |
48 | This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting
49 |
50 | ### Analyzing the Bundle Size
51 |
52 | This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size
53 |
54 | ### Making a Progressive Web App
55 |
56 | This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app
57 |
58 | ### Advanced Configuration
59 |
60 | This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration
61 |
62 | ### Deployment
63 |
64 | This section has moved here: https://facebook.github.io/create-react-app/docs/deployment
65 |
66 | ### `npm run build` fails to minify
67 |
68 | This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify
69 |
--------------------------------------------------------------------------------
/auth-service/src/main/java/com/clone/instagram/authservice/endpoint/UserEndpoint.java:
--------------------------------------------------------------------------------
1 | package com.clone.instagram.authservice.endpoint;
2 |
3 | import com.clone.instagram.authservice.exception.*;
4 | import com.clone.instagram.authservice.model.InstaUserDetails;
5 | import com.clone.instagram.authservice.model.User;
6 | import com.clone.instagram.authservice.payload.*;
7 | import com.clone.instagram.authservice.service.UserService;
8 | import lombok.extern.slf4j.Slf4j;
9 | import org.springframework.beans.factory.annotation.Autowired;
10 | import org.springframework.http.HttpStatus;
11 | import org.springframework.http.MediaType;
12 | import org.springframework.http.ResponseEntity;
13 | import org.springframework.security.access.prepost.PreAuthorize;
14 | import org.springframework.security.core.annotation.AuthenticationPrincipal;
15 | import org.springframework.web.bind.annotation.*;
16 |
17 |
18 | @RestController
19 | @Slf4j
20 | public class UserEndpoint {
21 |
22 | @Autowired
23 | private UserService userService;
24 |
25 | @GetMapping(value = "/users/{username}", produces = MediaType.APPLICATION_JSON_VALUE)
26 | public ResponseEntity> findUser(@PathVariable("username") String username) {
27 | log.info("retrieving user {}", username);
28 |
29 | return userService
30 | .findByUsername(username)
31 | .map(user -> ResponseEntity.ok(user))
32 | .orElseThrow(() -> new ResourceNotFoundException(username));
33 | }
34 |
35 | @GetMapping(value = "/users", produces = MediaType.APPLICATION_JSON_VALUE)
36 | public ResponseEntity> findAll() {
37 | log.info("retrieving all users");
38 |
39 | return ResponseEntity
40 | .ok(userService.findAll());
41 | }
42 |
43 | @GetMapping(value = "/users/me", produces = MediaType.APPLICATION_JSON_VALUE)
44 | @PreAuthorize("hasRole('USER') or hasRole('FACEBOOK_USER')")
45 | @ResponseStatus(HttpStatus.OK)
46 | public UserSummary getCurrentUser(@AuthenticationPrincipal InstaUserDetails userDetails) {
47 | return UserSummary
48 | .builder()
49 | .id(userDetails.getId())
50 | .username(userDetails.getUsername())
51 | .name(userDetails.getUserProfile().getDisplayName())
52 | .profilePicture(userDetails.getUserProfile().getProfilePictureUrl())
53 | .build();
54 | }
55 |
56 | @GetMapping(value = "/users/summary/{username}", produces = MediaType.APPLICATION_JSON_VALUE)
57 | public ResponseEntity> getUserSummary(@PathVariable("username") String username) {
58 | log.info("retrieving user {}", username);
59 |
60 | return userService
61 | .findByUsername(username)
62 | .map(user -> ResponseEntity.ok(convertTo(user)))
63 | .orElseThrow(() -> new ResourceNotFoundException(username));
64 | }
65 |
66 | private UserSummary convertTo(User user) {
67 | return UserSummary
68 | .builder()
69 | .id(user.getId())
70 | .username(user.getUsername())
71 | .name(user.getUserProfile().getDisplayName())
72 | .profilePicture(user.getUserProfile().getProfilePictureUrl())
73 | .build();
74 | }
75 | }
--------------------------------------------------------------------------------
/two-factor-auth-client/src/signin/Signin.js:
--------------------------------------------------------------------------------
1 | import React, { useEffect, useState } from "react";
2 | import { Form, Input, Button, notification } from "antd";
3 | import { Redirect } from "react-router-dom";
4 | import {
5 | UserOutlined,
6 | LockOutlined,
7 | DingtalkOutlined,
8 | } from "@ant-design/icons";
9 | import { login } from "../util/ApiUtil";
10 | import "./Signin.css";
11 |
12 | const Signin = (props) => {
13 | const [loading, setLoading] = useState(false);
14 | const [redirect, setRedirect] = useState();
15 | const [username, setUsername] = useState();
16 |
17 | useEffect(() => {
18 | if (localStorage.getItem("accessToken") !== null) {
19 | props.history.push("/");
20 | }
21 | }, []);
22 |
23 | const onFinish = (values) => {
24 | setLoading(true);
25 | login(values)
26 | .then((response) => {
27 | if (response.mfa) {
28 | setUsername(values.username);
29 | setRedirect("/verify");
30 | } else {
31 | localStorage.setItem("accessToken", response.accessToken);
32 | props.history.push("/");
33 | }
34 | setLoading(false);
35 | })
36 | .catch((error) => {
37 | if (error.status === 401) {
38 | notification.error({
39 | message: "Error",
40 | description: "Username or Password is incorrect. Please try again!",
41 | });
42 | } else {
43 | notification.error({
44 | message: "Error",
45 | description:
46 | error.message || "Sorry! Something went wrong. Please try again!",
47 | });
48 | }
49 | setLoading(false);
50 | });
51 | };
52 |
53 | if (redirect) {
54 | return (
55 |
56 | );
57 | }
58 |
59 | return (
60 |
61 |
62 |
72 | }
75 | placeholder="Username"
76 | />
77 |
78 |
82 | }
85 | type="password"
86 | placeholder="Password"
87 | />
88 |
89 |
90 |
99 |
100 | Not a member yet?
Sign up
101 |
102 |
103 | );
104 | };
105 |
106 | export default Signin;
107 |
--------------------------------------------------------------------------------
/auth-service/src/main/java/com/clone/instagram/authservice/endpoint/AuthEndpoint.java:
--------------------------------------------------------------------------------
1 | package com.clone.instagram.authservice.endpoint;
2 |
3 |
4 | import com.clone.instagram.authservice.exception.BadRequestException;
5 | import com.clone.instagram.authservice.exception.EmailAlreadyExistsException;
6 | import com.clone.instagram.authservice.exception.UsernameAlreadyExistsException;
7 | import com.clone.instagram.authservice.model.Profile;
8 | import com.clone.instagram.authservice.model.Role;
9 | import com.clone.instagram.authservice.model.User;
10 | import com.clone.instagram.authservice.payload.*;
11 | import com.clone.instagram.authservice.service.TotpManager;
12 | import com.clone.instagram.authservice.service.UserService;
13 | import lombok.extern.slf4j.Slf4j;
14 | import org.springframework.beans.factory.annotation.Autowired;
15 | import org.springframework.http.MediaType;
16 | import org.springframework.http.ResponseEntity;
17 | import org.springframework.util.StringUtils;
18 | import org.springframework.web.bind.annotation.PostMapping;
19 | import org.springframework.web.bind.annotation.RequestBody;
20 | import org.springframework.web.bind.annotation.RestController;
21 | import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
22 |
23 | import javax.validation.Valid;
24 | import java.net.URI;
25 |
26 | @RestController
27 | @Slf4j
28 | public class AuthEndpoint {
29 |
30 | @Autowired private UserService userService;
31 | @Autowired private TotpManager totpManager;
32 |
33 | @PostMapping("/signin")
34 | public ResponseEntity> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
35 | String token = userService.loginUser(loginRequest.getUsername(), loginRequest.getPassword());
36 | return ResponseEntity.ok(new JwtAuthenticationResponse(token, StringUtils.isEmpty(token)));
37 | }
38 |
39 | @PostMapping("/verify")
40 | public ResponseEntity> verifyCode(@Valid @RequestBody VerifyCodeRequest verifyCodeRequest) {
41 | String token = userService.verify(verifyCodeRequest.getUsername(), verifyCodeRequest.getCode());
42 | return ResponseEntity.ok(new JwtAuthenticationResponse(token, StringUtils.isEmpty(token)));
43 | }
44 |
45 | @PostMapping(value = "/users", produces = MediaType.APPLICATION_JSON_VALUE)
46 | public ResponseEntity> createUser(@Valid @RequestBody SignUpRequest payload) {
47 | log.info("creating user {}", payload.getUsername());
48 |
49 | User user = User
50 | .builder()
51 | .username(payload.getUsername())
52 | .email(payload.getEmail())
53 | .password(payload.getPassword())
54 | .userProfile(Profile
55 | .builder()
56 | .displayName(payload.getName())
57 | .build())
58 | .mfa(payload.isMfa())
59 | .build();
60 |
61 | User saved;
62 | try {
63 | saved = userService.registerUser(user, Role.USER);
64 | } catch (UsernameAlreadyExistsException | EmailAlreadyExistsException e) {
65 | throw new BadRequestException(e.getMessage());
66 | }
67 |
68 | URI location = ServletUriComponentsBuilder
69 | .fromCurrentContextPath().path("/users/{username}")
70 | .buildAndExpand(user.getUsername()).toUri();
71 |
72 | return ResponseEntity
73 | .created(location)
74 | .body(new SignupResponse(saved.isMfa(),
75 | totpManager.getUriForImage(saved.getSecret())));
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/two-factor-auth-client/src/signup/Signup.js:
--------------------------------------------------------------------------------
1 | import React, { useEffect, useState } from "react";
2 | import { Form, Input, Button, notification, Checkbox } from "antd";
3 | import { Redirect } from "react-router-dom";
4 | import { DingtalkOutlined } from "@ant-design/icons";
5 | import { signup } from "../util/ApiUtil";
6 | import "./Signup.css";
7 |
8 | const Signup = (props) => {
9 | const [loading, setLoading] = useState(false);
10 | const [redirect, setRedirect] = useState();
11 | const [qrImageUrl, setQrImageUrl] = useState();
12 |
13 | useEffect(() => {
14 | if (localStorage.getItem("accessToken") !== null) {
15 | props.history.push("/");
16 | }
17 | }, []);
18 |
19 | const onFinish = (values) => {
20 | setLoading(true);
21 | signup(values)
22 | .then((response) => {
23 | notification.success({
24 | message: "Success",
25 | description:
26 | "Thank you! You're successfully registered. Please Login to continue!",
27 | });
28 | if (response.mfa) {
29 | console.log(response);
30 | setQrImageUrl(response.secretImageUri);
31 | setRedirect("/qrcode");
32 | } else {
33 | setRedirect("/");
34 | }
35 |
36 | setLoading(false);
37 | })
38 | .catch((error) => {
39 | notification.error({
40 | message: "Error",
41 | description:
42 | error.message || "Sorry! Something went wrong. Please try again!",
43 | });
44 | setLoading(false);
45 | });
46 | };
47 |
48 | if (redirect) {
49 | return (
50 |
51 | );
52 | }
53 |
54 | return (
55 |
104 | );
105 | };
106 |
107 | export default Signup;
108 |
--------------------------------------------------------------------------------
/auth-service/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | com.clone.instegram
7 | auth-service
8 | 0.0.1-SNAPSHOT
9 | jar
10 |
11 | auth-service
12 | Spring security jwt and social login
13 |
14 |
15 | org.springframework.boot
16 | spring-boot-starter-parent
17 | 2.1.3.RELEASE
18 |
19 |
20 |
21 |
22 | UTF-8
23 | UTF-8
24 | 10
25 | Greenwich.M1
26 |
27 |
28 |
29 |
30 | org.springframework.boot
31 | spring-boot-starter-data-mongodb
32 |
33 |
34 | org.springframework.boot
35 | spring-boot-starter-web
36 |
37 |
38 | dev.samstevens.totp
39 | totp
40 | 1.7
41 |
42 |
43 | org.springframework.boot
44 | spring-boot-starter-security
45 |
46 |
47 | de.flapdoodle.embed
48 | de.flapdoodle.embed.mongo
49 | 1.50.5
50 |
51 |
52 | cz.jirutka.spring
53 | embedmongo-spring
54 | RELEASE
55 |
56 |
57 | org.springframework.boot
58 | spring-boot-starter-actuator
59 |
60 |
61 | io.jsonwebtoken
62 | jjwt
63 | 0.9.0
64 |
65 |
66 | org.glassfish.jaxb
67 | jaxb-runtime
68 | 2.4.0-b180830.0438
69 |
70 |
71 | org.projectlombok
72 | lombok
73 | true
74 |
75 |
76 | org.springframework.boot
77 | spring-boot-starter-test
78 | test
79 |
80 |
81 |
82 |
83 |
84 |
85 | org.springframework.cloud
86 | spring-cloud-dependencies
87 | ${spring-cloud.version}
88 | pom
89 | import
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 | org.springframework.boot
98 | spring-boot-maven-plugin
99 |
100 |
101 |
102 |
103 |
104 |
105 | spring-milestones
106 | Spring Milestones
107 | https://repo.spring.io/milestone
108 |
109 | false
110 |
111 |
112 |
113 |
114 |
115 |
116 |
--------------------------------------------------------------------------------
/auth-service/src/main/java/com/clone/instagram/authservice/config/JwtTokenAuthenticationFilter.java:
--------------------------------------------------------------------------------
1 | package com.clone.instagram.authservice.config;
2 |
3 | import com.clone.instagram.authservice.model.InstaUserDetails;
4 | import com.clone.instagram.authservice.service.JwtTokenManager;
5 | import com.clone.instagram.authservice.service.UserService;
6 | import io.jsonwebtoken.Claims;
7 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
8 | import org.springframework.security.core.context.SecurityContextHolder;
9 | import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
10 | import org.springframework.web.filter.OncePerRequestFilter;
11 | import javax.servlet.FilterChain;
12 | import javax.servlet.ServletException;
13 | import javax.servlet.http.HttpServletRequest;
14 | import javax.servlet.http.HttpServletResponse;
15 | import java.io.IOException;
16 |
17 | public class JwtTokenAuthenticationFilter extends OncePerRequestFilter {
18 |
19 | private final JwtConfig jwtConfig;
20 | private JwtTokenManager tokenProvider;
21 | private UserService userService;
22 |
23 | public JwtTokenAuthenticationFilter(
24 | JwtConfig jwtConfig,
25 | JwtTokenManager tokenProvider,
26 | UserService userService) {
27 |
28 | this.jwtConfig = jwtConfig;
29 | this.tokenProvider = tokenProvider;
30 | this.userService = userService;
31 | }
32 |
33 | @Override
34 | protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
35 | throws ServletException, IOException {
36 |
37 | // 1. get the authentication header. Tokens are supposed to be passed in the authentication header
38 | String header = request.getHeader(jwtConfig.getHeader());
39 |
40 | // 2. validate the header and check the prefix
41 | if(header == null || !header.startsWith(jwtConfig.getPrefix())) {
42 | chain.doFilter(request, response); // If not valid, go to the next filter.
43 | return;
44 | }
45 |
46 | // If there is no token provided and hence the user won't be authenticated.
47 | // It's Ok. Maybe the user accessing a public path or asking for a token.
48 |
49 | // All secured paths that needs a token are already defined and secured in config class.
50 | // And If user tried to access without access token, then he won't be authenticated and an exception will be thrown.
51 |
52 | // 3. Get the token
53 | String token = header.replace(jwtConfig.getPrefix(), "");
54 |
55 | if(tokenProvider.validateToken(token)) {
56 | Claims claims = tokenProvider.getClaimsFromJWT(token);
57 | String username = claims.getSubject();
58 |
59 | UsernamePasswordAuthenticationToken auth =
60 | userService.findByUsername(username)
61 | .map(InstaUserDetails::new)
62 | .map(userDetails -> {
63 | UsernamePasswordAuthenticationToken authentication =
64 | new UsernamePasswordAuthenticationToken(
65 | userDetails, null, userDetails.getAuthorities());
66 | authentication
67 | .setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
68 |
69 | return authentication;
70 | })
71 | .orElse(null);
72 |
73 | SecurityContextHolder.getContext().setAuthentication(auth);
74 | } else {
75 | SecurityContextHolder.clearContext();
76 | }
77 |
78 | // go to the next filter in the filter chain
79 | chain.doFilter(request, response);
80 | }
81 |
82 | }
83 |
--------------------------------------------------------------------------------
/auth-service/src/main/java/com/clone/instagram/authservice/service/UserService.java:
--------------------------------------------------------------------------------
1 | package com.clone.instagram.authservice.service;
2 |
3 | import com.clone.instagram.authservice.exception.*;
4 | import com.clone.instagram.authservice.model.InstaUserDetails;
5 | import com.clone.instagram.authservice.model.Role;
6 | import com.clone.instagram.authservice.repository.UserRepository;
7 | import com.clone.instagram.authservice.model.User;
8 | import lombok.extern.slf4j.Slf4j;
9 | import org.springframework.beans.factory.annotation.Autowired;
10 | import org.springframework.security.authentication.AuthenticationManager;
11 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
12 | import org.springframework.security.core.Authentication;
13 | import org.springframework.security.core.userdetails.UserDetails;
14 | import org.springframework.security.crypto.password.PasswordEncoder;
15 | import org.springframework.stereotype.Service;
16 | import java.util.HashSet;
17 | import java.util.List;
18 | import java.util.Optional;
19 |
20 | @Service
21 | @Slf4j
22 | public class UserService {
23 |
24 | @Autowired private PasswordEncoder passwordEncoder;
25 | @Autowired private UserRepository userRepository;
26 | @Autowired private AuthenticationManager authenticationManager;
27 | @Autowired private JwtTokenManager jwtTokenManager;
28 | @Autowired private TotpManager totpManager;
29 |
30 | public String loginUser(String username, String password) {
31 | Authentication authentication = authenticationManager
32 | .authenticate(new UsernamePasswordAuthenticationToken(username, password));
33 |
34 | User user = userRepository.findByUsername(username).get();
35 | if(user.isMfa()) {
36 | return "";
37 | }
38 |
39 | return jwtTokenManager.generateToken(authentication);
40 | }
41 |
42 | public String verify(String username, String code) {
43 | User user = userRepository
44 | .findByUsername(username)
45 | .orElseThrow(() -> new ResourceNotFoundException( String.format("username %s", username)));
46 |
47 | if(!totpManager.verifyCode(code, user.getSecret())) {
48 | throw new BadRequestException("Code is incorrect");
49 | }
50 |
51 | return Optional.of(user)
52 | .map(InstaUserDetails::new)
53 | .map(userDetails -> new UsernamePasswordAuthenticationToken(
54 | userDetails, null, userDetails.getAuthorities()))
55 | .map(jwtTokenManager::generateToken)
56 | .orElseThrow(() ->
57 | new InternalServerException("unable to generate access token"));
58 | }
59 |
60 | public User registerUser(User user, Role role) {
61 | log.info("registering user {}", user.getUsername());
62 |
63 | if(userRepository.existsByUsername(user.getUsername())) {
64 | log.warn("username {} already exists.", user.getUsername());
65 |
66 | throw new UsernameAlreadyExistsException(
67 | String.format("username %s already exists", user.getUsername()));
68 | }
69 |
70 | if(userRepository.existsByEmail(user.getEmail())) {
71 | log.warn("email {} already exists.", user.getEmail());
72 |
73 | throw new EmailAlreadyExistsException(
74 | String.format("email %s already exists", user.getEmail()));
75 | }
76 | user.setActive(true);
77 | user.setPassword(passwordEncoder.encode(user.getPassword()));
78 | user.setRoles(new HashSet<>() {{
79 | add(role);
80 | }});
81 |
82 | if(user.isMfa()) {
83 | user.setSecret(totpManager.generateSecret());
84 | }
85 |
86 | return userRepository.save(user);
87 | }
88 |
89 | public List findAll() {
90 | log.info("retrieving all users");
91 | return userRepository.findAll();
92 | }
93 |
94 | public Optional findByUsername(String username) {
95 | log.info("retrieving user {}", username);
96 | return userRepository.findByUsername(username);
97 | }
98 |
99 | public Optional findById(String id) {
100 | log.info("retrieving user {}", id);
101 | return userRepository.findById(id);
102 | }
103 | }
104 |
--------------------------------------------------------------------------------
/auth-service/src/main/java/com/clone/instagram/authservice/config/SecurityCredentialsConfig.java:
--------------------------------------------------------------------------------
1 | package com.clone.instagram.authservice.config;
2 |
3 |
4 | import com.clone.instagram.authservice.service.JwtTokenManager;
5 | import com.clone.instagram.authservice.service.UserService;
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.context.annotation.Bean;
8 | import org.springframework.http.HttpMethod;
9 | import org.springframework.security.authentication.AuthenticationManager;
10 | import org.springframework.security.config.BeanIds;
11 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
12 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
13 | import org.springframework.security.config.annotation.web.builders.HttpSecurity;
14 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
15 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
16 | import org.springframework.security.config.http.SessionCreationPolicy;
17 | import org.springframework.security.core.userdetails.UserDetailsService;
18 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
19 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
20 | import org.springframework.web.cors.CorsConfiguration;
21 | import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
22 | import org.springframework.web.filter.CorsFilter;
23 |
24 | import javax.servlet.http.HttpServletResponse;
25 |
26 | @EnableWebSecurity
27 | @EnableGlobalMethodSecurity(prePostEnabled = true)
28 | public class SecurityCredentialsConfig extends WebSecurityConfigurerAdapter {
29 |
30 | @Autowired
31 | private UserDetailsService userDetailsService;
32 |
33 | @Autowired
34 | private JwtConfig jwtConfig;
35 |
36 | @Autowired
37 | private JwtTokenManager tokenProvider;
38 |
39 | @Autowired
40 | private UserService userService;
41 |
42 |
43 | @Override
44 | protected void configure(HttpSecurity http) throws Exception {
45 | http
46 | .cors().and()
47 | .csrf().disable()
48 | .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
49 | .and()
50 | .exceptionHandling().authenticationEntryPoint((req, rsp, e) -> rsp.sendError(HttpServletResponse.SC_UNAUTHORIZED))
51 | .and()
52 | .addFilterBefore(new JwtTokenAuthenticationFilter(jwtConfig, tokenProvider, userService), UsernamePasswordAuthenticationFilter.class)
53 | .authorizeRequests()
54 | .antMatchers(HttpMethod.POST, "/signin").permitAll()
55 | .antMatchers(HttpMethod.POST, "/verify").anonymous()
56 | .antMatchers(HttpMethod.POST, "/users").anonymous()
57 | .anyRequest().authenticated();
58 | }
59 |
60 | @Override
61 | protected void configure(AuthenticationManagerBuilder auth) throws Exception {
62 | // Configure DB authentication provider for user accounts
63 | auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
64 | }
65 |
66 | @Bean
67 | public BCryptPasswordEncoder passwordEncoder() {
68 | return new BCryptPasswordEncoder();
69 | }
70 |
71 | @Bean(BeanIds.AUTHENTICATION_MANAGER)
72 | @Override
73 | public AuthenticationManager authenticationManagerBean() throws Exception {
74 | return super.authenticationManagerBean();
75 | }
76 |
77 | @Bean
78 | public CorsFilter corsFilter() {
79 | final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
80 | final CorsConfiguration config = new CorsConfiguration();
81 | config.setAllowCredentials(true);
82 | config.addAllowedOrigin("*");
83 | config.addAllowedHeader("*");
84 | config.addAllowedMethod("OPTIONS");
85 | config.addAllowedMethod("HEAD");
86 | config.addAllowedMethod("GET");
87 | config.addAllowedMethod("PUT");
88 | config.addAllowedMethod("POST");
89 | config.addAllowedMethod("DELETE");
90 | config.addAllowedMethod("PATCH");
91 | source.registerCorsConfiguration("/**", config);
92 | return new CorsFilter(source);
93 | }
94 |
95 | }
96 |
--------------------------------------------------------------------------------
/two-factor-auth-client/src/serviceWorker.js:
--------------------------------------------------------------------------------
1 | // This optional code is used to register a service worker.
2 | // register() is not called by default.
3 |
4 | // This lets the app load faster on subsequent visits in production, and gives
5 | // it offline capabilities. However, it also means that developers (and users)
6 | // will only see deployed updates on subsequent visits to a page, after all the
7 | // existing tabs open on the page have been closed, since previously cached
8 | // resources are updated in the background.
9 |
10 | // To learn more about the benefits of this model and instructions on how to
11 | // opt-in, read https://bit.ly/CRA-PWA
12 |
13 | const isLocalhost = Boolean(
14 | window.location.hostname === 'localhost' ||
15 | // [::1] is the IPv6 localhost address.
16 | window.location.hostname === '[::1]' ||
17 | // 127.0.0.0/8 are considered localhost for IPv4.
18 | window.location.hostname.match(
19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
20 | )
21 | );
22 |
23 | export function register(config) {
24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
25 | // The URL constructor is available in all browsers that support SW.
26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
27 | if (publicUrl.origin !== window.location.origin) {
28 | // Our service worker won't work if PUBLIC_URL is on a different origin
29 | // from what our page is served on. This might happen if a CDN is used to
30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374
31 | return;
32 | }
33 |
34 | window.addEventListener('load', () => {
35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
36 |
37 | if (isLocalhost) {
38 | // This is running on localhost. Let's check if a service worker still exists or not.
39 | checkValidServiceWorker(swUrl, config);
40 |
41 | // Add some additional logging to localhost, pointing developers to the
42 | // service worker/PWA documentation.
43 | navigator.serviceWorker.ready.then(() => {
44 | console.log(
45 | 'This web app is being served cache-first by a service ' +
46 | 'worker. To learn more, visit https://bit.ly/CRA-PWA'
47 | );
48 | });
49 | } else {
50 | // Is not localhost. Just register service worker
51 | registerValidSW(swUrl, config);
52 | }
53 | });
54 | }
55 | }
56 |
57 | function registerValidSW(swUrl, config) {
58 | navigator.serviceWorker
59 | .register(swUrl)
60 | .then(registration => {
61 | registration.onupdatefound = () => {
62 | const installingWorker = registration.installing;
63 | if (installingWorker == null) {
64 | return;
65 | }
66 | installingWorker.onstatechange = () => {
67 | if (installingWorker.state === 'installed') {
68 | if (navigator.serviceWorker.controller) {
69 | // At this point, the updated precached content has been fetched,
70 | // but the previous service worker will still serve the older
71 | // content until all client tabs are closed.
72 | console.log(
73 | 'New content is available and will be used when all ' +
74 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
75 | );
76 |
77 | // Execute callback
78 | if (config && config.onUpdate) {
79 | config.onUpdate(registration);
80 | }
81 | } else {
82 | // At this point, everything has been precached.
83 | // It's the perfect time to display a
84 | // "Content is cached for offline use." message.
85 | console.log('Content is cached for offline use.');
86 |
87 | // Execute callback
88 | if (config && config.onSuccess) {
89 | config.onSuccess(registration);
90 | }
91 | }
92 | }
93 | };
94 | };
95 | })
96 | .catch(error => {
97 | console.error('Error during service worker registration:', error);
98 | });
99 | }
100 |
101 | function checkValidServiceWorker(swUrl, config) {
102 | // Check if the service worker can be found. If it can't reload the page.
103 | fetch(swUrl, {
104 | headers: { 'Service-Worker': 'script' },
105 | })
106 | .then(response => {
107 | // Ensure service worker exists, and that we really are getting a JS file.
108 | const contentType = response.headers.get('content-type');
109 | if (
110 | response.status === 404 ||
111 | (contentType != null && contentType.indexOf('javascript') === -1)
112 | ) {
113 | // No service worker found. Probably a different app. Reload the page.
114 | navigator.serviceWorker.ready.then(registration => {
115 | registration.unregister().then(() => {
116 | window.location.reload();
117 | });
118 | });
119 | } else {
120 | // Service worker found. Proceed as normal.
121 | registerValidSW(swUrl, config);
122 | }
123 | })
124 | .catch(() => {
125 | console.log(
126 | 'No internet connection found. App is running in offline mode.'
127 | );
128 | });
129 | }
130 |
131 | export function unregister() {
132 | if ('serviceWorker' in navigator) {
133 | navigator.serviceWorker.ready
134 | .then(registration => {
135 | registration.unregister();
136 | })
137 | .catch(error => {
138 | console.error(error.message);
139 | });
140 | }
141 | }
142 |
--------------------------------------------------------------------------------
/auth-service/mvnw.cmd:
--------------------------------------------------------------------------------
1 | @REM ----------------------------------------------------------------------------
2 | @REM Licensed to the Apache Software Foundation (ASF) under one
3 | @REM or more contributor license agreements. See the NOTICE file
4 | @REM distributed with this work for additional information
5 | @REM regarding copyright ownership. The ASF licenses this file
6 | @REM to you under the Apache License, Version 2.0 (the
7 | @REM "License"); you may not use this file except in compliance
8 | @REM with the License. You may obtain a copy of the License at
9 | @REM
10 | @REM http://www.apache.org/licenses/LICENSE-2.0
11 | @REM
12 | @REM Unless required by applicable law or agreed to in writing,
13 | @REM software distributed under the License is distributed on an
14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | @REM KIND, either express or implied. See the License for the
16 | @REM specific language governing permissions and limitations
17 | @REM under the License.
18 | @REM ----------------------------------------------------------------------------
19 |
20 | @REM ----------------------------------------------------------------------------
21 | @REM Maven2 Start Up Batch script
22 | @REM
23 | @REM Required ENV vars:
24 | @REM JAVA_HOME - location of a JDK home dir
25 | @REM
26 | @REM Optional ENV vars
27 | @REM M2_HOME - location of maven2's installed home dir
28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
31 | @REM e.g. to debug Maven itself, use
32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
34 | @REM ----------------------------------------------------------------------------
35 |
36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
37 | @echo off
38 | @REM set title of command window
39 | title %0
40 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
42 |
43 | @REM set %HOME% to equivalent of $HOME
44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
45 |
46 | @REM Execute a user defined script before this one
47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending
49 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
50 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
51 | :skipRcPre
52 |
53 | @setlocal
54 |
55 | set ERROR_CODE=0
56 |
57 | @REM To isolate internal variables from possible post scripts, we use another setlocal
58 | @setlocal
59 |
60 | @REM ==== START VALIDATION ====
61 | if not "%JAVA_HOME%" == "" goto OkJHome
62 |
63 | echo.
64 | echo Error: JAVA_HOME not found in your environment. >&2
65 | echo Please set the JAVA_HOME variable in your environment to match the >&2
66 | echo location of your Java installation. >&2
67 | echo.
68 | goto error
69 |
70 | :OkJHome
71 | if exist "%JAVA_HOME%\bin\java.exe" goto init
72 |
73 | echo.
74 | echo Error: JAVA_HOME is set to an invalid directory. >&2
75 | echo JAVA_HOME = "%JAVA_HOME%" >&2
76 | echo Please set the JAVA_HOME variable in your environment to match the >&2
77 | echo location of your Java installation. >&2
78 | echo.
79 | goto error
80 |
81 | @REM ==== END VALIDATION ====
82 |
83 | :init
84 |
85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
86 | @REM Fallback to current working directory if not found.
87 |
88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
90 |
91 | set EXEC_DIR=%CD%
92 | set WDIR=%EXEC_DIR%
93 | :findBaseDir
94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound
95 | cd ..
96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound
97 | set WDIR=%CD%
98 | goto findBaseDir
99 |
100 | :baseDirFound
101 | set MAVEN_PROJECTBASEDIR=%WDIR%
102 | cd "%EXEC_DIR%"
103 | goto endDetectBaseDir
104 |
105 | :baseDirNotFound
106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
107 | cd "%EXEC_DIR%"
108 |
109 | :endDetectBaseDir
110 |
111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
112 |
113 | @setlocal EnableExtensions EnableDelayedExpansion
114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
116 |
117 | :endReadAdditionalConfig
118 |
119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
122 |
123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
124 | FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO (
125 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
126 | )
127 |
128 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
129 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data.
130 | if exist %WRAPPER_JAR% (
131 | echo Found %WRAPPER_JAR%
132 | ) else (
133 | echo Couldn't find %WRAPPER_JAR%, downloading it ...
134 | echo Downloading from: %DOWNLOAD_URL%
135 | powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"
136 | echo Finished downloading %WRAPPER_JAR%
137 | )
138 | @REM End of extension
139 |
140 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
141 | if ERRORLEVEL 1 goto error
142 | goto end
143 |
144 | :error
145 | set ERROR_CODE=1
146 |
147 | :end
148 | @endlocal & set ERROR_CODE=%ERROR_CODE%
149 |
150 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
151 | @REM check for post script, once with legacy .bat ending and once with .cmd ending
152 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
153 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
154 | :skipRcPost
155 |
156 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
157 | if "%MAVEN_BATCH_PAUSE%" == "on" pause
158 |
159 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
160 |
161 | exit /B %ERROR_CODE%
162 |
--------------------------------------------------------------------------------
/auth-service/mvnw:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 | # ----------------------------------------------------------------------------
3 | # Licensed to the Apache Software Foundation (ASF) under one
4 | # or more contributor license agreements. See the NOTICE file
5 | # distributed with this work for additional information
6 | # regarding copyright ownership. The ASF licenses this file
7 | # to you under the Apache License, Version 2.0 (the
8 | # "License"); you may not use this file except in compliance
9 | # with the License. You may obtain a copy of the License at
10 | #
11 | # http://www.apache.org/licenses/LICENSE-2.0
12 | #
13 | # Unless required by applicable law or agreed to in writing,
14 | # software distributed under the License is distributed on an
15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 | # KIND, either express or implied. See the License for the
17 | # specific language governing permissions and limitations
18 | # under the License.
19 | # ----------------------------------------------------------------------------
20 |
21 | # ----------------------------------------------------------------------------
22 | # Maven2 Start Up Batch script
23 | #
24 | # Required ENV vars:
25 | # ------------------
26 | # JAVA_HOME - location of a JDK home dir
27 | #
28 | # Optional ENV vars
29 | # -----------------
30 | # M2_HOME - location of maven2's installed home dir
31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven
32 | # e.g. to debug Maven itself, use
33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files
35 | # ----------------------------------------------------------------------------
36 |
37 | if [ -z "$MAVEN_SKIP_RC" ] ; then
38 |
39 | if [ -f /etc/mavenrc ] ; then
40 | . /etc/mavenrc
41 | fi
42 |
43 | if [ -f "$HOME/.mavenrc" ] ; then
44 | . "$HOME/.mavenrc"
45 | fi
46 |
47 | fi
48 |
49 | # OS specific support. $var _must_ be set to either true or false.
50 | cygwin=false;
51 | darwin=false;
52 | mingw=false
53 | case "`uname`" in
54 | CYGWIN*) cygwin=true ;;
55 | MINGW*) mingw=true;;
56 | Darwin*) darwin=true
57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html
59 | if [ -z "$JAVA_HOME" ]; then
60 | if [ -x "/usr/libexec/java_home" ]; then
61 | export JAVA_HOME="`/usr/libexec/java_home`"
62 | else
63 | export JAVA_HOME="/Library/Java/Home"
64 | fi
65 | fi
66 | ;;
67 | esac
68 |
69 | if [ -z "$JAVA_HOME" ] ; then
70 | if [ -r /etc/gentoo-release ] ; then
71 | JAVA_HOME=`java-config --jre-home`
72 | fi
73 | fi
74 |
75 | if [ -z "$M2_HOME" ] ; then
76 | ## resolve links - $0 may be a link to maven's home
77 | PRG="$0"
78 |
79 | # need this for relative symlinks
80 | while [ -h "$PRG" ] ; do
81 | ls=`ls -ld "$PRG"`
82 | link=`expr "$ls" : '.*-> \(.*\)$'`
83 | if expr "$link" : '/.*' > /dev/null; then
84 | PRG="$link"
85 | else
86 | PRG="`dirname "$PRG"`/$link"
87 | fi
88 | done
89 |
90 | saveddir=`pwd`
91 |
92 | M2_HOME=`dirname "$PRG"`/..
93 |
94 | # make it fully qualified
95 | M2_HOME=`cd "$M2_HOME" && pwd`
96 |
97 | cd "$saveddir"
98 | # echo Using m2 at $M2_HOME
99 | fi
100 |
101 | # For Cygwin, ensure paths are in UNIX format before anything is touched
102 | if $cygwin ; then
103 | [ -n "$M2_HOME" ] &&
104 | M2_HOME=`cygpath --unix "$M2_HOME"`
105 | [ -n "$JAVA_HOME" ] &&
106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
107 | [ -n "$CLASSPATH" ] &&
108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
109 | fi
110 |
111 | # For Mingw, ensure paths are in UNIX format before anything is touched
112 | if $mingw ; then
113 | [ -n "$M2_HOME" ] &&
114 | M2_HOME="`(cd "$M2_HOME"; pwd)`"
115 | [ -n "$JAVA_HOME" ] &&
116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
117 | # TODO classpath?
118 | fi
119 |
120 | if [ -z "$JAVA_HOME" ]; then
121 | javaExecutable="`which javac`"
122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
123 | # readlink(1) is not available as standard on Solaris 10.
124 | readLink=`which readlink`
125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
126 | if $darwin ; then
127 | javaHome="`dirname \"$javaExecutable\"`"
128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
129 | else
130 | javaExecutable="`readlink -f \"$javaExecutable\"`"
131 | fi
132 | javaHome="`dirname \"$javaExecutable\"`"
133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'`
134 | JAVA_HOME="$javaHome"
135 | export JAVA_HOME
136 | fi
137 | fi
138 | fi
139 |
140 | if [ -z "$JAVACMD" ] ; then
141 | if [ -n "$JAVA_HOME" ] ; then
142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
143 | # IBM's JDK on AIX uses strange locations for the executables
144 | JAVACMD="$JAVA_HOME/jre/sh/java"
145 | else
146 | JAVACMD="$JAVA_HOME/bin/java"
147 | fi
148 | else
149 | JAVACMD="`which java`"
150 | fi
151 | fi
152 |
153 | if [ ! -x "$JAVACMD" ] ; then
154 | echo "Error: JAVA_HOME is not defined correctly." >&2
155 | echo " We cannot execute $JAVACMD" >&2
156 | exit 1
157 | fi
158 |
159 | if [ -z "$JAVA_HOME" ] ; then
160 | echo "Warning: JAVA_HOME environment variable is not set."
161 | fi
162 |
163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
164 |
165 | # traverses directory structure from process work directory to filesystem root
166 | # first directory with .mvn subdirectory is considered project base directory
167 | find_maven_basedir() {
168 |
169 | if [ -z "$1" ]
170 | then
171 | echo "Path not specified to find_maven_basedir"
172 | return 1
173 | fi
174 |
175 | basedir="$1"
176 | wdir="$1"
177 | while [ "$wdir" != '/' ] ; do
178 | if [ -d "$wdir"/.mvn ] ; then
179 | basedir=$wdir
180 | break
181 | fi
182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc)
183 | if [ -d "${wdir}" ]; then
184 | wdir=`cd "$wdir/.."; pwd`
185 | fi
186 | # end of workaround
187 | done
188 | echo "${basedir}"
189 | }
190 |
191 | # concatenates all lines of a file
192 | concat_lines() {
193 | if [ -f "$1" ]; then
194 | echo "$(tr -s '\n' ' ' < "$1")"
195 | fi
196 | }
197 |
198 | BASE_DIR=`find_maven_basedir "$(pwd)"`
199 | if [ -z "$BASE_DIR" ]; then
200 | exit 1;
201 | fi
202 |
203 | ##########################################################################################
204 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
205 | # This allows using the maven wrapper in projects that prohibit checking in binary data.
206 | ##########################################################################################
207 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
208 | if [ "$MVNW_VERBOSE" = true ]; then
209 | echo "Found .mvn/wrapper/maven-wrapper.jar"
210 | fi
211 | else
212 | if [ "$MVNW_VERBOSE" = true ]; then
213 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
214 | fi
215 | jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
216 | while IFS="=" read key value; do
217 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
218 | esac
219 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
220 | if [ "$MVNW_VERBOSE" = true ]; then
221 | echo "Downloading from: $jarUrl"
222 | fi
223 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
224 |
225 | if command -v wget > /dev/null; then
226 | if [ "$MVNW_VERBOSE" = true ]; then
227 | echo "Found wget ... using wget"
228 | fi
229 | wget "$jarUrl" -O "$wrapperJarPath"
230 | elif command -v curl > /dev/null; then
231 | if [ "$MVNW_VERBOSE" = true ]; then
232 | echo "Found curl ... using curl"
233 | fi
234 | curl -o "$wrapperJarPath" "$jarUrl"
235 | else
236 | if [ "$MVNW_VERBOSE" = true ]; then
237 | echo "Falling back to using Java to download"
238 | fi
239 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
240 | if [ -e "$javaClass" ]; then
241 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
242 | if [ "$MVNW_VERBOSE" = true ]; then
243 | echo " - Compiling MavenWrapperDownloader.java ..."
244 | fi
245 | # Compiling the Java class
246 | ("$JAVA_HOME/bin/javac" "$javaClass")
247 | fi
248 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
249 | # Running the downloader
250 | if [ "$MVNW_VERBOSE" = true ]; then
251 | echo " - Running MavenWrapperDownloader.java ..."
252 | fi
253 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
254 | fi
255 | fi
256 | fi
257 | fi
258 | ##########################################################################################
259 | # End of extension
260 | ##########################################################################################
261 |
262 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
263 | if [ "$MVNW_VERBOSE" = true ]; then
264 | echo $MAVEN_PROJECTBASEDIR
265 | fi
266 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
267 |
268 | # For Cygwin, switch paths to Windows format before running java
269 | if $cygwin; then
270 | [ -n "$M2_HOME" ] &&
271 | M2_HOME=`cygpath --path --windows "$M2_HOME"`
272 | [ -n "$JAVA_HOME" ] &&
273 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
274 | [ -n "$CLASSPATH" ] &&
275 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
276 | [ -n "$MAVEN_PROJECTBASEDIR" ] &&
277 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
278 | fi
279 |
280 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
281 |
282 | exec "$JAVACMD" \
283 | $MAVEN_OPTS \
284 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
285 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
286 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
287 |
--------------------------------------------------------------------------------