Skip to content

Commit

Permalink
refs #1 Usuario:CRUD+Autenticação
Browse files Browse the repository at this point in the history
  • Loading branch information
ruan-pb committed Feb 8, 2021
1 parent f4cf1c5 commit 2bc2b12
Show file tree
Hide file tree
Showing 30 changed files with 391 additions and 413 deletions.
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,12 @@ local.properties
# .idea/modules
# *.iml
# *.ipr
# *.idea/compiler.xml#.
# *.idea/dataSources.xml
# *.idea/hatcher-api.iml
# *.idea/misc.xml
# *.idea/sqldialects.xml


# CMake
cmake-build-*/
Expand Down
16 changes: 0 additions & 16 deletions src/main/java/org/ayty/hatcher/api/HatcherApiApplication.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
package org.ayty.hatcher.api;

import org.ayty.hatcher.api.v1.security.JwtAuthFilter;
import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class HatcherApiApplication {
Expand All @@ -15,18 +11,6 @@ public static void main(String[] args) {
SpringApplication.run(HatcherApiApplication.class, args);
}

/*
@Bean
public FilterRegistrationBean<JwtAuthFilter> filtroJwt(){
FilterRegistrationBean<JwtAuthFilter> filtroRB = new FilterRegistrationBean<JwtAuthFilter>();
filtroRB.setFilter(new JwtAuthFilter());
filtroRB.addUrlPatterns("hatcher/profile/registerUser","hatcher/profile/user/registerCourse","hatcher/profile/user/course/remove","hatche/profile/user/course/edit");
return filtroRB;

}
*/

}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import java.util.Locale;


import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
Expand All @@ -11,20 +12,21 @@
@Configuration
public class ConfigurationInternationalization {

@Bean
public MessageSource messageSource(){
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:messages");
messageSource.setDefaultEncoding("ISO-8859-1");
messageSource.setDefaultLocale(Locale.getDefault());
return messageSource;
}
@Bean
public MessageSource messageSource(){
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:messages.properties");
messageSource.setDefaultEncoding("ISO-8859-1");
messageSource.setDefaultLocale(Locale.getDefault());
return messageSource;
}

@Bean
public LocalValidatorFactoryBean validatorFactoryBean(){
LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
bean.setValidationMessageSource(messageSource());
return bean;
}

@Bean
public LocalValidatorFactoryBean validatorFactoryBean(){
LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
bean.setValidationMessageSource(messageSource());
return bean;
}

}
44 changes: 8 additions & 36 deletions src/main/java/org/ayty/hatcher/api/v1/security/JwtAuthFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,30 +8,27 @@
import javax.servlet.http.HttpServletResponse;

import org.ayty.hatcher.api.v1.user.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import lombok.RequiredArgsConstructor;


