├── webapp-application ├── src │ ├── main │ │ ├── resources │ │ │ ├── application.properties │ │ │ └── static │ │ │ │ ├── logout.html │ │ │ │ ├── styles.css │ │ │ │ ├── permissions.js │ │ │ │ ├── index.html │ │ │ │ ├── permissions.html │ │ │ │ ├── index.js │ │ │ │ ├── settings.html │ │ │ │ ├── roles.html │ │ │ │ ├── roles.js │ │ │ │ ├── users.html │ │ │ │ ├── users.js │ │ │ │ └── settings.js │ │ └── java │ │ │ └── com │ │ │ └── talk2amareswaran │ │ │ └── projects │ │ │ └── webapp │ │ │ └── WebappApplication.java │ └── test │ │ └── java │ │ └── com │ │ └── talk2amareswaran │ │ └── projects │ │ └── webapp │ │ └── WebappApplicationTests.java └── build.gradle ├── two-factor-service ├── src │ ├── main │ │ ├── java │ │ │ └── com │ │ │ │ └── talk2amareswaran │ │ │ │ └── projects │ │ │ │ └── twofactorservice │ │ │ │ ├── TwofactorserviceApplication.java │ │ │ │ ├── SMSService.java │ │ │ │ ├── DAOService.java │ │ │ │ ├── EmailService.java │ │ │ │ ├── SimpleCORSFiler.java │ │ │ │ └── TwoFactorServiceController.java │ │ └── resources │ │ │ └── application.yml │ └── test │ │ └── java │ │ └── com │ │ └── talk2amareswaran │ │ └── projects │ │ └── twofactorservice │ │ └── TwofactorserviceApplicationTests.java └── build.gradle ├── resource-server ├── src │ ├── test │ │ └── java │ │ │ └── com │ │ │ └── talk2amareswaran │ │ │ └── projects │ │ │ └── resourceserver │ │ │ └── ResourceserverApplicationTests.java │ └── main │ │ ├── java │ │ └── com │ │ │ └── talk2amareswaran │ │ │ └── projects │ │ │ └── resourceserver │ │ │ ├── UserRole.java │ │ │ ├── Permission.java │ │ │ ├── ResourceserverApplication.java │ │ │ ├── PermissionResourceDAO.java │ │ │ ├── SecurityConfiguration.java │ │ │ ├── PermissionsByRoleResourceDAO.java │ │ │ ├── RolesDAO.java │ │ │ ├── PermissionResource.java │ │ │ ├── UsersByRoleResource.java │ │ │ ├── AccessTokenMapper.java │ │ │ ├── PermissionsByRoleResource.java │ │ │ ├── UserModel.java │ │ │ ├── SimpleCorsFilter.java │ │ │ ├── UsersByRoleResourceDAO.java │ │ │ ├── JwtConverter.java │ │ │ ├── RoleResource.java │ │ │ ├── UserResourceDAO.java │ │ │ └── UserResource.java │ │ └── resources │ │ └── application.yml └── build.gradle ├── authorization-server ├── src │ ├── test │ │ └── java │ │ │ └── com │ │ │ └── talk2amareswaran │ │ │ └── projects │ │ │ └── authorizationserver │ │ │ └── AuthorizationserverApplicationTests.java │ └── main │ │ ├── java │ │ └── com │ │ │ └── talk2amareswaran │ │ │ └── projects │ │ │ └── authorizationserver │ │ │ ├── AuthorizationserverApplication.java │ │ │ ├── RestConfig.java │ │ │ ├── CustomUserDetailsService.java │ │ │ ├── SimpleCorsFilter.java │ │ │ ├── CustomTokenEnhancer.java │ │ │ ├── SecurityConfiguration.java │ │ │ ├── CustomUser.java │ │ │ ├── UserEntity.java │ │ │ ├── OAuth2Config.java │ │ │ └── OAuthDAOService.java │ │ └── resources │ │ └── application.yml └── build.gradle └── README.md /webapp-application/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.port=9090 -------------------------------------------------------------------------------- /webapp-application/src/main/resources/static/logout.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /webapp-application/src/main/java/com/talk2amareswaran/projects/webapp/WebappApplication.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.webapp; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class WebappApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(WebappApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /two-factor-service/src/main/java/com/talk2amareswaran/projects/twofactorservice/TwofactorserviceApplication.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.twofactorservice; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class TwofactorserviceApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(TwofactorserviceApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /webapp-application/src/test/java/com/talk2amareswaran/projects/webapp/WebappApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.webapp; 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 WebappApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /resource-server/src/test/java/com/talk2amareswaran/projects/resourceserver/ResourceserverApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.resourceserver; 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 ResourceserverApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /two-factor-service/src/test/java/com/talk2amareswaran/projects/twofactorservice/TwofactorserviceApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.twofactorservice; 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 TwofactorserviceApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /authorization-server/src/test/java/com/talk2amareswaran/projects/authorizationserver/AuthorizationserverApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.authorizationserver; 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 AuthorizationserverApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /resource-server/src/main/java/com/talk2amareswaran/projects/resourceserver/UserRole.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.resourceserver; 2 | 3 | public class UserRole { 4 | 5 | private String id; 6 | private String role_name; 7 | 8 | public String getId() { 9 | return id; 10 | } 11 | 12 | public void setId(String id) { 13 | this.id = id; 14 | } 15 | 16 | public String getRole_name() { 17 | return role_name; 18 | } 19 | 20 | public void setRole_name(String role_name) { 21 | this.role_name = role_name; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /resource-server/src/main/java/com/talk2amareswaran/projects/resourceserver/Permission.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.resourceserver; 2 | 3 | public class Permission { 4 | 5 | private String id; 6 | private String permission_name; 7 | 8 | public String getId() { 9 | return id; 10 | } 11 | 12 | public void setId(String id) { 13 | this.id = id; 14 | } 15 | 16 | public String getPermission_name() { 17 | return permission_name; 18 | } 19 | 20 | public void setPermission_name(String permission_name) { 21 | this.permission_name = permission_name; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /resource-server/src/main/java/com/talk2amareswaran/projects/resourceserver/ResourceserverApplication.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.resourceserver; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; 6 | 7 | @SpringBootApplication 8 | @EnableResourceServer 9 | public class ResourceserverApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(ResourceserverApplication.class, args); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /two-factor-service/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | application: 3 | name: two-factor-service 4 | datasource: 5 | driverClassName: com.mysql.jdbc.Driver 6 | url: "jdbc:mysql://localhost:3306/userservice?autoreconnect=true" 7 | password: "root" 8 | username: "root" 9 | testOnBorrow: true 10 | testWhileIdle: true 11 | timeBetweenEvictionRunsMillis: 60000 12 | minEvictableIdleTimeMillis: 30000 13 | validationQuery: SELECT 1 14 | max-active: 15 15 | max-idle: 10 16 | max-wait: 8000 17 | 18 | server: 19 | port: 8087 -------------------------------------------------------------------------------- /authorization-server/src/main/java/com/talk2amareswaran/projects/authorizationserver/AuthorizationserverApplication.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.authorizationserver; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; 6 | 7 | 8 | @SpringBootApplication 9 | @EnableAuthorizationServer 10 | public class AuthorizationserverApplication { 11 | 12 | public static void main(String[] args) { 13 | SpringApplication.run(AuthorizationserverApplication.class, args); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /resource-server/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | application: 3 | name: resource-server 4 | datasource: 5 | driverClassName: com.mysql.jdbc.Driver 6 | url: "jdbc:mysql://localhost:3306/userservice?autoreconnect=true" 7 | password: "root" 8 | username: "root" 9 | testOnBorrow: true 10 | testWhileIdle: true 11 | timeBetweenEvictionRunsMillis: 60000 12 | minEvictableIdleTimeMillis: 30000 13 | validationQuery: SELECT 1 14 | max-active: 15 15 | max-idle: 10 16 | max-wait: 8000 17 | server: 18 | port: 8000 19 | 20 | security: 21 | oauth2: 22 | resource: 23 | filter-order: 3 24 | jwt: 25 | key-value: 26 | -------------------------------------------------------------------------------- /authorization-server/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | application: 3 | name: authorization-server 4 | datasource: 5 | driverClassName: com.mysql.jdbc.Driver 6 | url: "jdbc:mysql://localhost:3306/userservice?autoreconnect=true" 7 | password: "root" 8 | username: "root" 9 | testOnBorrow: true 10 | testWhileIdle: true 11 | timeBetweenEvictionRunsMillis: 60000 12 | minEvictableIdleTimeMillis: 30000 13 | validationQuery: SELECT 1 14 | max-active: 15 15 | max-idle: 10 16 | max-wait: 8000 17 | config: 18 | oauth2: 19 | privateKey: 20 | publicKey: 21 | clientid: talk2amareswaran 22 | clientSecret: talk@amareswaran 23 | -------------------------------------------------------------------------------- /webapp-application/build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | ext { 3 | springBootVersion = '2.0.4.RELEASE' 4 | } 5 | repositories { 6 | mavenCentral() 7 | } 8 | dependencies { 9 | classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") 10 | } 11 | } 12 | 13 | apply plugin: 'java' 14 | apply plugin: 'eclipse' 15 | apply plugin: 'org.springframework.boot' 16 | apply plugin: 'io.spring.dependency-management' 17 | 18 | group = 'com.talk2amareswaran.projects' 19 | version = '0.0.1-SNAPSHOT' 20 | sourceCompatibility = 1.8 21 | 22 | repositories { 23 | mavenCentral() 24 | } 25 | 26 | 27 | dependencies { 28 | compile('org.springframework.boot:spring-boot-starter-thymeleaf') 29 | compile('org.springframework.boot:spring-boot-starter-web') 30 | testCompile('org.springframework.boot:spring-boot-starter-test') 31 | } 32 | -------------------------------------------------------------------------------- /two-factor-service/src/main/java/com/talk2amareswaran/projects/twofactorservice/SMSService.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.twofactorservice; 2 | 3 | import org.springframework.stereotype.Service; 4 | 5 | import com.twilio.Twilio; 6 | import com.twilio.rest.api.v2010.account.Message; 7 | import com.twilio.type.PhoneNumber; 8 | 9 | @Service 10 | public class SMSService { 11 | 12 | private final static String ACCOUNT_SID = ""; 13 | private final static String AUTH_ID = "**********************"; 14 | 15 | static { 16 | Twilio.init(ACCOUNT_SID, AUTH_ID); 17 | } 18 | 19 | public boolean send2FaCode(String mobilenumber, String twoFaCode) { 20 | 21 | Message.creator(new PhoneNumber(mobilenumber), new PhoneNumber(""), 22 | "Your Two Factor Authentication code is: "+ twoFaCode).create(); 23 | 24 | return true; 25 | 26 | 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /two-factor-service/build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | ext { 3 | springBootVersion = '2.0.4.RELEASE' 4 | } 5 | repositories { 6 | mavenCentral() 7 | } 8 | dependencies { 9 | classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") 10 | } 11 | } 12 | 13 | apply plugin: 'java' 14 | apply plugin: 'eclipse' 15 | apply plugin: 'org.springframework.boot' 16 | apply plugin: 'io.spring.dependency-management' 17 | 18 | group = 'com.talk2amareswaran.projects' 19 | version = '0.0.1-SNAPSHOT' 20 | sourceCompatibility = 1.8 21 | 22 | repositories { 23 | mavenCentral() 24 | } 25 | 26 | 27 | dependencies { 28 | compile('org.springframework.boot:spring-boot-starter-web') 29 | compile group: 'com.twilio.sdk', name: 'twilio', version: '7.11.0' 30 | compile('org.springframework.boot:spring-boot-starter-mail') 31 | compile('org.springframework.boot:spring-boot-starter-jdbc') 32 | runtime('mysql:mysql-connector-java') 33 | testCompile('org.springframework.boot:spring-boot-starter-test') 34 | } 35 | -------------------------------------------------------------------------------- /two-factor-service/src/main/java/com/talk2amareswaran/projects/twofactorservice/DAOService.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.twofactorservice; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.jdbc.core.JdbcTemplate; 5 | import org.springframework.stereotype.Repository; 6 | 7 | @Repository 8 | public class DAOService { 9 | 10 | @Autowired 11 | JdbcTemplate jdbcTemplate; 12 | 13 | public void update2FAProperties(String userid, String twofacode) { 14 | jdbcTemplate.update("update users set 2fa_code=?, 2fa_expire_time=? where id=?", new Object[] { 15 | twofacode, (System.currentTimeMillis()/1000) + 120, userid 16 | }); 17 | } 18 | 19 | public boolean checkCode(String id, String code) { 20 | return jdbcTemplate.queryForObject("select count(*) from users where 2fa_code=? and id=?" 21 | + " and 2fa_expire_time >=?", new Object[] {code, id, 22 | System.currentTimeMillis()/1000}, Integer.class) >0; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /authorization-server/build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | ext { 3 | springBootVersion = '1.5.9.RELEASE' 4 | } 5 | repositories { 6 | mavenCentral() 7 | } 8 | dependencies { 9 | classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") 10 | } 11 | } 12 | 13 | apply plugin: 'java' 14 | apply plugin: 'eclipse' 15 | apply plugin: 'org.springframework.boot' 16 | 17 | group = 'com.talk2amareswaran.projects' 18 | version = '0.0.1-SNAPSHOT' 19 | sourceCompatibility = 1.8 20 | 21 | repositories { 22 | mavenCentral() 23 | } 24 | 25 | 26 | dependencies { 27 | compile('org.springframework.boot:spring-boot-starter') 28 | compile('org.springframework.boot:spring-boot-starter-web') 29 | compile('org.springframework.boot:spring-boot-starter-jdbc') 30 | runtime('mysql:mysql-connector-java') 31 | compile('org.springframework.security.oauth:spring-security-oauth2') 32 | compile('org.springframework.security:spring-security-jwt') 33 | testCompile('org.springframework.boot:spring-boot-starter-test') 34 | } 35 | -------------------------------------------------------------------------------- /resource-server/build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | ext { 3 | springBootVersion = '1.5.9.RELEASE' 4 | } 5 | repositories { 6 | mavenCentral() 7 | } 8 | dependencies { 9 | classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") 10 | } 11 | } 12 | 13 | apply plugin: 'java' 14 | apply plugin: 'eclipse' 15 | apply plugin: 'org.springframework.boot' 16 | 17 | group = 'com.talk2amareswaran.projects' 18 | version = '0.0.1-SNAPSHOT' 19 | sourceCompatibility = 1.8 20 | 21 | repositories { 22 | mavenCentral() 23 | } 24 | 25 | 26 | dependencies { 27 | compile('org.springframework.boot:spring-boot-starter') 28 | compile('org.springframework.boot:spring-boot-starter-web') 29 | compile('org.springframework.boot:spring-boot-starter-jdbc') 30 | runtime('mysql:mysql-connector-java') 31 | testCompile('org.springframework.boot:spring-boot-starter-test') 32 | compile('org.springframework.boot:spring-boot-starter-security') 33 | compile("org.springframework.security.oauth:spring-security-oauth2") 34 | compile('org.springframework.security:spring-security-jwt') 35 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # two-factor-authentication-springboot 2 | 3 | Two Factor Authentication course videos 4 | ********************************************** 5 | Hello Everyone, 6 | 7 | Here is the Two Factor Authentication course developed by Spring Boot OAUTH2 Security. Course video links are given below. 8 | 9 | SMS Authentication - Twilio 10 | 11 | Email Authentication - Gmail Transport Layer Security 12 | 13 | Please subscribe my youtube channel - https://www.youtube.com/c/Talk2Amareswaran 14 | 15 | Please like my Facebook page - https://www.facebook.com/talk2amareswaran/ 16 | 17 | Introduction - https://youtu.be/uQyYQhXpdak 18 | 19 | Database Schema design - https://youtu.be/W1sqlcD9VMs 20 | 21 | 2FA Authorization - Spring Security OAUTH2 - Authorization server - https://youtu.be/GzgCga5wxDc 22 | 23 | 2FA Service Implementation - https://youtu.be/5MHxCnlXkEY 24 | 25 | 2FA CORS - https://youtu.be/PqrwQrkOX5U 26 | 27 | Web application integration - https://youtu.be/L_Xap3gBYGI 28 | 29 | Two Factor Authentication Playlist - https://www.youtube.com/playlist?list=PL_U4i-WTE-SXpmV_ZfPwppXZzrhQWabDp 30 | -------------------------------------------------------------------------------- /resource-server/src/main/java/com/talk2amareswaran/projects/resourceserver/PermissionResourceDAO.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.resourceserver; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collection; 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.jdbc.core.JdbcTemplate; 10 | import org.springframework.stereotype.Repository; 11 | 12 | @Repository 13 | public class PermissionResourceDAO { 14 | 15 | @Autowired 16 | JdbcTemplate jdbcTemplate; 17 | 18 | public List getListOfPermissions() { 19 | Collection> rows3 = jdbcTemplate.queryForList("select * from permission"); 20 | List permissionsList = new ArrayList<>(); 21 | rows3.stream().map((row) -> { 22 | Permission p = new Permission(); 23 | p.setPermission_name((String)row.get("permission_name")); 24 | p.setId(String.valueOf(row.get("id"))); 25 | return p; 26 | }).forEach((ss3) -> { 27 | permissionsList.add(ss3); 28 | }); 29 | return permissionsList; 30 | } 31 | } -------------------------------------------------------------------------------- /resource-server/src/main/java/com/talk2amareswaran/projects/resourceserver/SecurityConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.resourceserver; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 5 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 6 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 7 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 8 | import org.springframework.security.config.http.SessionCreationPolicy; 9 | 10 | @Configuration 11 | @EnableWebSecurity 12 | @EnableGlobalMethodSecurity(prePostEnabled = true) 13 | public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 14 | 15 | @Override 16 | protected void configure(HttpSecurity http) throws Exception { 17 | http.authorizeRequests().anyRequest().authenticated().and().sessionManagement() 18 | .sessionCreationPolicy(SessionCreationPolicy.NEVER); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /authorization-server/src/main/java/com/talk2amareswaran/projects/authorizationserver/RestConfig.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.authorizationserver; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.web.cors.CorsConfiguration; 6 | import org.springframework.web.cors.UrlBasedCorsConfigurationSource; 7 | import org.springframework.web.filter.CorsFilter; 8 | 9 | @Configuration 10 | public class RestConfig { 11 | @Bean 12 | public CorsFilter corsFilter() { 13 | UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 14 | CorsConfiguration config = new CorsConfiguration(); 15 | config.setAllowCredentials(true); 16 | config.addAllowedOrigin("*"); 17 | config.addAllowedHeader("*"); 18 | config.addAllowedMethod("OPTIONS"); 19 | config.addAllowedMethod("GET"); 20 | config.addAllowedMethod("POST"); 21 | config.addAllowedMethod("PUT"); 22 | config.addAllowedMethod("DELETE"); 23 | source.registerCorsConfiguration("/**", config); 24 | return new CorsFilter(source); 25 | } 26 | } -------------------------------------------------------------------------------- /authorization-server/src/main/java/com/talk2amareswaran/projects/authorizationserver/CustomUserDetailsService.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.authorizationserver; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.security.core.userdetails.UserDetails; 5 | import org.springframework.security.core.userdetails.UserDetailsService; 6 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 7 | import org.springframework.stereotype.Service; 8 | 9 | @Service 10 | public class CustomUserDetailsService implements UserDetailsService { 11 | 12 | @Autowired 13 | OAuthDAOService oauthDaoService; 14 | 15 | @Override 16 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 17 | 18 | UserEntity userEntity = null; 19 | try { 20 | userEntity = oauthDaoService.getUserDetails(username); 21 | if (userEntity != null && userEntity.getId() != null && !"".equalsIgnoreCase(userEntity.getId())) { 22 | CustomUser customUser = new CustomUser(userEntity); 23 | return customUser; 24 | } else { 25 | throw new UsernameNotFoundException("User " + username + " was not found in the database"); 26 | } 27 | } catch (Exception e) { 28 | e.printStackTrace(); 29 | throw new UsernameNotFoundException("User " + username + " was not found in the database"); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /resource-server/src/main/java/com/talk2amareswaran/projects/resourceserver/PermissionsByRoleResourceDAO.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.resourceserver; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collection; 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.jdbc.core.JdbcTemplate; 10 | import org.springframework.stereotype.Repository; 11 | 12 | @Repository 13 | public class PermissionsByRoleResourceDAO { 14 | 15 | @Autowired 16 | JdbcTemplate jdbcTemplate; 17 | 18 | public List getViewPermissionsByRole(String role_id) { 19 | Collection> rows3 = jdbcTemplate.queryForList( 20 | "select p.permission_name from permission p " 21 | + "inner join role_permission role_p on p.id=role_p.permission_id " + "where role_p.role_id=?", 22 | new Object[] { role_id }); 23 | List permissionsList = new ArrayList<>(); 24 | rows3.stream().map((row) -> { 25 | return (String) row.get("permission_name"); 26 | }).forEach((ss3) -> { 27 | permissionsList.add(ss3); 28 | }); 29 | return permissionsList; 30 | } 31 | 32 | public void assignPermissions2Role(String role_id, List permissionsList) { 33 | jdbcTemplate.update("delete from role_permission where role_id=?", new Object[] {role_id}); 34 | for(String id:permissionsList) { 35 | jdbcTemplate.update("insert into role_permission (role_id, permission_id) values (?,?)", new Object[]{role_id,id}); 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /resource-server/src/main/java/com/talk2amareswaran/projects/resourceserver/RolesDAO.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.resourceserver; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collection; 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.jdbc.core.JdbcTemplate; 10 | import org.springframework.stereotype.Repository; 11 | 12 | @Repository 13 | public class RolesDAO { 14 | 15 | @Autowired 16 | JdbcTemplate jdbcTemplate; 17 | 18 | public List getListOfRoles() { 19 | 20 | Collection> rows3 = jdbcTemplate.queryForList("select * from role order by id asc"); 21 | List rolesList = new ArrayList<>(); 22 | rows3.stream().map((row) -> { 23 | UserRole role = new UserRole(); 24 | role.setId(String.valueOf(row.get("id"))); 25 | role.setRole_name((String) row.get("role_name")); 26 | return role; 27 | }).forEach((ss3) -> { 28 | rolesList.add(ss3); 29 | }); 30 | return rolesList; 31 | 32 | } 33 | 34 | public void deleteRole(String role_id) { 35 | jdbcTemplate.update("delete from role where id=?", new Object[] { role_id }); 36 | } 37 | 38 | public void updateRole(String role_id, UserRole role) { 39 | jdbcTemplate.update("update role set role_name=? where id=?", new Object[] { role.getRole_name(), role_id }); 40 | } 41 | 42 | public void createRole(UserRole role) { 43 | jdbcTemplate.update("insert into role (role_name) values (?)", new Object[] { role.getRole_name() }); 44 | } 45 | 46 | } -------------------------------------------------------------------------------- /resource-server/src/main/java/com/talk2amareswaran/projects/resourceserver/PermissionResource.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.resourceserver; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.http.HttpStatus; 5 | import org.springframework.http.ResponseEntity; 6 | import org.springframework.security.access.prepost.PreAuthorize; 7 | import org.springframework.security.core.context.SecurityContextHolder; 8 | import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails; 9 | import org.springframework.web.bind.annotation.RequestMapping; 10 | import org.springframework.web.bind.annotation.RequestMethod; 11 | import org.springframework.web.bind.annotation.RestController; 12 | 13 | @RestController 14 | public class PermissionResource { 15 | 16 | @Autowired 17 | PermissionResourceDAO permissionResourceDAO; 18 | 19 | @PreAuthorize("hasAnyRole('view_permission', 'SUPERADMIN')") 20 | @RequestMapping(value="/permissions", method=RequestMethod.GET) 21 | public ResponseEntity getListOfPermissions() { 22 | AccessTokenMapper accessTokenMapper = (AccessTokenMapper) 23 | ((OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails()).getDecodedDetails(); 24 | System.out.println("accessTokenMapper.getFirst_name()::"+accessTokenMapper.getFirst_name()); 25 | System.out.println("accessTokenMapper.getLast_name()::"+accessTokenMapper.getLast_name()); 26 | return new ResponseEntity(permissionResourceDAO.getListOfPermissions(), HttpStatus.OK); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /resource-server/src/main/java/com/talk2amareswaran/projects/resourceserver/UsersByRoleResource.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.resourceserver; 2 | 3 | import java.util.ArrayList; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.http.HttpStatus; 7 | import org.springframework.http.ResponseEntity; 8 | import org.springframework.security.access.prepost.PreAuthorize; 9 | import org.springframework.web.bind.annotation.PathVariable; 10 | import org.springframework.web.bind.annotation.RequestBody; 11 | import org.springframework.web.bind.annotation.RequestMapping; 12 | import org.springframework.web.bind.annotation.RequestMethod; 13 | import org.springframework.web.bind.annotation.RestController; 14 | 15 | @RestController 16 | public class UsersByRoleResource { 17 | 18 | @Autowired 19 | UsersByRoleResourceDAO usersByRoleResourceDAO; 20 | 21 | @PreAuthorize("hasAnyRole('view_users_by_role', 'SUPERADMIN')") 22 | @RequestMapping(value = "/roles/{id}/users", method = RequestMethod.GET) 23 | public ResponseEntity viewUsersByRole(@PathVariable("id") String role_id) { 24 | return new ResponseEntity<>(usersByRoleResourceDAO.viewUsersByRole(role_id), HttpStatus.OK); 25 | } 26 | 27 | @PreAuthorize("hasAnyRole('assign_users_to_role', 'SUPERADMIN')") 28 | @RequestMapping(value = "/roles/{id}/users", method = RequestMethod.PUT) 29 | public ResponseEntity assignUsers2Role(@PathVariable("id") String role_id, @RequestBody ArrayList usersList) { 30 | usersByRoleResourceDAO.assignUsers2Role(role_id, usersList); 31 | return new ResponseEntity<>("Users are assigned to role successfully", HttpStatus.OK); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /resource-server/src/main/java/com/talk2amareswaran/projects/resourceserver/AccessTokenMapper.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.resourceserver; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class AccessTokenMapper { 7 | 8 | private String id; 9 | private List authorities = new ArrayList(); 10 | private String first_name; 11 | private String last_name; 12 | private String user_type; 13 | private String mobile; 14 | private String country; 15 | 16 | public String getId() { 17 | return id; 18 | } 19 | 20 | public void setId(String id) { 21 | this.id = id; 22 | } 23 | 24 | public List getAuthorities() { 25 | return authorities; 26 | } 27 | 28 | public void setAuthorities(List authorities) { 29 | this.authorities = authorities; 30 | } 31 | 32 | public String getFirst_name() { 33 | return first_name; 34 | } 35 | 36 | public void setFirst_name(String first_name) { 37 | this.first_name = first_name; 38 | } 39 | 40 | public String getLast_name() { 41 | return last_name; 42 | } 43 | 44 | public void setLast_name(String last_name) { 45 | this.last_name = last_name; 46 | } 47 | 48 | public String getUser_type() { 49 | return user_type; 50 | } 51 | 52 | public void setUser_type(String user_type) { 53 | this.user_type = user_type; 54 | } 55 | 56 | public String getMobile() { 57 | return mobile; 58 | } 59 | 60 | public void setMobile(String mobile) { 61 | this.mobile = mobile; 62 | } 63 | 64 | public String getCountry() { 65 | return country; 66 | } 67 | 68 | public void setCountry(String country) { 69 | this.country = country; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /resource-server/src/main/java/com/talk2amareswaran/projects/resourceserver/PermissionsByRoleResource.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.resourceserver; 2 | 3 | import java.util.ArrayList; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.http.HttpStatus; 7 | import org.springframework.http.ResponseEntity; 8 | import org.springframework.security.access.prepost.PreAuthorize; 9 | import org.springframework.web.bind.annotation.PathVariable; 10 | import org.springframework.web.bind.annotation.RequestBody; 11 | import org.springframework.web.bind.annotation.RequestMapping; 12 | import org.springframework.web.bind.annotation.RequestMethod; 13 | import org.springframework.web.bind.annotation.RestController; 14 | 15 | @RestController 16 | public class PermissionsByRoleResource { 17 | 18 | @Autowired 19 | PermissionsByRoleResourceDAO permissionsByRoleResourceDAO; 20 | 21 | @PreAuthorize("hasAnyRole('view_permissions_by_role', 'SUPERADMIN')") 22 | @RequestMapping(value = "/roles/{id}/permissions", method = RequestMethod.GET) 23 | public ResponseEntity viewPermissionsByRole(@PathVariable("id") String role_id) { 24 | return new ResponseEntity<>(permissionsByRoleResourceDAO.getViewPermissionsByRole(role_id), HttpStatus.OK); 25 | } 26 | 27 | @PreAuthorize("hasAnyRole('assign_permissions_to_role', 'SUPERADMIN')") 28 | @RequestMapping(value = "/roles/{id}/permissions", method = RequestMethod.PUT) 29 | public ResponseEntity assignPermissions2Role(@PathVariable("id") String role_id, @RequestBody ArrayList permissionsList) { 30 | permissionsByRoleResourceDAO.assignPermissions2Role(role_id, permissionsList); 31 | return new ResponseEntity<>("Permissions are assigned to role successfully", HttpStatus.OK); 32 | } 33 | 34 | } -------------------------------------------------------------------------------- /webapp-application/src/main/resources/static/styles.css: -------------------------------------------------------------------------------- 1 | .pageCenterDiv { 2 | position: absolute; 3 | margin: auto; 4 | top: 0; 5 | right: 0; 6 | bottom: 0; 7 | left: 0; 8 | width: 550px; 9 | height: 450px; 10 | } 11 | 12 | .font_bold { 13 | font-weight: bold; 14 | } 15 | 16 | .width_150 { 17 | width: 150px; 18 | } 19 | 20 | .width_120 { 21 | width: 120px; 22 | } 23 | 24 | .marginTop_minus1px { 25 | margin-top: -1px; 26 | } 27 | 28 | .margin_left_0px { 29 | margin-left: 0px; 30 | } 31 | 32 | .margin_right_0px { 33 | margin-right: 0px; 34 | } 35 | 36 | .max_height_550px { 37 | max-height: 950px; 38 | } 39 | 40 | .text_align_right { 41 | text-align:right; 42 | } 43 | 44 | .text_align_center { 45 | text-align:center; 46 | } 47 | 48 | .font_size_37 { 49 | font-size: 37px; 50 | } 51 | 52 | .closeBtn { 53 | 54 | background-color: IndianRed; /* Blue background */ 55 | border: none; /* Remove borders */ 56 | color: white; /* White text */ 57 | padding: 2px 12px; /* Some padding */ 58 | font-size: 16px; /* Set a font size */ 59 | cursor: pointer; /* Mouse pointer on hover */ 60 | } 61 | .customBtn { 62 | background-color: DodgerBlue; /* Blue background */ 63 | border: none; /* Remove borders */ 64 | color: white; /* White text */ 65 | padding: 2px 12px; /* Some padding */ 66 | font-size: 16px; /* Set a font size */ 67 | cursor: pointer; /* Mouse pointer on hover */ 68 | } 69 | 70 | /* Darker background on mouse-over */ 71 | .customBtn:hover { 72 | background-color: RoyalBlue; 73 | } 74 | 75 | .closeBtn:hover { 76 | background-color: DarkRed; 77 | } 78 | 79 | .dropdown_custom { 80 | height: 35px; 81 | width: 250px; 82 | padding-left:5px; 83 | } 84 | 85 | #mainContent { 86 | height:934px; 87 | } -------------------------------------------------------------------------------- /two-factor-service/src/main/java/com/talk2amareswaran/projects/twofactorservice/EmailService.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.twofactorservice; 2 | 3 | import java.util.Properties; 4 | 5 | import javax.mail.Message; 6 | import javax.mail.MessagingException; 7 | import javax.mail.PasswordAuthentication; 8 | import javax.mail.Session; 9 | import javax.mail.Transport; 10 | import javax.mail.internet.AddressException; 11 | import javax.mail.internet.InternetAddress; 12 | import javax.mail.internet.MimeMessage; 13 | 14 | import org.springframework.stereotype.Service; 15 | 16 | 17 | @Service 18 | public class EmailService { 19 | 20 | private static final String username="talk2amareswaran@gmail.com"; 21 | private static final String password = "*****************************"; 22 | 23 | public boolean sendEmail(String emailid, String twoFaCode) throws AddressException, MessagingException { 24 | Properties props = new Properties(); 25 | props.put("mail.smtp.auth", "true"); 26 | props.put("mail.smtp.starttls.enable", "true"); 27 | props.put("mail.smtp.host", "smtp.gmail.com"); 28 | props.put("mail.smtp.port", "587"); 29 | 30 | Session session = Session.getInstance(props, 31 | new javax.mail.Authenticator() { 32 | protected PasswordAuthentication getPasswordAuthentication() { 33 | return new PasswordAuthentication(username, password); 34 | } 35 | }); 36 | 37 | MimeMessage message = new MimeMessage(session); 38 | message.setFrom(new InternetAddress(username)); 39 | message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailid)); 40 | 41 | message.setSubject("Two Factor Authentication code from our Service"); 42 | message.setText("Your Two Factor Authentication code is:"+twoFaCode); 43 | Transport.send(message); 44 | return true; 45 | } 46 | } -------------------------------------------------------------------------------- /resource-server/src/main/java/com/talk2amareswaran/projects/resourceserver/UserModel.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.resourceserver; 2 | 3 | import com.fasterxml.jackson.annotation.JsonInclude; 4 | 5 | @JsonInclude(JsonInclude.Include.NON_DEFAULT) 6 | public class UserModel { 7 | 8 | private String id; 9 | private String first_name; 10 | private String last_name; 11 | private String email_id; 12 | private String password; 13 | private String user_type; 14 | private String mobile; 15 | private String country; 16 | 17 | public String getId() { 18 | return id; 19 | } 20 | 21 | public void setId(String id) { 22 | this.id = id; 23 | } 24 | 25 | public String getFirst_name() { 26 | return first_name; 27 | } 28 | 29 | public void setFirst_name(String first_name) { 30 | this.first_name = first_name; 31 | } 32 | 33 | public String getLast_name() { 34 | return last_name; 35 | } 36 | 37 | public void setLast_name(String last_name) { 38 | this.last_name = last_name; 39 | } 40 | 41 | public String getEmail_id() { 42 | return email_id; 43 | } 44 | 45 | public void setEmail_id(String email_id) { 46 | this.email_id = email_id; 47 | } 48 | 49 | public String getPassword() { 50 | return password; 51 | } 52 | 53 | public void setPassword(String password) { 54 | this.password = password; 55 | } 56 | 57 | public String getUser_type() { 58 | return user_type; 59 | } 60 | 61 | public void setUser_type(String user_type) { 62 | this.user_type = user_type; 63 | } 64 | 65 | public String getMobile() { 66 | return mobile; 67 | } 68 | 69 | public void setMobile(String mobile) { 70 | this.mobile = mobile; 71 | } 72 | 73 | public String getCountry() { 74 | return country; 75 | } 76 | 77 | public void setCountry(String country) { 78 | this.country = country; 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /two-factor-service/src/main/java/com/talk2amareswaran/projects/twofactorservice/SimpleCORSFiler.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.twofactorservice; 2 | 3 | import java.io.IOException; 4 | 5 | import javax.servlet.Filter; 6 | import javax.servlet.FilterChain; 7 | import javax.servlet.FilterConfig; 8 | import javax.servlet.ServletException; 9 | import javax.servlet.ServletRequest; 10 | import javax.servlet.ServletResponse; 11 | import javax.servlet.http.HttpServletRequest; 12 | import javax.servlet.http.HttpServletResponse; 13 | 14 | import org.springframework.core.Ordered; 15 | import org.springframework.core.annotation.Order; 16 | import org.springframework.stereotype.Component; 17 | 18 | @Component 19 | @Order(Ordered.HIGHEST_PRECEDENCE) 20 | public class SimpleCORSFiler implements Filter { 21 | 22 | public SimpleCORSFiler() { 23 | } 24 | 25 | @Override 26 | public void init(FilterConfig filterConfig) { 27 | } 28 | 29 | @Override 30 | public void destroy() { 31 | } 32 | 33 | 34 | @Override 35 | public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { 36 | HttpServletResponse response = (HttpServletResponse) res; 37 | HttpServletRequest request = (HttpServletRequest) req; 38 | response.setHeader("Access-Control-Allow-Origin", "*"); 39 | response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT"); 40 | response.setHeader("Access-Control-Max-Age", "3600"); 41 | response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization, content-type"); 42 | 43 | if ("OPTIONS".equalsIgnoreCase(request.getMethod())) { 44 | response.setStatus(HttpServletResponse.SC_OK); 45 | } else { 46 | chain.doFilter(req, res); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /resource-server/src/main/java/com/talk2amareswaran/projects/resourceserver/SimpleCorsFilter.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.resourceserver; 2 | 3 | import java.io.IOException; 4 | 5 | import javax.servlet.Filter; 6 | import javax.servlet.FilterChain; 7 | import javax.servlet.FilterConfig; 8 | import javax.servlet.ServletException; 9 | import javax.servlet.ServletRequest; 10 | import javax.servlet.ServletResponse; 11 | import javax.servlet.http.HttpServletRequest; 12 | import javax.servlet.http.HttpServletResponse; 13 | 14 | import org.springframework.core.Ordered; 15 | import org.springframework.core.annotation.Order; 16 | import org.springframework.stereotype.Component; 17 | 18 | @Component 19 | @Order(Ordered.HIGHEST_PRECEDENCE) 20 | public class SimpleCorsFilter implements Filter { 21 | 22 | public SimpleCorsFilter() { 23 | } 24 | 25 | @Override 26 | public void init(FilterConfig filterConfig) { 27 | } 28 | 29 | @Override 30 | public void destroy() { 31 | } 32 | 33 | @Override 34 | public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { 35 | 36 | HttpServletResponse response = (HttpServletResponse) res; 37 | HttpServletRequest request = (HttpServletRequest) req; 38 | 39 | response.setHeader("Access-Control-Allow-Origin", "*"); 40 | response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT"); 41 | response.setHeader("Access-Control-Max-Age", "3600"); 42 | response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization, content-type"); 43 | 44 | if ("OPTIONS".equalsIgnoreCase(request.getMethod())) { 45 | response.setStatus(HttpServletResponse.SC_OK); 46 | } else { 47 | chain.doFilter(req, res); 48 | } 49 | } 50 | } -------------------------------------------------------------------------------- /authorization-server/src/main/java/com/talk2amareswaran/projects/authorizationserver/SimpleCorsFilter.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.authorizationserver; 2 | 3 | import java.io.IOException; 4 | 5 | import javax.servlet.Filter; 6 | import javax.servlet.FilterChain; 7 | import javax.servlet.FilterConfig; 8 | import javax.servlet.ServletException; 9 | import javax.servlet.ServletRequest; 10 | import javax.servlet.ServletResponse; 11 | import javax.servlet.http.HttpServletRequest; 12 | import javax.servlet.http.HttpServletResponse; 13 | 14 | import org.springframework.core.Ordered; 15 | import org.springframework.core.annotation.Order; 16 | import org.springframework.stereotype.Component; 17 | 18 | @Component 19 | @Order(Ordered.HIGHEST_PRECEDENCE) 20 | public class SimpleCorsFilter implements Filter { 21 | 22 | public SimpleCorsFilter() { 23 | } 24 | 25 | @Override 26 | public void init(FilterConfig filterConfig) { 27 | } 28 | 29 | @Override 30 | public void destroy() { 31 | } 32 | 33 | @Override 34 | public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { 35 | 36 | HttpServletResponse response = (HttpServletResponse) res; 37 | HttpServletRequest request = (HttpServletRequest) req; 38 | 39 | response.setHeader("Access-Control-Allow-Origin", "*"); 40 | response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT"); 41 | response.setHeader("Access-Control-Max-Age", "3600"); 42 | response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization, content-type"); 43 | 44 | if ("OPTIONS".equalsIgnoreCase(request.getMethod())) { 45 | response.setStatus(HttpServletResponse.SC_OK); 46 | } else { 47 | chain.doFilter(req, res); 48 | } 49 | } 50 | } -------------------------------------------------------------------------------- /resource-server/src/main/java/com/talk2amareswaran/projects/resourceserver/UsersByRoleResourceDAO.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.resourceserver; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collection; 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.jdbc.core.JdbcTemplate; 10 | import org.springframework.stereotype.Repository; 11 | 12 | @Repository 13 | public class UsersByRoleResourceDAO { 14 | 15 | @Autowired 16 | JdbcTemplate jdbcTemplate; 17 | 18 | public Object viewUsersByRole(String role_id) { 19 | 20 | Collection> rows3 = jdbcTemplate.queryForList( 21 | "select u.id,u.first_name, u.last_name, u.email_id, u.country, u.user_type, u.mobile from users u " 22 | + "inner join role_users role_u on u.id=role_u.user_id " + "where role_u.role_id=?", 23 | new Object[] { role_id }); 24 | List usersList = new ArrayList<>(); 25 | rows3.stream().map((row) -> { 26 | UserModel user = new UserModel(); 27 | user.setCountry((String) row.get("country")); 28 | user.setEmail_id((String) row.get("email_id")); 29 | user.setFirst_name((String) row.get("first_name")); 30 | user.setId(String.valueOf(row.get("id"))); 31 | user.setLast_name((String) row.get("last_name")); 32 | user.setMobile((String) row.get("mobile")); 33 | user.setUser_type((String) row.get("user_type")); 34 | return user; 35 | }).forEach((ss3) -> { 36 | usersList.add(ss3); 37 | }); 38 | return usersList; 39 | 40 | } 41 | 42 | public void assignUsers2Role(String role_id, ArrayList usersList) { 43 | jdbcTemplate.update("delete from role_users where role_id=?", new Object[] {role_id}); 44 | for(String id:usersList) { 45 | jdbcTemplate.update("insert into role_users (role_id, user_id) values (?,?)", new Object[]{role_id,id}); 46 | } 47 | } 48 | } -------------------------------------------------------------------------------- /authorization-server/src/main/java/com/talk2amareswaran/projects/authorizationserver/CustomTokenEnhancer.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.authorizationserver; 2 | 3 | import java.util.LinkedHashMap; 4 | import java.util.Map; 5 | 6 | import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; 7 | import org.springframework.security.oauth2.common.OAuth2AccessToken; 8 | import org.springframework.security.oauth2.provider.OAuth2Authentication; 9 | import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; 10 | 11 | public class CustomTokenEnhancer extends JwtAccessTokenConverter { 12 | 13 | @Override 14 | public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { 15 | CustomUser user = (CustomUser) authentication.getPrincipal(); 16 | Map info = new LinkedHashMap<>(accessToken.getAdditionalInformation()); 17 | if (user.getId() != null) 18 | info.put("id", user.getId()); 19 | if (user.getFirst_name() != null) 20 | info.put("first_name", user.getFirst_name()); 21 | if (user.getLast_name() != null) 22 | info.put("last_name", user.getLast_name()); 23 | if (user.getCountry() != null) 24 | info.put("country", user.getCountry()); 25 | if (user.getMobile() != null) 26 | info.put("mobile", user.getMobile()); 27 | if (user.getUser_type() != null) 28 | info.put("user_type", user.getUser_type()); 29 | if (user.getIs_tfa_enabled() != null) 30 | info.put("is_2fa_enabled", user.getIs_tfa_enabled()); 31 | if (user.getTfa_default_type() != null) 32 | info.put("tfa_default_type", user.getTfa_default_type()); 33 | if (user.getUsername() != null) 34 | info.put("email_id", user.getUsername()); 35 | DefaultOAuth2AccessToken customAccessToken = new DefaultOAuth2AccessToken(accessToken); 36 | customAccessToken.setAdditionalInformation(info); 37 | return super.enhance(customAccessToken, authentication); 38 | } 39 | } -------------------------------------------------------------------------------- /webapp-application/src/main/resources/static/permissions.js: -------------------------------------------------------------------------------- 1 | $(document).ready(function(){ 2 | getPermissionsList(); 3 | }); 4 | function getPermissionsList() { 5 | $.ajax({ 6 | type: "GET", 7 | url: "http://localhost:8000/permissions", 8 | beforeSend: function(request) { 9 | request.setRequestHeader("Authorization", "Bearer "+localStorage.getItem("access_token")); 10 | }, 11 | success: function(msg){ 12 | if(msg.length>0) { 13 | $.each(msg, function (index, value) { 14 | $("tbody").append(" "+(index+1)+""+value.permission_name+""); 15 | }); 16 | } else { 17 | $("tbody").append(" No records to display"); 18 | } 19 | }, 20 | error: function(XMLHttpRequest, textStatus, errorThrown) { 21 | if(XMLHttpRequest.responseText.indexOf("Access token expired:")!=-1) { 22 | getNewToken("permissions.html"); 23 | } else if(XMLHttpRequest.status==403) { 24 | $("table").remove(); $(".alert-danger").show(); 25 | } else { localStorage.clear(); window.location.href="index.html"; } 26 | } 27 | }); 28 | } 29 | 30 | function getNewToken(pageName) { 31 | $.ajax({ 32 | type: "POST", 33 | url: "http://localhost:8080/oauth/token", 34 | data: "refresh_token="+localStorage.getItem("refresh_token")+"&grant_type=refresh_token", 35 | beforeSend: function(request) { 36 | request.setRequestHeader("Authorization", "Basic "+btoa("talk2amareswaran:talk@amareswaran")); 37 | request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 38 | }, 39 | success: function(msg){ 40 | localStorage.setItem("access_token", JSON.parse(JSON.stringify(msg)).access_token); 41 | localStorage.setItem("refresh_token", JSON.parse(JSON.stringify(msg)).refresh_token); 42 | window.location.reload(pageName); 43 | }, 44 | error: function(XMLHttpRequest, textStatus, errorThrown) { 45 | localStorage.clear(); 46 | window.location.href="index.html"; 47 | } 48 | }); 49 | } -------------------------------------------------------------------------------- /resource-server/src/main/java/com/talk2amareswaran/projects/resourceserver/JwtConverter.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.resourceserver; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.Map; 6 | 7 | import org.springframework.boot.autoconfigure.security.oauth2.resource.JwtAccessTokenConverterConfigurer; 8 | import org.springframework.security.core.GrantedAuthority; 9 | import org.springframework.security.oauth2.provider.OAuth2Authentication; 10 | import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter; 11 | import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; 12 | import org.springframework.stereotype.Component; 13 | 14 | @Component 15 | public class JwtConverter extends DefaultAccessTokenConverter implements JwtAccessTokenConverterConfigurer { 16 | 17 | @Override 18 | public void configure(JwtAccessTokenConverter converter) { 19 | converter.setAccessTokenConverter(this); 20 | } 21 | 22 | @Override 23 | public OAuth2Authentication extractAuthentication(Map map) { 24 | OAuth2Authentication auth = super.extractAuthentication(map); 25 | AccessTokenMapper details = new AccessTokenMapper(); 26 | if (map.get("id") != null) 27 | details.setId((String) map.get("id")); 28 | if (map.get("first_name") != null) 29 | details.setFirst_name((String) map.get("first_name")); 30 | if (map.get("last_name") != null) 31 | details.setLast_name((String) map.get("last_name")); 32 | if (map.get("country") != null) 33 | details.setCountry((String) map.get("country")); 34 | if (map.get("mobile") != null) 35 | details.setMobile((String) map.get("mobile")); 36 | if (map.get("user_type") != null) 37 | details.setUser_type((String) map.get("user_type")); 38 | if (auth.getAuthorities() != null && !auth.getAuthorities().isEmpty()) { 39 | List authorities = new ArrayList<>(); 40 | for (GrantedAuthority gn : auth.getAuthorities()) { 41 | authorities.add(gn.getAuthority()); 42 | } 43 | details.setAuthorities(authorities); 44 | } 45 | auth.setDetails(details); 46 | return auth; 47 | } 48 | 49 | } -------------------------------------------------------------------------------- /resource-server/src/main/java/com/talk2amareswaran/projects/resourceserver/RoleResource.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.resourceserver; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.http.HttpStatus; 5 | import org.springframework.http.ResponseEntity; 6 | import org.springframework.security.access.prepost.PreAuthorize; 7 | import org.springframework.web.bind.annotation.PathVariable; 8 | import org.springframework.web.bind.annotation.RequestBody; 9 | import org.springframework.web.bind.annotation.RequestMapping; 10 | import org.springframework.web.bind.annotation.RequestMethod; 11 | import org.springframework.web.bind.annotation.RestController; 12 | 13 | @RestController 14 | public class RoleResource { 15 | 16 | @Autowired 17 | RolesDAO rolesDAO; 18 | 19 | @PreAuthorize("hasAnyRole('view_role', 'SUPERADMIN')") 20 | @RequestMapping(value = "/roles", method = RequestMethod.GET) 21 | public ResponseEntity getListOfRoles() { 22 | return new ResponseEntity(rolesDAO.getListOfRoles(), HttpStatus.OK); 23 | } 24 | 25 | @PreAuthorize("hasAnyRole('delete_role', 'SUPERADMIN')") 26 | @RequestMapping(value = "/roles/{id}", method = RequestMethod.DELETE) 27 | public ResponseEntity deleteRole(@PathVariable("id") String role_id) { 28 | rolesDAO.deleteRole(role_id); 29 | return new ResponseEntity("Role deleted successfully", HttpStatus.OK); 30 | } 31 | 32 | @PreAuthorize("hasAnyRole('edit_role', 'SUPERADMIN')") 33 | @RequestMapping(value = "/roles/{id}", method = RequestMethod.PUT) 34 | public ResponseEntity deleteRole(@PathVariable("id") String role_id, @RequestBody UserRole role) { 35 | rolesDAO.updateRole(role_id, role); 36 | return new ResponseEntity("Role updated successfully", HttpStatus.OK); 37 | } 38 | 39 | @PreAuthorize("hasAnyRole('create_role', 'SUPERADMIN')") 40 | @RequestMapping(value = "/roles", method = RequestMethod.POST) 41 | public ResponseEntity createRole(@RequestBody UserRole role) { 42 | rolesDAO.createRole(role); 43 | return new ResponseEntity("Role created successfully", HttpStatus.OK); 44 | } 45 | } -------------------------------------------------------------------------------- /authorization-server/src/main/java/com/talk2amareswaran/projects/authorizationserver/SecurityConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.authorizationserver; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.security.authentication.AuthenticationManager; 7 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 8 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 9 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 10 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 11 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 12 | import org.springframework.security.config.http.SessionCreationPolicy; 13 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 14 | import org.springframework.security.crypto.password.PasswordEncoder; 15 | 16 | @Configuration 17 | @EnableWebSecurity 18 | @EnableGlobalMethodSecurity(prePostEnabled = true) 19 | public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 20 | 21 | @Autowired 22 | CustomUserDetailsService customDetailsService; 23 | 24 | @Bean 25 | public PasswordEncoder encoder() { 26 | return new BCryptPasswordEncoder(); 27 | } 28 | 29 | @Override 30 | @Autowired 31 | protected void configure(AuthenticationManagerBuilder auth) throws Exception { 32 | auth.userDetailsService(customDetailsService).passwordEncoder(encoder()); 33 | } 34 | 35 | @Override 36 | protected void configure(HttpSecurity http) throws Exception { 37 | http.authorizeRequests().anyRequest().authenticated().and().sessionManagement() 38 | .sessionCreationPolicy(SessionCreationPolicy.NEVER); 39 | } 40 | 41 | @Override 42 | @Bean 43 | public AuthenticationManager authenticationManagerBean() throws Exception { 44 | return super.authenticationManagerBean(); 45 | } 46 | 47 | 48 | } 49 | -------------------------------------------------------------------------------- /two-factor-service/src/main/java/com/talk2amareswaran/projects/twofactorservice/TwoFactorServiceController.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.twofactorservice; 2 | 3 | import java.util.Random; 4 | 5 | import javax.mail.MessagingException; 6 | import javax.mail.internet.AddressException; 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.web.bind.annotation.PathVariable; 12 | import org.springframework.web.bind.annotation.RequestMapping; 13 | import org.springframework.web.bind.annotation.RequestMethod; 14 | import org.springframework.web.bind.annotation.RestController; 15 | 16 | @RestController 17 | public class TwoFactorServiceController { 18 | 19 | @Autowired 20 | EmailService emailService; 21 | @Autowired 22 | DAOService daoService; 23 | @Autowired 24 | SMSService smsService; 25 | 26 | @RequestMapping(value="/users/{userid}/emails/{emailid}/2fa", method=RequestMethod.PUT) 27 | public ResponseEntity send2faCodeinEmail(@PathVariable("userid") String id, @PathVariable("emailid") String emailid) throws AddressException, MessagingException { 28 | String twoFaCode = String.valueOf(new Random().nextInt(9999) + 1000); 29 | emailService.sendEmail(emailid, twoFaCode); 30 | daoService.update2FAProperties(id, twoFaCode); 31 | return new ResponseEntity<>(HttpStatus.OK); 32 | } 33 | 34 | @RequestMapping(value="/users/{userid}/mobilenumbers/{mobilenumber}/2fa", method=RequestMethod.PUT) 35 | public ResponseEntity send2faCodeinSMS(@PathVariable("userid") String id, @PathVariable("mobilenumber") String mobile) { 36 | String twoFaCode = String.valueOf(new Random().nextInt(9999) + 1000); 37 | smsService.send2FaCode(mobile, twoFaCode); 38 | daoService.update2FAProperties(id, twoFaCode); 39 | return new ResponseEntity<>(HttpStatus.OK); 40 | } 41 | 42 | @RequestMapping(value="/users/{userid}/codes/{2facode}", method=RequestMethod.PUT) 43 | public ResponseEntity verify(@PathVariable("userid") String id, @PathVariable("2facode") String code) { 44 | 45 | boolean isValid = daoService.checkCode(id, code); 46 | 47 | if(isValid) 48 | return new ResponseEntity<>(HttpStatus.OK); 49 | 50 | return new ResponseEntity<>(HttpStatus.FORBIDDEN); 51 | } 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | } 66 | -------------------------------------------------------------------------------- /authorization-server/src/main/java/com/talk2amareswaran/projects/authorizationserver/CustomUser.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.authorizationserver; 2 | 3 | import org.springframework.security.core.userdetails.User; 4 | 5 | public class CustomUser extends User { 6 | 7 | private static final long serialVersionUID = 1L; 8 | private String id; 9 | private String first_name; 10 | private String last_name; 11 | private String mobile; 12 | private String country; 13 | private String user_type; 14 | private String is_tfa_enabled; 15 | private String tfa_default_type; 16 | 17 | public CustomUser(UserEntity user) { 18 | super(user.getEmail_id(), user.getPasssword(), user.getGrantedAuthoritiesList()); 19 | this.id = user.getId(); 20 | this.first_name = user.getFirst_name(); 21 | this.last_name = user.getLast_name(); 22 | this.mobile = user.getMobile(); 23 | this.country = user.getCountry(); 24 | this.user_type = user.getUser_type(); 25 | this.tfa_default_type = user.getTfa_default_type(); 26 | this.is_tfa_enabled = user.getIs_tfa_enabled(); 27 | } 28 | 29 | public String getId() { 30 | return id; 31 | } 32 | 33 | public void setId(String id) { 34 | this.id = id; 35 | } 36 | 37 | public String getFirst_name() { 38 | return first_name; 39 | } 40 | 41 | public void setFirst_name(String first_name) { 42 | this.first_name = first_name; 43 | } 44 | 45 | public String getLast_name() { 46 | return last_name; 47 | } 48 | 49 | public void setLast_name(String last_name) { 50 | this.last_name = last_name; 51 | } 52 | 53 | public String getMobile() { 54 | return mobile; 55 | } 56 | 57 | public void setMobile(String mobile) { 58 | this.mobile = mobile; 59 | } 60 | 61 | public String getCountry() { 62 | return country; 63 | } 64 | 65 | public void setCountry(String country) { 66 | this.country = country; 67 | } 68 | 69 | public String getUser_type() { 70 | return user_type; 71 | } 72 | 73 | public void setUser_type(String user_type) { 74 | this.user_type = user_type; 75 | } 76 | 77 | public String getIs_tfa_enabled() { 78 | return is_tfa_enabled; 79 | } 80 | 81 | public void setIs_tfa_enabled(String is_tfa_enabled) { 82 | this.is_tfa_enabled = is_tfa_enabled; 83 | } 84 | 85 | public String getTfa_default_type() { 86 | return tfa_default_type; 87 | } 88 | 89 | public void setTfa_default_type(String tfa_default_type) { 90 | this.tfa_default_type = tfa_default_type; 91 | } 92 | 93 | 94 | 95 | 96 | } 97 | -------------------------------------------------------------------------------- /resource-server/src/main/java/com/talk2amareswaran/projects/resourceserver/UserResourceDAO.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.resourceserver; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collection; 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.jdbc.core.JdbcTemplate; 10 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 11 | import org.springframework.security.crypto.password.PasswordEncoder; 12 | import org.springframework.stereotype.Repository; 13 | 14 | @Repository 15 | public class UserResourceDAO { 16 | 17 | @Autowired 18 | JdbcTemplate jdbcTemplate; 19 | 20 | private PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); 21 | 22 | public List getListOfUsers() { 23 | 24 | Collection> rows3 = jdbcTemplate.queryForList("select * from users"); 25 | List usersList = new ArrayList<>(); 26 | rows3.stream().map((row) -> { 27 | UserModel user = new UserModel(); 28 | user.setCountry((String) row.get("country")); 29 | user.setEmail_id((String) row.get("email_id")); 30 | user.setFirst_name((String) row.get("first_name")); 31 | user.setId(String.valueOf(row.get("id"))); 32 | user.setLast_name((String) row.get("last_name")); 33 | user.setMobile((String) row.get("mobile")); 34 | user.setUser_type((String) row.get("user_type")); 35 | return user; 36 | }).forEach((ss3) -> { 37 | usersList.add(ss3); 38 | }); 39 | return usersList; 40 | } 41 | 42 | public void deleteUser(String user_id) { 43 | jdbcTemplate.update("delete from users where id=?", new Object[] { user_id }); 44 | } 45 | 46 | public void updateUser(String user_id, UserModel userModel) { 47 | jdbcTemplate.update("update users set country=?, first_name=?, last_name=?, mobile=? where id=?", 48 | new Object[] { userModel.getCountry(), userModel.getFirst_name(), userModel.getLast_name(), 49 | userModel.getMobile(), user_id }); 50 | } 51 | 52 | public void createUser(UserModel userModel) { 53 | jdbcTemplate.update( 54 | "insert into users (country, first_name, last_name, mobile, email_id, password, user_type) values " 55 | + "(?,?,?,?,?,?,?)", 56 | new Object[] { userModel.getCountry(), userModel.getFirst_name(), userModel.getLast_name(), 57 | userModel.getMobile(), userModel.getEmail_id(), passwordEncoder.encode(userModel.getPassword()), 58 | userModel.getUser_type() }); 59 | } 60 | 61 | 62 | public boolean isSuperAdmin(String id) { 63 | return jdbcTemplate.queryForObject("select count(id) from users where user_type=? and id=?", new Object[] {"super_admin",id} , Integer.class) >0; 64 | } 65 | 66 | } -------------------------------------------------------------------------------- /authorization-server/src/main/java/com/talk2amareswaran/projects/authorizationserver/UserEntity.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.authorizationserver; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collection; 5 | 6 | import org.springframework.security.core.GrantedAuthority; 7 | 8 | public class UserEntity { 9 | 10 | private String email_id; 11 | private String passsword; 12 | private Collection grantedAuthoritiesList = new ArrayList<>(); 13 | private String id; 14 | private String first_name; 15 | private String last_name; 16 | private String mobile; 17 | private String country; 18 | private String user_type; 19 | private String is_tfa_enabled; 20 | private String tfa_default_type; 21 | 22 | public String getEmail_id() { 23 | return email_id; 24 | } 25 | 26 | public void setEmail_id(String email_id) { 27 | this.email_id = email_id; 28 | } 29 | 30 | public String getPasssword() { 31 | return passsword; 32 | } 33 | 34 | public void setPasssword(String passsword) { 35 | this.passsword = passsword; 36 | } 37 | 38 | public Collection getGrantedAuthoritiesList() { 39 | return grantedAuthoritiesList; 40 | } 41 | 42 | public void setGrantedAuthoritiesList(Collection grantedAuthoritiesList) { 43 | this.grantedAuthoritiesList = grantedAuthoritiesList; 44 | } 45 | 46 | public String getId() { 47 | return id; 48 | } 49 | 50 | public void setId(String id) { 51 | this.id = id; 52 | } 53 | 54 | public String getFirst_name() { 55 | return first_name; 56 | } 57 | 58 | public void setFirst_name(String first_name) { 59 | this.first_name = first_name; 60 | } 61 | 62 | public String getLast_name() { 63 | return last_name; 64 | } 65 | 66 | public void setLast_name(String last_name) { 67 | this.last_name = last_name; 68 | } 69 | 70 | public String getMobile() { 71 | return mobile; 72 | } 73 | 74 | public void setMobile(String mobile) { 75 | this.mobile = mobile; 76 | } 77 | 78 | public String getCountry() { 79 | return country; 80 | } 81 | 82 | public void setCountry(String country) { 83 | this.country = country; 84 | } 85 | 86 | public String getUser_type() { 87 | return user_type; 88 | } 89 | 90 | public void setUser_type(String user_type) { 91 | this.user_type = user_type; 92 | } 93 | 94 | public String getIs_tfa_enabled() { 95 | return is_tfa_enabled; 96 | } 97 | 98 | public void setIs_tfa_enabled(String is_tfa_enabled) { 99 | this.is_tfa_enabled = is_tfa_enabled; 100 | } 101 | 102 | public String getTfa_default_type() { 103 | return tfa_default_type; 104 | } 105 | 106 | public void setTfa_default_type(String tfa_default_type) { 107 | this.tfa_default_type = tfa_default_type; 108 | } 109 | 110 | } 111 | -------------------------------------------------------------------------------- /authorization-server/src/main/java/com/talk2amareswaran/projects/authorizationserver/OAuth2Config.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.authorizationserver; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.beans.factory.annotation.Qualifier; 5 | import org.springframework.beans.factory.annotation.Value; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.security.authentication.AuthenticationManager; 9 | import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; 10 | import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; 11 | import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; 12 | import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; 13 | import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; 14 | import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; 15 | 16 | @Configuration 17 | public class OAuth2Config extends AuthorizationServerConfigurerAdapter { 18 | 19 | @Value("${config.oauth2.clientid}") 20 | private String clientid; 21 | 22 | @Value("${config.oauth2.clientSecret}") 23 | private String clientSecret; 24 | 25 | @Value("${config.oauth2.privateKey}") 26 | private String privateKey; 27 | 28 | @Value("${config.oauth2.publicKey}") 29 | private String publicKey; 30 | 31 | @Autowired 32 | @Qualifier("authenticationManagerBean") 33 | private AuthenticationManager authenticationManager; 34 | 35 | @Override 36 | public void configure(AuthorizationServerSecurityConfigurer security) throws Exception { 37 | security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()"); 38 | } 39 | 40 | @Override 41 | public void configure(ClientDetailsServiceConfigurer clients) throws Exception { 42 | clients.inMemory().withClient(clientid).secret(clientSecret).scopes("read", "write") 43 | .authorizedGrantTypes("password", "refresh_token").accessTokenValiditySeconds(3600) 44 | .refreshTokenValiditySeconds(18000); 45 | } 46 | 47 | 48 | @Override 49 | public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { 50 | endpoints.authenticationManager(authenticationManager).tokenStore(tokenStore()).accessTokenConverter(tokenEnhancer()); 51 | } 52 | 53 | @Bean 54 | public JwtTokenStore tokenStore() { 55 | return new JwtTokenStore(tokenEnhancer()); 56 | } 57 | 58 | @Bean 59 | public JwtAccessTokenConverter tokenEnhancer() { 60 | JwtAccessTokenConverter converter = new CustomTokenEnhancer(); 61 | converter.setSigningKey(privateKey); 62 | converter.setVerifierKey(publicKey); 63 | return converter; 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /authorization-server/src/main/java/com/talk2amareswaran/projects/authorizationserver/OAuthDAOService.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.authorizationserver; 2 | 3 | import java.sql.ResultSet; 4 | import java.util.ArrayList; 5 | import java.util.Collection; 6 | import java.util.List; 7 | 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.jdbc.core.JdbcTemplate; 10 | import org.springframework.security.core.GrantedAuthority; 11 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 12 | import org.springframework.stereotype.Repository; 13 | 14 | @Repository 15 | public class OAuthDAOService { 16 | 17 | @Autowired 18 | private JdbcTemplate jdbcTemplate; 19 | 20 | public UserEntity getUserDetails(String username) { 21 | Collection grantedAuthoritiesList = new ArrayList<>(); 22 | String userSQLQuery = "select * from users where email_id=?"; 23 | List list = jdbcTemplate.query(userSQLQuery, new String[] { username }, 24 | (ResultSet rs, int rowNum) -> { 25 | UserEntity user = new UserEntity(); 26 | user.setCountry(rs.getString("country")); 27 | user.setEmail_id(username); 28 | user.setFirst_name(rs.getString("first_name")); 29 | user.setId(rs.getString("id")); 30 | user.setLast_name(rs.getString("last_name")); 31 | user.setMobile(rs.getString("mobile")); 32 | user.setUser_type(rs.getString("user_type")); 33 | user.setPasssword(rs.getString("password")); 34 | user.setIs_tfa_enabled(rs.getString("is_2fa_enabled")); 35 | user.setTfa_default_type(rs.getString("2fa_default_type")); 36 | return user; 37 | }); 38 | 39 | if (!list.isEmpty()) { 40 | UserEntity userEntity = list.get(0); 41 | 42 | if (userEntity.getUser_type() != null) { 43 | if (!userEntity.getUser_type().trim().equalsIgnoreCase("super_admin")) { 44 | String permissionQuery = "select distinct p.permission_name from users u inner join role_users r_u on u.id=r_u.user_id " 45 | + "inner join role r on r_u.role_id=r.id " 46 | + "inner join role_permission r_p on r_p.role_id=r.id " 47 | + "inner join permission p on p.id=r_p.permission_id where u.email_id=?"; 48 | List permissionList = jdbcTemplate.query(permissionQuery.toString(), 49 | new String[] { username }, (ResultSet rs, int rowNum) -> { 50 | return "ROLE_" + rs.getString("permission_name"); 51 | }); 52 | if (permissionList != null && !permissionList.isEmpty()) { 53 | for (String permission : permissionList) { 54 | GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission); 55 | grantedAuthoritiesList.add(grantedAuthority); 56 | } 57 | list.get(0).setGrantedAuthoritiesList(grantedAuthoritiesList); 58 | } 59 | return list.get(0); 60 | } else { 61 | GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_SUPERADMIN"); 62 | grantedAuthoritiesList.add(grantedAuthority); 63 | list.get(0).setGrantedAuthoritiesList(grantedAuthoritiesList); 64 | return list.get(0); 65 | } 66 | } else { 67 | return null; 68 | } 69 | } 70 | return null; 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /resource-server/src/main/java/com/talk2amareswaran/projects/resourceserver/UserResource.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.resourceserver; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.http.HttpStatus; 5 | import org.springframework.http.ResponseEntity; 6 | import org.springframework.security.access.prepost.PreAuthorize; 7 | import org.springframework.security.core.context.SecurityContextHolder; 8 | import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails; 9 | import org.springframework.web.bind.annotation.PathVariable; 10 | import org.springframework.web.bind.annotation.RequestBody; 11 | import org.springframework.web.bind.annotation.RequestMapping; 12 | import org.springframework.web.bind.annotation.RequestMethod; 13 | import org.springframework.web.bind.annotation.RestController; 14 | 15 | @RestController 16 | public class UserResource { 17 | 18 | @Autowired 19 | UserResourceDAO userResourceDAO; 20 | 21 | @PreAuthorize("hasAnyRole('view_users', 'SUPERADMIN')") 22 | @RequestMapping(value = "/users", method = RequestMethod.GET) 23 | public ResponseEntity getListOfUsers() { 24 | return new ResponseEntity<>(userResourceDAO.getListOfUsers(), HttpStatus.OK); 25 | } 26 | 27 | @PreAuthorize("hasAnyRole('delete_users', 'SUPERADMIN')") 28 | @RequestMapping(value = "/users/{id}", method = RequestMethod.DELETE) 29 | public ResponseEntity deleteUser(@PathVariable("id") String user_id) { 30 | 31 | 32 | AccessTokenMapper accessTokenMapper = (AccessTokenMapper) 33 | ((OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails()).getDecodedDetails(); 34 | 35 | 36 | if(accessTokenMapper.getUser_type().equalsIgnoreCase("admin") && userResourceDAO.isSuperAdmin(user_id)) { 37 | return new ResponseEntity<>(HttpStatus.FORBIDDEN); 38 | } 39 | 40 | userResourceDAO.deleteUser(user_id); 41 | return new ResponseEntity<>("User deleted successfully", HttpStatus.OK); 42 | } 43 | 44 | @PreAuthorize("hasAnyRole('edit_users', 'SUPERADMIN')") 45 | @RequestMapping(value = "/users/{id}", method = RequestMethod.PUT) 46 | public ResponseEntity updateUser(@PathVariable("id") String user_id, @RequestBody UserModel userModel) { 47 | AccessTokenMapper accessTokenMapper = (AccessTokenMapper) 48 | ((OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails()).getDecodedDetails(); 49 | 50 | 51 | if(accessTokenMapper.getUser_type().equalsIgnoreCase("admin") && userResourceDAO.isSuperAdmin(user_id)) { 52 | return new ResponseEntity<>(HttpStatus.FORBIDDEN); 53 | } 54 | userResourceDAO.updateUser(user_id, userModel); 55 | return new ResponseEntity<>("User updated successfully", HttpStatus.OK); 56 | } 57 | 58 | @PreAuthorize("hasAnyRole('create_users', 'SUPERADMIN')") 59 | @RequestMapping(value = "/users", method = RequestMethod.POST) 60 | public ResponseEntity createUser(@RequestBody UserModel userModel) { 61 | AccessTokenMapper accessTokenMapper = (AccessTokenMapper) 62 | ((OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails()).getDecodedDetails(); 63 | 64 | 65 | if(accessTokenMapper.getUser_type().equalsIgnoreCase("admin") && userModel.getUser_type().equalsIgnoreCase("super_admin")) { 66 | return new ResponseEntity<>(HttpStatus.FORBIDDEN); 67 | } 68 | userResourceDAO.createUser(userModel); 69 | return new ResponseEntity<>("User created successfully", HttpStatus.OK); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /webapp-application/src/main/resources/static/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Administrator Login 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | Incorrect email address or password 23 | 24 | Administrator Login 25 | 26 | 27 | 28 | Email Address 29 | 30 | 31 | 32 | Password 33 | 34 | 35 | 36 | Login 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | Two Factor Authentication 52 | × 53 | 54 | 55 | 56 | 57 | 58 | 59 | Your code will be expire in 2 minutes. 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | Please enter your code 71 | 72 | 73 | 74 | Resend code (Email) | 75 | Resend code (SMS) 76 | 77 | 78 | 79 | 80 | 81 | 82 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | -------------------------------------------------------------------------------- /webapp-application/src/main/resources/static/permissions.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Administrator Login 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | Administrator 20 | 21 | 22 | 23 | 24 | 48 | 49 | Permissions 50 | 51 | You don't have the permission to see this page 52 | 53 | 54 | 55 | 56 | S.No 57 | Permission name 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | -------------------------------------------------------------------------------- /webapp-application/src/main/resources/static/index.js: -------------------------------------------------------------------------------- 1 | $(document).ready(function(){ 2 | $('#emailAddressTxt').keyup(function(){ 3 | checkAllowLogin(); 4 | }); 5 | 6 | $('#pwd').keyup(function(){ 7 | checkAllowLogin(); 8 | }); 9 | 10 | $("#submitBtn").click(function() { 11 | getToken($('#emailAddressTxt').val().trim(),$('#pwd').val()); 12 | }); 13 | 14 | $("#sendEmailLink").click(function() { 15 | 16 | send2facode(sessionStorage.getItem("email_two_fa_url"), function() { 17 | $("#2fa_error").hide(); 18 | $(".alert-success").show(); 19 | $(".alert-success").html("Your code has been sent your email id"); 20 | }); 21 | }); 22 | 23 | $("#sendSMSLink").click(function() { 24 | send2facode(sessionStorage.getItem("mobile_two_fa_url"), function() { 25 | $(".alert-success").show(); 26 | $("#2fa_error").hide(); 27 | $(".alert-success").html("Your code has been sent your mobile"); 28 | }); 29 | }); 30 | 31 | $("#verifyBtn").click(function() { 32 | verify2faCode(); 33 | }); 34 | 35 | }); 36 | 37 | function allowLogin() { 38 | if(localStorage.getItem("access_token")!=null) { 39 | window.location.href="permissions.html"; 40 | } 41 | } 42 | 43 | function checkAllowLogin() { 44 | if($("#emailAddressTxt").val()!=null && $("#pwd").val()!=null 45 | && $("#emailAddressTxt").val().length>0 && $("#pwd").val().length>0 && validateEmail($("#emailAddressTxt").val())) { 46 | $("#submitBtn").removeAttr("disabled"); 47 | } else if(!$("#submitBtn").attr("disabled")) { 48 | $("#submitBtn").attr("disabled","disabled"); 49 | } 50 | } 51 | 52 | 53 | function validateEmail(sEmail) { 54 | var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/; 55 | return filter.test(sEmail); 56 | } 57 | 58 | function getToken(username, password) { 59 | $.ajax({ 60 | type: "POST", 61 | url: "http://localhost:8080/oauth/token", 62 | data: "username="+username+"&password="+password+"&grant_type=password", 63 | beforeSend: function(request) { 64 | request.setRequestHeader("Authorization", "Basic "+btoa("talk2amareswaran:talk@amareswaran")); 65 | request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 66 | }, 67 | success: function(msg){ 68 | if(JSON.parse(JSON.stringify(msg)).is_2fa_enabled=="Y") { 69 | 70 | var email_two_fa_url = "http://localhost:8087/users/"+JSON.parse(JSON.stringify(msg)).id 71 | +"/emails/"+JSON.parse(JSON.stringify(msg)).email_id+"/2fa"; 72 | 73 | var mobile_two_fa_url = "http://localhost:8087/users/"+JSON.parse(JSON.stringify(msg)).id 74 | +"/mobilenumbers/"+JSON.parse(JSON.stringify(msg)).mobile+"/2fa"; 75 | 76 | var verify_2fa_url = "http://localhost:8087/users/"+JSON.parse(JSON.stringify(msg)).id 77 | +"/codes/"; 78 | 79 | sessionStorage.setItem("email_two_fa_url",email_two_fa_url); 80 | sessionStorage.setItem("mobile_two_fa_url",mobile_two_fa_url); 81 | sessionStorage.setItem("verify_2fa_url",verify_2fa_url); 82 | 83 | sessionStorage.setItem("access_token", JSON.parse(JSON.stringify(msg)).access_token); 84 | sessionStorage.setItem("refresh_token", JSON.parse(JSON.stringify(msg)).refresh_token); 85 | 86 | if(JSON.parse(JSON.stringify(msg)).tfa_default_type=="sms") { 87 | two_fa_url = mobile_two_fa_url; 88 | } else { 89 | two_fa_url = email_two_fa_url; 90 | } 91 | 92 | send2facode(two_fa_url, function() { 93 | $("#myModal").modal('show'); 94 | }); 95 | } 96 | }, 97 | error: function(XMLHttpRequest, textStatus, errorThrown) { 98 | $(".alert-danger").show(); 99 | } 100 | }); 101 | } 102 | 103 | function send2facode(two_fa_code_url, callbackmethod) { 104 | $.ajax({ 105 | type: "PUT", 106 | url: two_fa_code_url, 107 | success: function(msg){ 108 | callbackmethod(); 109 | }, 110 | error: function(XMLHttpRequest, textStatus, errorThrown) { 111 | $(".alert-danger").show(); 112 | $(".alert-danger").html("Unable to send 2FA code. Please try again."); 113 | } 114 | }); 115 | } 116 | 117 | function verify2faCode() { 118 | 119 | $.ajax({ 120 | type: "PUT", 121 | url: sessionStorage.getItem("verify_2fa_url")+$("#tfa_code").val(), 122 | success: function(msg){ 123 | localStorage.setItem("access_token", sessionStorage.getItem("access_token")); 124 | localStorage.setItem("refresh_token", sessionStorage.getItem("refresh_token")); 125 | window.location.reload("permissions.html"); 126 | }, 127 | error: function(XMLHttpRequest, textStatus, errorThrown) { 128 | $("#2fa_error").show(); 129 | $(".alert-success").hide(); 130 | $("#2fa_error").html("Invalid code. Please try again."); 131 | } 132 | }); 133 | } -------------------------------------------------------------------------------- /webapp-application/src/main/resources/static/settings.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Administrator Login 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | Administrator 21 | 22 | 23 | 24 | 25 | 49 | 50 | Settings 51 | 52 | 53 | You don't have the permission to see this page 54 | 55 | 56 | 57 | Permissions are assigned to the role successfully 58 | 59 | 60 | 61 | 62 | View Permissions by Role 63 | 64 | 65 | View Users by Role 66 | 67 | 68 | Assign Permissions by Role 69 | 70 | 71 | Assign Users by Role 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | S.No 89 | Permission name 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | S.No 109 | Email Address 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | Assign 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | Assign 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | -------------------------------------------------------------------------------- /webapp-application/src/main/resources/static/roles.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Administrator Login 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | Administrator 21 | 22 | 23 | 24 | 25 | 49 | 50 | Roles 51 | 52 | You don't have the permission to see this page 53 | 54 | 55 | Role updated successfully 56 | 57 | Add New 58 | 59 | 60 | 61 | 62 | S.No 63 | Role name 64 | Action 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | Add Role 82 | × 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | Role Name 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | Edit Role 116 | × 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | Role Name 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | Delete Role 150 | × 151 | 152 | 153 | 154 | 155 | 156 | 157 | Are you sure you want to delete the role? 158 | 159 | 160 | 161 | 162 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | -------------------------------------------------------------------------------- /webapp-application/src/main/resources/static/roles.js: -------------------------------------------------------------------------------- 1 | $(document).ready(function(){ 2 | getRolesList(); 3 | 4 | $("#updateOperation").click(function() { 5 | doUpdate(); 6 | }); 7 | 8 | 9 | $("#deleteOperation").click(function() { 10 | doDelete(); 11 | }); 12 | 13 | 14 | $("#addOperation").click(function() { 15 | doAdd(); 16 | }); 17 | 18 | 19 | 20 | }); 21 | 22 | function getRolesList() { 23 | $.ajax({ 24 | type: "GET", 25 | url: "http://localhost:8000/roles", 26 | beforeSend: function(request) { 27 | request.setRequestHeader("Authorization", "Bearer "+localStorage.getItem("access_token")); 28 | }, 29 | success: function(msg){ 30 | 31 | if(msg.length>0) { 32 | $("tbody").empty(); 33 | $.each(msg, function (index, value) { 34 | 35 | $("tbody").append(" "+(index+1)+""+value.role_name+"" + 36 | " " + 37 | ""); 38 | }); 39 | 40 | } else { 41 | $("tbody").append(" No records to display"); 42 | } 43 | }, 44 | error: function(XMLHttpRequest, textStatus, errorThrown) { 45 | if(XMLHttpRequest.responseText.indexOf("Access token expired:")!=-1) { 46 | getNewToken("roles.html"); 47 | } else if(XMLHttpRequest.status==403) { 48 | $("table").remove(); 49 | $(".alert-danger").show(); 50 | $(".alert-success").hide(); 51 | $("#addNewBtn").hide(); 52 | } else { 53 | localStorage.clear(); 54 | window.location.href="index.html"; 55 | } 56 | } 57 | }); 58 | } 59 | 60 | function editOperationModel(id, role_name) { 61 | $("#edit_role_name").val(role_name); 62 | $("#edit_id").val(id); 63 | $("#editModal").modal('show'); 64 | } 65 | 66 | function doAdd() { 67 | 68 | $.ajax({ 69 | type: "POST", 70 | url: "http://localhost:8000/roles", 71 | beforeSend: function(request) { 72 | request.setRequestHeader("Authorization", "Bearer "+localStorage.getItem("access_token")); 73 | request.setRequestHeader("Content-Type", "application/json"); 74 | }, 75 | data: JSON.stringify({ "role_name": $("#new_role_name").val().trim() }), 76 | success: function(msg){ 77 | $("#myModal").modal('hide'); 78 | $(".alert-success").show(); 79 | $(".alert-danger").hide(); 80 | $(".alert-success").html('Role added successfully'); 81 | getRolesList(); 82 | $("#new_role_name").val(''); 83 | 84 | }, 85 | error: function(XMLHttpRequest, textStatus, errorThrown) { 86 | if(XMLHttpRequest.responseText.indexOf("Access token expired:")!=-1) { 87 | getNewTokenOnOperation(function() { 88 | doAdd(); 89 | }); 90 | } else if(XMLHttpRequest.status==403) { 91 | $("#myModal").modal('hide'); 92 | $(".alert-danger").html('You don\'t have the permission to do add a new role'); 93 | $(".alert-danger").show(); 94 | $(".alert-success").hide(); 95 | } else { 96 | localStorage.clear(); 97 | window.location.href="index.html"; 98 | } 99 | } 100 | }); 101 | } 102 | 103 | function doDelete() { 104 | 105 | $.ajax({ 106 | type: "DELETE", 107 | url: "http://localhost:8000/roles/"+$("#delete_id").val(), 108 | beforeSend: function(request) { 109 | request.setRequestHeader("Authorization", "Bearer "+localStorage.getItem("access_token")); 110 | }, 111 | success: function(msg){ 112 | $(".alert-success").show(); 113 | $(".alert-danger").hide(); 114 | $(".alert-success").html('Role deleted successfully'); 115 | $("#deleteModel").modal('hide'); 116 | getRolesList(); 117 | 118 | }, 119 | error: function(XMLHttpRequest, textStatus, errorThrown) { 120 | if(XMLHttpRequest.responseText.indexOf("Access token expired:")!=-1) { 121 | getNewTokenOnOperation(function() { 122 | doDelete(); 123 | }); 124 | } else if(XMLHttpRequest.status==403) { 125 | $("#deleteModel").modal('hide'); 126 | $(".alert-danger").html('You don\'t have the permission to do delete operation'); 127 | $(".alert-danger").show(); 128 | $(".alert-success").hide(); 129 | } 130 | else if(XMLHttpRequest.status==500) { 131 | $(".alert-danger").html('Users are assigned to this role. You can\'t delete.'); 132 | $(".alert-danger").show(); 133 | $(".alert-success").hide(); 134 | $("#deleteModel").modal('hide'); 135 | } else { 136 | localStorage.clear(); 137 | window.location.href="index.html"; 138 | } 139 | } 140 | }); 141 | } 142 | 143 | function doUpdate() { 144 | $.ajax({ 145 | type: "PUT", 146 | url: "http://localhost:8000/roles/"+$("#edit_id").val(), 147 | beforeSend: function(request) { 148 | request.setRequestHeader("Authorization", "Bearer "+localStorage.getItem("access_token")); 149 | request.setRequestHeader("Content-Type", "application/json"); 150 | }, 151 | data: JSON.stringify({ "role_name": $("#edit_role_name").val().trim() }), 152 | success: function(msg){ 153 | $("#editModal").modal('hide'); 154 | $(".alert-success").show(); 155 | $(".alert-danger").hide(); 156 | $(".alert-success").html('Role updated successfully'); 157 | getRolesList(); 158 | 159 | }, 160 | error: function(XMLHttpRequest, textStatus, errorThrown) { 161 | if(XMLHttpRequest.responseText.indexOf("Access token expired:")!=-1) { 162 | getNewTokenOnOperation(function() { 163 | doUpdate(); 164 | }); 165 | } else if(XMLHttpRequest.status==403) { 166 | $("#editModal").modal('hide'); 167 | $(".alert-danger").html('You don\'t have the permission to do edit/update operation'); 168 | $(".alert-danger").show(); 169 | $(".alert-success").hide(); 170 | } else { 171 | localStorage.clear(); 172 | window.location.href="index.html"; 173 | } 174 | } 175 | }); 176 | 177 | } 178 | 179 | 180 | function deleteOperationModel(id) { 181 | $("#delete_id").val(id); 182 | $("#deleteModel").modal('show'); 183 | } 184 | 185 | function getNewTokenOnOperation(callbackMethod) { 186 | $.ajax({ 187 | type: "POST", 188 | url: "http://localhost:8080/oauth/token", 189 | data: "refresh_token="+localStorage.getItem("refresh_token")+"&grant_type=refresh_token", 190 | beforeSend: function(request) { 191 | request.setRequestHeader("Authorization", "Basic "+btoa("talk2amareswaran:talk@amareswaran")); 192 | request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 193 | }, 194 | success: function(msg){ 195 | localStorage.setItem("access_token", JSON.parse(JSON.stringify(msg)).access_token); 196 | localStorage.setItem("refresh_token", JSON.parse(JSON.stringify(msg)).refresh_token); 197 | callbackMethod(); 198 | }, 199 | error: function(XMLHttpRequest, textStatus, errorThrown) { 200 | localStorage.clear(); 201 | window.location.href="index.html"; 202 | } 203 | }); 204 | } 205 | 206 | function getNewToken(pageName) { 207 | $.ajax({ 208 | type: "POST", 209 | url: "http://localhost:8080/oauth/token", 210 | data: "refresh_token="+localStorage.getItem("refresh_token")+"&grant_type=refresh_token", 211 | beforeSend: function(request) { 212 | request.setRequestHeader("Authorization", "Basic "+btoa("talk2amareswaran:talk@amareswaran")); 213 | request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 214 | }, 215 | success: function(msg){ 216 | localStorage.setItem("access_token", JSON.parse(JSON.stringify(msg)).access_token); 217 | localStorage.setItem("refresh_token", JSON.parse(JSON.stringify(msg)).refresh_token); 218 | window.location.reload(pageName); 219 | }, 220 | error: function(XMLHttpRequest, textStatus, errorThrown) { 221 | localStorage.clear(); 222 | window.location.href="index.html"; 223 | } 224 | }); 225 | } -------------------------------------------------------------------------------- /webapp-application/src/main/resources/static/users.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Administrator Login 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | Administrator 21 | 22 | 23 | 24 | 25 | 49 | 50 | Users 51 | 52 | 53 | You don't have the permission to see this page 54 | 55 | 56 | Role updated successfully 57 | 58 | 59 | Add New 60 | 61 | 62 | 63 | 64 | First Name 65 | Last Name 66 | Email Address 67 | Mobile 68 | Country 69 | User Type 70 | Action 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | Add User 87 | × 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | First Name 97 | 98 | 99 | 100 | Last Name 101 | 102 | 103 | 104 | Email address 105 | 106 | 107 | 108 | Password 109 | 110 | 111 | 112 | Mobile 113 | 114 | 115 | 116 | Country 117 | 118 | 119 | 120 | 121 | Super Admin 122 | 123 | 124 | 125 | 126 | 127 | 128 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | Delete User 144 | × 145 | 146 | 147 | 148 | 149 | 150 | Are you sure you want to delete the user? 151 | 152 | 153 | 154 | 155 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | Edit User 171 | × 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | First Name 181 | 182 | 183 | 184 | Last Name 185 | 186 | 187 | 188 | 189 | Mobile 190 | 191 | 192 | 193 | Country 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | -------------------------------------------------------------------------------- /webapp-application/src/main/resources/static/users.js: -------------------------------------------------------------------------------- 1 | $(document).ready(function(){ 2 | getUsersList(); 3 | 4 | $("#updateOperation").click(function() { 5 | doUpdate(); 6 | }); 7 | 8 | 9 | $("#deleteOperation").click(function() { 10 | doDelete(); 11 | }); 12 | 13 | 14 | $("#addOperation").click(function() { 15 | doAdd(); 16 | }); 17 | 18 | 19 | 20 | }); 21 | 22 | function getUsersList() { 23 | $.ajax({ 24 | type: "GET", 25 | url: "http://localhost:8000/users", 26 | beforeSend: function(request) { 27 | request.setRequestHeader("Authorization", "Bearer "+localStorage.getItem("access_token")); 28 | }, 29 | success: function(msg){ 30 | 31 | if(msg.length>0) { 32 | $("tbody").empty(); 33 | $.each(msg, function (index, value) { 34 | 35 | value.first_name = (value.first_name==undefined ? " " : value.first_name); 36 | value.last_name = (value.last_name==undefined ? " " : value.last_name); 37 | value.email_id = (value.email_id==undefined ? " " : value.email_id); 38 | value.mobile = (value.mobile==undefined ? " " : value.mobile); 39 | value.country = (value.country==undefined ? " " : value.country); 40 | value.user_type = (value.user_type==undefined ? " " : value.user_type); 41 | 42 | $("tbody").append(" "+value.first_name+""+value.last_name+""+value.email_id+""+value.mobile+""+value.country+""+value.user_type+"" + 43 | " " + 51 | ""); 52 | }); 53 | 54 | } else { 55 | $("tbody").append(" No records to display"); 56 | } 57 | }, 58 | error: function(XMLHttpRequest, textStatus, errorThrown) { 59 | if(XMLHttpRequest.responseText.indexOf("Access token expired:")!=-1) { 60 | getNewToken("users.html"); 61 | } else if(XMLHttpRequest.status==403) { 62 | $("table").remove(); 63 | $(".alert-danger").show(); 64 | $(".alert-success").hide(); 65 | $("#addNewBtn").hide(); 66 | } else { 67 | localStorage.clear(); 68 | window.location.href="index.html"; 69 | } 70 | } 71 | }); 72 | } 73 | 74 | function editOperationModel(idName) { 75 | $("#editModal").modal('show'); 76 | $("#edit_first_name").val($("#"+idName).attr("data-first_name")); 77 | $("#edit_last_name").val($("#"+idName).attr("data-last_name")); 78 | $("#edit_mobile").val($("#"+idName).attr("data-mobile")); 79 | $("#edit_country").val($("#"+idName).attr("data-country")); 80 | $("#edit_id").val($("#"+idName).attr("data-id")); 81 | 82 | 83 | } 84 | 85 | function doAdd() { 86 | 87 | var user_type = "admin"; 88 | if($("#customCheck").prop("checked")) 89 | user_type = "super_admin"; 90 | 91 | $.ajax({ 92 | type: "POST", 93 | url: "http://localhost:8000/users", 94 | beforeSend: function(request) { 95 | request.setRequestHeader("Authorization", "Bearer "+localStorage.getItem("access_token")); 96 | request.setRequestHeader("Content-Type", "application/json"); 97 | }, 98 | data: JSON.stringify({ 99 | "first_name": $("#first_name").val(), 100 | "last_name":$("#last_name").val(), 101 | "mobile": $("#mobile").val(), 102 | "country": $("#country").val(), 103 | "email_id": $("#email_address").val(), 104 | "password": $("#pwd").val(), 105 | "user_type": user_type 106 | }), 107 | success: function(msg){ 108 | $("#myModal").modal('hide'); 109 | $(".alert-success").show(); 110 | $(".alert-danger").hide(); 111 | $(".alert-success").html('User added successfully'); 112 | getUsersList(); 113 | 114 | 115 | }, 116 | error: function(XMLHttpRequest, textStatus, errorThrown) { 117 | if(XMLHttpRequest.responseText.indexOf("Access token expired:")!=-1) { 118 | getNewTokenOnOperation(function() { 119 | doAdd(); 120 | }); 121 | } else if(XMLHttpRequest.status==403) { 122 | $("#myModal").modal('hide'); 123 | $(".alert-danger").html('You don\'t have the permission to do add a new user'); 124 | $(".alert-danger").show(); 125 | $(".alert-success").hide(); 126 | } else { 127 | localStorage.clear(); 128 | window.location.href="index.html"; 129 | } 130 | } 131 | }); 132 | } 133 | 134 | function doDelete() { 135 | 136 | $.ajax({ 137 | type: "DELETE", 138 | url: "http://localhost:8000/users/"+$("#delete_id").val(), 139 | beforeSend: function(request) { 140 | request.setRequestHeader("Authorization", "Bearer "+localStorage.getItem("access_token")); 141 | }, 142 | success: function(msg){ 143 | $(".alert-success").show(); 144 | $(".alert-danger").hide(); 145 | $(".alert-success").html('User deleted successfully'); 146 | $("#deleteModel").modal('hide'); 147 | getUsersList(); 148 | 149 | }, 150 | error: function(XMLHttpRequest, textStatus, errorThrown) { 151 | if(XMLHttpRequest.responseText.indexOf("Access token expired:")!=-1) { 152 | getNewTokenOnOperation(function() { 153 | doDelete(); 154 | }); 155 | } else if(XMLHttpRequest.status==403) { 156 | $("#deleteModel").modal('hide'); 157 | $(".alert-danger").html('You don\'t have the permission to do delete operation'); 158 | $(".alert-danger").show(); 159 | $(".alert-success").hide(); 160 | } 161 | else if(XMLHttpRequest.status==500) { 162 | $(".alert-danger").html('Users are assigned to the role. You can\'t delete.'); 163 | $(".alert-danger").show(); 164 | $(".alert-success").hide(); 165 | $("#deleteModel").modal('hide'); 166 | } else { 167 | localStorage.clear(); 168 | window.location.href="index.html"; 169 | } 170 | } 171 | }); 172 | } 173 | 174 | function doUpdate() { 175 | $.ajax({ 176 | type: "PUT", 177 | url: "http://localhost:8000/users/"+$("#edit_id").val(), 178 | beforeSend: function(request) { 179 | request.setRequestHeader("Authorization", "Bearer "+localStorage.getItem("access_token")); 180 | request.setRequestHeader("Content-Type", "application/json"); 181 | }, 182 | data: JSON.stringify({ 183 | "first_name": $("#edit_first_name").val(), 184 | "last_name":$("#edit_last_name").val(), 185 | "mobile": $("#edit_mobile").val(), 186 | "country": $("#edit_country").val() 187 | }), 188 | success: function(msg){ 189 | $("#editModal").modal('hide'); 190 | $(".alert-success").show(); 191 | $(".alert-danger").hide(); 192 | $(".alert-success").html('User updated successfully'); 193 | getUsersList(); 194 | 195 | }, 196 | error: function(XMLHttpRequest, textStatus, errorThrown) { 197 | if(XMLHttpRequest.responseText.indexOf("Access token expired:")!=-1) { 198 | getNewTokenOnOperation(function() { 199 | doUpdate(); 200 | }); 201 | } else if(XMLHttpRequest.status==403) { 202 | $("#editModal").modal('hide'); 203 | $(".alert-danger").html('You don\'t have the permission to do edit/update operation'); 204 | $(".alert-danger").show(); 205 | $(".alert-success").hide(); 206 | } else { 207 | localStorage.clear(); 208 | window.location.href="index.html"; 209 | } 210 | } 211 | }); 212 | 213 | } 214 | 215 | 216 | function deleteOperationModel(id) { 217 | $("#delete_id").val(id); 218 | $("#deleteModel").modal('show'); 219 | } 220 | 221 | function getNewTokenOnOperation(callbackMethod) { 222 | $.ajax({ 223 | type: "POST", 224 | url: "http://localhost:8080/oauth/token", 225 | data: "refresh_token="+localStorage.getItem("refresh_token")+"&grant_type=refresh_token", 226 | beforeSend: function(request) { 227 | request.setRequestHeader("Authorization", "Basic "+btoa("talk2amareswaran:talk@amareswaran")); 228 | request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 229 | }, 230 | success: function(msg){ 231 | localStorage.setItem("access_token", JSON.parse(JSON.stringify(msg)).access_token); 232 | localStorage.setItem("refresh_token", JSON.parse(JSON.stringify(msg)).refresh_token); 233 | callbackMethod(); 234 | }, 235 | error: function(XMLHttpRequest, textStatus, errorThrown) { 236 | localStorage.clear(); 237 | window.location.href="index.html"; 238 | } 239 | }); 240 | } 241 | 242 | function getNewToken(pageName) { 243 | $.ajax({ 244 | type: "POST", 245 | url: "http://localhost:8080/oauth/token", 246 | data: "refresh_token="+localStorage.getItem("refresh_token")+"&grant_type=refresh_token", 247 | beforeSend: function(request) { 248 | request.setRequestHeader("Authorization", "Basic "+btoa("talk2amareswaran:talk@amareswaran")); 249 | request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 250 | }, 251 | success: function(msg){ 252 | localStorage.setItem("access_token", JSON.parse(JSON.stringify(msg)).access_token); 253 | localStorage.setItem("refresh_token", JSON.parse(JSON.stringify(msg)).refresh_token); 254 | window.location.reload(pageName); 255 | }, 256 | error: function(XMLHttpRequest, textStatus, errorThrown) { 257 | localStorage.clear(); 258 | window.location.href="index.html"; 259 | } 260 | }); 261 | } -------------------------------------------------------------------------------- /webapp-application/src/main/resources/static/settings.js: -------------------------------------------------------------------------------- 1 | $(document).ready(function(){ 2 | getRolesList(); 3 | 4 | $(".nav-link").click(function() { 5 | $(".alert-danger").hide(); 6 | $(".alert-success").hide(); 7 | getRolesList(); 8 | $("#assign_users_role_select").hide(); 9 | $("#assign_permissions_role_select").hide(); 10 | $("#assign_permissions_btn").hide(); 11 | $("#assign_users_btn").hide(); 12 | $("#view_users_role_table").hide(); 13 | $("#view_permissions_role_table").hide(); 14 | 15 | }); 16 | 17 | $("#view_permissions_role").change(function() { 18 | showPermissionsTable($("#view_permissions_role option:selected").val()); 19 | }); 20 | 21 | 22 | $("#view_users_role").change(function() { 23 | showUsersTable($("#view_users_role option:selected").val()); 24 | }); 25 | 26 | $("#assign_permissions_role").change(function() { 27 | showPermissionsSelect($("#assign_permissions_role option:selected").val()); 28 | }); 29 | 30 | $("#assign_permissions_btn").click(function() { 31 | assignPermissions($("#assign_permissions_role option:selected").val()); 32 | }); 33 | 34 | $("#assign_users_role").click(function() { 35 | showUsersSelect($("#assign_users_role option:selected").val()); 36 | }); 37 | 38 | $("#assign_users_btn").click(function() { 39 | assignUsers($("#assign_users_role option:selected").val()); 40 | }); 41 | 42 | 43 | }); 44 | 45 | function assignUsers(val) { 46 | 47 | var selectedList = []; 48 | $.each($("#assign_users_role_select option:selected"), function(){ 49 | selectedList.push($(this).val()); 50 | }); 51 | 52 | 53 | $.ajax({ 54 | type: "PUT", 55 | url: "http://localhost:8000/roles/"+val+"/users", 56 | beforeSend: function(request) { 57 | request.setRequestHeader("Authorization", "Bearer "+localStorage.getItem("access_token")); 58 | request.setRequestHeader("Content-Type", "application/json"); 59 | }, 60 | data: JSON.stringify(selectedList), 61 | success: function(msg){ 62 | $(".alert-success").show(); 63 | $(".alert-success").html("Users are assigned to the role successfully. It will be effective from the users next login"); 64 | $(".alert-danger").hide(); 65 | }, 66 | error: function(XMLHttpRequest, textStatus, errorThrown) { 67 | if(XMLHttpRequest.responseText.indexOf("Access token expired:")!=-1) { 68 | getNewTokenOnOperation(function() { 69 | assignUsers(val); 70 | }); 71 | } else if(XMLHttpRequest.status==403) { 72 | $(".alert-danger").html('You don\'t have the permission to assign the users to this role'); 73 | $(".alert-danger").show(); 74 | $(".alert-success").hide(); 75 | } else { 76 | localStorage.clear(); 77 | window.location.href="index.html"; 78 | } 79 | } 80 | }); 81 | 82 | } 83 | 84 | function assignPermissions(val) { 85 | var selectedList = []; 86 | $.each($("#assign_permissions_role_select option:selected"), function(){ 87 | selectedList.push($(this).val()); 88 | }); 89 | 90 | 91 | $.ajax({ 92 | type: "PUT", 93 | url: "http://localhost:8000/roles/"+val+"/permissions", 94 | beforeSend: function(request) { 95 | request.setRequestHeader("Authorization", "Bearer "+localStorage.getItem("access_token")); 96 | request.setRequestHeader("Content-Type", "application/json"); 97 | }, 98 | data: JSON.stringify(selectedList), 99 | success: function(msg){ 100 | $(".alert-success").show(); 101 | $(".alert-success").html("Permissions are assigned to the role successfully. It will be effective from the users next login"); 102 | $(".alert-danger").hide(); 103 | }, 104 | error: function(XMLHttpRequest, textStatus, errorThrown) { 105 | if(XMLHttpRequest.responseText.indexOf("Access token expired:")!=-1) { 106 | getNewTokenOnOperation(function() { 107 | assignPermissions(val); 108 | }); 109 | } else if(XMLHttpRequest.status==403) { 110 | $(".alert-danger").html('You don\'t have the permission to assign the list of permissions to this role'); 111 | $(".alert-danger").show(); 112 | $(".alert-success").hide(); 113 | } else { 114 | localStorage.clear(); 115 | window.location.href="index.html"; 116 | } 117 | } 118 | }); 119 | 120 | 121 | } 122 | 123 | 124 | function showUsersSelect(val) { 125 | 126 | if(val=="") { 127 | $("#assign_users_role_select").hide(); 128 | $("#assign_users_role_select").empty(); 129 | $("#assign_users_btn").hide(); 130 | } else { 131 | $.ajax({ 132 | type: "GET", 133 | url: "http://localhost:8000/users", 134 | beforeSend: function(request) { 135 | request.setRequestHeader("Authorization", "Bearer "+localStorage.getItem("access_token")); 136 | }, 137 | success: function(msg){ 138 | $("#assign_users_role_select").show(); 139 | $("#assign_users_role_select").empty(); 140 | if(msg.length>0) { 141 | $("#assign_users_btn").show(); 142 | $.each(msg, function (index, value) { 143 | if(value.user_type!="super_admin") 144 | $("#assign_users_role_select").append(""+value.email_id+""); 145 | }); 146 | } 147 | }, 148 | error: function(XMLHttpRequest, textStatus, errorThrown) { 149 | if(XMLHttpRequest.responseText.indexOf("Access token expired:")!=-1) { 150 | getNewTokenOnOperation(function() { 151 | showUsersSelect(val); 152 | }); 153 | } else if(XMLHttpRequest.status==403) { 154 | $(".alert-danger").show(); 155 | $(".alert-success").hide(); 156 | $("#assign_users_role_select").hide(); 157 | $("#assign_users_role_select").empty(); 158 | $("#assign_users_btn").hide(); 159 | $(".alert-danger").html("You don't have permission to view the list of users"); 160 | } else { 161 | localStorage.clear(); 162 | window.location.href="index.html"; 163 | } 164 | } 165 | }); 166 | } 167 | } 168 | 169 | 170 | function showPermissionsSelect(val) { 171 | 172 | if(val=="") { 173 | $("#assign_permissions_role_select").hide(); 174 | $("#assign_permissions_role_select").empty(); 175 | $("#assign_permissions_btn").hide(); 176 | } else { 177 | $.ajax({ 178 | type: "GET", 179 | url: "http://localhost:8000/permissions", 180 | beforeSend: function(request) { 181 | request.setRequestHeader("Authorization", "Bearer "+localStorage.getItem("access_token")); 182 | }, 183 | success: function(msg){ 184 | $("#assign_permissions_role_select").show(); 185 | $("#assign_permissions_role_select").empty(); 186 | if(msg.length>0) { 187 | $("#assign_permissions_btn").show(); 188 | $.each(msg, function (index, value) { 189 | $("#assign_permissions_role_select").append(""+value.permission_name+""); 190 | }); 191 | } 192 | }, 193 | error: function(XMLHttpRequest, textStatus, errorThrown) { 194 | if(XMLHttpRequest.responseText.indexOf("Access token expired:")!=-1) { 195 | getNewTokenOnOperation(function() { 196 | showPermissionsSelect(val); 197 | }); 198 | } else if(XMLHttpRequest.status==403) { 199 | $(".alert-danger").show(); 200 | $(".alert-success").hide(); 201 | $("#assign_permissions_role_select").hide(); 202 | $("#assign_permissions_role_select").empty(); 203 | $("#assign_permissions_btn").hide(); 204 | $(".alert-danger").html("You don't have permission to view the list of permissions"); 205 | } else { 206 | localStorage.clear(); 207 | window.location.href="index.html"; 208 | } 209 | } 210 | }); 211 | } 212 | 213 | } 214 | 215 | 216 | function showUsersTable(val) { 217 | if(val=="") { 218 | $("#view_users_role_table").hide(); 219 | $("#view_users_role_table tbody").empty(); 220 | $(".alert-danger").hide(); 221 | } else { 222 | 223 | $.ajax({ 224 | type: "GET", 225 | url: "http://localhost:8000/roles/"+val+"/users", 226 | beforeSend: function(request) { 227 | request.setRequestHeader("Authorization", "Bearer "+localStorage.getItem("access_token")); 228 | }, 229 | success: function(msg){ 230 | if(msg.length>0) { 231 | $("#view_users_role_table tbody").empty(); 232 | $("#view_users_role_table").show(); 233 | $.each(msg, function (index, value) { 234 | $("#view_users_role_table tbody").append(" "+(index+1)+""+value.email_id+""); 235 | }); 236 | } else { 237 | $("#view_users_role_table tbody").empty(); 238 | $("#view_users_role_table").show(); 239 | $("#view_users_role_table tbody").append(" No records to display"); 240 | } 241 | }, 242 | error: function(XMLHttpRequest, textStatus, errorThrown) { 243 | if(XMLHttpRequest.responseText.indexOf("Access token expired:")!=-1) { 244 | getNewTokenOnOperation(function() { 245 | showUsersTable(val); 246 | }); 247 | } else if(XMLHttpRequest.status==403) { 248 | $(".alert-danger").show(); 249 | $(".alert-success").hide(); 250 | $(".alert-danger").html("You don't have permission to view the list of users by role"); 251 | } else { 252 | localStorage.clear(); 253 | window.location.href="index.html"; 254 | } 255 | } 256 | }); 257 | 258 | } 259 | } 260 | 261 | function showPermissionsTable(val) { 262 | if(val=="") { 263 | $("#view_permissions_role_table").hide(); 264 | $("#view_permissions_role_table tbody").empty(); 265 | $(".alert-danger").hide(); 266 | } else { 267 | 268 | $.ajax({ 269 | type: "GET", 270 | url: "http://localhost:8000/roles/"+val+"/permissions", 271 | beforeSend: function(request) { 272 | request.setRequestHeader("Authorization", "Bearer "+localStorage.getItem("access_token")); 273 | }, 274 | success: function(msg){ 275 | if(msg.length>0) { 276 | $("#view_permissions_role_table tbody").empty(); 277 | $("#view_permissions_role_table").show(); 278 | $.each(msg, function (index, value) { 279 | $("#view_permissions_role_table tbody").append(" "+(index+1)+""+value+""); 280 | }); 281 | } else { 282 | $("#view_permissions_role_table tbody").empty(); 283 | $("#view_permissions_role_table").show(); 284 | $("#view_permissions_role_table tbody").append(" No records to display"); 285 | } 286 | }, 287 | error: function(XMLHttpRequest, textStatus, errorThrown) { 288 | if(XMLHttpRequest.responseText.indexOf("Access token expired:")!=-1) { 289 | getNewTokenOnOperation(function() { 290 | showPermissionsTable(val); 291 | }); 292 | } else if(XMLHttpRequest.status==403) { 293 | $(".alert-danger").show(); 294 | $(".alert-success").hide(); 295 | $(".alert-danger").html("You don't have permission to view the list of permissions by role"); 296 | } else { 297 | localStorage.clear(); 298 | window.location.href="index.html"; 299 | } 300 | } 301 | }); 302 | 303 | } 304 | } 305 | 306 | 307 | function getRolesList() { 308 | $.ajax({ 309 | type: "GET", 310 | url: "http://localhost:8000/roles", 311 | beforeSend: function(request) { 312 | request.setRequestHeader("Authorization", "Bearer "+localStorage.getItem("access_token")); 313 | }, 314 | success: function(msg){ 315 | 316 | if(msg.length>0) { 317 | $("#view_permissions_role").empty(); 318 | $("#view_users_role").empty(); 319 | $("#assign_permissions_role").empty(); 320 | $("#assign_users_role").empty(); 321 | 322 | $("#view_permissions_role").append("---Select Role---"); 323 | $("#view_users_role").append("---Select Role---"); 324 | $("#assign_permissions_role").append("---Select Role---"); 325 | $("#assign_users_role").append("---Select Role---"); 326 | 327 | $.each(msg, function (index, value) { 328 | $("#view_permissions_role").append(""+value.role_name+""); 329 | $("#view_users_role").append(""+value.role_name+""); 330 | $("#assign_permissions_role").append(""+value.role_name+""); 331 | $("#assign_users_role").append(""+value.role_name+""); 332 | }); 333 | } 334 | 335 | }, 336 | error: function(XMLHttpRequest, textStatus, errorThrown) { 337 | if(XMLHttpRequest.responseText.indexOf("Access token expired:")!=-1) { 338 | getNewToken("settings.html"); 339 | } else if(XMLHttpRequest.status==403) { 340 | $(".nav-tabs").empty(); 341 | $(".alert-danger").show(); 342 | $(".alert-success").hide(); 343 | $(".tab-content").empty(); 344 | } else { 345 | localStorage.clear(); 346 | window.location.href="index.html"; 347 | } 348 | } 349 | }); 350 | } 351 | 352 | function getNewTokenOnOperation(callbackMethod) { 353 | $.ajax({ 354 | type: "POST", 355 | url: "http://localhost:8080/oauth/token", 356 | data: "refresh_token="+localStorage.getItem("refresh_token")+"&grant_type=refresh_token", 357 | beforeSend: function(request) { 358 | request.setRequestHeader("Authorization", "Basic "+btoa("talk2amareswaran:talk@amareswaran")); 359 | request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 360 | }, 361 | success: function(msg){ 362 | localStorage.setItem("access_token", JSON.parse(JSON.stringify(msg)).access_token); 363 | localStorage.setItem("refresh_token", JSON.parse(JSON.stringify(msg)).refresh_token); 364 | callbackMethod(); 365 | }, 366 | error: function(XMLHttpRequest, textStatus, errorThrown) { 367 | localStorage.clear(); 368 | window.location.href="index.html"; 369 | } 370 | }); 371 | } 372 | 373 | function getNewToken(pageName) { 374 | $.ajax({ 375 | type: "POST", 376 | url: "http://localhost:8080/oauth/token", 377 | data: "refresh_token="+localStorage.getItem("refresh_token")+"&grant_type=refresh_token", 378 | beforeSend: function(request) { 379 | request.setRequestHeader("Authorization", "Basic "+btoa("talk2amareswaran:talk@amareswaran")); 380 | request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 381 | }, 382 | success: function(msg){ 383 | localStorage.setItem("access_token", JSON.parse(JSON.stringify(msg)).access_token); 384 | localStorage.setItem("refresh_token", JSON.parse(JSON.stringify(msg)).refresh_token); 385 | window.location.reload(pageName); 386 | }, 387 | error: function(XMLHttpRequest, textStatus, errorThrown) { 388 | localStorage.clear(); 389 | window.location.href="index.html"; 390 | } 391 | }); 392 | } --------------------------------------------------------------------------------