Commit 2cdc791f authored by qiaozhanwei's avatar qiaozhanwei
Browse files

api access token dev

parent 226f53fb
Loading
Loading
Loading
Loading
+144 −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 cn.escheduler.api.controller;


import cn.escheduler.api.enums.Status;
import cn.escheduler.api.service.AccessTokenService;
import cn.escheduler.api.service.UsersService;
import cn.escheduler.api.utils.Constants;
import cn.escheduler.api.utils.Result;
import cn.escheduler.dao.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

import static cn.escheduler.api.enums.Status.*;


/**
 * user controller
 */
@RestController
@RequestMapping("/access-token")
public class AccessTokenController extends BaseController{


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


    @Autowired
    private AccessTokenService accessTokenService;

    /**
     * create token
     * @param loginUser
     * @return
     */
    @PostMapping(value = "/create")
    @ResponseStatus(HttpStatus.CREATED)
    public Result createToken(@RequestAttribute(value = Constants.SESSION_USER) User loginUser,
                                                  @RequestParam(value = "userId") int userId,
                                                  @RequestParam(value = "expireTime") String expireTime,
                                                  @RequestParam(value = "token") String token){
        logger.info("login user {}, create token , userId : {} , token expire time : {} , token : {}", loginUser.getUserName(),
                userId,expireTime,token);

        try {
            Map<String, Object> result = accessTokenService.createToken(userId, expireTime, token);
            return returnDataList(result);
        }catch (Exception e){
            logger.error(CREATE_ACCESS_TOKEN_ERROR.getMsg(),e);
            return error(CREATE_ACCESS_TOKEN_ERROR.getCode(), CREATE_ACCESS_TOKEN_ERROR.getMsg());
        }
    }

    /**
     * create token
     * @param loginUser
     * @return
     */
    @PostMapping(value = "/generate")
    @ResponseStatus(HttpStatus.CREATED)
    public Result generateToken(@RequestAttribute(value = Constants.SESSION_USER) User loginUser,
                              @RequestParam(value = "userId") int userId,
                              @RequestParam(value = "expireTime") String expireTime){
        logger.info("login user {}, generate token , userId : {} , token expire time : {}",loginUser,userId,expireTime);
        try {
            Map<String, Object> result = accessTokenService.generateToken(userId, expireTime);
            return returnDataList(result);
        }catch (Exception e){
            logger.error(GENERATE_TOKEN_ERROR.getMsg(),e);
            return error(GENERATE_TOKEN_ERROR.getCode(), GENERATE_TOKEN_ERROR.getMsg());
        }
    }

    /**
     * query access token list paging
     *
     * @param loginUser
     * @param pageNo
     * @param searchVal
     * @param pageSize
     * @return
     */
    @GetMapping(value="/list-paging")
    @ResponseStatus(HttpStatus.OK)
    public Result queryAccessTokenList(@RequestAttribute(value = Constants.SESSION_USER) User loginUser,
                                @RequestParam("pageNo") Integer pageNo,
                                @RequestParam(value = "searchVal", required = false) String searchVal,
                                @RequestParam("pageSize") Integer pageSize){
        logger.info("login user {}, list access token paging, pageNo: {}, searchVal: {}, pageSize: {}",
                loginUser.getUserName(),pageNo,searchVal,pageSize);
        try{
            Map<String, Object> result = checkPageParams(pageNo, pageSize);
            if(result.get(Constants.STATUS) != Status.SUCCESS){
                return returnDataListPaging(result);
            }
            result = accessTokenService.queryAccessTokenList(loginUser, searchVal, pageNo, pageSize);
            return returnDataListPaging(result);
        }catch (Exception e){
            logger.error(QUERY_ACCESSTOKEN_LIST_PAGING_ERROR.getMsg(),e);
            return error(QUERY_ACCESSTOKEN_LIST_PAGING_ERROR.getCode(),QUERY_ACCESSTOKEN_LIST_PAGING_ERROR.getMsg());
        }
    }

