Skip to content
Snippets Groups Projects
Commit cd7b68cc authored by josborg's avatar josborg
Browse files

Refactorizacion y Autenticacion jwt sin terminar

parent 5f069019
No related branches found
No related tags found
No related merge requests found
Showing
with 188 additions and 70 deletions
......@@ -88,6 +88,7 @@ export class AuthComponent implements OnInit {
resp => {
//Gurdas jwt
this.jwt = resp.body as string;
console.log("JWT: "+this.jwt);
this.clienteApiRest.setSession(this.jwt);
this.getIdByCode();
}
......
......@@ -12,6 +12,7 @@ import com.uva.discordbot.util.Global;
import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
......@@ -78,7 +79,43 @@ public class ControllerBot {
JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
String user = jsonObject.get("user").getAsString();
List<String> customerList = Global.guilds.get(user);
HashMap<String,String> customerHashMap = Global.guilds.get(user);
List<String> customerList = new ArrayList<String>();
customerList.addAll(customerHashMap.keySet());
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(customerList, new TypeToken<List<String>>() {}.getType());
if (!element.isJsonArray() ) {
// fail appropriately
throw new BotException("Error de creacion");
}
JsonArray jsonArray = element.getAsJsonArray();
System.out.println("return: "+jsonArray.toString());
return jsonArray.toString();
}
@PostMapping(produces = MediaType.APPLICATION_JSON_VALUE, value = "/profesores")
public String guildsProfesor(@RequestBody String json) {
JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
String user = jsonObject.get("user").getAsString();
HashMap<String,String> customerHashMap = Global.guilds.get(user);
List<String> customerList = new ArrayList<String>();
List<String> aux = new ArrayList<String>();
aux.addAll(customerHashMap.keySet());
for (String key : aux) {
if(customerHashMap.get(key).equalsIgnoreCase("Profesor")){
customerList.add(key);
}
}
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(customerList, new TypeToken<List<String>>() {}.getType());
......
......@@ -6,6 +6,7 @@ import discord4j.core.object.entity.Role;
import discord4j.core.spec.RoleCreateSpec;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.function.Consumer;
......@@ -22,13 +23,29 @@ public abstract class ReadyEventListener {
for (Guild guild : client.getClient().getGuilds().collectList().block()) {
uploadRole(guild, "Alumno");
uploadRole(guild, "Profesor");
for (Member member : guild.getMembers().collectList().block()) {
if(!Global.guilds.containsKey(member.getId().asString())){
ArrayList<String> guilds = new ArrayList<String>();
guilds.add(guild.getId().asString());
HashMap<String,String> guilds = new HashMap<String,String>();
List<Role> roles = member.getRoles().collectList().block();
String rol = "";
for (Role role : roles) {
if(role.getName().equalsIgnoreCase("Profesor")){
rol = "Profesor";
}
}
guilds.put(guild.getId().asString(), rol);
Global.guilds.put(member.getId().asString(), guilds);
}else{
Global.guilds.get(member.getId().asString()).add(guild.getId().asString());
List<Role> roles = member.getRoles().collectList().block();
String rol = "";
for (Role role : roles) {
if(role.getName().equalsIgnoreCase("Profesor")){
rol = "Profesor";
}
}
Global.guilds.get(member.getId().asString()).put(guild.getId().asString(), rol);
}
}
}
......@@ -37,9 +54,12 @@ public abstract class ReadyEventListener {
while(value.hasNext()){
String user = (String) value.next();
System.out.println("user:"+user.toString());
ArrayList<String> guilds = Global.guilds.get(user);
for (String guild : guilds) {
HashMap<String,String> guilds = Global.guilds.get(user);
List<String> aux = new ArrayList<>();
aux.addAll(guilds.keySet());
for (String guild : aux) {
System.out.println("\tguild:"+guild.toString());
System.out.println("\t\trole:"+guilds.get(guild.toString()));
}
}
......
package com.uva.discordbot.util;
import java.util.ArrayList;
import java.util.HashMap;
public class Global {
public static HashMap<String,ArrayList<String>> guilds = new HashMap<>();
/**
* {
* user : [
* guild : rol
* ]
* }
*/
public static HashMap<String,HashMap<String,String>> guilds = new HashMap<>();
public static String redir = "";
}
......@@ -45,7 +45,7 @@
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
<version>2.9.0</version>
</dependency>
......
package com.uva.surveys;
import com.uva.surveys.security.JWTAuthorizationFilter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
......@@ -25,19 +22,7 @@ public class EncuestaApplication {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable();/*
.addFilterAfter(new JWTAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class)
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/**").permitAll()
.antMatchers(HttpMethod.POST,"/**").permitAll()
.antMatchers(HttpMethod.PUT, "/**").permitAll()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.antMatchers(HttpMethod.GET, "/**").authenticated()
.antMatchers(HttpMethod.POST, "/**").authenticated()
.antMatchers(HttpMethod.PUT, "/**").authenticated()
.antMatchers(HttpMethod.DELETE, "/**").authenticated()
.antMatchers(HttpMethod.OPTIONS, "/**").authenticated()
.anyRequest().authenticated();*/
http.cors().and().csrf().disable();
}
}
......
......@@ -50,7 +50,7 @@ public class AuthController {
this.linkRepository = linkRepository;
}
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public String guildsEncuesta(@RequestBody String json) {
JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
......@@ -86,9 +86,10 @@ public class AuthController {
String jwtString = "";
for (JsonElement jsonElement : guildsCodeJsonArray) {
if(guildUserJsonArray.contains(jsonElement)){
jwtString = getJWTToken(user, code);
jwtString = getJWTToken(user, code, "Profesor");
}
}
jwtString = getJWTToken(user, code, "Profesor");//OJOOOOOO
System.out.println("jwtString: "+jwtString);
......@@ -97,15 +98,15 @@ public class AuthController {
}
private String getJWTToken(String user, String code ) {
private String getJWTToken(String user, String code, String rol) {
String secretKey = SECRET;
List<GrantedAuthority> grantedAuthorities = AuthorityUtils
.commaSeparatedStringToAuthorityList("ROLE_USER");
.commaSeparatedStringToAuthorityList(rol);
String token = Jwts
.builder()
.setId("softtekJWT")
.setSubject(user+code)
.setSubject(user)
.claim("authorities",
grantedAuthorities.stream()
.map(GrantedAuthority::getAuthority)
......
......@@ -27,6 +27,38 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--Seguridad-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<!--JWT-->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.2</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.2</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId> <!-- or jjwt-gson if Gson is preferred -->
<version>0.11.2</version>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
......
package com.uva.gateway;
import com.uva.gateway.security.JWTAuthorizationFilter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@SpringBootApplication
public class GatewayApplication {
......@@ -10,4 +18,44 @@ public class GatewayApplication {
SpringApplication.run(GatewayApplication.class, args);
}
@EnableWebSecurity
@Configuration
class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
.addFilterAfter(new JWTAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class)
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/styles**").permitAll()
.antMatchers(HttpMethod.GET, "/runtime**").permitAll()
.antMatchers(HttpMethod.GET, "/polyfills**").permitAll()
.antMatchers(HttpMethod.GET, "/main**").permitAll()
.antMatchers(HttpMethod.POST, "/api/auth/**").permitAll()
.antMatchers(HttpMethod.PUT, "/api/auth/**").permitAll()
.antMatchers(HttpMethod.DELETE, "/api/auth/**").permitAll()
.antMatchers(HttpMethod.GET, "/api/auth/**").permitAll()
.antMatchers(HttpMethod.OPTIONS, "/api/auth/**").permitAll()
.antMatchers(HttpMethod.POST, "/api/bot/**").permitAll()
.antMatchers(HttpMethod.PUT, "/api/bot/**").permitAll()
.antMatchers(HttpMethod.DELETE, "/api/bot/**").permitAll()
.antMatchers(HttpMethod.GET, "/api/bot/**").permitAll()
.antMatchers(HttpMethod.OPTIONS, "/api/bot/**").permitAll()
.antMatchers(HttpMethod.POST, "/client/**").permitAll()
.antMatchers(HttpMethod.PUT, "/client/**").permitAll()
.antMatchers(HttpMethod.DELETE, "/client/**").permitAll()
.antMatchers(HttpMethod.GET, "/client/**").permitAll()
.antMatchers(HttpMethod.OPTIONS, "/client/**").permitAll()
.antMatchers(HttpMethod.PUT, "/**").authenticated()
.antMatchers(HttpMethod.DELETE, "/**").authenticated()
.antMatchers(HttpMethod.GET, "/**").authenticated()
.antMatchers(HttpMethod.POST, "/**").authenticated()
.antMatchers(HttpMethod.OPTIONS, "/**").authenticated()
.anyRequest().authenticated();
}
}
}
package com.uva.gateway.controller;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
......@@ -16,6 +18,7 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.GetMapping;
......@@ -45,12 +48,14 @@ public class AuthController {
//Back POST
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
private String postAuth(HttpServletRequest req, @RequestBody String body) {
private ResponseEntity<String> postAuth(HttpServletRequest req, @RequestBody String body) {
System.out.println("/api/auth");
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
List<String> list = Collections.list(req.getHeaderNames());
for (String e : list) {
headers.set(e, req.getHeader(e));
}
HttpEntity request = new HttpEntity(body, headers);
ResponseEntity<String> response = restTemplate.exchange(
"http://api-poll:8082"+req.getRequestURI(),
......@@ -59,7 +64,7 @@ public class AuthController {
String.class,
1
);
return response.toString();
return response;
}
......@@ -67,23 +72,14 @@ public class AuthController {
@PutMapping()
private ResponseEntity<String> putAuth(HttpServletRequest req, @RequestBody String body) {
// create an instance of RestTemplate
System.out.println("/api/auth");
RestTemplate restTemplate = new RestTemplate();
// create headers
HttpHeaders headers = new HttpHeaders();
// set `Content-Type` and `Accept` headers
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
// example of custom header
//headers.set("X-Request-Source", "Desktop");
// build the request
HttpEntity request = new HttpEntity(headers);
// make an HTTP GET request with headers
List<String> list = Collections.list(req.getHeaderNames());
for (String e : list) {
headers.set(e, req.getHeader(e));
}
HttpEntity request = new HttpEntity(body, headers);
ResponseEntity<String> response = restTemplate.exchange(
"http://api-poll:8082"+req.getRequestURI(),
HttpMethod.PUT,
......
package com.uva.gateway.controller;
import java.util.Collections;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
......@@ -47,12 +48,14 @@ public class PollController {
//Back POST
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
private String postEncuestas(HttpServletRequest req, @RequestBody String body) {
private ResponseEntity<String> postEncuestas(HttpServletRequest req, @RequestBody String body) {
System.out.println("/api/encuestas");
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
List<String> list = Collections.list(req.getHeaderNames());
for (String e : list) {
headers.set(e, req.getHeader(e));
}
HttpEntity request = new HttpEntity(body, headers);
ResponseEntity<String> response = restTemplate.exchange(
"http://api-poll:8082"+req.getRequestURI(),
......@@ -61,7 +64,7 @@ public class PollController {
String.class,
1
);
return response.toString();
return response;
}
......@@ -69,25 +72,14 @@ public class PollController {
@PutMapping()
private ResponseEntity<String> putEncuestas(HttpServletRequest req, @RequestBody String body) {
// create an instance of RestTemplate
System.out.println("PUT:/api/encuestas");
System.out.println("http://api-poll:8082"+req.getRequestURI());
System.out.println("/api/encuestas");
RestTemplate restTemplate = new RestTemplate();
// create headers
HttpHeaders headers = new HttpHeaders();
// set `Content-Type` and `Accept` headers
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
// example of custom header
//headers.set("X-Request-Source", "Desktop");
// build the request
List<String> list = Collections.list(req.getHeaderNames());
for (String e : list) {
headers.set(e, req.getHeader(e));
}
HttpEntity request = new HttpEntity(body, headers);
// make an HTTP GET request with headers
ResponseEntity<String> response = restTemplate.exchange(
"http://api-poll:8082"+req.getRequestURI(),
HttpMethod.PUT,
......
package com.uva.surveys.security;
package com.uva.gateway.security;
import java.io.IOException;
import java.util.List;
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment