Browse Source

Merge pull request #76 from qiaozhanwei/dev-20190415

api access token dev
pull/2/head
乔占卫 6 years ago committed by GitHub
parent
commit
dd1be123ed
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 169
      escheduler-api/src/main/java/cn/escheduler/api/controller/AccessTokenController.java
  2. 1
      escheduler-api/src/main/java/cn/escheduler/api/controller/SchedulerController.java
  3. 6
      escheduler-api/src/main/java/cn/escheduler/api/enums/Status.java
  4. 43
      escheduler-api/src/main/java/cn/escheduler/api/interceptor/LoginHandlerInterceptor.java
  5. 184
      escheduler-api/src/main/java/cn/escheduler/api/service/AccessTokenService.java
  6. 162
      escheduler-api/src/test/java/cn/escheduler/api/HttpClientTest.java
  7. 12
      escheduler-dao/readme.txt
  8. 88
      escheduler-dao/src/main/java/cn/escheduler/dao/mapper/AccessTokenMapper.java
  9. 130
      escheduler-dao/src/main/java/cn/escheduler/dao/mapper/AccessTokenMapperProvider.java
  10. 20
      escheduler-dao/src/main/java/cn/escheduler/dao/mapper/UserMapper.java
  11. 16
      escheduler-dao/src/main/java/cn/escheduler/dao/mapper/UserMapperProvider.java
  12. 126
      escheduler-dao/src/main/java/cn/escheduler/dao/model/AccessToken.java
  13. 62
      escheduler-dao/src/test/java/cn/escheduler/dao/mapper/AccessTokenMapperTest.java
  14. 6
      escheduler-dao/src/test/java/cn/escheduler/dao/mapper/UserMapperTest.java

169
escheduler-api/src/main/java/cn/escheduler/api/controller/AccessTokenController.java

@ -0,0 +1,169 @@
/*
* 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());
}
}
/**
* update token
* @param loginUser
* @return
*/
@PostMapping(value = "/update")
@ResponseStatus(HttpStatus.CREATED)
public Result updateToken(@RequestAttribute(value = Constants.SESSION_USER) User loginUser,
@RequestParam(value = "id") int id,
@RequestParam(value = "userId") int userId,
@RequestParam(value = "expireTime") String expireTime,
@RequestParam(value = "token") String token){
logger.info("login user {}, update token , userId : {} , token expire time : {} , token : {}", loginUser.getUserName(),
userId,expireTime,token);
try {
Map<String, Object> result = accessTokenService.updateToken(id,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());
}
}
}

1
escheduler-api/src/main/java/cn/escheduler/api/controller/SchedulerController.java

@ -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
escheduler-api/src/main/java/cn/escheduler/api/enums/Status.java

@ -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;

43
escheduler-api/src/main/java/cn/escheduler/api/interceptor/LoginHandlerInterceptor.java

@ -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) {
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 token
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.queryById(session.getUserId());
}else {
user = userMapper.queryUserByToken(token);
}
//get user object from session
User user = userMapper.queryById(session.getUserId());
if(logger.isDebugEnabled()){
logger.info("user info : " + user);
}
// 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;
}

184
escheduler-api/src/main/java/cn/escheduler/api/service/AccessTokenService.java

@ -0,0 +1,184 @@
/*
* 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);
accessToken.setCreateTime(new Date());
accessToken.setUpdateTime(new Date());
// 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;
}
/**
* delete access token
* @param loginUser
* @param id
* @return
*/
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;
}
/**
* update token by id
* @param id
* @param userId
* @param expireTime
* @param token
* @return
*/
public Map<String, Object> updateToken(int id,int userId, String expireTime, String token) {
Map<String, Object> result = new HashMap<>(5);
AccessToken accessToken = new AccessToken();
accessToken.setId(id);
accessToken.setUserId(userId);
accessToken.setExpireTime(DateUtils.stringToDate(expireTime));
accessToken.setToken(token);
accessToken.setUpdateTime(new Date());
accessTokenMapper.update(accessToken);
putMsg(result, Status.SUCCESS);
return result;
}
}

162
escheduler-api/src/test/java/cn/escheduler/api/HttpClientTest.java

@ -0,0 +1,162 @@
/*
* 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;
import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import cn.escheduler.common.utils.EncryptionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HttpClientTest {
private static final Logger logger = LoggerFactory.getLogger(HttpClientTest.class);
public static void main(String[] args) throws Exception {
// doGETParamPathVariableAndChinese();
// doGETParam();
// doPOSTParam();
String md5 = EncryptionUtils.getMd5(String.valueOf(System.currentTimeMillis()) + "张三");
System.out.println(md5);
System.out.println(md5.length());
}
public static void doPOSTParam()throws Exception{
// create Httpclient
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建http POST请求
HttpPost httpPost = new HttpPost("http://127.0.0.1:12345/escheduler/projects/create");
httpPost.setHeader("token", "123");
// set parameters
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("projectName", "qzw"));
parameters.add(new BasicNameValuePair("desc", "qzw"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
httpPost.setEntity(formEntity);
CloseableHttpResponse response = null;
try {
// execute
response = httpclient.execute(httpPost);
// eponse status code 200
if (response.getStatusLine().getStatusCode() == 200) {
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(content);
}
} finally {
if (response != null) {
response.close();
}
httpclient.close();
}
}
/**
*
* @throws Exception
*/
public static void doGETParamPathVariableAndChinese()throws Exception{
// create HttpClient
CloseableHttpClient httpclient = HttpClients.createDefault();
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
// parameters.add(new BasicNameValuePair("pageSize", "10"));
// define the parameters of the request
URI uri = new URIBuilder("http://127.0.0.1:12345/escheduler/projects/%E5%85%A8%E9%83%A8%E6%B5%81%E7%A8%8B%E6%B5%8B%E8%AF%95/process/list")
.build();
// create http GET request
HttpGet httpGet = new HttpGet(uri);
httpGet.setHeader("token","123");
//response object
CloseableHttpResponse response = null;
try {
// execute http get request
response = httpclient.execute(httpGet);
// reponse status code 200
if (response.getStatusLine().getStatusCode() == 200) {
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
logger.info("start--------------->");
logger.info(content);
logger.info("end----------------->");
}
} finally {
if (response != null) {
response.close();
}
httpclient.close();
}
}
/**
*
* @throws Exception
*/
public static void doGETParam()throws Exception{
// create HttpClient
CloseableHttpClient httpclient = HttpClients.createDefault();
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("processInstanceId", "41415"));
// define the parameters of the request
URI uri = new URIBuilder("http://127.0.0.1:12345/escheduler/projects/%E5%85%A8%E9%83%A8%E6%B5%81%E7%A8%8B%E6%B5%8B%E8%AF%95/instance/view-variables")
.setParameters(parameters)
.build();
// create http GET request
HttpGet httpGet = new HttpGet(uri);
httpGet.setHeader("token","123");
//response object
CloseableHttpResponse response = null;
try {
// execute http get request
response = httpclient.execute(httpGet);
// reponse status code 200
if (response.getStatusLine().getStatusCode() == 200) {
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
logger.info("start--------------->");
logger.info(content);
logger.info("end----------------->");
}
} finally {
if (response != null) {
response.close();
}
httpclient.close();
}
}
}

12
escheduler-dao/readme.txt

@ -1 +1,13 @@
-- 用户指定队列
alter table t_escheduler_user add queue varchar(64);
-- 访问token
CREATE TABLE `t_escheduler_access_token` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`user_id` int(11) DEFAULT NULL COMMENT '用户id',
`token` varchar(64) DEFAULT NULL COMMENT 'token令牌',
`expire_time` datetime DEFAULT NULL COMMENT 'token有效结束时间',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`update_time` datetime DEFAULT NULL COMMENT '更新时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

88
escheduler-dao/src/main/java/cn/escheduler/dao/mapper/AccessTokenMapper.java

