Commit 8ae401e3 authored by elonlo's avatar elonlo Committed by dailidong
Browse files

Refactor login verification process (#1543)



* Refactor login verification process

* Delete application-combined.properties

application-combined.properties doesn't needed

Co-authored-by: default avatardailidong <dailidong66@gmail.com>
parent 7762a622
Loading
Loading
Loading
Loading
+14 −19
Original line number Diff line number Diff line
@@ -18,8 +18,8 @@ package org.apache.dolphinscheduler.api.controller;


import org.apache.dolphinscheduler.api.enums.Status;
import org.apache.dolphinscheduler.api.security.Authenticator;
import org.apache.dolphinscheduler.api.service.SessionService;
import org.apache.dolphinscheduler.api.service.UsersService;
import org.apache.dolphinscheduler.api.utils.Result;
import org.apache.dolphinscheduler.common.Constants;
import org.apache.dolphinscheduler.common.utils.StringUtils;
@@ -36,6 +36,8 @@ import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Map;

import static org.apache.dolphinscheduler.api.enums.Status.*;

/**
@@ -55,7 +57,7 @@ public class LoginController extends BaseController {
    private SessionService sessionService;

    @Autowired
    private UsersService userService;
    private Authenticator authenticator;


    /**
@@ -94,27 +96,20 @@ public class LoginController extends BaseController {
            }

            // 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()
                );
            Result<Map<String, String>> result = authenticator.authenticate(userName, userPassword, ip);
            if (result.getCode() != Status.SUCCESS.getCode()) {
                return result;
            }

            response.setStatus(HttpStatus.SC_OK);
            response.addCookie(new Cookie(Constants.SESSION_ID, sessionId));
            Map<String, String> cookieMap = result.getData();
            for (Map.Entry<String, String> cookieEntry : cookieMap.entrySet()) {
                Cookie cookie = new Cookie(cookieEntry.getKey(), cookieEntry.getValue());
                cookie.setHttpOnly(true);
                response.addCookie(cookie);
            }

            logger.info("sessionId : {}" , sessionId);
            return success(LOGIN_SUCCESS.getMsg(), sessionId);
            return result;
        } catch (Exception e) {
            logger.error(USER_LOGIN_FAILURE.getMsg(),e);
            return error(USER_LOGIN_FAILURE.getCode(), USER_LOGIN_FAILURE.getMsg());
+5 −12
Original line number Diff line number Diff line
@@ -16,9 +16,9 @@
 */
package org.apache.dolphinscheduler.api.interceptor;

import org.apache.dolphinscheduler.api.security.Authenticator;
import org.apache.dolphinscheduler.api.service.SessionService;
import org.apache.dolphinscheduler.common.Constants;
import org.apache.dolphinscheduler.dao.entity.Session;
import org.apache.dolphinscheduler.dao.entity.User;
import org.apache.dolphinscheduler.dao.mapper.UserMapper;
import org.apache.commons.httpclient.HttpStatus;
@@ -44,6 +44,9 @@ public class LoginHandlerInterceptor implements HandlerInterceptor {
  @Autowired
  private UserMapper userMapper;

  @Autowired
  private Authenticator authenticator;

  /**
   * Intercept the execution of a handler. Called after HandlerMapping determined
   * an appropriate handler object, but before HandlerAdapter invokes the handler.
@@ -68,17 +71,7 @@ public class LoginHandlerInterceptor implements HandlerInterceptor {
    String token = request.getHeader("token");
    User user = null;
    if (StringUtils.isEmpty(token)){
      Session session = sessionService.getSession(request);

      if (session == null) {
        response.setStatus(HttpStatus.SC_UNAUTHORIZED);
        logger.info("session info is null ");
        return false;
      }

      //get user object from session
      user = userMapper.selectById(session.getUserId());

      user = authenticator.getAuthUser(request);
      // if user is null
      if (user == null) {
        response.setStatus(HttpStatus.SC_UNAUTHORIZED);
+37 −0
Original line number Diff line number Diff line
/*
 * 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 org.apache.dolphinscheduler.api.security;

import com.baomidou.mybatisplus.annotation.EnumValue;

/**
 * authentication type
 */
public enum AuthenticationType {

    PASSWORD(0, "verify via user name and password"),
    ;

    AuthenticationType(int code, String desc) {
        this.code = code;
        this.desc = desc;
    }

    @EnumValue
    private final int code;
    private final String desc;
}
+40 −0
Original line number Diff line number Diff line
/*
 * 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 org.apache.dolphinscheduler.api.security;

import org.apache.dolphinscheduler.api.utils.Result;
import org.apache.dolphinscheduler.dao.entity.User;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

public interface Authenticator {
    /**
     * Verifying legality via username and password
     * @param username user name
     * @param password user password
     * @param extra extra info
     * @return result object
     */
    Result<Map<String, String>> authenticate(String username, String password, String extra);

    /**
     * Get authenticated user
     * @param request http servlet request
     * @return user
     */
    User getAuthUser(HttpServletRequest request);
}
+76 −0
Original line number Diff line number Diff line
/*
 * 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 org.apache.dolphinscheduler.api.security;

import org.apache.dolphinscheduler.api.enums.Status;
import org.apache.dolphinscheduler.api.service.SessionService;
import org.apache.dolphinscheduler.api.service.UsersService;
import org.apache.dolphinscheduler.api.utils.Result;
import org.apache.dolphinscheduler.common.Constants;
import org.apache.dolphinscheduler.dao.entity.Session;
import org.apache.dolphinscheduler.dao.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.Map;

public class PasswordAuthenticator implements Authenticator {
    private static final Logger logger = LoggerFactory.getLogger(PasswordAuthenticator.class);

    @Autowired
    private UsersService userService;
    @Autowired
    private SessionService sessionService;

    @Override
    public Result<Map<String, String>> authenticate(String username, String password, String extra) {
        Result<Map<String, String>> result = new Result<>();
        // verify username and password
        User user = userService.queryUser(username, password);
        if (user == null) {
            result.setCode(Status.USER_NAME_PASSWD_ERROR.getCode());
            result.setMsg(Status.USER_NAME_PASSWD_ERROR.getMsg());
            return result;
        }

        // create session
        String sessionId = sessionService.createSession(user, extra);
        if (sessionId == null) {
            result.setCode(Status.LOGIN_SESSION_FAILED.getCode());
            result.setMsg(Status.LOGIN_SESSION_FAILED.getMsg());
            return result;
        }
        logger.info("sessionId : {}" , sessionId);
        result.setData(Collections.singletonMap(Constants.SESSION_ID, sessionId));
        result.setCode(Status.SUCCESS.getCode());
        result.setMsg(Status.LOGIN_SUCCESS.getMsg());
        return result;
    }

    @Override
    public User getAuthUser(HttpServletRequest request) {
        Session session = sessionService.getSession(request);
        if (session == null) {
            logger.info("session info is null ");
            return null;
        }
        //get user object from session
        return userService.queryUser(session.getUserId());
    }
}
Loading