Search in sources :

Example 6 with AuthConstraint

use of com.peterphi.std.guice.common.auth.annotations.AuthConstraint in project stdlib by petergeneric.

the class AuthConstraintMethodInterceptor method invoke.

@Override
public Object invoke(final MethodInvocation invocation) throws Throwable {
    // Never handle calls to base methods (like hashCode, toString, etc.)
    if (invocation.getMethod().getDeclaringClass().equals(Object.class))
        return invocation.proceed();
    if (log.isTraceEnabled())
        log.trace("Check authn for: " + invocation.getMethod());
    // Skip auth if we're not inside a Servlet call and we are only to enforce auth constraints on service calls
    if (onlyServletRequest && HttpCallContext.peek() == null) {
        if (log.isTraceEnabled())
            log.trace("Skip authn, should only run on servlet requests and this is not a servlet request");
        return invocation.proceed();
    }
    calls.mark();
    final AuthConstraint constraint = readConstraint(invocation);
    final CurrentUser user = userProvider.get();
    if (user == null)
        throw new IllegalArgumentException("Provider for CurrentUser returned null! Cannot apply AuthConstraint to method " + invocation.getMethod());
    // Acquire the auth scope (for constraint override)
    final AuthScope scope = getScope(constraint);
    // Test the user
    if (passes(scope, constraint, user)) {
        granted.mark();
        return invocation.proceed();
    } else {
        if (!user.isAnonymous())
            authenticatedDenied.mark();
        denied.mark();
        // Throw an exception to refuse access
        throw user.getAccessRefuser().refuse(scope, constraint, user);
    }
}
Also used : CurrentUser(com.peterphi.std.guice.common.auth.iface.CurrentUser) AuthConstraint(com.peterphi.std.guice.common.auth.annotations.AuthConstraint) AuthScope(com.peterphi.std.guice.common.auth.AuthScope)

Example 7 with AuthConstraint

use of com.peterphi.std.guice.common.auth.annotations.AuthConstraint in project stdlib by petergeneric.

the class LoginUIServiceImpl method doLogout.

@Override
@AuthConstraint(skip = true, comment = "Logout page")
public Response doLogout(String returnTo) {
    // Change the session reconnect key (if one is used)
    if (login.isLoggedIn())
        accountDao.changeSessionReconnectKey(login.getId());
    // Invalidate the current session
    HttpSession session = HttpCallContext.get().getRequest().getSession(false);
    if (session != null)
        session.invalidate();
    // Clear the login (in case the session isn't correctly invalidated)
    login.clear();
    if (StringUtils.isEmpty(returnTo))
        return Response.seeOther(URI.create("/")).build();
    else
        return Response.seeOther(URI.create(returnTo)).build();
}
Also used : HttpSession(javax.servlet.http.HttpSession) AuthConstraint(com.peterphi.std.guice.common.auth.annotations.AuthConstraint)

Example 8 with AuthConstraint

use of com.peterphi.std.guice.common.auth.annotations.AuthConstraint in project stdlib by petergeneric.

the class LoginUIServiceImpl method doLogin.

@AuthConstraint(skip = true, comment = "login page")
@Override
public Response doLogin(String nonce, String returnTo, String user, String password) {
    nonceStore.validate(nonce, true);
    if (login.isLoggedIn()) {
        throw new IllegalArgumentException("You are already logged in!");
    } else {
        final UserEntity account = authenticationService.authenticate(user, password, false);
        if (account != null) {
            // Successful login
            login.reload(account);
            final Response.ResponseBuilder builder;
            if (returnTo != null)
                builder = Response.seeOther(URI.create(returnTo));
            else
                builder = Response.seeOther(URI.create("/"));
            // If this account has a Session Reconnect Key we should give it to the browser
            if (account.getSessionReconnectKey() != null) {
                // Mark the cookie as secure if the request arrived on a secure channel
                final boolean secure = HttpCallContext.get().getRequest().isSecure();
                NewCookie cookie = new NewCookie(UserLogin.SESSION_RECONNECT_COOKIE, account.getSessionReconnectKey(), null, null, null, ONE_YEAR, secure, true);
                builder.cookie(cookie);
            }
            return builder.build();
        } else {
            // Send the user back to the login page
            final String page = getLogin(returnTo, "E-mail/password incorrect");
            return Response.status(403).entity(page).build();
        }
    }
}
Also used : Response(javax.ws.rs.core.Response) UserEntity(com.peterphi.usermanager.db.entity.UserEntity) NewCookie(javax.ws.rs.core.NewCookie) AuthConstraint(com.peterphi.std.guice.common.auth.annotations.AuthConstraint)

Example 9 with AuthConstraint

use of com.peterphi.std.guice.common.auth.annotations.AuthConstraint in project stdlib by petergeneric.

the class RegisterUIServiceImpl method getRegister.

