Skip to content
Snippets Groups Projects
Commit d581ab85 authored by Ondřej Trojan's avatar Ondřej Trojan
Browse files

integrace roli pro uzivatele

parent 64aad3c7
No related branches found
No related tags found
No related merge requests found
package com.museum.projection.controller;
import com.museum.projection.service.MainService;
import com.museum.projection.service.ResponseService;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
......@@ -14,12 +16,14 @@ public class PageController {
@Resource()
public ResponseService responseService;
@Resource()
public MainService mainService;
@GetMapping
public String Index(Principal principal, Model model) {
if(principal != null) {
model.addAttribute("name",principal.getName());
public String Index(Authentication authentication, Principal principal, Model model) {
if (authentication != null) {
var details = authentication.getDetails();
mainService.populateForAdmin(principal, model);
return "main";
}
return "index";
......@@ -31,5 +35,4 @@ public class PageController {
}
}
......@@ -3,14 +3,15 @@ package com.museum.projection.dao;
import com.museum.projection.model.Account;
import com.museum.projection.security.ApplicationUser;
import com.museum.projection.security.ApplicationUserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.*;
import java.util.stream.Collectors;
import static com.museum.projection.security.ApplicationUserRole.*;
......@@ -37,10 +38,10 @@ public class PostgresApplicationUserDaoService implements ApplicationUserDao {
}
private List<ApplicationUser> getApplicationUsers() {
List<ApplicationUser> applicationUsers = getAccounts().stream().map(x -> new ApplicationUser(
ADMIN.getGrantedAuthorities(),
x.getPassword(),
x.getUsername(),
List<ApplicationUser> applicationUsers = getAccounts().stream().map(account -> new ApplicationUser(
Arrays.stream(account.getRoles().split(",")).map(role -> ApplicationUserRole.valueOf(role).getGrantedAuthorities()).findFirst().orElse(Collections.emptySet()),
account.getPassword(),
account.getUsername(),
true,
true,
true,
......@@ -49,14 +50,13 @@ public class PostgresApplicationUserDaoService implements ApplicationUserDao {
}
private List<Account> getAccounts() {
final String sql = "SELECT id, username, password FROM account";
final String sql = "SELECT id, username, password, roles FROM account";
List<Account> accounts = jdbcTemplate.query(sql, (resultSet, i) -> {
UUID id = UUID.fromString(resultSet.getString("id"));
String name = resultSet.getString("username");
String password = resultSet.getString("password");
return new Account(id, name, password);
return new Account(UUID.fromString(resultSet.getString("id")),
resultSet.getString("username"),
resultSet.getString("password"),
resultSet.getString("roles"));
});
return accounts;
}
}
\ No newline at end of file
......@@ -16,10 +16,13 @@ public class Account {
@NotBlank
private final String password;
public Account(@JsonProperty("id") UUID id, @JsonProperty("username") String username, @JsonProperty("password") String password) {
private final String roles;
public Account(@JsonProperty("id") UUID id, @JsonProperty("username") String username, @JsonProperty("password") String password, @JsonProperty("roles") String roles) {
this.id = id;
this.username = username;
this.password = password;
this.roles = roles;
}
public UUID getId() {
......@@ -34,4 +37,8 @@ public class Account {
public String getPassword() {
return password;
}
public String getRoles() {
return roles;
}
}
package com.museum.projection.service;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import java.security.Principal;
@Service
public class MainService {
// @PreAuthorize("hasRole('ROLE_ADMIN')")
public Model populateForAdmin(Principal principal, Model model) {
model.addAttribute("name", principal.getName());
return model;
}
}
......@@ -3,8 +3,11 @@ DROP TABLE IF EXISTS account;
CREATE TABLE account (
id UUID NOT NULL PRIMARY KEY,
username VARCHAR(100) NOT NULL,
password VARCHAR(100) NOT NULL
password VARCHAR(100) NOT NULL,
roles VARCHAR(100)
);
CREATE EXTENSION "uuid-ossp";
INSERT INTO account (id,username,password) VALUES (uuid_generate_v4(),'admin','$2a$10$2DAipSvgd75ir6BZ3a7NiOHRwi5sEWr9AP5yDO65034aZjZnc2f8e');
INSERT INTO account (id,username,password,roles) VALUES (uuid_generate_v4(),'admin','$2a$10$2DAipSvgd75ir6BZ3a7NiOHRwi5sEWr9AP5yDO65034aZjZnc2f8e','ADMIN');
INSERT INTO account (id,username,password,roles) VALUES (uuid_generate_v4(),'user1','$2a$10$2DAipSvgd75ir6BZ3a7NiOHRwi5sEWr9AP5yDO65034aZjZnc2f8e','STUDENT');
INSERT INTO account (id,username,password,roles) VALUES (uuid_generate_v4(),'user2','$2a$10$2DAipSvgd75ir6BZ3a7NiOHRwi5sEWr9AP5yDO65034aZjZnc2f8e','ADMIN,STUDENT');
......@@ -4,47 +4,48 @@ var form = document.querySelector('.form-signin');
var token
var serverUrl = 'http://localhost:8080';
var alertbox = document.querySelector('.alert-message-box');
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
const sendHttpRequest = (method, url, data) => {
const promise = new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(method,url)
console.log("data "+ data)
if(data){
xhr.setRequestHeader('Content-Type', 'application/json');
}
xhr.onload = () => {
if(xhr.status > 400){
reject(xhr.response)
} else {
resolve(xhr)
const xhr = new XMLHttpRequest();
xhr.open(method, url)
console.log("data " + data)
if (data) {
xhr.setRequestHeader('Content-Type', 'application/json');
}
};
xhr.onerror = () => {
reject('Something went wrong check the backend log')
};
xhr.send(JSON.stringify(data));
xhr.onload = () => {
if (xhr.status > 400) {
reject(xhr.response)
} else {
resolve(xhr)
}
};
xhr.onerror = () => {
reject('Something went wrong check the backend log')
};
xhr.send(JSON.stringify(data));
});
return promise;
}
const formLogin = (event) => {
alertbox.innerHTML = '';
console.log(event)
sendHttpRequest('POST', serverUrl +'/login', {
"username": document.querySelector('#username').value,
"password": document.querySelector('#password').value
}).then(xhr =>{
alertbox.innerHTML = '';
console.log(event)
sendHttpRequest('POST', serverUrl + '/login', {
"username": document.querySelector('#username').value,
"password": document.querySelector('#password').value
}).then(xhr => {
alertbox.innerHTML = '';
token= xhr.getResponseHeader("Authorization");
document.cookie = "Authorization="+token;
token = xhr.getResponseHeader("Authorization");
document.cookie = "Authorization=" + token;
window.location.replace(serverUrl);
}).catch(err => {
alertbox.insertAdjacentHTML('beforeend', '<div class="alert alert-danger" role="alert">Wrong username or password</div>');
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment