001/*
002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     bstefanescu
011 */
012package org.nuxeo.ecm.automation.core.operations.login;
013
014import java.security.Principal;
015
016import javax.security.auth.login.LoginContext;
017import javax.security.auth.login.LoginException;
018
019import org.nuxeo.ecm.automation.OperationContext;
020import org.nuxeo.ecm.automation.OperationException;
021import org.nuxeo.ecm.automation.core.Constants;
022import org.nuxeo.ecm.automation.core.annotations.Context;
023import org.nuxeo.ecm.automation.core.annotations.Operation;
024import org.nuxeo.ecm.automation.core.annotations.OperationMethod;
025import org.nuxeo.ecm.automation.core.annotations.Param;
026import org.nuxeo.ecm.core.api.DocumentModel;
027import org.nuxeo.runtime.api.Framework;
028
029/**
030 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
031 */
032@Operation(id = LoginAs.ID, category = Constants.CAT_USERS_GROUPS, label = "Login As", description = "Login As the given user. If no user is given a system login is performed. This is a void operations - the input will be returned back as the output.")
033public class LoginAs {
034
035    public static final String ID = "Auth.LoginAs";
036
037    @Context
038    protected OperationContext ctx;
039
040    @Param(name = "name", required = false)
041    protected String name;
042
043    @OperationMethod
044    public void run() throws LoginException, OperationException {
045        LoginContext lc = null;
046        if (name == null) {
047            Principal origPrincipal = ctx.getPrincipal();
048            if (origPrincipal != null) {
049                lc = Framework.loginAs(origPrincipal.getName());
050            } else {
051                lc = Framework.login();
052            }
053        } else {
054            lc = Framework.loginAsUser(name);
055        }
056        if (lc != null) {
057            ctx.getLoginStack().push(lc);
058        }
059    }
060
061    @OperationMethod
062    public DocumentModel run(DocumentModel doc) throws LoginException, OperationException {
063        run();
064        // refetch the input document if any using the new session
065        // otherwise using document methods that are delegating the call to the
066        // session that created the document will call the old session.
067        return ctx.getCoreSession().getDocument(doc.getRef());
068    }
069}