Search in sources :

Example 6 with NotLogin

use of io.jpom.common.interceptor.NotLogin in project Jpom by dromara.

the class InstallController method installSubmit.

/**
 * 初始化提交
 *
 * @param userName 系统管理员登录名
 * @param userPwd  系统管理员的登录密码
 * @return json
 * @api {post} install_submit.json 初始化提交
 * @apiGroup index
 * @apiUse defResultJson
 * @apiParam {String} userName 系统管理员登录名
 * @apiParam {String} userPwd 设置的登录密码 sha1 后传入
 * @apiSuccess {JSON}  data.tokenData token 相关信息
 * @apiSuccess {String}  data.mfaKey 二次验证的key
 * @apiSuccess {String}  data.url 二次验证的二维码相关字符串用户快速扫码导入
 */
@PostMapping(value = "install_submit.json", produces = MediaType.APPLICATION_JSON_VALUE)
@NotLogin
public String installSubmit(@ValidatorConfig(value = { @ValidatorItem(value = ValidatorRule.NOT_EMPTY, msg = "登录名不能为空"), @ValidatorItem(value = ValidatorRule.NOT_BLANK, range = UserModel.USER_NAME_MIN_LEN + ":" + Const.ID_MAX_LEN, msg = "登录名长度范围" + UserModel.USER_NAME_MIN_LEN + "-" + Const.ID_MAX_LEN), @ValidatorItem(value = ValidatorRule.WORD, msg = "登录名不能包含汉字并且不能包含特殊字符") }) String userName, @ValidatorItem(value = ValidatorRule.NOT_BLANK, msg = "密码不能为空") String userPwd) {
    // 
    Assert.state(!userService.canUse(), "系统已经初始化过啦,请勿重复初始化");
    boolean systemOccupyUserName = StrUtil.equalsAnyIgnoreCase(userName, UserModel.DEMO_USER, JpomApplication.SYSTEM_ID, UserModel.SYSTEM_ADMIN);
    Assert.state(!systemOccupyUserName, "当前登录名已经被系统占用啦");
    // 创建用户
    UserModel userModel = new UserModel();
    userModel.setName(UserModel.SYSTEM_OCCUPY_NAME);
    userModel.setId(userName);
    userModel.setSalt(userService.generateSalt());
    userModel.setPassword(SecureUtil.sha1(userPwd + userModel.getSalt()));
    userModel.setSystemUser(1);
    userModel.setParent(UserModel.SYSTEM_ADMIN);
    try {
        BaseServerController.resetInfo(userModel);
        userService.insert(userModel);
    } catch (Exception e) {
        DefaultSystemLog.getLog().error("初始化用户失败", e);
        return JsonMessage.getString(400, "初始化失败:" + e.getMessage());
    }
    // 自动登录
    setSessionAttribute(LoginInterceptor.SESSION_NAME, userModel);
    UserLoginDto userLoginDto = userService.getUserJwtId(userModel);
    List<WorkspaceModel> bindWorkspaceModels = userBindWorkspaceService.listUserWorkspaceInfo(userModel);
    userLoginDto.setBindWorkspaceModels(bindWorkspaceModels);
    // 二次验证信息
    JSONObject jsonObject = new JSONObject();
    String tfaKey = TwoFactorAuthUtils.generateTFAKey();
    jsonObject.put("mfaKey", tfaKey);
    jsonObject.put("url", TwoFactorAuthUtils.generateOtpAuthUrl(userName, tfaKey));
    jsonObject.put("tokenData", userLoginDto);
    return JsonMessage.getString(200, "初始化成功", jsonObject);
}
Also used : UserModel(io.jpom.model.data.UserModel) WorkspaceModel(io.jpom.model.data.WorkspaceModel) JSONObject(com.alibaba.fastjson.JSONObject) UserLoginDto(io.jpom.model.dto.UserLoginDto) NotLogin(io.jpom.common.interceptor.NotLogin) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 7 with NotLogin

use of io.jpom.common.interceptor.NotLogin in project Jpom by dromara.

the class IndexControl method index.

/**
 * 加载首页
 *
 * @api {get} / 加载首页 服务端前端页面
 * @apiGroup index
 * @apiSuccess {String} BODY HTML
 */
@GetMapping(value = { "index", "", "/" }, produces = MediaType.TEXT_HTML_VALUE)
@NotLogin
public void index(HttpServletResponse response) {
    InputStream inputStream = ResourceUtil.getStream("classpath:/dist/index.html");
    String html = IoUtil.read(inputStream, CharsetUtil.CHARSET_UTF_8);
    // <div id="jpomCommonJs"></div>
    String path = ExtConfigBean.getInstance().getPath();
    File file = FileUtil.file(String.format("%s/script/common.js", path));
    if (file.exists()) {
        String jsCommonContext = FileUtil.readString(file, CharsetUtil.CHARSET_UTF_8);
        // <div id="jpomCommonJs"><!--Don't delete this line, place for public JS --></div>
        String[] commonJsTemps = new String[] { "<div id=\"jpomCommonJs\"><!--Don't delete this line, place for public JS --></div>", "<div id=\"jpomCommonJs\"></div>" };
        for (String item : commonJsTemps) {
            html = StrUtil.replace(html, item, jsCommonContext);
        }
    }
    // <routerBase>
    String proxyPath = UrlRedirectUtil.getHeaderProxyPath(getRequest(), BaseJpomInterceptor.PROXY_PATH);
    html = StrUtil.replace(html, "<routerBase>", proxyPath);
    // <apiTimeOut>
    int webApiTimeout = ServerExtConfigBean.getInstance().getWebApiTimeout();
    html = StrUtil.replace(html, "<apiTimeout>", TimeUnit.SECONDS.toMillis(webApiTimeout) + "");
    // 修改网页标题
    String title = ReUtil.get("<title>.*?</title>", html, 0);
    if (StrUtil.isNotEmpty(title)) {
        html = StrUtil.replace(html, title, "<title>" + ServerExtConfigBean.getInstance().getName() + "</title>");
    }
    ServletUtil.write(response, html, ContentType.TEXT_HTML.getValue());
}
Also used : InputStream(java.io.InputStream) File(java.io.File) NotLogin(io.jpom.common.interceptor.NotLogin) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 8 with NotLogin

use of io.jpom.common.interceptor.NotLogin in project Jpom by dromara.

the class LoginControl method renewalToken.

/**
 * 刷新token
 *
 * @return json
 */
