Skip to content

Commit ee57f47

Browse files
committed
ApiServlet: use the new and refactored authentication mechanism
Signed-off-by: Rohit Yadav <rohit.yadav@shapeblue.com>
1 parent 2e5bbc9 commit ee57f47

1 file changed

Lines changed: 62 additions & 189 deletions

File tree

‎server/src/com/cloud/api/ApiServlet.java‎

100755100644
Lines changed: 62 additions & 189 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,22 @@
1616
// under the License.
1717
package com.cloud.api;
1818

19-
import java.io.IOException;
20-
import java.io.UnsupportedEncodingException;
21-
import java.net.URLDecoder;
22-
import java.util.Enumeration;
23-
import java.util.HashMap;
24-
import java.util.Map;
19+
import com.cloud.api.auth.APIAuthenticationManager;
20+
import com.cloud.api.auth.APIAuthenticationType;
21+
import com.cloud.api.auth.APIAuthenticator;
22+
import com.cloud.user.Account;
23+
import com.cloud.user.AccountService;
24+
import com.cloud.user.User;
25+
import com.cloud.utils.StringUtils;
26+
import com.cloud.utils.db.EntityManager;
27+
import org.apache.cloudstack.api.ApiConstants;
28+
import org.apache.cloudstack.api.BaseCmd;
29+
import org.apache.cloudstack.api.ServerApiException;
30+
import org.apache.cloudstack.context.CallContext;
31+
import org.apache.cloudstack.managed.context.ManagedContext;
32+
import org.apache.log4j.Logger;
33+
import org.springframework.stereotype.Component;
34+
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
2535

2636
import javax.inject.Inject;
2737
import javax.servlet.ServletConfig;
@@ -30,24 +40,11 @@
3040
import javax.servlet.http.HttpServletRequest;
3141
import javax.servlet.http.HttpServletResponse;
3242
import javax.servlet.http.HttpSession;
33-
34-
import org.apache.log4j.Logger;
35-
import org.springframework.stereotype.Component;
36-
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
37-
38-
import org.apache.cloudstack.api.ApiConstants;
39-
import org.apache.cloudstack.api.ApiErrorCode;
40-
import org.apache.cloudstack.api.BaseCmd;
41-
import org.apache.cloudstack.api.ServerApiException;
42-
import org.apache.cloudstack.context.CallContext;
43-
import org.apache.cloudstack.managed.context.ManagedContext;
44-
45-
import com.cloud.exception.CloudAuthenticationException;
46-
import com.cloud.user.Account;
47-
import com.cloud.user.AccountService;
48-
import com.cloud.user.User;
49-
import com.cloud.utils.StringUtils;
50-
import com.cloud.utils.db.EntityManager;
43+
import java.io.IOException;
44+
import java.io.UnsupportedEncodingException;
45+
import java.net.URLDecoder;
46+
import java.util.HashMap;
47+
import java.util.Map;
5148

