Skip to content

Commit

Permalink
replace role name teacher with tutor
Browse files Browse the repository at this point in the history
  • Loading branch information
linxiaoxin committed Jul 19, 2024
1 parent 4c8f249 commit 412496f
Show file tree
Hide file tree
Showing 9 changed files with 48 additions and 12 deletions.
11 changes: 6 additions & 5 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -42,20 +42,21 @@ dependencies {

implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.flywaydb:flyway-database-postgresql'
implementation 'org.flywaydb:flyway-core'
implementation 'org.mapstruct:mapstruct:1.5.5.Final'
implementation 'org.flywaydb:flyway-core'

implementation 'com.fasterxml.jackson.core:jackson-databind'
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
implementation 'redis.clients:jedis'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'

implementation 'org.mapstruct:mapstruct:1.5.5.Final'
implementation 'com.fasterxml.jackson.core:jackson-databind'

compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-docker-compose'
annotationProcessor 'org.projectlombok:lombok'

testImplementation 'org.springframework.boot:spring-boot-starter-test'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
testImplementation 'com.h2database:h2:1.4.200' // Replace with the latest version
testImplementation 'com.h2database:h2:2.3.230' // Replace with the latest version

runtimeOnly "org.springframework.boot:spring-boot-starter-actuator"
runtimeOnly 'org.postgresql:postgresql'
Expand Down
5 changes: 5 additions & 0 deletions src/main/java/com/quemistry/auth_ms/constant/Auth.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package com.quemistry.auth_ms.constant;

public class Auth {
public static final String COOKIE_NAME = "QUESESSION";
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
import java.util.HashMap;
import java.util.Map;

import static com.quemistry.auth_ms.constant.Auth.COOKIE_NAME;

@RestController
@RequestMapping("/v1/auth")
public class AuthenticationController {
Expand Down Expand Up @@ -45,17 +47,17 @@ public ResponseEntity<UserProfile> getAccess(@RequestBody TokenRequest request){

//create cookie and return code with cookie session
HttpHeaders headers = new HttpHeaders();
headers.add("Set-Cookie", String.format("QUESESSION=%s; Max-Age=%s; Path=/; HttpOnly;",userProfile.getSessionId(),sessionTimeout));
headers.add("Set-Cookie", String.format("%s=%s; Max-Age=%s; Path=/; HttpOnly;", COOKIE_NAME, userProfile.getSessionId(),sessionTimeout));

return ResponseEntity.status(HttpStatus.OK).headers(headers).body(userProfile);
}

@PostMapping("signout")
public ResponseEntity<String> signOut(@CookieValue("QUESESSION") String cookie,@RequestBody SignOutRequest signOutRequest){
public ResponseEntity<String> signOut(@CookieValue(COOKIE_NAME) String cookie, @RequestBody SignOutRequest signOutRequest){
authenticationService.signOut(cookie, signOutRequest.getClientId());
//expire cookie to remove from session
HttpHeaders headers = new HttpHeaders();
headers.add("Set-Cookie", String.format("QUESESSION=%s; Max-Age=0; Path=/; HttpOnly;",""));
headers.add("Set-Cookie", String.format("%s=%s; Max-Age=0; Path=/; HttpOnly;", COOKIE_NAME,""));

return ResponseEntity.status(HttpStatus.OK).headers(headers).body(null);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,6 @@ public interface RoleRepository extends JpaRepository<Role, Long> {
Optional<Role> findByName(@Param("name") String name);

@Query("select r from Role r left join fetch r.grantedWith where r.name in :names")
List<Role> findByNames(@Param("name") String[] names);
List<Role> findByNames(@Param("names") String[] names);
}

Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.rmi.ServerException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Base64;
Expand Down Expand Up @@ -64,7 +65,10 @@ public UserProfile getAccessToken(TokenRequest request) {

if(response.getStatusCode() == HttpStatus.OK){
var idToken = response.getBody().getIdToken();
String[] chunks = idToken.split("\\.");
String[] chunks = (idToken == null) ? null : idToken.split("\\.");
if(chunks == null || chunks.length < 3) {
log.error("Invalid response from Idp Cognito.");
}
Base64.Decoder decoder = Base64.getUrlDecoder();
String payload = new String(decoder.decode(chunks[1]));
ObjectMapper mapper = new ObjectMapper();
Expand Down Expand Up @@ -134,10 +138,22 @@ public Boolean checkUserSessionAccess(String sessionId, String path, String meth
//get user profile role
var profile = ((UserProfile) redisTemplate.opsForValue().get(sessionId + "_profile"));
if(profile == null)
{
log.debug("checkUserSessionAccess: session not found");
return false;

}else{
log.debug("checkUserSessionAccess: found. With roles:"+ String.join(";",profile.getRoles()));
}
//get role
var roles = roleRepository.findByNames(profile.getRoles());
if(roles.size() == 0){
log.info("checkUserSessionAccess: roles does missing in data store.");
}
else{
StringBuilder rolesFound = new StringBuilder();
roles.forEach(role -> rolesFound.append(role.getName()+";"));
log.debug("checkUserSessionAccess: "+rolesFound);
}
if(roles.stream().anyMatch(role ->
role.getGrantedWith().stream().anyMatch(granted -> granted.getPath().compareToIgnoreCase(path) == 0
&& granted.getMethod().compareToIgnoreCase(method) == 0))){
Expand Down
4 changes: 4 additions & 0 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ spring:
server:
port: 80

logging:
level:
root: DEBUG

quemistry:
cognito:
url: ${COGNITO_URL}
Expand Down
3 changes: 3 additions & 0 deletions src/main/resources/db/migration/V1.3__changes_values.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
UPDATE qms_auth.role
SET name = 'tutor'
WHERE name = 'teacher'
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

import java.util.UUID;

import static com.quemistry.auth_ms.constant.Auth.COOKIE_NAME;
import static org.mockito.Mockito.doNothing;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
Expand Down Expand Up @@ -91,7 +92,7 @@ void givenSignOut_Success() throws Exception{
doNothing().when(authenticationService).signOut(user.getSessionId(), signOutRequest.getClientId());
ObjectMapper mapper = new ObjectMapper();

jakarta.servlet.http.Cookie cookie = new jakarta.servlet.http.Cookie("QUESESSION",mapper.writeValueAsString(tokenResponse) );
jakarta.servlet.http.Cookie cookie = new jakarta.servlet.http.Cookie(COOKIE_NAME,mapper.writeValueAsString(tokenResponse) );
cookie.setHttpOnly(true);
cookie.setPath("/");

Expand Down
4 changes: 4 additions & 0 deletions src/test/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,10 @@ spring:
server:
port: 80

logging:
level:
root: DEBUG

quemistry:
cognito:
url: ${COGNITO_URL}
Expand Down

0 comments on commit 412496f

Please sign in to comment.