Skip to content
Snippets Groups Projects
Commit e50a1048 authored by Antoine Hazebrouck's avatar Antoine Hazebrouck
Browse files

register marche a peu pres

parent a5a63b13
Branches
No related tags found
No related merge requests found
package jez.authentication2;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.core.userdetails.User;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
......@@ -34,7 +34,7 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
.usersByUsernameQuery(
"SELECT username, password, enabled FROM users WHERE username = ?")
.authoritiesByUsernameQuery(
"SELECT username, authority FROM authorities WHERE username = ?");
"SELECT username, authority FROM users WHERE username = ?");
}
@Bean
......
......@@ -39,6 +39,13 @@ public class MainController {
public String displayNotes(@PathVariable Integer note_id, Model model) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
User user = userService.findUserByUsername(authentication.getName());
// si l'utilisateur a 0 notes
if (user.getNotes().isEmpty()) {
user = createNewNote(user);
// user = userService.findUserByUsername(authentication.getName());
}
user.getNotes().sort(new Comparator<Note>() {
@Override
......@@ -47,8 +54,8 @@ public class MainController {
}
});
System.out.println(user);
System.out.println(user.getNotes().get(note_id - 1));
// System.out.println(user);
// System.out.println(user.getNotes().get(note_id - 1));
// model.addAttribute("user", user);
model.addAttribute("note_id", note_id);
......@@ -67,6 +74,7 @@ public class MainController {
@RequestParam(name = "notes") String notes) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
User user = userService.findUserByUsername(authentication.getName());
user.getNotes().sort(new Comparator<Note>() {
@Override
......@@ -87,14 +95,19 @@ public class MainController {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
User user = userService.findUserByUsername(authentication.getName());
Note newNote = new Note(user.getNotes().size() + 1, "new note", user);
user = createNewNote(user);
return "redirect:/notes/%s".formatted(user.getNotes().size());
}
private User createNewNote(User user) {
Note newNote = new Note("new note", user);
// Note newNote = new Note(user.getNotes().size() + 1, "new note", user);
user.getNotes().add(newNote);
notesService.saveNote(newNote);
userService.saveUser(user);
// select * from notes;
// \dt
return "redirect:/notes/%s".formatted(user.getNotes().size());
return userService.findUserByUsername(user.getUsername());
}
@GetMapping(value = "/user")
......
package jez.authentication2.controllers;
import java.sql.SQLException;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
......@@ -8,6 +10,7 @@ import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import jez.authentication2.entities.User;
import jez.authentication2.services.UserService;
......@@ -17,18 +20,22 @@ public class RegistrationController {
UserService userService;
@GetMapping("/register")
public String displayRegistrationPage(Model model)
{
public String displayRegistrationPage(Model model) {
model.addAttribute("user", new User());
return "registration_page";
}
@PostMapping("/register")
public String registerUser(@ModelAttribute("user") User user, RedirectAttributes redirectAttributes) throws SQLException
{
public String registerUser(@ModelAttribute("user") User user, RedirectAttributes redirectAttributes)
throws SQLException {
user.setEnabled(true);
user.setAuthority("ROLE_USER");
user.setNotes(new ArrayList<>());
// Note newNote = new Note("new note", user);
// user.getNotes().add(newNote);
userService.saveUser(user);
System.out.println("id:" + userService.findUserByUsername(user.getUsername()).getId());
return "redirect:/";
}
}
......@@ -11,6 +11,7 @@ import javax.persistence.Table;
@Entity
@Table(name = "notes")
public class Note {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
......@@ -20,54 +21,50 @@ public class Note {
@JoinColumn(name = "user_id", nullable = false)
private User user;
public Note() {
}
public Note(Integer id, String note, User user) {
this.id = id;
this.note = note;
this.user = user;
}
public Note(String note, User user) {
this.note = note;
this.user = user;
}
public Note(Integer id, String note) {
this.id = id;
this.note = note;
}
@Override
public String toString() {
return "Note [id=" + id + ", note=" + note + "]";
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
......
package jez.authentication2.entities;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
......@@ -17,7 +19,8 @@ public class User {
private String username;
private String password;
private boolean enabled;
@OneToMany(mappedBy = "user")
private String authority;
@OneToMany(mappedBy = "user", cascade = {CascadeType.PERSIST})
private List<Note> notes;
public User(Integer id, String username, String password, boolean enabled, List<Note> notes) {
......@@ -28,8 +31,10 @@ public class User {
this.notes = notes;
}
public List<Note> getNotes()
{
public User() {
}
public List<Note> getNotes() {
return notes;
}
......@@ -37,40 +42,50 @@ public class User {
this.notes = notes;
}
public User() {}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getAuthority() {
return authority;
}
public void setAuthority(String authority) {
this.authority = authority;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password=" + password + ", enabled="
+ enabled + ", notes=" + notes + "]";
}
}
package jez.authentication2.services;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashSet;
import java.util.Set;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class NotesServiceBis {
@Autowired
DataSource dataSource;
public void setNotes(String username, int id, String notes) throws SQLException {
Connection conn = dataSource.getConnection();
Statement statement = conn.createStatement();
statement.executeUpdate("""
UPDATE notes SET notes='%s' WHERE username='%s AND id=%s';
""".formatted(notes, username, id));
}
public String getNotes(String username, int id) throws SQLException {
Connection conn = dataSource.getConnection();
Statement statement = conn.createStatement();
ResultSet result = statement
.executeQuery("SELECT notes FROM notes WHERE username='%s' AND id=%s;".formatted(username, id));
result.next();
String notes = result.getString(1);
return notes;
}
public Set<Integer> getAllIds(String username) throws SQLException {
Connection conn = dataSource.getConnection();
Statement statement = conn.createStatement();
ResultSet result = statement
.executeQuery("SELECT id FROM notes WHERE username='%s';".formatted(username));
Set<Integer> ids = new HashSet<>();
while (result.next()) {
ids.add(result.getInt(1));
}
return ids;
}
}
// package jez.authentication2.services;
// import java.sql.Connection;
// import java.sql.ResultSet;
// import java.sql.SQLException;
// import java.sql.Statement;
// import javax.sql.DataSource;
// import org.springframework.beans.factory.annotation.Autowired;
// import org.springframework.stereotype.Service;
// import jez.authentication2.entities.User;
// import jez.authentication2.exceptions.DuplicateUsernameException;
// @Service
// public class UserService {
// @Autowired
// DataSource dataSource;
// public void addUser(User user) throws DuplicateUsernameException, SQLException {
// Connection conn = dataSource.getConnection();
// Statement statement = conn.createStatement();
// try {
// statement.executeUpdate("""
// INSERT INTO users (username, password, enabled) VALUES ('%s', '%s', '%s');
// """.formatted(user.getUsername(), user.getPassword(), user.isEnabled()));
// } catch (SQLException e) {
// e.printStackTrace();
// if (e.getErrorCode() == 0) {
// throw new DuplicateUsernameException();
// }
// }
// statement.executeUpdate("""
// INSERT INTO authorities (username, authority) VALUES ('%s', '%s');
// """.formatted(user.getUsername(), "ROLE_USER"));
// statement.executeUpdate("""
// INSERT INTO notes (username, notes)
// values ('%s', 'write notes here');
// """.formatted(user.getUsername()));
// }
// public User getUser(String username) throws SQLException {
// Connection conn = dataSource.getConnection();
// Statement statement = conn.createStatement();
// ResultSet result = statement
// .executeQuery("SELECT username, password, enabled, notes FROM users NATURAL JOIN notes WHERE username='%s';".formatted(username));
// result.next();
// return new User(result.getString(1), result.getString(2), result.getBoolean(3),
// result.getString(4));
// }
// }
insert into users (username, password, enabled)
values ('user', 'password', true);
insert into users (username, password, enabled, authority)
values ('user', 'password', true, 'ROLE_USER');
insert into notes (user_id, note)
values (1, 'some ...1');
insert into notes (user_id, note)
values (1, 'some notes ...2');
insert into users (username, password, enabled)
values ('admin', 'password', true);
insert into users (username, password, enabled, authority)
values ('admin', 'password', true, 'ROLE_ADMIN');
insert into authorities (username, authority)
values ('user', 'ROLE_USER');
-- insert into authorities (username, authority)
-- values ('user', 'ROLE_USER');
insert into authorities (username, authority)
values ('admin', 'ROLE_ADMIN');
-- insert into authorities (username, authority)
-- values ('admin', 'ROLE_ADMIN');
......@@ -3,19 +3,20 @@ create table users(
id serial primary key,
username varchar(50) not null unique,
password varchar(50) not null,
enabled boolean not null
enabled boolean not null,
authority varchar(10) not null
);
drop table if exists authorities cascade;
create table authorities (
username varchar(50) not null,
authority varchar(50) not null,
foreign key(username) references users(username)
);
-- drop table if exists authorities cascade;
-- create table authorities (
-- username varchar(50) not null,
-- authority varchar(50) not null,
-- foreign key(username) references users(username)
-- );
drop table if exists notes cascade;
create table notes (
id serial not null primary key,
id serial primary key,
note text,
user_id int not null,
foreign key(user_id) references users(id)
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment