/*
 * Copyright 2002-2008 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/
package anyframe.sample.struts.web.action;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import javax.security.auth.Subject;
import javax.security.auth.login.FailedLoginException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import anyframe.sample.struts.web.form.UserForm;

import com.tagish.auth.TypedPrincipal;

public class LoginAction extends Action{
	
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		UserForm userForm = (UserForm) form;
		
		String userId = userForm.getUserId();
		String password = userForm.getPassword(); 
		
		//사용자 Id, Password 체크
		if ((userId != null && userId.equals("anyframe"))
				&& (password != null && password.equals("anyframe"))) {
			
			//로그인 성공시 Session에 유저 정보를 저장한다.
			Set principals = new HashSet();
			Set credentials = new HashSet();
			
			//사용자의 이름과 권한을 저장한다.
			principals.add(new TypedPrincipal("Anyframe", TypedPrincipal.USER));

			principals.add(new TypedPrincipal("ADMIN", TypedPrincipal.GROUP));

			Subject subject = new Subject(false, principals, credentials,
					credentials);

			HttpSession session = request.getSession();

			session.setAttribute("subject", subject);

		} else {
			throw new FailedLoginException();
		}
		return (mapping.findForward("success"));
	}
}

