22
33import com .okta .developer .jugtours .model .Group ;
44import com .okta .developer .jugtours .model .GroupRepository ;
5+ import com .okta .developer .jugtours .model .User ;
56import org .slf4j .Logger ;
67import org .slf4j .LoggerFactory ;
78import org .springframework .http .HttpStatus ;
89import org .springframework .http .ResponseEntity ;
10+ import org .springframework .security .core .context .SecurityContextHolder ;
11+ import org .springframework .security .oauth2 .provider .OAuth2Authentication ;
912import org .springframework .web .bind .annotation .*;
1013
1114import javax .validation .Valid ;
1215import java .net .URI ;
1316import java .net .URISyntaxException ;
17+ import java .security .Principal ;
1418import java .util .Collection ;
19+ import java .util .Map ;
1520import java .util .Optional ;
1621
1722@ RestController
@@ -26,8 +31,8 @@ public GroupController(GroupRepository repository) {
2631 }
2732
2833 @ GetMapping ("/groups" )
29- Collection <Group > groups () {
30- return repository .findAll ( );
34+ Collection <Group > groups (Principal principal ) {
35+ return repository .findAllByUserName ( principal . getName () );
3136 }
3237
3338 @ GetMapping ("/group/{id}" )
@@ -38,8 +43,13 @@ ResponseEntity<?> getGroup(@PathVariable Long id) {
3843 }
3944
4045 @ PostMapping ("/group" )
41- ResponseEntity <Group > createGroup (@ Valid @ RequestBody Group group ) throws URISyntaxException {
46+ ResponseEntity <Group > createGroup (@ Valid @ RequestBody Group group , Principal principal ) throws URISyntaxException {
4247 log .info ("Request to create group: {}" , group );
48+ OAuth2Authentication authentication = (OAuth2Authentication ) principal ;
49+ Map <String , Object > details = (Map <String , Object >) authentication .getUserAuthentication ().getDetails ();
50+ User user = new User (details .get ("sub" ).toString (),
51+ details .get ("name" ).toString (), details .get ("email" ).toString ());
52+ group .setUser (user );
4353 Group result = repository .save (group );
4454 return ResponseEntity .created (new URI ("/api/group/" + result .getId ()))
4555 .body (result );
0 commit comments