use of fi.otavanopisto.pyramus.plugin.auth.AuthenticationException in project pyramus by otavanopisto.
the class OpenIDAuthorizationStrategy method processResponse.
@SuppressWarnings("unchecked")
public User processResponse(RequestContext requestContext) throws AuthenticationException {
UserDAO userDAO = DAOFactory.getInstance().getUserDAO();
try {
HttpSession session = requestContext.getRequest().getSession();
// extract the parameters from the authentication response
// (which comes in as a HTTP request from the OpenID provider)
ParameterList openidResp = new ParameterList(requestContext.getRequest().getParameterMap());
// retrieve the previously stored discovery information
DiscoveryInformation discovered = (DiscoveryInformation) session.getAttribute("discovered");
// extract the receiving URL from the HTTP request
StringBuffer receivingURL = requestContext.getRequest().getRequestURL();
String queryString = requestContext.getRequest().getQueryString();
if (queryString != null && queryString.length() > 0) {
receivingURL.append("?").append(requestContext.getRequest().getQueryString());
}
// verify the response
VerificationResult verification = consumerManager.verify(receivingURL.toString(), openidResp, discovered);
// examine the verification result and extract the verified identifier
Identifier verified = verification.getVerifiedId();
if (verified != null) {
AuthSuccess authSuccess = (AuthSuccess) verification.getAuthResponse();
List<String> emails = null;
if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) {
FetchResponse fetchResp = (FetchResponse) authSuccess.getExtension(AxMessage.OPENID_NS_AX);
emails = fetchResp.getAttributeValues("email");
}
UserVariableDAO userVariableDAO = DAOFactory.getInstance().getUserVariableDAO();
User user = userDAO.findByExternalIdAndAuthProvider(verified.getIdentifier(), getName());
if (user == null) {
user = userDAO.findByEmail(emails.get(0));
if (user != null) {
String expectedLoginServer = userVariableDAO.findByUserAndKey(user, "openid.expectedlogin");
String loginServer = verification.getAuthResponse().getParameterValue("openid.op_endpoint");
if (!StringUtils.isBlank(expectedLoginServer) && expectedLoginServer.equals(loginServer)) {
userVariableDAO.setUserVariable(user, "openid.expectedlogin", null);
userDAO.updateExternalId(user, verified.getIdentifier());
} else {
throw new AuthenticationException(AuthenticationException.LOCAL_USER_MISSING);
}
} else {
throw new AuthenticationException(AuthenticationException.LOCAL_USER_MISSING);
}
}
return user;
} else {
return null;
}
} catch (MessageException e) {
throw new SmvcRuntimeException(e);
} catch (DiscoveryException e) {
throw new SmvcRuntimeException(e);
} catch (AssociationException e) {
throw new SmvcRuntimeException(e);
}
}
use of fi.otavanopisto.pyramus.plugin.auth.AuthenticationException in project pyramus by otavanopisto.
the class LDAPAuthorizationStrategy method getUser.
/**
* Returns the user corresponding to the given credentials. If no user cannot be found, returns
* <code>null</code>.
*
* @param username The username
* @param password The password
*
* @return The user corresponding to the given credentials, or <code>null</code> if not found
* @throws AuthenticationException
*/
public User getUser(String username, String password) throws AuthenticationException {
UserDAO userDAO = DAOFactory.getInstance().getUserDAO();
LDAPConnection connection;
try {
connection = LDAPUtils.getLDAPConnection();
final String searchFilter = "(" + System.getProperty("authentication.ldap.usernameAttr") + "=" + username + ")";
final LDAPSearchResults searchResults = connection.search(System.getProperty("authentication.ldap.authdn"), LDAPConnection.SCOPE_SUB, searchFilter, null, false);
if (searchResults != null && searchResults.hasMore()) {
LDAPEntry entry = searchResults.next();
try {
String uniqueIdAttr = System.getProperty("authentication.ldap.uniqueIdAttr");
boolean idEncoded = "1".equals(System.getProperty("authentication.ldap.uniqueIdEncoded"));
connection.bind(Integer.parseInt(System.getProperty("authentication.ldap.version")), entry.getDN(), password.getBytes("UTF8"));
String id = idEncoded ? LDAPUtils.getAttributeBinaryValue(entry.getAttribute(uniqueIdAttr)) : entry.getAttribute(uniqueIdAttr).getStringValue();
User user = userDAO.findByExternalIdAndAuthProvider(id, getName());
if (user == null)
throw new AuthenticationException(AuthenticationException.LOCAL_USER_MISSING);
return user;
} catch (UnsupportedEncodingException e) {
throw new LDAPException();
}
}
} catch (LDAPException e) {
throw new SmvcRuntimeException(e);
}
return null;
}
use of fi.otavanopisto.pyramus.plugin.auth.AuthenticationException in project pyramus by otavanopisto.
the class LoginJSONRequestController method process.
/**
* Processes the request to log in. Authorizes the given credentials and if they match a user,
* stores the user into the session (keys <code>loggedUserId</code>, <code>loggedUserName</code>,
* and <code>loggedUserRole</code>).
* <p/>
* If the session contains a <code>loginRedirectUrl</code> key, redirects the user to that URL.
* Otherwise, redirects back to the index page of the application.
* <p/>
* If the user is already logged in or the authentication fails, a <code>PyramusRuntimeException</code>
* is thrown with a localized message stating so.
*
* @param jsonRequestContext The JSON request context
*/
public void process(JSONRequestContext jsonRequestContext) {
// Fields submitted from the web page
String username = jsonRequestContext.getRequest().getParameter("username");
String password = jsonRequestContext.getRequest().getParameter("password");
Locale locale = jsonRequestContext.getRequest().getLocale();
// Ensure that the user trying to login isn't already logged in
HttpSession session = jsonRequestContext.getRequest().getSession(true);
if (!session.isNew() && session.getAttribute("loggedUserId") != null) {
String msg = Messages.getInstance().getText(locale, "users.login.alreadyLoggedIn");
throw new AlreadyLoggedInException(PyramusStatusCode.ALREADY_LOGGED_IN, msg);
}
for (InternalAuthenticationProvider provider : AuthenticationProviderVault.getInstance().getInternalAuthenticationProviders()) {
try {
User user = provider.getUser(username, password);
if (user != null && !user.getArchived() && !Role.CLOSED.equals(user.getRole())) {
// User has been authorized, so store him in the session
session.setAttribute("loggedUserId", user.getId());
session.setAttribute("loggedUserName", user.getFullName());
session.setAttribute("authenticationProvider", provider.getName());
if (user instanceof StaffMember) {
session.setAttribute("loggedUserRole", UserRole.valueOf(((StaffMember) user).getRole().name()));
}
try {
DAOFactory.getInstance().getLoginLogDAO().create(user, new Date());
} catch (Exception ex) {
ex.printStackTrace();
}
if (session.getAttribute("loginRedirectUrl") != null) {
String url = (String) session.getAttribute("loginRedirectUrl");
session.removeAttribute("loginRedirectUrl");
jsonRequestContext.setRedirectURL(url);
} else {
jsonRequestContext.setRedirectURL(jsonRequestContext.getRequest().getContextPath() + "/index.page");
}
return;
}
} catch (LocalUserMissingException lume) {
throw new SmvcRuntimeException(PyramusStatusCode.LOCAL_USER_MISSING, Messages.getInstance().getText(locale, "users.login.localUserMissing", new String[] { lume.getExternalUser() }));
} catch (AuthenticationException ae) {
throw new SmvcRuntimeException(ae);
}
}
// Reaching this point means no authentication provider authorized the user, so throw a login exception
String msg = Messages.getInstance().getText(jsonRequestContext.getRequest().getLocale(), "users.login.loginFailed");
throw new InvalidLoginException(msg);
}
use of fi.otavanopisto.pyramus.plugin.auth.AuthenticationException in project pyramus by otavanopisto.
the class GoogleOauthAuthorizationStrategy method processLogin.
private User processLogin(String externalId, String email) throws AuthenticationException {
UserIdentificationDAO userIdentificationDAO = DAOFactory.getInstance().getUserIdentificationDAO();
PersonDAO personDAO = DAOFactory.getInstance().getPersonDAO();
// Trim the email address
email = email != null ? email.trim() : null;
Person emailPerson = personDAO.findByUniqueEmail(email);
if (emailPerson == null) {
throw new LocalUserMissingException(email);
}
UserIdentification userIdentification = userIdentificationDAO.findByAuthSourceAndExternalId(getName(), externalId);
if (userIdentification != null) {
// User has identified by this auth source before
if (!emailPerson.getId().equals(userIdentification.getPerson().getId())) {
throw new AuthenticationException(AuthenticationException.EMAIL_BELONGS_TO_ANOTHER_PERSON);
}
} else {
userIdentificationDAO.create(emailPerson, getName(), externalId);
}
return emailPerson.getDefaultUser();
}
use of fi.otavanopisto.pyramus.plugin.auth.AuthenticationException in project pyramus by otavanopisto.
the class GoogleOauthAuthorizationStrategy method processResponse.
public User processResponse(RequestContext requestContext) throws AuthenticationException {
HttpServletRequest req = requestContext.getRequest();
HttpSession session = req.getSession();
String authCode = req.getParameter("code");
Verifier verifier = new Verifier(authCode);
OAuthService service = new ServiceBuilder().provider(GoogleApi20.class).apiKey(this.getClientId()).apiSecret(this.getClientSecret()).callback(this.getRedirectUrl()).scope(this.getScope()).build();
Token accessToken = service.getAccessToken(null, verifier);
OAuthRequest request = new OAuthRequest(Verb.GET, "https://www.googleapis.com/oauth2/v1/userinfo?alt=json");
service.signRequest(accessToken, request);
Response response = request.send();
JSONObject userInfo = JSONObject.fromObject(response.getBody());
if (userInfo != null) {
try {
return processLogin(userInfo.getString("id"), userInfo.getString("email"));
} finally {
setGoogleLoggedIn(session, true);
}
} else {
throw new AuthenticationException(AuthenticationException.EXTERNAL_LOGIN_SERVER_ERROR);
}
}
Aggregations