Authenticate against Facebook
[examples/facebook-app] / src / main / java / de / juplo / yourshouter / HomeController.java
1 package de.juplo.yourshouter;
2
3 import javax.inject.Inject;
4 import org.slf4j.Logger;
5 import org.slf4j.LoggerFactory;
6
7 import org.springframework.social.facebook.api.Facebook;
8 import org.springframework.social.facebook.api.User;
9 import org.springframework.stereotype.Controller;
10 import org.springframework.ui.Model;
11 import org.springframework.web.bind.annotation.RequestMapping;
12 import org.springframework.web.bind.annotation.RequestMethod;
13
14
15 /**
16  * Controller, that handles the welcome-page.
17  *
18  * @author Kai Moritz
19  */
20 @Controller
21 @RequestMapping("/")
22 public class HomeController
23 {
24   private final static Logger LOG = LoggerFactory.getLogger(HomeController.class);
25
26
27   private final Facebook facebook;
28
29
30   @Inject
31   public HomeController(Facebook facebook)
32   {
33     this.facebook = facebook;
34   }
35
36
37   @RequestMapping(method = RequestMethod.GET)
38   public String home(Model model)
39   {
40     boolean authorized = true;
41     try
42     {
43       authorized = facebook.isAuthorized();
44     }
45     catch (NullPointerException e)
46     {
47       LOG.debug("NPE while acessing Facebook: {}", e);
48       authorized = false;
49     }
50     if (!authorized)
51     {
52       LOG.info("no authorized user, redirecting to /connect/facebook");
53       return "redirect:/connect/facebook";
54     }
55
56     User user = facebook.userOperations().getUserProfile();
57     LOG.info("authorized user {}, id: {}", user.getName(), user.getId());
58     model.addAttribute("user", user);
59     return "home";
60   }
61 }