@ -0,0 +1,88 @@
/*
* 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.dao.mapper;
import cn.escheduler.common.enums.UserType;
import cn.escheduler.dao.model.AccessToken;
import cn.escheduler.dao.model.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.type.EnumOrdinalTypeHandler;
import org.apache.ibatis.type.JdbcType;
import java.sql.Timestamp;
import java.util.List;
public interface AccessTokenMapper {
/**
* insert accessToken
* @param accessToken
* @return
*/
@InsertProvider(type = AccessTokenMapperProvider.class, method = "insert")
@Options(useGeneratedKeys = true,keyProperty = "accessToken.id")
@SelectKey(statement = "SELECT LAST_INSERT_ID()", keyProperty = "accessToken.id", before = false, resultType = int.class)
int insert(@Param("accessToken") AccessToken accessToken);
/**
* delete accessToken
* @param accessTokenId
* @return
*/
@DeleteProvider(type = AccessTokenMapperProvider.class, method = "delete")
int delete(@Param("accessTokenId") int accessTokenId);
/**
* update accessToken
*
* @param accessToken
* @return
*/
@UpdateProvider(type = AccessTokenMapperProvider.class, method = "update")
int update(@Param("accessToken") AccessToken accessToken);
/**
* query access token list paging
* @param searchVal
* @param offset
* @param pageSize
* @return
*/
@Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER),
@Result(property = "userId", column = "user_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER),
@Result(property = "token", column = "token", javaType = String.class, jdbcType = JdbcType.VARCHAR),
@Result(property = "userName", column = "user_name", javaType = String.class, jdbcType = JdbcType.VARCHAR),
@Result(property = "expireTime", column = "expire_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE),
@Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE),
@Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE)
})
@SelectProvider(type = AccessTokenMapperProvider.class, method = "queryAccessTokenPaging")
List<AccessToken> queryAccessTokenPaging(@Param("searchVal") String searchVal,
@Param("offset") Integer offset,
@Param("pageSize") Integer pageSize);
/**
* count access token by search value
* @param searchVal
* @return
*/
@SelectProvider(type = AccessTokenMapperProvider.class, method = "countAccessTokenPaging")
Integer countAccessTokenPaging(@Param("searchVal") String searchVal);
}

130
escheduler-dao/src/main/java/cn/escheduler/dao/mapper/AccessTokenMapperProvider.java

@ -0,0 +1,130 @@
/*
* 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.dao.mapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.jdbc.SQL;
import java.util.Map;
/**
* access token mapper provider
*
*/
public class AccessTokenMapperProvider {
private static final String TABLE_NAME = "t_escheduler_access_token";
/**
* insert accessToken
*
* @param parameter
* @return
*/
public String insert(Map<String, Object> parameter) {
return new SQL() {
{
INSERT_INTO(TABLE_NAME);
VALUES("`user_id`", "#{accessToken.userId}");
VALUES("`token`", "#{accessToken.token}");
VALUES("`expire_time`", "#{accessToken.expireTime}");;
VALUES("`create_time`", "#{accessToken.createTime}");
VALUES("`update_time`", "#{accessToken.updateTime}");
}
}.toString();
}
/**
* delete accessToken
*
* @param parameter
* @return
*/
public String delete(Map<String, Object> parameter) {
return new SQL() {
{
DELETE_FROM(TABLE_NAME);
WHERE("`id`=#{accessTokenId}");
}
}.toString();
}
/**
* update accessToken
*
* @param parameter
* @return
*/
public String update(Map<String, Object> parameter) {
return new SQL() {
{
UPDATE(TABLE_NAME);
SET("`user_id`=#{accessToken.userId}");
SET("`token`=#{accessToken.token}");
SET("`expire_time`=#{accessToken.expireTime}");
SET("`update_time`=#{accessToken.updateTime}");
WHERE("`id`=#{user.id}");
}
}.toString();
}
/**
* count user number by search value
* @param parameter
* @return
*/
public String countAccessTokenPaging(Map<String, Object> parameter) {
return new SQL() {{
SELECT("count(0)");
FROM(TABLE_NAME + " t,t_escheduler_user u");
Object searchVal = parameter.get("searchVal");
WHERE("u.id = t.user_id");
if(searchVal != null && StringUtils.isNotEmpty(searchVal.toString())){
WHERE(" u.user_name like concat('%', #{searchVal}, '%')");
}
}}.toString();
}
/**
* query user list paging
* @param parameter
* @return
*/
public String queryAccessTokenPaging(Map<String, Object> parameter) {
return new SQL() {
{
SELECT("t.*,u.user_name");
FROM(TABLE_NAME + " t,t_escheduler_user u");
Object searchVal = parameter.get("searchVal");
WHERE("u.id = t.user_id");
if(searchVal != null && StringUtils.isNotEmpty(searchVal.toString())){
WHERE(" u.user_name like concat('%', #{searchVal}, '%') ");
}
ORDER_BY(" t.update_time desc limit #{offset},#{pageSize} ");
}
}.toString();
}
}

20
escheduler-dao/src/main/java/cn/escheduler/dao/mapper/UserMapper.java

