Search in sources :

Example 1 with AuthenticationException

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);
    }
}
Also used : User(fi.otavanopisto.pyramus.domainmodel.users.User) AuthenticationException(fi.otavanopisto.pyramus.plugin.auth.AuthenticationException) HttpSession(javax.servlet.http.HttpSession) SmvcRuntimeException(fi.internetix.smvc.SmvcRuntimeException) FetchResponse(org.openid4java.message.ax.FetchResponse) Identifier(org.openid4java.discovery.Identifier) UserDAO(fi.otavanopisto.pyramus.dao.users.UserDAO) VerificationResult(org.openid4java.consumer.VerificationResult) UserVariableDAO(fi.otavanopisto.pyramus.dao.users.UserVariableDAO) MessageException(org.openid4java.message.MessageException) DiscoveryInformation(org.openid4java.discovery.DiscoveryInformation) AuthSuccess(org.openid4java.message.AuthSuccess) ParameterList(org.openid4java.message.ParameterList) AssociationException(org.openid4java.association.AssociationException) DiscoveryException(org.openid4java.discovery.DiscoveryException)

Example 2 with AuthenticationException

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;
}
Also used : LDAPEntry(com.novell.ldap.LDAPEntry) LDAPSearchResults(com.novell.ldap.LDAPSearchResults) User(fi.otavanopisto.pyramus.domainmodel.users.User) UserDAO(fi.otavanopisto.pyramus.dao.users.UserDAO) LDAPException(com.novell.ldap.LDAPException) AuthenticationException(fi.otavanopisto.pyramus.plugin.auth.AuthenticationException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) SmvcRuntimeException(fi.internetix.smvc.SmvcRuntimeException) LDAPConnection(com.novell.ldap.LDAPConnection)

Example 3 with AuthenticationException

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);
}
Also used : Locale(java.util.Locale) User(fi.otavanopisto.pyramus.domainmodel.users.User) AuthenticationException(fi.otavanopisto.pyramus.plugin.auth.AuthenticationException) HttpSession(javax.servlet.http.HttpSession) SmvcRuntimeException(fi.internetix.smvc.SmvcRuntimeException) AlreadyLoggedInException(fi.internetix.smvc.AlreadyLoggedInException) StaffMember(fi.otavanopisto.pyramus.domainmodel.users.StaffMember) Date(java.util.Date) LocalUserMissingException(fi.otavanopisto.pyramus.plugin.auth.LocalUserMissingException) AuthenticationException(fi.otavanopisto.pyramus.plugin.auth.AuthenticationException) AlreadyLoggedInException(fi.internetix.smvc.AlreadyLoggedInException) InvalidLoginException(fi.internetix.smvc.InvalidLoginException) SmvcRuntimeException(fi.internetix.smvc.SmvcRuntimeException) LocalUserMissingException(fi.otavanopisto.pyramus.plugin.auth.LocalUserMissingException) InternalAuthenticationProvider(fi.otavanopisto.pyramus.plugin.auth.InternalAuthenticationProvider) InvalidLoginException(fi.internetix.smvc.InvalidLoginException)

Example 4 with AuthenticationException

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();
}
Also used : PersonDAO(fi.otavanopisto.pyramus.dao.base.PersonDAO) LocalUserMissingException(fi.otavanopisto.pyramus.plugin.auth.LocalUserMissingException) AuthenticationException(fi.otavanopisto.pyramus.plugin.auth.AuthenticationException) Person(fi.otavanopisto.pyramus.domainmodel.base.Person) UserIdentification(fi.otavanopisto.pyramus.domainmodel.users.UserIdentification) UserIdentificationDAO(fi.otavanopisto.pyramus.dao.users.UserIdentificationDAO)

Example 5 with AuthenticationException

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);
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) OAuthRequest(org.scribe.model.OAuthRequest) Response(org.scribe.model.Response) GoogleApi20(fi.otavanopisto.pyramus.plugin.googleoauth.scribe.GoogleApi20) OAuthService(org.scribe.oauth.OAuthService) JSONObject(net.sf.json.JSONObject) AuthenticationException(fi.otavanopisto.pyramus.plugin.auth.AuthenticationException) HttpSession(javax.servlet.http.HttpSession) Token(org.scribe.model.Token) Verifier(org.scribe.model.Verifier) ServiceBuilder(org.scribe.builder.ServiceBuilder)

Aggregations

AuthenticationException (fi.otavanopisto.pyramus.plugin.auth.AuthenticationException)6 SmvcRuntimeException (fi.internetix.smvc.SmvcRuntimeException)4 User (fi.otavanopisto.pyramus.domainmodel.users.User)4 HttpSession (javax.servlet.http.HttpSession)4 LocalUserMissingException (fi.otavanopisto.pyramus.plugin.auth.LocalUserMissingException)3 AlreadyLoggedInException (fi.internetix.smvc.AlreadyLoggedInException)2 UserDAO (fi.otavanopisto.pyramus.dao.users.UserDAO)2 StaffMember (fi.otavanopisto.pyramus.domainmodel.users.StaffMember)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 Date (java.util.Date)2 Locale (java.util.Locale)2 LDAPConnection (com.novell.ldap.LDAPConnection)1 LDAPEntry (com.novell.ldap.LDAPEntry)1 LDAPException (com.novell.ldap.LDAPException)1 LDAPSearchResults (com.novell.ldap.LDAPSearchResults)1 InvalidLoginException (fi.internetix.smvc.InvalidLoginException)1 PersonDAO (fi.otavanopisto.pyramus.dao.base.PersonDAO)1 UserIdentificationDAO (fi.otavanopisto.pyramus.dao.users.UserIdentificationDAO)1 UserVariableDAO (fi.otavanopisto.pyramus.dao.users.UserVariableDAO)1 Person (fi.otavanopisto.pyramus.domainmodel.base.Person)1