5249
@Component("apiServlet")
5350
@SuppressWarnings("serial")
@@ -63,6 +60,8 @@ public class ApiServlet extends HttpServlet {
6360
EntityManager _entityMgr;
6461
@Inject
6562
ManagedContext _managedContext;
63+
@Inject
64+
APIAuthenticationManager _authManager;
6665

6766
public ApiServlet() {
6867
}
@@ -121,8 +120,9 @@ public void run() {
121120
}
122121

123122
void processRequestInContext(final HttpServletRequest req, final HttpServletResponse resp) {
123+
final String remoteAddress = req.getRemoteAddr();
124124
final StringBuilder auditTrailSb = new StringBuilder(128);
125-
auditTrailSb.append(" ").append(req.getRemoteAddr());
125+
auditTrailSb.append(" ").append(remoteAddress);
126126
auditTrailSb.append(" -- ").append(req.getMethod()).append(' ');
127127
// get the response format since we'll need it in a couple of places
128128
String responseType = BaseCmd.RESPONSE_TYPE_XML;
@@ -151,107 +151,56 @@ void processRequestInContext(final HttpServletRequest req, final HttpServletResp
151151

152152
final Object[] commandObj = params.get(ApiConstants.COMMAND);
153153
if (commandObj != null) {
154-
final String command = (String)commandObj[0];
155-
if ("logout".equalsIgnoreCase(command)) {
156-
// if this is just a logout, invalidate the session and return
157-
if (session != null) {
158-
final Long userId = (Long)session.getAttribute("userid");
159-
final Account account = (Account)session.getAttribute("accountobj");
160-
Long accountId = null;
161-
if (account != null) {
162-
accountId = account.getId();
163-
}
164-
auditTrailSb.insert(0, "(userId=" + userId + " accountId=" + accountId + " sessionId=" + session.getId() + ")");
165-
if (userId != null) {
166-
_apiServer.logoutUser(userId);
167-
}
168-
try {
169-
session.invalidate();
170-
} catch (final IllegalStateException ise) {
171-
}
172-
}
173-
auditTrailSb.append("command=logout");
174-
auditTrailSb.append(" ").append(HttpServletResponse.SC_OK);
175-
writeResponse(resp, getLogoutSuccessResponse(responseType), HttpServletResponse.SC_OK, responseType);
176-
return;
177-
} else if ("login".equalsIgnoreCase(command)) {
178-
auditTrailSb.append("command=login");
179-
// if this is a login, authenticate the user and return
180-
if (session != null) {
181-
try {
182-
session.invalidate();
183-
} catch (final IllegalStateException ise) {
184-
}
185-
}
186-
session = req.getSession(true);
187-
final String[] username = (String[])params.get(ApiConstants.USERNAME);
188-
final String[] password = (String[])params.get(ApiConstants.PASSWORD);
189-
String[] domainIdArr = (String[])params.get(ApiConstants.DOMAIN_ID);
154+
final String command = (String) commandObj[0];
190155

191-
if (domainIdArr == null) {
192-
domainIdArr = (String[])params.get(ApiConstants.DOMAIN__ID);
193-
}
194-
final String[] domainName = (String[])params.get(ApiConstants.DOMAIN);
195-
Long domainId = null;
196-
if ((domainIdArr != null) && (domainIdArr.length > 0)) {
197-
try {
198-
//check if UUID is passed in for domain
199-
domainId = _apiServer.fetchDomainId(domainIdArr[0]);
200-
if (domainId == null) {
201-
domainId = Long.parseLong(domainIdArr[0]);
156+
APIAuthenticator apiAuthenticator = _authManager.getAPIAuthenticator(command);
157+
if (apiAuthenticator != null) {
158+
auditTrailSb.append("command=");
159+
auditTrailSb.append(command);
160+
161+
int httpResponseCode = HttpServletResponse.SC_OK;
162+
String responseString = null;
163+
164+
if (apiAuthenticator.getAPIType() == APIAuthenticationType.LOGIN_API) {
165+
if (session != null) {
166+
try {
167+
session.invalidate();
168+
} catch (final IllegalStateException ise) {
202169
}
203-
auditTrailSb.append(" domainid=" + domainId);// building the params for POST call
204-
} catch (final NumberFormatException e) {
205-
s_logger.warn("Invalid domain id entered by user");
206-
auditTrailSb.append(" " + HttpServletResponse.SC_UNAUTHORIZED + " " + "Invalid domain id entered, please enter a valid one");
207-
final String serializedResponse =
208-
_apiServer.getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid domain id entered, please enter a valid one", params,
209-
responseType);
210-
writeResponse(resp, serializedResponse, HttpServletResponse.SC_UNAUTHORIZED, responseType);
211170
}
171+
session = req.getSession(true);
172+
}
173+
174+
try {
175+
responseString = apiAuthenticator.authenticate(command, params, session, remoteAddress, responseType, auditTrailSb);
176+
} catch (ServerApiException e) {
177+
httpResponseCode = e.getErrorCode().getHttpCode();
178+
responseString = e.getMessage();
179+
s_logger.debug("Authentication failure: " + e.getMessage());
212180
}
213-
String domain = null;
214-
if (domainName != null) {
215-
domain = domainName[0];
216-
auditTrailSb.append(" domain=" + domain);
217-
if (domain != null) {
218-
// ensure domain starts with '/' and ends with '/'
219-
if (!domain.endsWith("/")) {
220-
domain += '/';
181+
if (apiAuthenticator.getAPIType() == APIAuthenticationType.LOGOUT_API) {
182+
if (session != null) {
183+
final Long userId = (Long) session.getAttribute("userid");
184+
final Account account = (Account) session.getAttribute("accountobj");
185+
Long accountId = null;
186+
if (account != null) {
187+
accountId = account.getId();
221188
}
222-
if (!domain.startsWith("/")) {
223-
domain = "/" + domain;
189+
auditTrailSb.insert(0, "(userId=" + userId + " accountId=" + accountId + " sessionId=" + session.getId() + ")");
190+
if (userId != null) {
191+
_apiServer.logoutUser(userId);
224192
}
225-
}
226-
}
227-
228-
if (username != null) {
229-
final String pwd = ((password == null) ? null : password[0]);
230-
try {
231-
_apiServer.loginUser(session, username[0], pwd, domainId, domain, req.getRemoteAddr(), params);
232-
auditTrailSb.insert(0, "(userId=" + session.getAttribute("userid") + " accountId=" + ((Account)session.getAttribute("accountobj")).getId() +
233-
" sessionId=" + session.getId() + ")");
234-
final String loginResponse = getLoginSuccessResponse(session, responseType);
235-
writeResponse(resp, loginResponse, HttpServletResponse.SC_OK, responseType);
236-
return;
237-
} catch (final CloudAuthenticationException ex) {
238-
// TODO: fall through to API key, or just fail here w/ auth error? (HTTP 401)
239193
try {
240194
session.invalidate();
241-
} catch (final IllegalStateException ise) {
195+
} catch (final IllegalStateException ignored) {
242196
}
243-
244-
auditTrailSb.append(" " + ApiErrorCode.ACCOUNT_ERROR + " " + ex.getMessage() != null ? ex.getMessage()
245-
: "failed to authenticate user, check if username/password are correct");
246-
final String serializedResponse =
247-
_apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), ex.getMessage() != null ? ex.getMessage()
248-
: "failed to authenticate user, check if username/password are correct", params, responseType);
249-
writeResponse(resp, serializedResponse, ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), responseType);
250-
return;
251197
}
252198
}
199+
writeResponse(resp, responseString, httpResponseCode, responseType);
200+
return;
253201
}
254202
}
203+
255204
auditTrailSb.append(req.getQueryString());
256205
final boolean isNew = ((session == null) ? true : session.isNew());
257206

@@ -371,80 +320,4 @@ private void writeResponse(final HttpServletResponse resp, final String response
371320
}
372321
}
373322

374-
@SuppressWarnings("rawtypes")
375-
String getLoginSuccessResponse(final HttpSession session, final String responseType) {
376-
final StringBuilder sb = new StringBuilder();
377-
final int inactiveInterval = session.getMaxInactiveInterval();
378-
379-
final String user_UUID = (String)session.getAttribute("user_UUID");
380-
session.removeAttribute("user_UUID");
381-
382-
final String domain_UUID = (String)session.getAttribute("domain_UUID");
383-
session.removeAttribute("domain_UUID");
384-
385-
if (BaseCmd.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) {
386-
sb.append("{ \"loginresponse\" : { ");
387-
final Enumeration attrNames = session.getAttributeNames();
388-
if (attrNames != null) {
389-
sb.append("\"timeout\" : \"").append(inactiveInterval).append("\"");
390-
while (attrNames.hasMoreElements()) {
391-
final String attrName = (String)attrNames.nextElement();
392-
if ("userid".equalsIgnoreCase(attrName)) {
393-
sb.append(", \"" + attrName + "\" : \"" + user_UUID + "\"");
394-
} else if ("domainid".equalsIgnoreCase(attrName)) {
395-
sb.append(", \"" + attrName + "\" : \"" + domain_UUID + "\"");
396-
} else {
397-
final Object attrObj = session.getAttribute(attrName);
398-
if ((attrObj instanceof String) || (attrObj instanceof Long)) {
399-
sb.append(", \"" + attrName + "\" : \"" + attrObj.toString() + "\"");
400-
}
401-
}
402-
}
403-
}
404-
sb.append(" } }");
405-
} else {
406-
sb.append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
407-
sb.append("<loginresponse cloud-stack-version=\"").append(ApiDBUtils.getVersion()).append("\">");
408-
sb.append("<timeout>").append(inactiveInterval).append("</timeout>");
409-
final Enumeration attrNames = session.getAttributeNames();
410-
if (attrNames != null) {
411-
while (attrNames.hasMoreElements()) {
412-
final String attrName = (String)attrNames.nextElement();
413-
if (ApiConstants.USER_ID.equalsIgnoreCase(attrName)) {
414-
sb.append("<").append(attrName).append(">")
415-
.append(user_UUID).append("</")
416-
.append(attrName).append(">");
417-
} else if ("domainid".equalsIgnoreCase(attrName)) {
418-
sb.append("<").append(attrName).append(">")
419-
.append(domain_UUID).append("</")
420-
.append(attrName).append(">");
421-
} else {
422-
final Object attrObj = session.getAttribute(attrName);
423-
if (attrObj instanceof String || attrObj instanceof Long || attrObj instanceof Short) {
424-
sb.append("<").append(attrName).append(">")
425-
.append(attrObj.toString()).append("</")
426-
.append(attrName).append(">");
427-
}
428-
}
429-
}
430-
}
431-
432-
sb.append("</loginresponse>");
433-
}
434-
return sb.toString();
435-
}
436-
437-
private String getLogoutSuccessResponse(final String responseType) {
438-
final StringBuilder sb = new StringBuilder();
439-
if (BaseCmd.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) {
440-
sb.append("{ \"logoutresponse\" : { \"description\" : \"success\" } }");
441-
} else {
442-
sb.append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
443-
sb.append("<logoutresponse cloud-stack-version=\"").append(ApiDBUtils.getVersion()).append("\">");
444-
sb.append("<description>success</description>");
445-
sb.append("</logoutresponse>");
446-
}
447-
return sb.toString();
448-
}
449-
450323
}

0 commit comments

Comments
 (0)