    /**
     * delete access token by id
     * @param loginUser
     * @param id
     * @return
     */
    @PostMapping(value = "/delete")
    @ResponseStatus(HttpStatus.OK)
    public Result delAccessTokenById(@RequestAttribute(value = Constants.SESSION_USER) User loginUser,
                              @RequestParam(value = "id") int  id) {
        logger.info("login user {}, delete access token, id: {},", loginUser.getUserName(), id);
        try {
            Map<String, Object> result = accessTokenService.delAccessTokenById(loginUser, id);
            return returnDataList(result);
        }catch (Exception e){
            logger.error(DELETE_USER_BY_ID_ERROR.getMsg(),e);
            return error(Status.DELETE_USER_BY_ID_ERROR.getCode(), Status.DELETE_USER_BY_ID_ERROR.getMsg());
        }
    }

}
+0 −1
Original line number Diff line number Diff line
@@ -46,7 +46,6 @@ public class SchedulerController extends BaseController{
    private static final Logger logger = LoggerFactory.getLogger(SchedulerController.class);
    public static final String DEFAULT_WARNING_TYPE = "NONE";
    public static final String DEFAULT_NOTIFY_GROUP_ID = "1";
    public static final String DEFAULT_MAX_TRY_TIMES = "0";
    public static final String DEFAULT_FAILURE_POLICY = "CONTINUE";


+6 −0
Original line number Diff line number Diff line
@@ -199,6 +199,12 @@ public enum Status {


    HDFS_NOT_STARTUP(60001,"hdfs not startup"),


    CREATE_ACCESS_TOKEN_ERROR(70001,"create access token error"),
    GENERATE_TOKEN_ERROR(70002,"generate token error"),
    QUERY_ACCESSTOKEN_LIST_PAGING_ERROR(70003,"query access token list paging error"),

    ;

    private int code;
+19 −24
Original line number Diff line number Diff line
@@ -22,6 +22,7 @@ import cn.escheduler.dao.mapper.UserMapper;
import cn.escheduler.dao.model.Session;
import cn.escheduler.dao.model.User;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@@ -64,37 +65,31 @@ public class LoginHandlerInterceptor implements HandlerInterceptor {
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

    // get token
    String token = request.getHeader("token");
    User user = null;
    if (StringUtils.isEmpty(token)){
      Session session = sessionService.getSession(request);

    if(logger.isDebugEnabled()){
      logger.debug("session info : " + session);
    }

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

    if(logger.isDebugEnabled()){
      logger.debug("session id: {}", session.getId());
    }

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

    if(logger.isDebugEnabled()){
      logger.info("user info : " + user);
      user = userMapper.queryById(session.getUserId());
    }else {
       user = userMapper.queryUserByToken(token);
    }


    // if user is null
    if (user == null) {
      response.setStatus(HttpStatus.SC_UNAUTHORIZED);
      logger.info("user does not exist");
      return false;
    }

    request.setAttribute(Constants.SESSION_USER, user);

    return true;
  }

+152 −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 cn.escheduler.api.service;

import cn.escheduler.api.enums.Status;
import cn.escheduler.api.utils.CheckUtils;
import cn.escheduler.api.utils.Constants;
import cn.escheduler.api.utils.PageInfo;
import cn.escheduler.api.utils.Result;
import cn.escheduler.common.enums.UserType;
import cn.escheduler.common.utils.*;
import cn.escheduler.dao.mapper.*;
import cn.escheduler.dao.model.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * user service
 */
@Service
public class AccessTokenService extends BaseService {

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

    @Autowired
    private AccessTokenMapper accessTokenMapper;


    /**
     * query access token list
     *
     * @param loginUser
     * @param searchVal
     * @param pageNo
     * @param pageSize
     * @return
     */
    public Map<String, Object> queryAccessTokenList(User loginUser, String searchVal, Integer pageNo, Integer pageSize) {
        Map<String, Object> result = new HashMap<>(5);

        if (check(result, !isAdmin(loginUser), Status.USER_NO_OPERATION_PERM, Constants.STATUS)) {
            return result;
        }

        Integer count = accessTokenMapper.countAccessTokenPaging(searchVal);

        PageInfo<AccessToken> pageInfo = new PageInfo<>(pageNo, pageSize);

        List<AccessToken> accessTokenList = accessTokenMapper.queryAccessTokenPaging(searchVal, pageInfo.getStart(), pageSize);

        pageInfo.setTotalCount(count);
        pageInfo.setLists(accessTokenList);
        result.put(Constants.DATA_LIST, pageInfo);
        putMsg(result, Status.SUCCESS);

        return result;
    }

    /**
     * check
     *
     * @param result
     * @param bool
     * @param userNoOperationPerm
     * @param status
     * @return
     */
    private boolean check(Map<String, Object> result, boolean bool, Status userNoOperationPerm, String status) {
        //only admin can operate
        if (bool) {
            result.put(Constants.STATUS, userNoOperationPerm);
            result.put(status, userNoOperationPerm.getMsg());
            return true;
        }
        return false;
    }


    /**
     * create token
     *
     * @param userId
     * @param expireTime
     * @param token
     * @return
     */
    public Map<String, Object> createToken(int userId, String expireTime, String token) {
        Map<String, Object> result = new HashMap<>(5);

        AccessToken accessToken = new AccessToken();
        accessToken.setUserId(userId);
        accessToken.setExpireTime(DateUtils.stringToDate(expireTime));
        accessToken.setToken(token);

        // insert
        int insert = accessTokenMapper.insert(accessToken);

        if (insert > 0) {
            putMsg(result, Status.SUCCESS);
        } else {
            putMsg(result, Status.CREATE_ALERT_GROUP_ERROR);
        }
        return result;
    }

    /**
     * generate token
     * @param userId
     * @param expireTime
     * @return
     */
    public Map<String, Object> generateToken(int userId, String expireTime) {
        Map<String, Object> result = new HashMap<>(5);
        String token = EncryptionUtils.getMd5(userId + expireTime + String.valueOf(System.currentTimeMillis()));
        result.put(Constants.DATA_LIST, token);
        putMsg(result, Status.SUCCESS);
        return result;
    }

    public Map<String, Object> delAccessTokenById(User loginUser, int id) {
        Map<String, Object> result = new HashMap<>(5);
        //only admin can operate
        if (!isAdmin(loginUser)) {
            putMsg(result, Status.USER_NOT_EXIST, id);
            return result;
        }

        accessTokenMapper.delete(id);
        putMsg(result, Status.SUCCESS);
        return result;
    }
}
Loading