Skip to content

Commit

Permalink
complete
Browse files Browse the repository at this point in the history
  • Loading branch information
Keesun Baik (a.k.a, Whiteship) committed Nov 10, 2018
1 parent 29e9c34 commit 3e50caf
Show file tree
Hide file tree
Showing 7 changed files with 86 additions and 8 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package me.whiteship.ksug201811restapi.accounts;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;

import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;


public class AccountAdapter extends User {

private Account account;

public AccountAdapter(Account account) {
super(account.getUsername(), account.getPassword(), authorities(account.getRoles()));
this.account = account;
}

private static Collection<? extends GrantedAuthority> authorities(Set<AccountRoles> roles) {
return roles.stream().map(r -> new SimpleGrantedAuthority("ROLE_" + r.name()))
.collect(Collectors.toSet());
}

public Account getAccount() {
return account;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package me.whiteship.ksug201811restapi.accounts;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;

public class AccountSerializer extends JsonSerializer<Account> {
@Override
public void serialize(Account account, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeStartObject();
jsonGenerator.writeNumberField("id", account.getId());
jsonGenerator.writeEndObject();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,10 @@ public class AccountService implements UserDetailsService {
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Optional<Account> accountOptional = this.accountRepository.findByUsername(username);
Account account = accountOptional.orElseThrow(() -> new UsernameNotFoundException(username));
return new User(account.getUsername(), account.getPassword(), authorities(account.getRoles()));
return new AccountAdapter(account);
}

private Collection<? extends GrantedAuthority> authorities(Set<AccountRoles> roles) {
return roles.stream().map(r -> new SimpleGrantedAuthority("ROLE_" + r.name()))
.collect(Collectors.toSet());
}


public void createAccount(Account account) {
account.setPassword(passwordEncoder.encode(account.getPassword()));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package me.whiteship.ksug201811restapi.events;

import org.springframework.security.core.annotation.AuthenticationPrincipal;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@AuthenticationPrincipal(expression = "#this == 'anonymousUser' ? null : account")
public @interface CurrentUser {
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package me.whiteship.ksug201811restapi.events;

import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.*;
import me.whiteship.ksug201811restapi.accounts.Account;
import me.whiteship.ksug201811restapi.accounts.AccountSerializer;

import javax.persistence.*;
import java.time.LocalDateTime;
Expand Down Expand Up @@ -29,6 +31,7 @@ public class Event {
private EventStatus eventStatus = EventStatus.DRAFT;

@ManyToOne
@JsonSerialize(using = AccountSerializer.class)
private Account owner;

public void update() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package me.whiteship.ksug201811restapi.events;

import me.whiteship.ksug201811restapi.accounts.Account;
import me.whiteship.ksug201811restapi.accounts.AccountAdapter;
import me.whiteship.ksug201811restapi.common.ErrorResource;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
Expand All @@ -10,6 +12,10 @@
import org.springframework.hateoas.MediaTypes;
import org.springframework.hateoas.PagedResources;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;

Expand All @@ -34,7 +40,8 @@ public class EventController {

@PostMapping
public ResponseEntity create(@RequestBody @Valid EventDto eventDto,
Errors errors) {
Errors errors,
@CurrentUser Account account) {
if (errors.hasErrors()) {
return ResponseEntity.badRequest().body(new ErrorResource(errors));
}
Expand All @@ -46,6 +53,7 @@ public ResponseEntity create(@RequestBody @Valid EventDto eventDto,

Event event = modelMapper.map(eventDto, Event.class);
event.update();
event.setOwner(account);

Event savedEvent = eventRepository.save(event);
URI uri = linkTo(EventController.class).slash(savedEvent.getId()).toUri();
Expand All @@ -57,22 +65,32 @@ public ResponseEntity create(@RequestBody @Valid EventDto eventDto,
}

@GetMapping
public ResponseEntity getEvents(Pageable pageable, PagedResourcesAssembler<Event> assembler) {
public ResponseEntity getEvents(Pageable pageable,
PagedResourcesAssembler<Event> assembler,
@CurrentUser Account account) {
Page<Event> page = this.eventRepository.findAll(pageable);
PagedResources<EventResource> pagedResources = assembler.toResource(page, e -> new EventResource(e));
if (account != null) {
pagedResources.add(linkTo(EventController.class).withRel("create"));
}
return ResponseEntity.ok(pagedResources);
}


@GetMapping("/{id}")
public ResponseEntity getEvent(@PathVariable Integer id) {
public ResponseEntity getEvent(@PathVariable Integer id,
@CurrentUser Account account) {
Optional<Event> byId = this.eventRepository.findById(id);
if (byId.isEmpty()) {
return ResponseEntity.notFound().build();
}

Event event = byId.get();
EventResource eventResource = new EventResource(event);

if (event.getOwner().equals(account)) {
eventResource.add(linkTo(EventController.class).slash(event.getId()).withRel("update"));
}
return ResponseEntity.ok(eventResource);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ public void getEvents() throws Exception {

// When & Then
this.mockMvc.perform(get("/api/events")
// .header(HttpHeaders.AUTHORIZATION, "bearer " + getAccessToken())
.param("size", "10")
.param("page", "1"))
.andDo(print())
Expand Down

0 comments on commit 3e50caf

Please sign in to comment.