NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io

package com.example.doItnew.Controller;


import com.example.doItnew.Entity.Employee;
import com.example.doItnew.Service.EmployeeService;
//import com.example.doItnew.exception.EmployeeNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("data")
@CrossOrigin(allowedHeaders = "*", origins = "*")
public class EmployeeController {

@Autowired
private EmployeeService employeeService;

@Autowired
private PasswordEncoder passwordEncoder;

@PreAuthorize("hasAnyRole('USER', 'ADMIN')")
@PostMapping("/saveEmployee")
public Employee saveEmployee(@RequestBody Employee employee) {
// Encode the password before saving
String encodedPassword = passwordEncoder.encode(employee.getPassword());
employee.setPassword(encodedPassword);
System.out.println(employee);
return employeeService.saveEmployee(employee);
}

@PreAuthorize("hasAnyRole('USER', 'ADMIN')")
@GetMapping("/getEmployee")
public ResponseEntity<List<Employee>> getAllEmployees() {
try {
List<Employee> employees = employeeService.getAllEmployees();
return new ResponseEntity<>(employees, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@PreAuthorize("hasAnyRole('USER', 'ADMIN')")
@GetMapping("/email/{emailid}")
public Employee getEmployeeById(@PathVariable String emailid) {
return employeeService.getByemailid(emailid);
}
// @PreAuthorize("hasAnyRole('USER', 'ADMIN')")
//// @GetMapping("/login")
// @GetMapping("/login")
// public ResponseEntity<Employee> login(@RequestParam("emailid") String email, @RequestParam("password") String password) {
// try {
//
// String hashedPassword = passwordEncoder.encode(password);
//
//
// Employee employee = employeeService.login(email, hashedPassword);
//
// return new ResponseEntity<>(employee, HttpStatus.OK);
// } catch (EmployeeNotFoundException e) {
// return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
// }
// }
@GetMapping("/loginbyemail")
public ResponseEntity<String> findUserNameByEmail(@RequestParam("email") String email) {
try {
String userName = employeeService.findByUserByEmail(email);
return new ResponseEntity<>(userName, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
// @PreAuthorize("hasAnyRole('USER', 'ADMIN')")
@ResponseBody
@GetMapping("/employeeloginname")
public String login1(@RequestParam("query") String query) {
String loginData = employeeService.employeeLogin(query);
return loginData;
}

@ResponseBody
@PreAuthorize("hasAnyRole('ROLE_USER','ROLE_ADMIN')")
@GetMapping("/employeelogin")
public String login(@RequestParam("query") String query) {
String loginData = employeeService.employeeLogin(query);
return loginData;
}
@PreAuthorize("hasAnyRole('USER', 'ADMIN')")
@GetMapping("/employee/search")
public List<Employee> getEmployeesByName(@RequestParam String name) {
return employeeService.getemployeesByName(name);
}

@PreAuthorize("hasAnyRole('USER', 'ADMIN')")
@GetMapping("/employee/{id}")
public Employee getEmployeesById(@PathVariable Long id) {
return employeeService.getEmpployeesById(id);
}

@PreAuthorize("hasRole('ADMIN')")
@PutMapping("/employee/update/{id}")
public Employee updateEmployees(@PathVariable Long id, @RequestBody Employee student) {
Employee stud = employeeService.updateEmployee(id, student);
return stud;
}

@PreAuthorize("hasRole('ADMIN')")
@DeleteMapping("/delete/{id}")
public String deleteEmployees(@PathVariable Long id) {
return employeeService.deleteEmployee(id);
}
}package com.example.doItnew.Entity;

import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "Emp_Tab")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String name;
private String emailid;
private int experiance;
private Long phonenumber;
private String password;
private String roles;

@ManyToOne
@JoinColumn(name = "department_id")
private Department department;



}package com.example.doItnew.Repository;


import com.example.doItnew.Entity.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;
import java.util.Optional;

public interface EmployeeRespository extends JpaRepository<Employee, Long> {
List<Employee> findByName(String name);
// Optional<Employee> findByEmailidAndPassword(String emailid, String password);
Optional<Employee> findByPhonenumber(Long phonenumber);

@Query("SELECT e.name FROM Employee e WHERE e.emailid = :info")
String findByEmployeeLogin(@Param("info") String email);

Optional<Employee> findByNameAndPassword(@Param("name") String name, @Param("password") String password);



Optional<Employee>findEmpByName(String name);
Optional<Employee> findByEmailid(String emailid);

// Optional<Object> findByEmail(String email);
}
package com.example.doItnew.Service;


import com.example.doItnew.Entity.Employee;
import com.example.doItnew.Repository.EmployeeRespository;
import com.example.doItnew.exception.EmployeeNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class EmployeeService {

@Autowired
private EmployeeRespository employeeRespository;
@Autowired
private PasswordEncoder passwordEncoder;


public Employee saveEmployee(Employee employee){
return employeeRespository.save(employee);
}
public List<Employee> getAllEmployees(){
return employeeRespository.findAll();
}
public List<Employee> getemployeesByName(String name) {
return employeeRespository.findByName(name);
}
public Employee getByPhonenumber(Long phonenumber) {
return employeeRespository.findByPhonenumber(phonenumber)
.orElseThrow(() -> new EmployeeNotFoundException("Employee with phone number " + phonenumber + " not found"));
}
public Employee getEmpployeesById(Long id){
return employeeRespository.findById(id).orElse(null);
}
public Employee getByemailid(String emailid){
return employeeRespository.findByEmailid(emailid).orElseThrow(null);
}

public String findByUserByEmail(String email) {
return employeeRespository.findByEmployeeLogin(email);
}

public String employeeLogin(String query) {
return "Employee data for " + query;
}



public Employee updateEmployee(Long id, Employee employee){
Employee existingStudnet = employeeRespository.findById(id).orElse(null);
// existingStudnet.setId(employee.getId());
existingStudnet.setName(employee.getName());
existingStudnet.setEmailid(employee.getEmailid());
return employeeRespository.save(existingStudnet);
}
public String deleteEmployee(Long id){
employeeRespository.deleteById(id);
return null;
}

// public Employee login(String email, String password) {
// Employee employee = employeeRespository.findByEmailid(email)
// .orElseThrow(() -> new EmployeeNotFoundException("Employee with email " + email + " not found"));
//
// if (passwordEncoder.matches(password, employee.getPassword())) {
// // Passwords match, return the authenticated user
// return employee;
// } else {
// // Passwords do not match, throw an exception or handle it as needed
// throw new EmployeeNotFoundException("Invalid password");
// }
// }
}package com.example.doItnew.Config;

//import com.example.newCart.exception.ProdNotFoundException;
import com.example.doItnew.Entity.Employee;
import com.example.doItnew.Repository.EmployeeRespository;
import com.example.doItnew.exception.EmployeeNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class UserSecurity implements UserDetailsService {

@Autowired
private EmployeeRespository employeeRespository;
private List<GrantedAuthority> authorities;

@Override
public UserDetails loadUserByUsername(String name) throws EmployeeNotFoundException {
Employee employee = employeeRespository.findEmpByName(name).orElseThrow(() -> new EmployeeNotFoundException("Employee with name " + name + " not found in database"));

this.authorities = Arrays.stream(employee.getRoles().split(","))
.map(SimpleGrantedAuthority::new).collect(Collectors.toList());

return org.springframework.security.core.userdetails.User
.withUsername(name)
.password(employee.getPassword())
.authorities(authorities)
.build();
}
}package com.example.doItnew.Config;

import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
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.configurers.AbstractHttpConfigurer;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@EnableWebSecurity
@EnableMethodSecurity
@Configuration
@AllArgsConstructor
public class SpringSecurityClass {
@Autowired
private UserSecurity userDetailsService;
// @Bean
// public UserDetailsService userDetailsService(PasswordEncoder encoder){
//
// UserDetails shiva = User.builder()
// .username("user")
// .password(passwordEncoder().encode("abcd"))
// .roles("USER")
// .build();
//
// UserDetails admin = User.builder()
// .username("admin")
// .password(passwordEncoder().encode("pop1"))
// .roles("ADMIN")
// .build();
//
// return new InMemoryUserDetailsManager(shiva, admin);
// }
@Bean
public AuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userDetailsService);
authenticationProvider.setPasswordEncoder(passwordEncoder());
return authenticationProvider;
}

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.cors(Customizer.withDefaults());
http.csrf(AbstractHttpConfigurer::disable);
http.authorizeHttpRequests((requests) -> {
requests
// .requestMatchers("")
.requestMatchers("/student/getEmployee","student/saveEmployee", "/student/employee/search", "/department/dep", "/department/dep/{id}")
.permitAll();
});
http.authorizeHttpRequests((requests) -> {
requests
.requestMatchers("/student/***", "/department/***").hasAnyRole("ADMIN", "USER")
// .requestMatchers("/department/**").hasAnyRole("ADMIN", "USER")
.anyRequest().fullyAuthenticated();
})
.httpBasic(Customizer.withDefaults());

return http.build();
}

@Bean
public static PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Details, Employee, Department, updatex, User } from './model';

@Injectable({
providedIn: 'root'
})
export class ServiceService {
private username: string = '';
private password: string = '';
isAdmin: boolean = false;


private baseUrl = 'http://localhost:8080';
// isLoggedIn: any;

constructor(private http: HttpClient) { }

getAllEmployees(): Observable<Details[]> {
const url = `${this.baseUrl}/data/getEmployee`;
const headers = new HttpHeaders({ Authorization: 'Basic ' + btoa(this.username + ":" + this.password) });
return this.http.get<Details[]>(url, { headers });
// return this.http.get<Details[]>(url);
}

saveEmployee(employee: Employee): Observable<Employee> {
const url = `${this.baseUrl}/data/saveEmployee`;
const headers = new HttpHeaders({ Authorization: 'Basic ' + btoa(this.username + ":" + this.password) });

return this.http.post<Employee>(url, employee ,{ headers });
}

getDepartments(): Observable<Department[]> {
const url = `${this.baseUrl}/department/dep`;
const headers = new HttpHeaders({ Authorization: 'Basic ' + btoa(this.username + ":" + this.password) });

return this.http.get<Department[]>(url,{ headers });
}

getEmployeesByName(name: string): Observable<any[]> {
const url = `${this.baseUrl}/data/employee/search?name=${name}`;
const headers = new HttpHeaders({ Authorization: 'Basic ' + btoa(this.username + ":" + this.password) });
return this.http.get<any[]>(url,{headers});
}

getEmployeeById(id: number): Observable<Employee> {
const url = `${this.baseUrl}/data/employee/${id}`;
const headers = new HttpHeaders({ Authorization: 'Basic ' + btoa(this.username + ":" + this.password) });
return this.http.get<Employee>(url,{headers});
}

updateEmployee(id: number, stud: updatex): Observable<updatex> {
const url = `${this.baseUrl}/data/employee/update/${id}`;
const headers = new HttpHeaders({ Authorization: 'Basic ' + btoa(this.username + ":" + this.password) });

return this.http.put<updatex>(url, stud,{headers});
}

deleteEmployee(id: number): Observable<object> {
const url = `${this.baseUrl}/data/delete/${id}`;
const headers = new HttpHeaders({ Authorization: 'Basic ' + btoa(this.username + ":" + this.password) });

return this.http.delete(url,{headers});

}


public userlogin(username: string, password: string): Observable<string> {
this.username = username;
this.password = password;
const headers = new HttpHeaders({ Authorization: 'Basic ' + btoa(username + ":" + password) });
return this.http.get<string>("http://localhost:8080/data/employeelogin?query=" + username, { headers, responseType: 'text' as 'json' });
}
// public userlogin(username: string, password: string): Observable<User> {
// this.username = username;
// this.password = password;
// const headers = new HttpHeaders({ Authorization: 'Basic ' + btoa(username + ":" + password) });
// return this.http.get<User>("http://localhost:8080/data/employeelogin?query=" + username, { headers, responseType: 'json' });
// }


getAllDepartments(): Observable<Department[]> {
const url = `${this.baseUrl}/department/dep`;
return this.http.get<Department[]>(url);
}

getDepartmentById(id: number): Observable<Department> {
const url = `${this.baseUrl}/department/dep/${id}`;
return this.http.get<Department>(url);
}

saveDepartment(department: Department): Observable<Department> {
const url = `${this.baseUrl}/department/saveDep`;
const headers = new HttpHeaders({ Authorization: 'Basic ' + btoa(this.username + ":" + this.password) });

return this.http.post<Department>(url, department,{headers});
}



}
import { Component, Output } from '@angular/core';
import { ServiceService } from '../service.service';
import { Router } from '@angular/router';
import { NgForm } from '@angular/forms';

@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent {
username: string = '';
password: string = '';
loginResult: string = '';
isLoggedIn: boolean = false;

constructor(private Service: ServiceService, private router: Router) {}
// @Output() pop = new EventEmitter<string>();
login(loginForm: NgForm): void {
if (loginForm.invalid) {

return;
}

this.Service.userlogin(this.username, this.password).subscribe(
result => {
this.loginResult = result;
this.isLoggedIn = true;
console.log(this.username + ' has logged in');
// isloggedin:true;
this.router.navigate(['/app-view']);
},
error => {
console.error('Login failed', error);
this.loginResult = 'Login failed. Please check your credentials.';
}
);
}
}[So when user login i need to know whteher it is user or admin in cons]

     
 
what is notes.io
 

Notes.io is a web-based application for taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000 notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 12 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.