@RequestMapping(value = "renewal", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
@NotLogin
public String renewalToken() {
    String token = getRequest().getHeader(ServerOpenApi.HTTP_HEAD_AUTHORIZATION);
    if (StrUtil.isEmpty(token)) {
        return JsonMessage.getString(ServerConfigBean.AUTHORIZE_TIME_OUT_CODE, "刷新token失败");
    }
    JWT jwt = JwtUtil.readBody(token);
    if (JwtUtil.expired(jwt, 0)) {
        int renewal = ServerExtConfigBean.getInstance().getAuthorizeRenewal();
        if (jwt == null || renewal <= 0 || JwtUtil.expired(jwt, TimeUnit.MINUTES.toSeconds(renewal))) {
            return JsonMessage.getString(ServerConfigBean.AUTHORIZE_TIME_OUT_CODE, "刷新token超时");
        }
    }
    UserModel userModel = userService.checkUser(JwtUtil.getId(jwt));
    if (userModel == null) {
        return JsonMessage.getString(ServerConfigBean.AUTHORIZE_TIME_OUT_CODE, "没有对应的用户");
    }
    UserLoginDto userLoginDto = userService.getUserJwtId(userModel);
    return JsonMessage.getString(200, "", userLoginDto);
}
Also used : UserModel(io.jpom.model.data.UserModel) JWT(cn.hutool.jwt.JWT) UserLoginDto(io.jpom.model.dto.UserLoginDto) NotLogin(io.jpom.common.interceptor.NotLogin)

Example 9 with NotLogin

use of io.jpom.common.interceptor.NotLogin in project Jpom by dromara.

the class LoginControl method mfaVerify.

@GetMapping(value = "mfa_verify", produces = MediaType.APPLICATION_JSON_VALUE)
@NotLogin
public String mfaVerify(String token, String code) {
    String userId = MFA_TOKEN.get(token);
    if (StrUtil.isEmpty(userId)) {
        return JsonMessage.getString(201, "登录信息已经过期请重新登录");
    }
    boolean mfaCode = userService.verifyMfaCode(userId, code);
    Assert.state(mfaCode, "验证码不正确,请重新输入");
    UserModel userModel = userService.getByKey(userId);
    // 
    UserLoginDto userLoginDto = this.createToken(userModel);
    MFA_TOKEN.remove(token);
    return JsonMessage.getString(200, "登录成功", userLoginDto);
}
Also used : UserModel(io.jpom.model.data.UserModel) UserLoginDto(io.jpom.model.dto.UserLoginDto) NotLogin(io.jpom.common.interceptor.NotLogin)

Example 10 with NotLogin

use of io.jpom.common.interceptor.NotLogin in project Jpom by dromara.

the class NodeInfoController method receivePush.

/**
 * 接收节点推送的信息
 * <p>
 * yum install -y wget && wget -O install.sh https://dromara.gitee.io/jpom/docs/install.sh && bash install.sh Agent jdk
 * --auto-push-to-server http://127.0.0.1:3000/api/node/receive_push?token=462a47b8fba8da1f824370bb9fcdc01aa1a0fe20&workspaceId=DEFAULT
 *
 * @return json
 */
@RequestMapping(value = ServerOpenApi.RECEIVE_PUSH, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@NotLogin
public String receivePush(@ValidatorItem(msg = "token empty") String token, @ValidatorItem(msg = "ips empty") String ips, @ValidatorItem(msg = "loginName empty") String loginName, @ValidatorItem(msg = "loginPwd empty") String loginPwd, @ValidatorItem(msg = "workspaceId empty") String workspaceId, @ValidatorItem(value = ValidatorRule.NUMBERS, msg = "port error") int port, String ping) {
    Assert.state(StrUtil.equals(token, JpomManifest.getInstance().randomIdSign()), "token error");
    boolean exists = workspaceService.exists(new WorkspaceModel(workspaceId));
    Assert.state(exists, "workspaceId error");
    String sha1Id = SecureUtil.sha1(ips);
    // 
    List<String> ipsList = StrUtil.split(ips, StrUtil.COMMA);
    String clientIp = getClientIP();
    if (!ipsList.contains(clientIp)) {
        ipsList.add(clientIp);
    }
    List<String> canUseIps = ipsList.stream().filter(s -> this.testIpProt(s, ping)).collect(Collectors.toList());
    List<NodeModel> canUseNode = canUseIps.stream().map(s -> {
        NodeModel model = NodeInfoController.this.createModel(s, loginName, loginPwd, port, workspaceId);
        try {
            nodeService.testNode(model);
        } catch (Exception e) {
            DefaultSystemLog.getLog().warn("测试结果:{} {}", model.getUrl(), e.getMessage());
            return null;
        }
        return model;
    }).filter(Objects::nonNull).collect(Collectors.toList());
    // 只返回能通的 IP
    canUseIps = canUseNode.stream().map(NodeModel::getName).collect(Collectors.toList());
    int size1 = CollUtil.size(canUseNode);
    // 
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("allIp", ipsList);
    jsonObject.put("canUseIp", canUseIps);
    jsonObject.put("port", port);
    jsonObject.put("id", sha1Id);
    jsonObject.put("canUseNode", canUseNode);
    // 
    exists = false;
    for (NodeModel nodeModel : canUseNode) {
        if (nodeService.existsByUrl(nodeModel.getUrl(), nodeModel.getWorkspaceId(), null)) {
            // 存在
            jsonObject.put("type", "exists");
            exists = true;
            break;
        }
    }
    if (!exists) {
        if (size1 == 1) {
            // 只有一个 ip 可以使用
            // 添加插件端
            NodeModel first = CollUtil.getFirst(canUseNode);
            nodeService.insertNotFill(first);
            jsonObject.put("type", "success");
        } else {
            jsonObject.put("type", size1 == 0 ? "canUseIpEmpty" : "multiIp");
        }
    }
    CACHE_RECEIVE_PUSH.put(sha1Id, jsonObject);
    return JsonMessage.getString(200, "done", jsonObject);
}
Also used : AbstractController(cn.jiangzeyin.controller.base.AbstractController) SecureUtil(cn.hutool.crypto.SecureUtil) java.util(java.util) ServerOpenApi(io.jpom.common.ServerOpenApi) DefaultSystemLog(cn.jiangzeyin.common.DefaultSystemLog) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) JsonMessage(cn.jiangzeyin.common.JsonMessage) NetUtil(cn.hutool.core.net.NetUtil) NodeService(io.jpom.service.node.NodeService) WorkspaceModel(io.jpom.model.data.WorkspaceModel) WorkspaceService(io.jpom.service.system.WorkspaceService) MediaType(org.springframework.http.MediaType) NodeModel(io.jpom.model.data.NodeModel) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) RestController(org.springframework.web.bind.annotation.RestController) Collectors(java.util.stream.Collectors) CollUtil(cn.hutool.core.collection.CollUtil) StrUtil(cn.hutool.core.util.StrUtil) ValidatorRule(cn.jiangzeyin.common.validator.ValidatorRule) JpomManifest(io.jpom.common.JpomManifest) ValidatorItem(cn.jiangzeyin.common.validator.ValidatorItem) Convert(cn.hutool.core.convert.Convert) JSONObject(com.alibaba.fastjson.JSONObject) NotLogin(io.jpom.common.interceptor.NotLogin) Assert(org.springframework.util.Assert) WorkspaceModel(io.jpom.model.data.WorkspaceModel) NodeModel(io.jpom.model.data.NodeModel) JSONObject(com.alibaba.fastjson.JSONObject) NotLogin(io.jpom.common.interceptor.NotLogin) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

NotLogin (io.jpom.common.interceptor.NotLogin)10 JSONObject (com.alibaba.fastjson.JSONObject)5 UserModel (io.jpom.model.data.UserModel)4 UserLoginDto (io.jpom.model.dto.UserLoginDto)4 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)3 WorkspaceModel (io.jpom.model.data.WorkspaceModel)2 ServerExtConfigBean (io.jpom.system.ServerExtConfigBean)2 File (java.io.File)2 InputStream (java.io.InputStream)2 CircleCaptcha (cn.hutool.captcha.CircleCaptcha)1 CollUtil (cn.hutool.core.collection.CollUtil)1 Convert (cn.hutool.core.convert.Convert)1 NetUtil (cn.hutool.core.net.NetUtil)1 StrUtil (cn.hutool.core.util.StrUtil)1 SecureUtil (cn.hutool.crypto.SecureUtil)1 JWT (cn.hutool.jwt.JWT)1 DefaultSystemLog (cn.jiangzeyin.common.DefaultSystemLog)1 JsonMessage (cn.jiangzeyin.common.JsonMessage)1 ValidatorItem (cn.jiangzeyin.common.validator.ValidatorItem)1 ValidatorRule (cn.jiangzeyin.common.validator.ValidatorRule)1