LoginController.java 5.3 KB
Newer Older
L
ligang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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 cn.escheduler.api.controller;


import cn.escheduler.api.enums.Status;
import cn.escheduler.api.service.SessionService;
import cn.escheduler.api.service.UsersService;
import cn.escheduler.api.utils.Constants;
import cn.escheduler.api.utils.Result;
import cn.escheduler.dao.model.User;
L
lidongdai 已提交
26
import io.swagger.annotations.Api;
L
lidongdai 已提交
27 28 29
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
L
ligang 已提交
30 31 32 33 34
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
L
lidongdai 已提交
35 36
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
L
ligang 已提交
37 38 39 40 41 42
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

L
lidongdai 已提交
43 44
import java.util.Locale;

L
ligang 已提交
45 46 47 48 49 50 51
import static cn.escheduler.api.enums.Status.*;

/**
 * user login controller
 */
@RestController
@RequestMapping("")
L
lidongdai 已提交
52
@Api(value = "", tags = {"中国"}, description = "中国")
L
ligang 已提交
53 54 55 56
public class LoginController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

L
lidongdai 已提交
57 58
    private Locale locale = LocaleContextHolder.getLocale();

L
ligang 已提交
59 60 61 62 63 64
    @Autowired
    private SessionService sessionService;

    @Autowired
    private UsersService userService;

L
lidongdai 已提交
65 66 67
    @Autowired
    private MessageSource messageSource;

L
ligang 已提交
68 69 70 71 72 73 74 75 76
    /**
     * login
     *
     * @param userName
     * @param userPassword
     * @param request
     * @param response
     * @return
     */
L
lidongdai 已提交
77
    @ApiOperation(value = "test", notes="loginNotes")
L
lidongdai 已提交
78
    @ApiImplicitParams({
L
lidongdai 已提交
79 80
            @ApiImplicitParam(name = "userName", value = "userName", required = true, type = "String"),
            @ApiImplicitParam(name = "userPassword", value = "userPassword", required = true, type ="String")
L
lidongdai 已提交
81
    })
L
ligang 已提交
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
    @RequestMapping(value = "/login")
    public Result login(@RequestParam(value = "userName") String userName,
                        @RequestParam(value = "userPassword") String userPassword,
                        HttpServletRequest request,
                        HttpServletResponse response) {


        try {
            logger.info("login user name: {} ", userName);

            //user name check
            if (StringUtils.isEmpty(userName)) {
                return error(Status.USER_NAME_NULL.getCode(),
                        Status.USER_NAME_NULL.getMsg());
            }


            // user ip check
            String ip = getClientIpAddress(request);
            if (StringUtils.isEmpty(ip)) {
                return error(IP_IS_EMPTY.getCode(), IP_IS_EMPTY.getMsg());
            }

            // verify username and password
            User user = userService.queryUser(userName, userPassword);

            if (user == null) {
                return error(Status.USER_NAME_PASSWD_ERROR.getCode(),Status.USER_NAME_PASSWD_ERROR.getMsg()
                );
            }

            // create session
            String sessionId = sessionService.createSession(user, ip);

            if (sessionId == null) {
                return error(Status.LOGIN_SESSION_FAILED.getCode(),
                        Status.LOGIN_SESSION_FAILED.getMsg()
                );
            }

            response.setStatus(HttpStatus.SC_OK);
            response.addCookie(new Cookie(Constants.SESSION_ID, sessionId));

            logger.info("sessionId = " + sessionId);
            return success(LOGIN_SUCCESS.getMsg(), sessionId);
        } catch (Exception e) {
            logger.error(USER_LOGIN_FAILURE.getMsg(),e);
            return error(USER_LOGIN_FAILURE.getCode(), USER_LOGIN_FAILURE.getMsg());
        }
    }

    /**
     * sign out
     *
     * @param loginUser
     * @return
     */
    @PostMapping(value = "/signOut")
    public Result signOut(@RequestAttribute(value = Constants.SESSION_USER) User loginUser,
                          HttpServletRequest request) {

        try {
            logger.info("login user:{} sign out", loginUser.getUserName());
            String ip = getClientIpAddress(request);
            sessionService.signOut(ip, loginUser);
            //clear session
            request.removeAttribute(Constants.SESSION_USER);
            return success();
        } catch (Exception e) {
            logger.error(SIGN_OUT_ERROR.getMsg(),e);
            return error(SIGN_OUT_ERROR.getCode(), SIGN_OUT_ERROR.getMsg());
        }
    }
}