@RequiredArgsConstructor
public class JwtAuthFilter extends OncePerRequestFilter {



@Autowired
private JwtService jwtService;

@Autowired
private UserServiceImpl userService;
private final JwtService jwtService;


private final UserServiceImpl userService;


public JwtAuthFilter( JwtService jwtService, UserServiceImpl userService ) {
this.jwtService = jwtService;
this.userService= userService;
}

@Override
protected void doFilterInternal(
Expand All @@ -58,30 +55,5 @@ protected void doFilterInternal(

}

/*
@Value("${security.jwt.token.secret-key}")
private String secretKey;
@Value("${security.jwt.token.expire-length}")
private String expiration;
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
String header = req.getHeader("Authorization");
if (header == null || !header.startsWith("Beare ")) {
throw new ServletException("missing or invalid token");
}
String token = header.substring(7);
try {
Jwts.parser().setSigningKey(this.secretKey).parseClaimsJws(token).getBody();
} catch (SignatureException e) {
throw new ServletException("Token Inválido");
}
chain.doFilter(request, response);
}
*/

}
98 changes: 54 additions & 44 deletions src/main/java/org/ayty/hatcher/api/v1/security/JwtService.java
Original file line number Diff line number Diff line change
@@ -1,20 +1,25 @@
package org.ayty.hatcher.api.v1.security;

import java.time.Instant;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashMap;
import java.util.Optional;

import org.ayty.hatcher.api.v1.user.dto.LoginDTO;
import org.ayty.hatcher.api.v1.user.entity.User;
import org.ayty.hatcher.api.v1.user.jpa.UserRepository;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
@Service
public class JwtService {

Expand All @@ -23,48 +28,53 @@ public class JwtService {

@Value("${security.jwt.token.expire-length}")
private String expiration;


public String generateToken( LoginDTO user ){

long expString = Long.valueOf(expiration);
LocalDateTime expireLength = LocalDateTime.now().plusMinutes(expString);
Instant instant = expireLength.atZone(ZoneId.systemDefault()).toInstant();
Date date = Date.from(instant);


//claims admin

String token = Jwts.builder()
.setSubject(user.getLogin())
.signWith(SignatureAlgorithm.HS512,secretKey)
.setExpiration(date)
.compact();
return token;
}

private Claims getClaims( String token ) throws ExpiredJwtException {
return Jwts
.parser()
.setSigningKey(secretKey)
.parseClaimsJws(token)
.getBody();
}

public boolean validToken( String token ){
try{
Claims claims = getClaims(token);
Date expirationDate= claims.getExpiration();
LocalDateTime date =
expirationDate.toInstant()
.atZone(ZoneId.systemDefault()).toLocalDateTime();
return !LocalDateTime.now().isAfter(date);
}catch (Exception e){
return false;
}
}
public String getUserLogin(String token) throws ExpiredJwtException{
return (String) getClaims(token).getSubject();
}

private final UserRepository userBD;

public String generateToken(LoginDTO user) {

long expString = Long.valueOf(expiration);
LocalDateTime expireLength = LocalDateTime.now().plusMinutes(expString);
Instant instant = expireLength.atZone(ZoneId.systemDefault()).toInstant();
Date date = Date.from(instant);

HashMap<String, Object> claim = new HashMap<String, Object>();
Optional<User> userAdmin = userBD.findByLogin(user.getLogin());

if (userAdmin.get().isAdmin() == true) {
claim.put("Roles", "ADMIN");
claim.put("Login", user.getLogin());
claim.put("Email", userAdmin.get().getEmail());
claim.put("Id", userAdmin.get().getId());
} else {
claim.put("Roles", "USER");
claim.put("Login", user.getLogin());
claim.put("Email", userAdmin.get().getEmail());
claim.put("Id", userAdmin.get().getId());
}

String token = Jwts.builder().setSubject(user.getLogin()).setClaims(claim)
.signWith(SignatureAlgorithm.HS512, secretKey).setExpiration(date).compact();
return token;
}

private Claims getClaims(String token) throws ExpiredJwtException {
return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody();
}

public boolean validToken(String token) {
try {
Claims claims = getClaims(token);
Date expirationDate = claims.getExpiration();
LocalDateTime date = expirationDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
return !LocalDateTime.now().isAfter(date);
} catch (Exception e) {
return false;
}
}

public String getUserLogin(String token) throws ExpiredJwtException {
return (String) getClaims(token).getSubject();
}

}
13 changes: 10 additions & 3 deletions src/main/java/org/ayty/hatcher/api/v1/security/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
private UserServiceImpl userService;

@Autowired
private JwtService jwtService;
JwtService jwtService;

@Bean
public PasswordEncoder passwordEncoder() {
Expand All @@ -49,6 +49,14 @@ protected void configure( HttpSecurity http ) throws Exception {
http
.cors().and().csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.POST,"/hatcher/Authenticate")
.permitAll()
.antMatchers(HttpMethod.GET,"/hatcher/listUsers")
.permitAll()
.antMatchers(HttpMethod.POST,"/hatcher/register")
.permitAll()
.antMatchers(HttpMethod.DELETE,"/hatcher/remove/**")
.permitAll()
.antMatchers("/hatcher/profile/registerUser")
.hasAnyRole("ADMIN")
.antMatchers("/hatcher/profile")
Expand All @@ -59,8 +67,7 @@ protected void configure( HttpSecurity http ) throws Exception {
.hasAnyRole("ADMIN")
.antMatchers("/hatcher/profile/user/course/edit")
.hasAnyRole("ADMIN")
.antMatchers(HttpMethod.POST, "/api/usuarios/**")
.permitAll()

.anyRequest().authenticated()
.and()
.sessionManagement()
Expand Down

This file was deleted.

Loading

0 comments on commit 2bc2b12

Please sign in to comment.