1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.springframework.extensions.webscripts.connector;
20
21 import java.text.MessageFormat;
22
23 import org.apache.commons.logging.Log;
24 import org.apache.commons.logging.LogFactory;
25 import org.json.JSONException;
26 import org.json.JSONObject;
27 import org.springframework.extensions.surf.exception.AuthenticationException;
28 import org.springframework.extensions.webscripts.json.JSONWriter;
29
30
31
32
33
34
35
36
37
38
39
40
41
42 public class AlfrescoAuthenticator extends AbstractAuthenticator
43 {
44 private static Log logger = LogFactory.getLog(AlfrescoAuthenticator.class);
45
46 private static final String JSON_lOGIN = "'{'\"username\": \"{0}\", \"password\": \"{1}\"'}'";
47 private static final String API_LOGIN = "/api/login";
48 private static final String MIMETYPE_APPLICATION_JSON = "application/json";
49
50 public final static String CS_PARAM_ALF_TICKET = "alfTicket";
51
52
53
54
55
56 public ConnectorSession authenticate(String endpoint, Credentials credentials, ConnectorSession connectorSession)
57 throws AuthenticationException
58 {
59 ConnectorSession cs = null;
60
61 if (credentials != null)
62 {
63
64 RemoteClient remoteClient = new RemoteClient(endpoint);
65
66
67 String user = (String) credentials.getProperty(Credentials.CREDENTIAL_USERNAME);
68 String pass = (String) credentials.getProperty(Credentials.CREDENTIAL_PASSWORD);
69
70 if (logger.isDebugEnabled())
71 logger.debug("Authenticating user: " + user);
72
73
74 remoteClient.setRequestContentType(MIMETYPE_APPLICATION_JSON);
75 String body = MessageFormat.format(JSON_lOGIN, JSONWriter.encodeJSONString(user), JSONWriter.encodeJSONString(pass));
76 Response response = remoteClient.call(API_LOGIN, body);
77
78
79 if (response.getStatus().getCode() == 200)
80 {
81 String ticket;
82 try
83 {
84 JSONObject json = new JSONObject(response.getResponse());
85 ticket = json.getJSONObject("data").getString("ticket");
86 }
87 catch (JSONException jErr)
88 {
89
90
91 throw new AuthenticationException(
92 "Unable to retrieve login ticket from Alfresco", jErr);
93 }
94
95 if (logger.isDebugEnabled())
96 logger.debug("Parsed ticket: " + ticket);
97
98
99 if (connectorSession != null)
100 {
101 connectorSession.setParameter(CS_PARAM_ALF_TICKET, ticket);
102
103
104 cs = connectorSession;
105 }
106 }
107 else
108 {
109 if (logger.isDebugEnabled())
110 logger.debug("Authentication failed, received response code: " + response.getStatus().getCode());
111 }
112 }
113 else if (logger.isDebugEnabled())
114 {
115 logger.debug("No user credentials available - cannot authenticate.");
116 }
117
118 return cs;
119 }
120
121
122
123
124 public boolean isAuthenticated(String endpoint, ConnectorSession connectorSession)
125 {
126 return (connectorSession.getParameter(CS_PARAM_ALF_TICKET) != null);
127 }
128 }