1   package com.atlassian.plugins.rest.helloworld;
2   
3   import com.atlassian.plugins.rest.common.security.AnonymousAllowed;
4   import com.atlassian.plugins.rest.common.security.AuthenticationContext;
5   import com.atlassian.sal.api.net.Request;
6   import com.atlassian.sal.api.net.RequestFactory;
7   import com.atlassian.sal.api.net.ResponseException;
8   
9   import javax.ws.rs.GET;
10  import javax.ws.rs.Path;
11  import javax.ws.rs.Produces;
12  import javax.ws.rs.core.Context;
13  import java.security.Principal;
14  
15  @Path("/helloworld")
16  public class HelloWorld
17  {
18      private final RequestFactory requestFactory;
19  
20      public HelloWorld(RequestFactory requestFactory)
21      {
22          this.requestFactory = requestFactory;
23      }
24  
25      @GET
26      @Produces("text/plain")
27      @Path("/authenticated")
28      public String getAuthenticatedMessage()
29      {
30          return "Hello Authenticated World";
31      }
32  
33      @GET
34      @Produces("text/plain")
35      @Path("/callingself")
36      @AnonymousAllowed
37      public String getAnonymousMessageFromSelf() throws ResponseException
38      {
39          String baseUrl = System.getProperty("baseurl");
40          Request request = requestFactory.createRequest(Request.MethodType.GET, baseUrl + "/rest/refimpl/1/helloworld/anonymous");
41          return request.execute();
42      }
43  
44      @GET
45      @Produces("text/plain")
46      @Path("/anonymous")
47      @AnonymousAllowed
48      public String getAnonymousMessage()
49      {
50          return "Hello Anonymous World";
51      }
52  
53      @GET
54      @Produces("text/plain")
55      @Path("/admin")
56      @AnonymousAllowed
57      public String getMessageForAdmin(@Context AuthenticationContext authenticationContext)
58      {
59          checkIsUser(authenticationContext, "admin");
60          return "Hello " + authenticationContext.getPrincipal();
61      }
62  
63      private void checkIsUser(AuthenticationContext context, String userName)
64      {
65          final Principal principal = context.getPrincipal();
66          if (principal == null || !principal.getName().equals(userName))
67          {
68              throw new SecurityException("You're not '" + userName + "' I know who you really are'" + principal + "', you can't access this information");
69          }
70      }
71  }