controller

Creamos el paquete controller clases controladoras y de autentificación
Creamoos la clase AuthResponse para devolver el token
 
   
    
  package com.tutosoftware.aloja.controller;



import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class AuthResponse {
	
	String token;
    String username;
}
  
    
    
    
    
    
         
   

Creamos la clase LoginRequest
 
   
 package com.tutosoftware.aloja.controller;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class LoginRequest {
	
	String username;
	String password;

}
 
  
  
      
   

Creamos la clase de servicio para logguernos AuthService
 
  
  package com.tutosoftware.aloja.controller;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.tutosoftware.aloja.jwt.JwtService;
import com.tutosoftware.aloja.repository.AdministradorRepository;

import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
public class AuthService {
	
	private final AdministradorRepository adminRepository;
	private final AuthenticationManager authenticationManager;
	private final JwtService jwtService;

	public AuthResponse login(LoginRequest request) {
	
		authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword()));
        UserDetails user=adminRepository.findByCorreo(request.getUsername()).orElseThrow(()-> new UsernameNotFoundException("User not fournd"));
        String token=jwtService.getToken(user);
        return AuthResponse.builder()
            .token(token)
            .username(user.getUsername())
            .build();
	}

}
  
    
   

Creamos la clase AuthController
 
  
package com.tutosoftware.aloja.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import lombok.RequiredArgsConstructor;

@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
@CrossOrigin(origins= {"http://localhost:4200"})
public class AuthController {
	
	private final AuthService authService;
	
	
	
	@PostMapping("/login")
	public ResponseEntity<AuthResponse> login(@RequestBody LoginRequest request) {
		return ResponseEntity.ok(authService.login(request));
	}

}

 
 
 
 
   
   

Creamos la clase AdministradorController
 
  
  package com.tutosoftware.aloja.controller;



import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import com.tutosoftware.aloja.dto.AdministradorDto;
import com.tutosoftware.aloja.model.Administrador;
import com.tutosoftware.aloja.model.AdministradorRequest;
import com.tutosoftware.aloja.model.Role;
import com.tutosoftware.aloja.service.AdministradorService;

import lombok.RequiredArgsConstructor;

@RestController
@RequestMapping(value="/api/v1")
@RequiredArgsConstructor
@CrossOrigin(origins= {"http://localhost:4200"})
public class AdministradorController {
	
	private final AdministradorService adminService;
	
	
	
	@GetMapping("/admin")
	public List<Administrador> getAdmistradores(){
		return adminService.getAdministradores();
	}
	
	
	@ResponseStatus(HttpStatus.OK)
    @GetMapping("/admin/{email}")
	public ResponseEntity<AdministradorDto> getAdminstradorByCorreo(@PathVariable String email) {
	  AdministradorDto adminData = adminService.getAdministrador(email);
       
	 
	    return new ResponseEntity<>(adminData, HttpStatus.OK);
	 
	}
	
	
	@PostMapping("/admin")
	@ResponseStatus(HttpStatus.CREATED)
	public ResponseEntity<?> registrar(@RequestBody AdministradorRequest admin) {
		
		
		adminService.crearAdministrador(admin);
		
		Map<String,Object> response = new HashMap<>();
		
		response.put("mensaje","el cliente se ha creado con éxito");
		
		return new ResponseEntity<Map<String,Object>>(response,HttpStatus.CREATED);
		
	}
	
	
	@PutMapping("/admin/{id}")
	public ResponseEntity<?> updateAdmin(@RequestBody AdministradorRequest admin,@PathVariable Integer id) {
		
		Administrador adminActual = adminService.findById(id);
		
		Map<String,Object> response = new HashMap<>();
		
		adminActual.setNombre(admin.getNombre());
		adminActual.setApellidoPaterno(admin.getApellidoPaterno());
		adminActual.setApellidoMaterno(admin.getApellidoMaterno());
		adminActual.setCorreo(admin.getCorreo());
		adminActual.setCelular(admin.getCelular());
	    adminActual.setRol(parse(admin.getRol()));
	
	     adminService.actualizarAdministrador(adminActual);
	     
	     
	     return new ResponseEntity<Map<String,Object>>(response,HttpStatus.CREATED);
	}	
	
	
	
	@DeleteMapping("/admin/{id}")
	public ResponseEntity<?> delete(@PathVariable Integer id) {
		Map<String,Object> response = new HashMap<>();
		try {
	     System.out.println("El id es:"+id);
		adminService.delete(id);
		}catch(DataAccessException e) {
			response.put("mensaje","Error al eliminar el cliente en la base de datos");
			response.put("error", e.getMessage()+": "+e.getMostSpecificCause().getMessage());
			return new ResponseEntity<Map<String,Object>>(response,HttpStatus.INTERNAL_SERVER_ERROR);
		
	}
	
	response.put("mensaje","el cliente se elimino con éxito");
	return new ResponseEntity<Map<String,Object>>(response,HttpStatus.CREATED);
	}
	
	
	
	
   
	
     public static Role parse(String text){
    if(text.equals("ADMIN")){
        return Role.ADMIN;
    } else {
        return Role.USER;
    }
     }

}