@AuthConstraint(id = "register_service", skip = true, comment = "register page handles own constraints")
@Transactional(readOnly = true)
@Override
public String getRegister() {
    if (!allowAnonymousRegistration && !login.isAdmin())
        throw new AuthenticationFailureException("Anonymous registration is not enabled. Please log in to create other users");
    TemplateCall call = templater.template("register");
    call.set("nonce", nonceStore.allocate());
    if (login.isAdmin())
        // Admin user, role picker will be available
        call.set("roles", roleDao.getAll());
    else
        // Anonymous registration, no role select
        call.set("roles", Collections.emptyList());
    return call.process();
}
Also used : AuthenticationFailureException(com.peterphi.usermanager.guice.authentication.AuthenticationFailureException) TemplateCall(com.peterphi.std.guice.web.rest.templating.TemplateCall) AuthConstraint(com.peterphi.std.guice.common.auth.annotations.AuthConstraint) Transactional(com.peterphi.std.guice.database.annotation.Transactional)

Example 10 with AuthConstraint

use of com.peterphi.std.guice.common.auth.annotations.AuthConstraint in project stdlib by petergeneric.

the class RegisterUIServiceImpl method doRegister.

@AuthConstraint(id = "register_service", skip = true, comment = "register page handles own constraints")
@Override
@Transactional
public Response doRegister(String nonce, String email, String name, String dateFormat, String timeZone, String password, String passwordConfirm, List<String> roles) {
    nonceStore.validate(nonce, true);
    if (!allowAnonymousRegistration && !login.isAdmin())
        throw new AuthenticationFailureException("Anonymous registration is not enabled. Please log in as an admin to register users");
    if (!password.equals(passwordConfirm))
        throw new IllegalArgumentException("The passwords you supplied do not match");
    if ((roles != null && roles.size() > 0) && !login.isAdmin())
        throw new IllegalArgumentException("Cannot specify roles with user registration: you are not an admin!");
    if (accountDao.getAll().size() == 0) {
        log.warn("User with e-mail " + email + " will be the first user in the system and so will be granted the role " + UserLogin.ROLE_ADMIN);
        roles = Arrays.asList(UserLogin.ROLE_ADMIN);
    }
    log.info("Creating user " + name + " with e-mail " + email + ". Created by " + login.getName() + " (" + login.getId() + ") with roles " + roles);
    // Create a user
    final int newUser = accountDao.register(name, email, password, dateFormat, timeZone);
    final UserEntity entity = accountDao.getById(newUser);
    for (String role : roles) {
        final RoleEntity roleEntity = roleDao.getById(role);
        if (roleEntity == null)
            throw new IllegalArgumentException("Role does not exist: " + role);
        roleEntity.getMembers().add(entity);
        roleDao.update(roleEntity);
    }
    log.info("Created user " + newUser + " with e-mail " + email);
    if (login.isLoggedIn())
        return Response.seeOther(URI.create("/users")).build();
    else
        return Response.seeOther(URI.create("/login")).build();
}
Also used : RoleEntity(com.peterphi.usermanager.db.entity.RoleEntity) AuthenticationFailureException(com.peterphi.usermanager.guice.authentication.AuthenticationFailureException) AuthConstraint(com.peterphi.std.guice.common.auth.annotations.AuthConstraint) UserEntity(com.peterphi.usermanager.db.entity.UserEntity) AuthConstraint(com.peterphi.std.guice.common.auth.annotations.AuthConstraint) Transactional(com.peterphi.std.guice.database.annotation.Transactional)

Aggregations

AuthConstraint (com.peterphi.std.guice.common.auth.annotations.AuthConstraint)11 Transactional (com.peterphi.std.guice.database.annotation.Transactional)4 TemplateCall (com.peterphi.std.guice.web.rest.templating.TemplateCall)4 UserEntity (com.peterphi.usermanager.db.entity.UserEntity)4 AuthenticationFailureException (com.peterphi.usermanager.guice.authentication.AuthenticationFailureException)2 OAuth2TokenResponse (com.peterphi.usermanager.rest.iface.oauth2server.types.OAuth2TokenResponse)2 Response (javax.ws.rs.core.Response)2 AuthScope (com.peterphi.std.guice.common.auth.AuthScope)1 CurrentUser (com.peterphi.std.guice.common.auth.iface.CurrentUser)1 Retry (com.peterphi.std.guice.common.retry.annotation.Retry)1 WebQuery (com.peterphi.std.guice.restclient.jaxb.webquery.WebQuery)1 OAuth2SessionRef (com.peterphi.std.guice.web.rest.auth.oauth2.OAuth2SessionRef)1 OAuthServiceEntity (com.peterphi.usermanager.db.entity.OAuthServiceEntity)1 RoleEntity (com.peterphi.usermanager.db.entity.RoleEntity)1 SessionNonceStore (com.peterphi.usermanager.guice.nonce.SessionNonceStore)1 URI (java.net.URI)1 HttpSession (javax.servlet.http.HttpSession)1 NewCookie (javax.ws.rs.core.NewCookie)1