@ -231,4 +231,24 @@ public interface UserMapper {
*/
@SelectProvider(type = UserMapperProvider.class, method = "queryQueueByProcessInstanceId")
String queryQueueByProcessInstanceId(@Param("processInstanceId") int processInstanceId);
/**
* query user by token
* @param token
* @return
*/
@Results(value = {
@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER),
@Result(property = "userName", column = "user_name", javaType = String.class, jdbcType = JdbcType.VARCHAR),
@Result(property = "userPassword", column = "user_password", javaType = String.class, jdbcType = JdbcType.VARCHAR),
@Result(property = "email", column = "email", javaType = String.class, jdbcType = JdbcType.VARCHAR),
@Result(property = "phone", column = "phone", javaType = String.class, jdbcType = JdbcType.VARCHAR),
@Result(property = "userType", column = "user_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = UserType.class, jdbcType = JdbcType.TINYINT),
@Result(property = "tenantId", column = "tenant_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER),
@Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE),
@Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE)
})
@SelectProvider(type = UserMapperProvider.class, method = "queryUserByToken")
User queryUserByToken(@Param("token") String token);
}

16
escheduler-dao/src/main/java/cn/escheduler/dao/mapper/UserMapperProvider.java

@ -265,4 +265,20 @@ public class UserMapperProvider {
}.toString();
}
/**
* query user by id
* @param parameter
* @return
*/
public String queryUserByToken(Map<String, Object> parameter) {
return new SQL() {
{
SELECT("u.*");
FROM(TABLE_NAME + " u ,t_escheduler_access_token t");
WHERE(" u.id = t.user_id and token=#{token}");
}
}.toString();
}
}

126
escheduler-dao/src/main/java/cn/escheduler/dao/model/AccessToken.java

@ -0,0 +1,126 @@
package cn.escheduler.dao.model;
import java.util.Date;
/*
* 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.
*/
public class AccessToken {
/**
* id
*/
private int id;
/**
* user id
*/
private int userId;
/**
* user name
*/
private String userName;
/**
* user token
*/
private String token;
/**
* token expire time
*/
private Date expireTime;
/**
* create time
*/
private Date createTime;
/**
* update time
*/
private Date updateTime;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public Date getExpireTime() {
return expireTime;
}
public void setExpireTime(Date expireTime) {
this.expireTime = expireTime;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Override
public String toString() {
return "AccessToken{" +
"id=" + id +
", userId=" + userId +
", userName='" + userName + '\'' +
", token='" + token + '\'' +
", expireTime=" + expireTime +
", createTime=" + createTime +
", updateTime=" + updateTime +
'}';
}
}

62
escheduler-dao/src/test/java/cn/escheduler/dao/mapper/AccessTokenMapperTest.java

@ -0,0 +1,62 @@
/*
* 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.dao.mapper;
import cn.escheduler.common.utils.EncryptionUtils;
import cn.escheduler.dao.datasource.ConnectionFactory;
import cn.escheduler.dao.model.AccessToken;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.Date;
import java.util.List;
public class AccessTokenMapperTest {
AccessTokenMapper accessTokenMapper;
@Before
public void before(){
accessTokenMapper = ConnectionFactory.getSqlSession().getMapper(AccessTokenMapper.class);
}
@Test
public void testInsert(){
AccessToken accessToken = new AccessToken();
accessToken.setUserId(10);
accessToken.setExpireTime(new Date());
accessToken.setToken("ssssssssssssssssssssssssss");
accessToken.setCreateTime(new Date());
accessToken.setUpdateTime(new Date());
accessTokenMapper.insert(accessToken);
}
@Test
public void testListPaging(){
Integer count = accessTokenMapper.countAccessTokenPaging("");
Assert.assertEquals(count, (Integer) 5);
List<AccessToken> accessTokenList = accessTokenMapper.queryAccessTokenPaging("", 0, 2);
Assert.assertEquals(accessTokenList.size(), 5);
}
}

6
escheduler-dao/src/test/java/cn/escheduler/dao/mapper/UserMapperTest.java

@ -66,4 +66,10 @@ public class UserMapperTest {
Assert.assertEquals(queue, "ait");
}
@Test
public void testQueryUserByToken(){
User user = userMapper.queryUserByToken("ad9e8fccfc11bd18bb45aa994568b8ef");
Assert.assertEquals(user.getUserName(), "qiaozhanwei");
}
}

Loading…
Cancel
Save