diff --git a/.gitignore b/.gitignore index 0886693..94d9114 100644 --- a/.gitignore +++ b/.gitignore @@ -113,9 +113,5 @@ gradle-app.setting # Cache of project .gradletasknamecache -# Eclipse Gradle plugin generated files -# Eclipse Core -.project -# JDT-specific (Eclipse Java Development Tools) -.classpath - +# ---> Gradle +.idea diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..7984f42 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,55 @@ +plugins { + java + id("org.springframework.boot") version "3.5.4" + id("io.spring.dependency-management") version "1.1.7" +} + +group = "day.gitlab" +version = "0.0.1-SNAPSHOT" + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(21) + } +} + +configurations { + compileOnly { + extendsFrom(configurations.annotationProcessor.get()) + } +} + +repositories { + mavenCentral() +} + +dependencies { + // spring boot starter + implementation("org.springframework.boot:spring-boot-starter-web") + implementation("org.springframework.boot:spring-boot-starter-data-jdbc") + implementation("org.springframework.boot:spring-boot-starter-data-redis") + // magic api + implementation("org.ssssssss:magic-api-spring-boot-starter:2.2.2") + implementation("org.ssssssss:magic-api-plugin-redis:2.2.2") + implementation("org.ssssssss:magic-api-plugin-task:2.2.2") + // database drivers + runtimeOnly("com.mysql:mysql-connector-j") + runtimeOnly("com.oracle.database.jdbc:ojdbc11") + runtimeOnly("org.postgresql:postgresql") + // hutool + implementation("org.dromara.hutool:hutool-all:6.0.0-M22") + // lombok + compileOnly("org.projectlombok:lombok") + annotationProcessor("org.projectlombok:lombok") + // fixed + implementation("commons-io:commons-io:2.20.0") + implementation("org.apache.commons:commons-lang3:3.18.0") + implementation("org.apache.commons:commons-compress:1.28.0") + // test + testImplementation("org.springframework.boot:spring-boot-starter-test") + testRuntimeOnly("org.junit.platform:junit-platform-launcher") +} + +tasks.withType { + useJUnitPlatform() +} diff --git a/data/magic-api/api/认证授权/group.json b/data/magic-api/api/认证授权/group.json new file mode 100644 index 0000000..a211bd7 --- /dev/null +++ b/data/magic-api/api/认证授权/group.json @@ -0,0 +1,14 @@ +{ + "properties" : { }, + "id" : "0f7392c3132d4ae698caf0e8ab55756b", + "name" : "认证授权", + "type" : "api", + "parentId" : "0", + "path" : "authorize", + "createTime" : 1754119561731, + "updateTime" : null, + "createBy" : "admin", + "updateBy" : null, + "paths" : [ ], + "options" : [ ] +} \ No newline at end of file diff --git a/data/magic-api/api/认证授权/注销.ms b/data/magic-api/api/认证授权/注销.ms new file mode 100644 index 0000000..9f5b4d1 --- /dev/null +++ b/data/magic-api/api/认证授权/注销.ms @@ -0,0 +1,47 @@ +{ + "properties" : { }, + "id" : "f8d0bf079a944feaaa98f9f55efb06ee", + "script" : null, + "groupId" : "0f7392c3132d4ae698caf0e8ab55756b", + "name" : "注销", + "createTime" : 1754121435355, + "updateTime" : 1754121748966, + "lock" : null, + "createBy" : "admin", + "updateBy" : "admin", + "path" : "logout", + "method" : "POST", + "parameters" : [ ], + "options" : [ ], + "requestBody" : "{\n \"refresh_token\": \"4f240f5143ae4b7abecf6061e0074ceb\"\n}", + "headers" : [ { + "name" : "access_token", + "value" : "66c010c2039e4939aaf8377c40ed1b07", + "description" : null, + "required" : true, + "dataType" : "String", + "type" : null, + "defaultValue" : null, + "validateType" : null, + "error" : null, + "expression" : null, + "children" : null + } ], + "paths" : [ ], + "responseBody" : "{\n \"code\": \"000001\",\n \"message\": \"失败: 请求参数无效,刷新令牌不能为空\",\n \"data\": null\n}", + "description" : null, + "requestBodyDefinition" : null, + "responseBodyDefinition" : null +} +================================ + +if (is_null(body) || is_blank(body.refresh_token)){ + return biz_failure_fmt(BizConstants.FAILURE, "请求参数无效,刷新令牌不能为空") +} + +var access_token = header.access_token +var refresh_token = body.refresh_token +redis_del("dolphin:access_token:" + access_token) +redis_del("dolphin:refresh_token:" + refresh_token) + +return success() \ No newline at end of file diff --git a/data/magic-api/api/认证授权/登录.ms b/data/magic-api/api/认证授权/登录.ms new file mode 100644 index 0000000..82ae048 --- /dev/null +++ b/data/magic-api/api/认证授权/登录.ms @@ -0,0 +1,171 @@ +{ + "properties" : { }, + "id" : "6fcf21ad09874c2ca00dd9283f2a16cb", + "script" : null, + "groupId" : "0f7392c3132d4ae698caf0e8ab55756b", + "name" : "登录", + "createTime" : 1754119582735, + "updateTime" : 1754121286889, + "lock" : null, + "createBy" : "admin", + "updateBy" : "admin", + "path" : "login", + "method" : "POST", + "parameters" : [ ], + "options" : [ ], + "requestBody" : "{\n \"username\": \"admin\",\n \"password\": \"123456\"\n}", + "headers" : [ ], + "paths" : [ ], + "responseBody" : "{\n \"code\": \"000000\",\n \"message\": \"成功\",\n \"data\": {\n \"access_token\": \"7a01c52f44d54dd6a6517ba36cba122f\",\n \"refresh_token\": \"d8c639f0288a4cdfa96ac56378bdcc23\"\n }\n}", + "description" : null, + "requestBodyDefinition" : { + "name" : "", + "value" : "", + "description" : "", + "required" : false, + "dataType" : "Object", + "type" : null, + "defaultValue" : null, + "validateType" : "", + "error" : "", + "expression" : "", + "children" : [ { + "name" : "username", + "value" : "admin", + "description" : "", + "required" : false, + "dataType" : "String", + "type" : null, + "defaultValue" : null, + "validateType" : "", + "error" : "", + "expression" : "", + "children" : [ ] + }, { + "name" : "password", + "value" : "123456", + "description" : "", + "required" : false, + "dataType" : "String", + "type" : null, + "defaultValue" : null, + "validateType" : "", + "error" : "", + "expression" : "", + "children" : [ ] + } ] + }, + "responseBodyDefinition" : { + "name" : "", + "value" : "", + "description" : "", + "required" : false, + "dataType" : "Object", + "type" : null, + "defaultValue" : null, + "validateType" : "", + "error" : "", + "expression" : "", + "children" : [ { + "name" : "code", + "value" : "000000", + "description" : "", + "required" : false, + "dataType" : "String", + "type" : null, + "defaultValue" : null, + "validateType" : "", + "error" : "", + "expression" : "", + "children" : [ ] + }, { + "name" : "message", + "value" : "成功", + "description" : "", + "required" : false, + "dataType" : "String", + "type" : null, + "defaultValue" : null, + "validateType" : "", + "error" : "", + "expression" : "", + "children" : [ ] + }, { + "name" : "data", + "value" : "", + "description" : "", + "required" : false, + "dataType" : "Object", + "type" : null, + "defaultValue" : null, + "validateType" : "", + "error" : "", + "expression" : "", + "children" : [ { + "name" : "access_token", + "value" : "1234e6e666184d479eb08e29d23bfa8e", + "description" : "", + "required" : false, + "dataType" : "String", + "type" : null, + "defaultValue" : null, + "validateType" : "", + "error" : "", + "expression" : "", + "children" : [ ] + }, { + "name" : "refresh_token", + "value" : "ddedf3a00fcf4a3ba7e88712ec446b45", + "description" : "", + "required" : false, + "dataType" : "String", + "type" : null, + "defaultValue" : null, + "validateType" : "", + "error" : "", + "expression" : "", + "children" : [ ] + } ] + } ] + } +} +================================ +// 参数校验 +if (is_null(body) || is_blank(body.username) || is_blank(body.password)){ + return biz_failure_fmt(BizConstants.FAILURE, "请求参数无效,用户名或密码不能为空") +} + +// 登录 +var userDO = db.select(""" + SELECT * FROM sys_org_user WHERE username = #{body.username} +""") +if (userDO == null || !bcrypt_match(body.password, userDO.password)){ + return biz_failure_fmt(BizConstants.FAILURE, "用户名或密码错误") +} +if (userDO.status == "PENDING") { + return biz_failure_fmt(BizConstants.FAILURE, "用户未审核通过") +} +if (userDO.status == "LOCKED") { + return biz_failure_fmt(BizConstants.FAILURE, "用户以被锁定,请稍后重试") +} +if (userDO.status == "BANNED") { + return biz_failure_fmt(BizConstants.FAILURE, "用户以被禁用") +} +if (userDO.status == "DELETED") { + return biz_failure_fmt(BizConstants.FAILURE, "用户不存在") +} + +var access_token = uuid() +redis_setex("dolphin:access_token:" + access_token, { + id: userDO.id, + username: userDO.username +}, 1000 * 60 * 30) +var refresh_token = uuid() +redis_setex("dolphin:refresh_token:" + refresh_token, { + access_token: access_token +}, 1000 * 60 * 60 * 24 * 7) + +return success({ + access_token: access_token, + refresh_token: refresh_token +}) \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..1b33c55 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..d4081da --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..23d15a9 --- /dev/null +++ b/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed 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 +# +# https://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. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH="\\\"\\\"" + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..db3a6ac --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..1aa204e --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "dolphin-parent" diff --git a/src/main/java/day/gitlab/dolphin/DolphinApplication.java b/src/main/java/day/gitlab/dolphin/DolphinApplication.java new file mode 100644 index 0000000..67cad44 --- /dev/null +++ b/src/main/java/day/gitlab/dolphin/DolphinApplication.java @@ -0,0 +1,13 @@ +package day.gitlab.dolphin; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class DolphinApplication { + + public static void main(String[] args) { + SpringApplication.run(DolphinApplication.class, args); + } + +} diff --git a/src/main/java/day/gitlab/dolphin/magic/config/MagicResultProvider.java b/src/main/java/day/gitlab/dolphin/magic/config/MagicResultProvider.java new file mode 100644 index 0000000..6226a7f --- /dev/null +++ b/src/main/java/day/gitlab/dolphin/magic/config/MagicResultProvider.java @@ -0,0 +1,23 @@ +package day.gitlab.dolphin.magic.config; + +import org.springframework.stereotype.Component; +import org.ssssssss.magicapi.core.context.RequestEntity; +import org.ssssssss.magicapi.core.interceptor.ResultProvider; +import org.ssssssss.magicapi.modules.db.model.Page; + +import java.util.List; +import java.util.Map; + +@Component +public class MagicResultProvider implements ResultProvider { + + @Override + public Object buildResult(RequestEntity requestEntity, int code, String message, Object data) { + return data; + } + + @Override + public Object buildPageResult(RequestEntity requestEntity, Page page, long total, List> data) { + return data; + } +} diff --git a/src/main/java/day/gitlab/dolphin/magic/constants/BizConstants.java b/src/main/java/day/gitlab/dolphin/magic/constants/BizConstants.java new file mode 100644 index 0000000..0083539 --- /dev/null +++ b/src/main/java/day/gitlab/dolphin/magic/constants/BizConstants.java @@ -0,0 +1,31 @@ +package day.gitlab.dolphin.magic.constants; + +public class BizConstants { + + // *************************************** + // * 通用 * + // *************************************** + + public static final String SUCCESS = "000000"; + public static final String FAILURE = "000001"; + + // *************************************** + // * 01-认证授权 * + // *************************************** + + /** 业务:认证 */ + public static final String AUTH_01 = "0101"; + /** 错误:认证-未登录 */ + public static final String AUTH_0101 = AUTH_01 + "01"; + /** 错误:认证-令牌过期 */ + public static final String AUTH_0102 = AUTH_01 + "02"; + /** 错误:认证-令牌无效 */ + public static final String AUTH_0103 = AUTH_01 + "03"; + /** 错误:认证-令牌刷新失败 */ + public static final String AUTH_0104 = AUTH_01 + "04"; + + /** 业务:鉴权 */ + public static final String AUTH_02 = "010200"; + /** 错误:鉴权-无权限 */ + public static final String AUTH_0201 = AUTH_02 + "01"; +} diff --git a/src/main/java/day/gitlab/dolphin/magic/functions/CryptoFunction.java b/src/main/java/day/gitlab/dolphin/magic/functions/CryptoFunction.java new file mode 100644 index 0000000..a0abbe7 --- /dev/null +++ b/src/main/java/day/gitlab/dolphin/magic/functions/CryptoFunction.java @@ -0,0 +1,55 @@ +package day.gitlab.dolphin.magic.functions; + +import lombok.NonNull; +import org.dromara.hutool.crypto.digest.BCrypt; +import org.dromara.hutool.crypto.digest.DigestUtil; +import org.springframework.stereotype.Component; +import org.ssssssss.magicapi.core.config.MagicFunction; +import org.ssssssss.script.annotation.Comment; +import org.ssssssss.script.annotation.Function; + +@Component +public class CryptoFunction implements MagicFunction { + + @Function + @Comment("计算MD5摘要") + public String md5(@NonNull String data) { + return DigestUtil.md5Hex(data); + } + + @Function + @Comment("计算SHA1摘要") + public String sha1(@NonNull String data) { + return DigestUtil.sha1Hex(data); + } + + @Function + @Comment("计算SHA256摘要") + public String sha256(@NonNull String data) { + return DigestUtil.sha256Hex(data); + } + + @Function + @Comment("计算SHA512摘要") + public String sha512(@NonNull String data) { + return DigestUtil.sha512Hex(data); + } + + @Function + @Comment("计算BCrypt摘要") + public String bcrypt(@NonNull String data) { + return BCrypt.hashpw(data); + } + + @Function + @Comment("计算BCrypt摘要") + public String bcrypt(@NonNull String data, int logRounds) { + return BCrypt.hashpw(data, BCrypt.gensalt(logRounds)); + } + + @Function + @Comment("验证BCrypt摘要") + public boolean bcrypt_match(@NonNull String plain_data, @NonNull String hashed_data) { + return BCrypt.checkpw(plain_data, hashed_data); + } +} diff --git a/src/main/java/day/gitlab/dolphin/magic/functions/MessageFunction.java b/src/main/java/day/gitlab/dolphin/magic/functions/MessageFunction.java new file mode 100644 index 0000000..e6d9a63 --- /dev/null +++ b/src/main/java/day/gitlab/dolphin/magic/functions/MessageFunction.java @@ -0,0 +1,35 @@ +package day.gitlab.dolphin.magic.functions; + +import day.gitlab.dolphin.magic.util.Messages; +import org.springframework.stereotype.Component; +import org.ssssssss.magicapi.core.config.MagicFunction; +import org.ssssssss.script.annotation.Comment; +import org.ssssssss.script.annotation.Function; + +@Component +public class MessageFunction implements MagicFunction { + + @Function + @Comment("获取资源文件中的消息") + public String message(String key) { + return Messages.message(key); + } + + @Function + @Comment("获取资源文件中的内容并格式化") + public String message_fmt(String key, Object... arguments) { + return Messages.messageFmt(key, arguments); + } + + @Function + @Comment("获取资源文件中的业务消息") + public String biz_message(String code) { + return Messages.bizMessage(code); + } + + @Function + @Comment("获取资源文件中的业务消息并格式化") + public String biz_message_fmt(String code, Object... arguments) { + return Messages.bizMessageFmt(code, arguments); + } +} diff --git a/src/main/java/day/gitlab/dolphin/magic/functions/RedisFunction.java b/src/main/java/day/gitlab/dolphin/magic/functions/RedisFunction.java new file mode 100644 index 0000000..1fc8759 --- /dev/null +++ b/src/main/java/day/gitlab/dolphin/magic/functions/RedisFunction.java @@ -0,0 +1,105 @@ +package day.gitlab.dolphin.magic.functions; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.Data; +import lombok.NonNull; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.stereotype.Component; +import org.ssssssss.magicapi.core.config.MagicFunction; +import org.ssssssss.script.annotation.Comment; +import org.ssssssss.script.annotation.Function; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +@Data +@Component +public class RedisFunction implements MagicFunction { + + private StringRedisTemplate stringRedisTemplate; + + private ObjectMapper objectMapper; + + @Autowired + public RedisFunction(StringRedisTemplate stringRedisTemplate, ObjectMapper objectMapper) { + this.stringRedisTemplate = stringRedisTemplate; + this.objectMapper = objectMapper; + } + + @Function + @Comment("设置Redis缓存") + public void redis_set(@NonNull String key, @NonNull Object value) { + if (value instanceof String) { + stringRedisTemplate.opsForValue().set(key, (String) value); + } else { + try { + stringRedisTemplate.opsForValue().set(key, objectMapper.writeValueAsString(value)); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + } + } + + @Function + @Comment("设置Redis缓存") + public void redis_setex(@NonNull String key, @NonNull Object value, long expire) { + if (value instanceof String) { + stringRedisTemplate.opsForValue().set(key, (String) value, expire, TimeUnit.MILLISECONDS); + } else { + try { + stringRedisTemplate.opsForValue().set(key, objectMapper.writeValueAsString(value), expire, TimeUnit.MILLISECONDS); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + } + } + + @Function + @Comment("判断是否存在Redis缓存") + public Object redis_haskey(@NonNull String key) { + return stringRedisTemplate.hasKey(key); + } + + @Function + @Comment("获取Redis缓存") + public String redis_get(@NonNull String key) { + return stringRedisTemplate.opsForValue().get(key); + } + + @Function + @Comment("获取Redis缓存") + public Map redis_getmap(@NonNull String key) { + String value = stringRedisTemplate.opsForValue().get(key); + try { + return value == null ? null : objectMapper.readValue(value, HashMap.class); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Function + @Comment("获取Redis缓存") + public T redis_getobj(@NonNull String key, @NonNull Class tClass) { + String value = stringRedisTemplate.opsForValue().get(key); + try { + return value == null ? null : objectMapper.readValue(value, tClass); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Function + @Comment("删除Redis缓存") + public Boolean redis_del(@NonNull String key) { + return stringRedisTemplate.delete(key); + } + + @Function + @Comment("设置Redis缓存过期时间") + public Boolean redis_expire(@NonNull String key, long expire) { + return stringRedisTemplate.expire(key, expire, TimeUnit.MILLISECONDS); + } +} diff --git a/src/main/java/day/gitlab/dolphin/magic/functions/ResultFunction.java b/src/main/java/day/gitlab/dolphin/magic/functions/ResultFunction.java new file mode 100644 index 0000000..02b3733 --- /dev/null +++ b/src/main/java/day/gitlab/dolphin/magic/functions/ResultFunction.java @@ -0,0 +1,41 @@ +package day.gitlab.dolphin.magic.functions; + +import day.gitlab.dolphin.magic.util.Result; +import org.springframework.stereotype.Component; +import org.ssssssss.magicapi.core.config.MagicFunction; +import org.ssssssss.script.annotation.Comment; +import org.ssssssss.script.annotation.Function; + +@Component +public class ResultFunction implements MagicFunction { + + @Function + @Comment("成功响应") + public Result success() { + return Result.success(); + } + + @Function + @Comment("具有数据的成功响应") + public Result success(Object data) { + return Result.success(data); + } + + @Function + @Comment("失败响应") + public Result failure(String code, String message) { + return Result.builder().code(code).message(message).build(); + } + + @Function + @Comment("业务失败响应") + public Result biz_failure(String code) { + return Result.failure(code); + } + + @Function + @Comment("具有格式化参数的业务失败响应") + public Result biz_failure_fmt(String code, Object... parameters) { + return Result.failureFmt(code, parameters); + } +} diff --git a/src/main/java/day/gitlab/dolphin/magic/util/Messages.java b/src/main/java/day/gitlab/dolphin/magic/util/Messages.java new file mode 100644 index 0000000..3c437a3 --- /dev/null +++ b/src/main/java/day/gitlab/dolphin/magic/util/Messages.java @@ -0,0 +1,41 @@ +package day.gitlab.dolphin.magic.util; + +import lombok.Synchronized; + +import java.text.MessageFormat; +import java.util.Locale; +import java.util.Map; +import java.util.ResourceBundle; +import java.util.concurrent.ConcurrentHashMap; + +public class Messages { + + private static final String MESSAGE_KEY = "lang.messages"; + private static final Map MESSAGE_MAP = new ConcurrentHashMap<>(); + + @Synchronized + public static String message(String key) { + // 加载资源包 + Locale currentLocale = Locale.getDefault(); + ResourceBundle bundle = MESSAGE_MAP.get(currentLocale); + if (bundle == null) { + bundle = ResourceBundle.getBundle(MESSAGE_KEY, currentLocale); + MESSAGE_MAP.put(currentLocale, bundle); + } + + return bundle.containsKey(key) ? bundle.getString(key) : null; + } + + public static String messageFmt(String key, Object... arguments) { + String pattern = message(key + ".fmt"); + return pattern == null ? null : arguments == null ? pattern : MessageFormat.format(pattern, arguments); + } + + public static String bizMessage(String code) { + return message("biz." + code); + } + + public static String bizMessageFmt(String code, Object... arguments) { + return messageFmt("biz." + code, arguments); + } +} diff --git a/src/main/java/day/gitlab/dolphin/magic/util/Result.java b/src/main/java/day/gitlab/dolphin/magic/util/Result.java new file mode 100644 index 0000000..c359a73 --- /dev/null +++ b/src/main/java/day/gitlab/dolphin/magic/util/Result.java @@ -0,0 +1,44 @@ +package day.gitlab.dolphin.magic.util; + +import day.gitlab.dolphin.magic.constants.BizConstants; +import lombok.Builder; +import lombok.Data; +import lombok.NonNull; + +@Data +@Builder +public class Result { + + /** 业务状态码 */ + private String code; + + /** 业务状态码描述 */ + private String message; + + /** 业务数据 */ + private Object data; + + public static Result success() { + return biz(BizConstants.SUCCESS, null); + } + + public static Result success(Object data) { + return biz(BizConstants.SUCCESS, data); + } + + public static Result failure(String code) { + return biz(code, null); + } + + public static Result failureFmt(String code, Object... parameters) { + return bizFmt(code, null, parameters); + } + + public static Result biz(@NonNull String code, Object data) { + return Result.builder().code(code).message(Messages.bizMessage(code)).data(data).build(); + } + + public static Result bizFmt(@NonNull String code, Object data, Object... parameters) { + return Result.builder().code(code).message(Messages.bizMessageFmt(code, parameters)).data(data).build(); + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..793b327 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,53 @@ +server: + port: 11001 + servlet: + context-path: / +spring: + application: + name: dolphin-parent + datasource: + name: postgres + driver-class-name: org.postgresql.Driver + url: jdbc:postgresql://192.168.5.7:5432/dolphin + username: postgres + password: postgres + hikari: + maximum-pool-size: 10 + minimum-idle: 5 + idle-timeout: 30000 + max-lifetime: 1800000 + connection-timeout: 30000 + pool-name: dolphin-pool + leak-detection-threshold: 2000 + connection-test-query: SELECT 1 + data: + redis: + host: 192.168.5.7 + port: 16379 + database: 0 + password: + timeout: 5000 + jackson: + locale: zh_CN + time-zone: GMT+8 + date-format: yyyy-MM-dd HH:mm:ss +magic-api: + web: /magic + resource: + type: file + location: data/magic-api + readonly: false + prefix: /api + auto-import-module: db,redis + auto-import-package: java.lang.*,java.util.*,day.gitlab.dolphin.magic.constants.* + allow-override: false + sql-column-case: camel + support-cross-domain: true + show-sql: true + compile-cache-size: 500 + persistence-response-body: true + secret-key: 123456 + push-path: data/magic-api-sync + security: + username: admin + password: 123456 \ No newline at end of file diff --git a/src/main/resources/lang/messages.properties b/src/main/resources/lang/messages.properties new file mode 100644 index 0000000..5d4bd4c --- /dev/null +++ b/src/main/resources/lang/messages.properties @@ -0,0 +1,21 @@ + +common.fmt={0} + +# ******************** business ******************** + +# 业务:通用-成功 +biz.000000=success +# 业务:通用-失败 +biz.000001=failure +biz.000001.fmt=failure: {0} + +# 业务:认证授权-未认证 +biz.010101=Unauthorized +# 业务:认证授权-令牌过期 +biz.010102=Token expired +# 业务:认证授权-令牌无效 +biz.010103=Invalid token +# 业务:认证授权-令牌刷新失败 +biz.010104=Token refresh failed +# 业务:认证授权-鉴权失败 +biz.010201=Forbidden diff --git a/src/main/resources/lang/messages_zh_CN.properties b/src/main/resources/lang/messages_zh_CN.properties new file mode 100644 index 0000000..7593218 --- /dev/null +++ b/src/main/resources/lang/messages_zh_CN.properties @@ -0,0 +1,21 @@ + +common.fmt={0} + +# ******************** business ******************** + +# 业务:通用-成功 +biz.000000=成功 +# 业务:通用-失败 +biz.000001=失败 +biz.000001.fmt=失败: {0} + +# 业务:认证授权-未认证 +biz.010101=认证失败 +# 业务:认证授权-令牌过期 +biz.010102=令牌过期 +# 业务:认证授权-令牌无效 +biz.010103=令牌无效 +# 业务:认证授权-令牌刷新失败 +biz.010104=令牌刷新失败 +# 业务:认证授权-鉴权失败 +biz.010201=无权限 diff --git a/src/test/java/day/gitlab/dolphin/DolphinApplicationTests.java b/src/test/java/day/gitlab/dolphin/DolphinApplicationTests.java new file mode 100644 index 0000000..dfb92ad --- /dev/null +++ b/src/test/java/day/gitlab/dolphin/DolphinApplicationTests.java @@ -0,0 +1,13 @@ +package day.gitlab.dolphin; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class DolphinApplicationTests { + + @Test + void contextLoads() { + } + +}