/*
 * Copyright 2016 http://www.hswebframework.org
 *
 * 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 org.hswebframework.web.authorization.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.hswebframework.web.BusinessException;
import org.hswebframework.web.NotFoundException;
import org.hswebframework.web.WebUtil;
import org.hswebframework.web.authorization.Authentication;
import org.hswebframework.web.authorization.AuthenticationManager;
import org.hswebframework.web.authorization.annotation.Authorize;
import org.hswebframework.web.authorization.listener.event.*;
import org.hswebframework.web.commons.entity.DataStatus;
import org.hswebframework.web.controller.message.ResponseMessage;
import org.hswebframework.web.entity.authorization.UserEntity;
import org.hswebframework.web.logging.AccessLogger;
import org.hswebframework.web.service.authorization.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;

import static org.hswebframework.web.controller.message.ResponseMessage.ok;

/**
 * @author zhouhao
 */
@RestController
@RequestMapping("${hsweb.web.mappings.authorize:authorize}")
@AccessLogger("授权")
@Api(tags = "权限-用户授权", value = "授权")
public class AuthorizationController {

    @Autowired
    private UserService userService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private ApplicationEventPublisher eventPublisher;

    @GetMapping({"/login-out", "/sign-out", "/exit"})
    @Authorize
    @ApiOperation("退出当前登录")
    public ResponseMessage exit(@ApiParam(hidden = true) Authentication authentication) {
        eventPublisher.publishEvent(new AuthorizationExitEvent(authentication));
        return ok();
    }

    @GetMapping("/me")
    @Authorize
    @ApiOperation("当前登录用户权限信息")
    public ResponseMessage<Authentication> me(@ApiParam(hidden = true) Authentication authentication) {
        return ok(authentication);
    }


    @PostMapping(value = "/login", consumes = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation("用户名密码登录,json方式")
    public ResponseMessage<Map<String, Object>> authorize(@ApiParam(example = "{\"username\":\"admin\",\"password\":\"admin\"}")
                                                          @RequestBody Map<String, String> parameter) {

        return doLogin(Objects.requireNonNull(parameter.get("username"), "用户名不能为空")
                , Objects.requireNonNull(parameter.get("password"), "密码不能为空")
                , parameter);
    }

    @PostMapping(value = "/login",consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    @ApiOperation("用户名密码登录,参数方式")
    public ResponseMessage<Map<String, Object>> authorize(@RequestParam @ApiParam("用户名") String username,
                                                          @RequestParam @ApiParam("密码") String password,
                                                          @ApiParam(hidden = true) HttpServletRequest request) {

        return doLogin(username, password, WebUtil.getParameters(request));
    }

    protected ResponseMessage<Map<String, Object>> doLogin(String username, String password, Map<String, ?> parameter) {
        AuthorizationFailedEvent.Reason reason = AuthorizationFailedEvent.Reason.OTHER;
        Function<String, Object> parameterGetter = parameter::get;
        try {
            AuthorizationDecodeEvent decodeEvent = new AuthorizationDecodeEvent(username, password, parameterGetter);
            eventPublisher.publishEvent(decodeEvent);
            username = decodeEvent.getUsername();
            password = decodeEvent.getPassword();
            AuthorizationBeforeEvent beforeEvent = new AuthorizationBeforeEvent(username, password, parameterGetter);
            eventPublisher.publishEvent(beforeEvent);
            UserEntity entity = userService.selectByUserNameAndPassword(username, password);
            if (entity == null) {
                reason = AuthorizationFailedEvent.Reason.PASSWORD_ERROR;
                throw new NotFoundException("密码错误");
            }
            if (!DataStatus.STATUS_ENABLED.equals(entity.getStatus())) {
                reason = AuthorizationFailedEvent.Reason.USER_DISABLED;
                throw new BusinessException("{user_is_disabled}", 400);
            }
            // 验证通过
            Authentication authentication = authenticationManager.getByUserId(entity.getId());
            //触发授权成功事件
            AuthorizationSuccessEvent event = new AuthorizationSuccessEvent(authentication, parameterGetter);
            event.getResult().put("userId", entity.getId());
            eventPublisher.publishEvent(event);
            return ok(event.getResult());
        } catch (Exception e) {
            AuthorizationFailedEvent failedEvent = new AuthorizationFailedEvent(username, password, parameterGetter, reason);
            failedEvent.setException(e);
            eventPublisher.publishEvent(failedEvent);
            throw e;
        }
    }

}

@@ -803,97 +803,27 @@
 ort 
-org.hswebframework.web.BusinessException;%0Aimport org.hswebframework.web.NotFoundException
+lombok.SneakyThrows
 ;%0Aim
@@ -1417,16 +1417,76 @@
 ervice;%0A
+import org.hswebframework.web.validate.ValidationException;%0A
 import o
@@ -3397,16 +3397,17 @@
 /login%22,
+ 
 consumes
@@ -3892,24 +3892,42 @@
 t));%0A    %7D%0A%0A
+    @SneakyThrows%0A
     protecte
@@ -4878,16 +4878,18 @@
 new 
-NotFound
+Validation
 Exce
@@ -4900,16 +4900,28 @@
 n(%22%E5%AF%86%E7%A0%81%E9%94%99%E8%AF%AF%22
+, %22password%22
 );%0A     
@@ -5104,16 +5104,18 @@
 new 
-Business
+Validation
 Exce
@@ -5125,32 +5125,27 @@
 on(%22
-%7Buser_is_disabled%7D%22, 400
+%E7%94%A8%E6%88%B7%E5%B7%B2%E8%A2%AB%E7%A6%81%E7%94%A8%22, %22username%22
 );%0A 
@@ -5827,17 +5827,42 @@
   throw 
-e
+failedEvent.getException()
 ;%0A      

优化异常逻辑，可通过AuthorizationFailedEvent去自定义异常信息