Commit cdf3304f authored by Spiros Koulouzis's avatar Spiros Koulouzis

Make password write only

Added exeptions 
parent ce2a5b04
......@@ -100,6 +100,7 @@
<scope>test</scope>
<type>jar</type>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
......
......@@ -34,6 +34,7 @@ public class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoi
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authEx)
throws IOException, ServletException {
// super.commence(request, response, authEx);
response.addHeader("WWW-Authenticate", "Basic realm=" + getRealmName() + "");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
......@@ -43,7 +44,7 @@ public class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoi
@Override
public void afterPropertiesSet() throws Exception {
setRealmName("DRIPs");
setRealmName("DRIP");
super.afterPropertiesSet();
}
}
......@@ -21,8 +21,6 @@ import nl.uva.sne.drip.api.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.BeanIds;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
......@@ -44,8 +42,6 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserService userService;
// @Autowired
// BasicAuthenticationFilter authenticationFilter;
@Autowired
private MyBasicAuthenticationEntryPoint authenticationEntryPoint;
......@@ -56,10 +52,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// http.authorizeRequests().antMatchers("/**").hasRole("USER");
// http.csrf().disable();
http
// .addFilterBefore(authenticationFilter, BasicAuthenticationFilter.class)
.csrf().disable()
.authorizeRequests()
.antMatchers("/user/*").hasRole("USER")
......@@ -82,5 +75,4 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
return encoder;
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
*
* @author S. Koulouzis
*/
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public class BadRequestException extends RuntimeException {
public BadRequestException(String massage) {
super(massage);
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
*
* @author S. Koulouzis
*/
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class NotFoundException extends RuntimeException {
public NotFoundException(String string) {
super(string);
}
public NotFoundException() {
super();
}
}
......@@ -15,9 +15,13 @@
*/
package nl.uva.sne.drip.api.rest;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.security.RolesAllowed;
import nl.uva.sne.drip.api.exception.BadRequestException;
import nl.uva.sne.drip.api.exception.NotFoundException;
import nl.uva.sne.drip.commons.types.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
......@@ -27,12 +31,14 @@ import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import nl.uva.sne.drip.api.service.UserService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
/**
*
* @author S. Koulouzis
*/
//@CrossOrigin(origins = "http://domain2.com", maxAge = 3600)
@RestController
@RequestMapping("/manager/user/")
@Component
......@@ -44,7 +50,30 @@ public class UserController {
@RequestMapping(value = "/register", method = RequestMethod.POST)
@RolesAllowed({UserService.ADMIN})
public @ResponseBody
String register(User user) {
String register(@RequestBody User user) {
if (user.getUsername() == null) {
throw new BadRequestException("Username can't be null");
}
if (user.getPassword() == null) {
throw new BadRequestException("Password can't be null");
}
UserDetails registeredUser = service.loadUserByUsername(user.getUsername());
if (registeredUser != null) {
throw new BadRequestException("Username " + user.getUsername() + " is used");
}
user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
service.getDao().save(user);
return user.getId();
}
@RequestMapping(value = "/modify", method = RequestMethod.POST)
@RolesAllowed({UserService.ADMIN})
public @ResponseBody
String modify(@RequestBody User user) {
UserDetails registeredUser = service.loadUserByUsername(user.getUsername());
if (registeredUser == null) {
throw new NotFoundException("User " + user.getUsername() + " not found");
}
service.getDao().save(user);
return user.getId();
}
......@@ -54,7 +83,57 @@ public class UserController {
public @ResponseBody
User get(@PathVariable("id") String id) {
try {
return service.getDao().findOne(id);
User user = service.getDao().findOne(id);
if (user == null) {
throw new NotFoundException();
}
return user;
} catch (Exception ex) {
Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
@RolesAllowed({UserService.ADMIN})
public @ResponseBody
String remove(@PathVariable("id") String id) {
try {
User user = service.getDao().findOne(id);
if (user == null) {
throw new NotFoundException();
}
service.getDao().delete(user);
return "Deleted used :" + id;
} catch (Exception ex) {
Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
@RequestMapping(value = "/ids", method = RequestMethod.GET)
@RolesAllowed({UserService.ADMIN})
public @ResponseBody
List<String> getIds() {
try {
List<User> all = service.getDao().findAll();
List<String> ids = new ArrayList<>();
for (User tr : all) {
ids.add(tr.getId());
}
return ids;
} catch (Exception ex) {
Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
@RequestMapping(value = "/all", method = RequestMethod.GET)
@RolesAllowed({UserService.ADMIN})
public @ResponseBody
List<User> getAll() {
try {
return service.getDao().findAll();
} catch (Exception ex) {
Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
}
......
......@@ -15,6 +15,8 @@
*/
package nl.uva.sne.drip.api.service;
import java.util.Collection;
import java.util.HashSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import nl.uva.sne.drip.api.dao.UserDao;
......@@ -23,6 +25,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
/**
......@@ -41,33 +44,6 @@ public class UserService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
try {
// dao.deleteAll();
// User u = new User();
// u.setAccountNonExpired(true);
// u.setAccountNonLocked(true);
// Collection<GrantedAuthority> athorities = new HashSet<>();
// GrantedAuthority ga = new SimpleGrantedAuthority("ROLE_USER");
// athorities.add(ga);
// u.setAthorities(athorities);
// u.setCredentialsNonExpired(true);
// u.setEnabled(true);
// u.setPassword(new BCryptPasswordEncoder().encode("123"));
// u.setUsername(username);
// dao.save(u);
//
// User u2 = new User();
// u2.setAccountNonExpired(true);
// u2.setAccountNonLocked(true);
// athorities = new HashSet<>();
// ga = new SimpleGrantedAuthority("ROLE_ADMIN");
// athorities.add(ga);
// u2.setAthorities(athorities);
// u2.setCredentialsNonExpired(true);
// u2.setEnabled(true);
// u2.setPassword(new BCryptPasswordEncoder().encode("admin"));
// u2.setUsername("admin");
// dao.save(u2);
User user = dao.findByUsername(username);
return user;
} catch (Exception ex) {
......
......@@ -15,25 +15,33 @@
*/
package nl.uva.sne.drip.commons.types;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonProperty.Access;
import java.util.Collection;
import java.util.HashSet;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
/**
*
* @author S. Koulouzis
*/
@JsonIgnoreProperties({"password"})
@Document
public class User implements UserDetails {
@Id
private String id;
private Collection<? extends GrantedAuthority> athorities;
private Collection<String> roles;
@JsonProperty(access = Access.WRITE_ONLY)
private String password;
@Indexed
private String username;
private boolean accountNonExpired;
private boolean accountNonLocked;
......@@ -55,8 +63,19 @@ public class User implements UserDetails {
}
@Override
@JsonIgnore
public Collection<? extends GrantedAuthority> getAuthorities() {
return this.athorities;
Collection<GrantedAuthority> athorities = new HashSet<>();
if (roles != null) {
for (String role : roles) {
String addedRole = role;
if (!role.startsWith("ROLE_")) {
addedRole = "ROLE_" + role;
}
athorities.add(new SimpleGrantedAuthority(addedRole));
}
}
return athorities;
}
@Override
......@@ -89,13 +108,6 @@ public class User implements UserDetails {
return this.enabled;
}
/**
* @param athorities the athorities to set
*/
public void setAthorities(Collection<? extends GrantedAuthority> athorities) {
this.athorities = athorities;
}
/**
* @param password the password to set
*/
......@@ -138,4 +150,18 @@ public class User implements UserDetails {
this.enabled = enabled;
}
/**
* @return the roles
*/
public Collection<String> getRoles() {
return roles;
}
/**
* @param roles the roles to set
*/
public void setRoles(Collection<String> roles) {
this.roles = roles;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment