/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/

package com.cesgroup.cesmonitor.ws;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.util.ThreadContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.cesgroup.cesmonitor.service.IdentityService;
import com.cesgroup.cesmonitor.service.LoginUser;

/**
 * 认证服务控制器
 *
 * @author zhang.erwei
 * @version 1.0.0 2017年5月24日
 */
@Controller
@RequestMapping(value = "/ws")
public class IdentifyServiceController {

    @Autowired
    protected IdentityService identityService;

    /**
     * 登录
     *
     * @param username
     *            用户名
     * @param password
     *            密码
     * @return 登录用户
     */
    @RequestMapping(value = "login")
    @ResponseBody
    public LoginUser login(String username, String password) {
        return identityService.login(username, password);
    }

    static public void checkLogin(IdentityService identityService) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
            .getRequest();

        String username = request.getHeader("username");
        String password = request.getHeader("password");
        if (identityService.getLoginUser(username) == null) {
            identityService.login(username, password);
        } else {
            ThreadContext.put(IdentityService.LOGIN_USER, username);
        }
    }

}
