mirror of
https://github.com/KaySar12/NextZen-UserService.git
synced 2025-10-06 19:59:42 +07:00
Compare commits
106 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 5f1a220316 | |||
| 75abc7e651 | |||
| 465e77832e | |||
| 219fa12590 | |||
| dd3a9ebea4 | |||
| f0d6780c12 | |||
| 2e845d29b7 | |||
| 11de9608cd | |||
| 4e1321db6d | |||
| cd28792c15 | |||
| 5cf4ed5424 | |||
| dd927fe1c8 | |||
| 9c261dd8df | |||
| 7bd0df6441 | |||
| 62006f61b5 | |||
| c75063d7ca | |||
| 6738be00df | |||
| 3db4be01c4 | |||
| 2fdbdcf1ec | |||
| 3f4558e23c | |||
| 4d2b65e34c | |||
| fd925df5d1 | |||
| 2c1a72c5e5 | |||
| cd06d3ca37 | |||
| dc6cf30f7d | |||
| 6267b241a0 | |||
| b65d1350e3 | |||
| 3eaceda8d1 | |||
| e6c78401e7 | |||
| 8093de59ad | |||
| 5f166b9d3c | |||
| 869aa367f9 | |||
| 527e583f22 | |||
| 9c9a30c028 | |||
| 9a986a60ad | |||
| f626b02570 | |||
| f4e5706935 | |||
| 97c42efa71 | |||
| a2a23d1541 | |||
| 28b9015f29 | |||
| 7ef878cb1a | |||
| 6dfbf0eba9 | |||
| f5fcd9ed92 | |||
| ac34a1356d | |||
| b7cc389ef9 | |||
| f4dda2d6dd | |||
| f054c5340e | |||
| 76adb01211 | |||
| 3f89c925f2 | |||
| 0d57552952 | |||
| 4fc80b5a1e | |||
| 13b6091c79 | |||
| 856c5aeb48 | |||
| 8c960524e0 | |||
| 6b1d67efb1 | |||
| cbaba50f6f | |||
| 2acf34b224 | |||
| e2f9de8d4c | |||
| a7aec4cc5b | |||
| 98a35cb107 | |||
| f6ad3aa89a | |||
| dab1fdd6be | |||
| b41ab1ecce | |||
| a45ded5088 | |||
| 36f4943020 | |||
| a50025f316 | |||
| 8512876392 | |||
| 23d3c28288 | |||
| 12b047295e | |||
| e2d9ecf229 | |||
| 7da057088c | |||
| 2866ad73b5 | |||
| f112ed1783 | |||
| 1813afe0ae | |||
| 86a8c845c6 | |||
| 06ec3d5142 | |||
| 58a10d2200 | |||
| 0d7fee0cb1 | |||
| 8fcaee063d | |||
| 71e4f36c42 | |||
| 58ce3d1210 | |||
| 828fd3b8f5 | |||
| ace8e30dfb | |||
| 931d466df6 | |||
| e141c51b93 | |||
| 7b3bdbbf8a | |||
| 38fee52518 | |||
| 6c73a4be13 | |||
| 9afe211d90 | |||
| 44ca8efc0d | |||
| 675ecb55f7 | |||
| 5417c6b94b | |||
| 8d9c3f987d | |||
| 210aa979f5 | |||
| 44780ac1b4 | |||
| acdbb326bc | |||
| 8b2af35f39 | |||
| 2493e91ce8 | |||
| 0b66fd838f | |||
| 52d38428b6 | |||
| c1272b4b30 | |||
| fe354dfa7f | |||
| 1d1a15a221 | |||
| 7792496f2d | |||
| e2b617e510 | |||
| a71dd10757 |
@@ -0,0 +1,28 @@
|
||||
name: Collect Code Coverage
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-22.04
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v4
|
||||
with:
|
||||
go-version: "1.20"
|
||||
- name: Go Generate
|
||||
run: go generate
|
||||
- name: Run coverage
|
||||
run: go test -race -failfast -coverprofile=coverage.txt -covermode=atomic -v ./...
|
||||
- name: Upload coverage to Codecov
|
||||
uses: codecov/codecov-action@v3
|
||||
@@ -0,0 +1,38 @@
|
||||
name: publish npm
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- v*.*.*
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
publish-npm:
|
||||
runs-on: ubuntu-22.04
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: 16
|
||||
registry-url: https://registry.npmjs.org/
|
||||
- name: Get version
|
||||
id: get_version
|
||||
run: echo ::set-output name=VERSION::${GITHUB_REF/refs\/tags\//}
|
||||
- name: Set version
|
||||
run: |
|
||||
apt install jq
|
||||
jq '.version="${{ steps.get_version.outputs.VERSION }}"' package.json > package.json.new
|
||||
mv package.json.new package.json
|
||||
- name: Generate SDK
|
||||
run: |
|
||||
npm cache clean --force
|
||||
npm install @openapitools/openapi-generator-cli -g
|
||||
make build
|
||||
- run: npm i
|
||||
- run: npm run start
|
||||
- run: npm publish
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{secrets.npm_token}}
|
||||
@@ -0,0 +1,75 @@
|
||||
name: Auto Publish Website
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
permissions:
|
||||
contents: write
|
||||
jobs:
|
||||
goreleaser:
|
||||
runs-on: ubuntu-22.04
|
||||
steps:
|
||||
-
|
||||
name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: isntall git
|
||||
run: sudo apt install --yes git
|
||||
- name: git global
|
||||
run: sudo git config --global --add safe.directory '*'
|
||||
-
|
||||
name: Fetch all tags
|
||||
run: sudo git fetch --force --tags
|
||||
|
||||
- name: set version
|
||||
run: sudo git tag v99.99.99-alpha
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v4
|
||||
with:
|
||||
go-version: 'stable'
|
||||
|
||||
- name: Run GoReleaser
|
||||
uses: goreleaser/goreleaser-action@v4
|
||||
with:
|
||||
# either 'goreleaser' (default) or 'goreleaser-pro'
|
||||
distribution: goreleaser
|
||||
version: 1.14.1
|
||||
args: release --rm-dist --snapshot
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
# Your GoReleaser Pro key, if you are using the 'goreleaser-pro' distribution
|
||||
# GORELEASER_KEY: ${{ secrets.GORELEASER_KEY }}
|
||||
|
||||
- name: remove migration file
|
||||
run: find . -type f \( -name '*migration*' \) -delete
|
||||
|
||||
- name: install sshpass
|
||||
run: sudo apt install sshpass --yes
|
||||
|
||||
- name: ZeroTier
|
||||
uses: zerotier/github-action@v1.0.1
|
||||
with:
|
||||
network_id: ${{ secrets.ZEROTIER_NETWORK_ID }}
|
||||
auth_token: ${{ secrets.ZEROTIER_CENTRAL_TOKEN }}
|
||||
|
||||
- name: ping host
|
||||
shell: bash
|
||||
run: |
|
||||
count=10
|
||||
while ! ping -c 1 10.147.18.11 ; do
|
||||
echo "waiting..." ;
|
||||
sleep 1 ;
|
||||
let count=count-1
|
||||
done
|
||||
echo "ping success"
|
||||
|
||||
- name: copy tar to target host
|
||||
shell: bash
|
||||
run: |
|
||||
sshpass -p "${{ secrets.ssh_password }}" scp -r -o StrictHostKeyChecking=no -P 22 ./dist/*.gz root@10.147.18.11:/var/www/download
|
||||
echo "ping success"
|
||||
- name: send message
|
||||
run: |
|
||||
curl -X POST -H "Content-Type: application/json" -d '{"msg_type":"text","content":{"text":"CasaOS-User updated"}}' ${{ secrets.SSH_ROBOT_URL }}
|
||||
@@ -0,0 +1,17 @@
|
||||
name: goreleaser
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- v*.*.*
|
||||
permissions:
|
||||
contents: write
|
||||
jobs:
|
||||
call-workflow-passing-data:
|
||||
uses: IceWhaleTech/github/.github/workflows/go_release.yml@main
|
||||
with:
|
||||
project-name: CasaOS-UserService
|
||||
file-name: casaos-user-service
|
||||
secrets:
|
||||
OSS_KEY_ID: ${{ secrets.OSS_KEY_ID }}
|
||||
OSS_KEY_SECRET: ${{ secrets.OSS_KEY_SECRET }}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
# Binaries for programs and plugins
|
||||
*.exe
|
||||
*.exe~
|
||||
*.dll
|
||||
*.so
|
||||
*.dylib
|
||||
|
||||
# Test binary, built with `go test -c`
|
||||
*.test
|
||||
|
||||
# Output of the go coverage tool, specifically when used with LiteIDE
|
||||
*.out
|
||||
|
||||
# Dependency directories (remove the comment below to include it)
|
||||
# vendor/
|
||||
|
||||
# IDE
|
||||
.vscode/
|
||||
target/
|
||||
dist/
|
||||
__debug_bin
|
||||
codegen/
|
||||
|
||||
node_modules/
|
||||
dist/
|
||||
.idea
|
||||
.package-lock.json
|
||||
*.sh
|
||||
build/scripts/setup/service.d/user-service/ubuntu/setup-user-service.sh
|
||||
linux-amd64-nextzenos-user-service-v1.3.tar.gz
|
||||
build/sysroot/usr/bin/casaos-user-service
|
||||
dist/casaos-user-service-amd64_linux_amd64_v1/build/sysroot/usr/bin/casaos-user-service
|
||||
/build/scripts/setup
|
||||
dist/casaos-user-service-amd64_linux_amd64_v1/build/sysroot/usr/bin/casaos-user-service
|
||||
linux-amd64-nextzenos-user-service-v1.3.0.tar.gz
|
||||
dist/casaos-user-service-amd64_linux_amd64_v1/build/sysroot/usr/bin/casaos-user-service
|
||||
Vendored
+1
-1
@@ -6,7 +6,7 @@
|
||||
"type": "go",
|
||||
"debugAdapter": "dlv-dap",
|
||||
"request": "launch",
|
||||
"port": 2345,
|
||||
"port": 2346,
|
||||
"host": "127.0.0.1",
|
||||
"mode": "exec",
|
||||
"program": "${workspaceFolder}/dist/casaos-user-service-amd64_linux_amd64_v1/build/sysroot/usr/bin/casaos-user-service"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# CasaOS-UserService
|
||||
|
||||
[](https://pkg.go.dev/github.com/KaySar12/NextZen-UserService) [](https://goreportcard.com/report/github.com/KaySar12/NextZen-UserService) [](https://github.com/KaySar12/NextZen-UserService/actions/workflows/release.yml) [](https://codecov.io/gh/IceWhaleTech/CasaOS-UserService)
|
||||
[](https://pkg.go.dev/github.com/IceWhaleTech/CasaOS-UserService) [](https://goreportcard.com/report/github.com/IceWhaleTech/CasaOS-UserService) [](https://github.com/IceWhaleTech/CasaOS-UserService/actions/workflows/release.yml) [](https://codecov.io/gh/IceWhaleTech/CasaOS-UserService)
|
||||
|
||||
User Service provides user management functionalities to CasaOS.
|
||||
|
||||
|
||||
+1
@@ -0,0 +1 @@
|
||||
../setup-user-service.sh
|
||||
@@ -0,0 +1,22 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -e
|
||||
|
||||
readonly APP_NAME="casaos-user-service"
|
||||
readonly APP_NAME_SHORT="user-service"
|
||||
|
||||
# copy config files
|
||||
readonly CONF_PATH=/etc/casaos
|
||||
readonly CONF_FILE=${CONF_PATH}/${APP_NAME_SHORT}.conf
|
||||
readonly CONF_FILE_SAMPLE=${CONF_PATH}/${APP_NAME_SHORT}.conf.sample
|
||||
|
||||
if [ ! -f "${CONF_FILE}" ]; then \
|
||||
echo "Initializing config file..."
|
||||
cp -v "${CONF_FILE_SAMPLE}" "${CONF_FILE}"; \
|
||||
fi
|
||||
|
||||
systemctl daemon-reload
|
||||
|
||||
# enable service (without starting)
|
||||
echo "Enabling service..."
|
||||
systemctl enable --force --no-ask-password "${APP_NAME}.service"
|
||||
@@ -0,0 +1 @@
|
||||
../setup-user-service.sh
|
||||
@@ -0,0 +1 @@
|
||||
../debian/setup-user-service.sh
|
||||
@@ -7,3 +7,5 @@ LogSaveName = user-service
|
||||
LogFileExt = log
|
||||
DBPath = /var/lib/casaos/db
|
||||
UserDataPath = /var/lib/casaos
|
||||
OMVServer = http://10.0.0.4:1081/rpc.php
|
||||
SecretKey = N1PCdw3M2B1TfJhoaY2mL736p2vCUc47
|
||||
@@ -0,0 +1,48 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -e
|
||||
|
||||
readonly APP_NAME_SHORT=user-service
|
||||
|
||||
__get_setup_script_directory_by_os_release() {
|
||||
pushd "$(dirname "${BASH_SOURCE[0]}")/../service.d/${APP_NAME_SHORT}" &>/dev/null
|
||||
|
||||
{
|
||||
# shellcheck source=/dev/null
|
||||
{
|
||||
source /etc/os-release
|
||||
{
|
||||
pushd "${ID}"/"${VERSION_CODENAME}" &>/dev/null
|
||||
} || {
|
||||
pushd "${ID}" &>/dev/null
|
||||
} || {
|
||||
[[ -n ${ID_LIKE} ]] && for ID in ${ID_LIKE}; do
|
||||
pushd "${ID}" >/dev/null && break
|
||||
done
|
||||
} || {
|
||||
echo "Unsupported OS: ${ID} ${VERSION_CODENAME} (${ID_LIKE})"
|
||||
exit 1
|
||||
}
|
||||
|
||||
pwd
|
||||
|
||||
popd &>/dev/null
|
||||
|
||||
} || {
|
||||
echo "Unsupported OS: unknown"
|
||||
exit 1
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
popd &>/dev/null
|
||||
}
|
||||
|
||||
SETUP_SCRIPT_DIRECTORY=$(__get_setup_script_directory_by_os_release)
|
||||
|
||||
readonly SETUP_SCRIPT_DIRECTORY
|
||||
readonly SETUP_SCRIPT_FILENAME="cleanup-${APP_NAME_SHORT}.sh"
|
||||
readonly SETUP_SCRIPT_FILEPATH="${SETUP_SCRIPT_DIRECTORY}/${SETUP_SCRIPT_FILENAME}"
|
||||
|
||||
echo "🟩 Running ${SETUP_SCRIPT_FILENAME}..."
|
||||
$BASH "${SETUP_SCRIPT_FILEPATH}" "${BUILD_PATH}"
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -e
|
||||
|
||||
readonly CASA_EXEC=casaos-user-service
|
||||
readonly CASA_SERVICE=casaos-user-service.service
|
||||
|
||||
CASA_SERVICE_PATH=$(systemctl show ${CASA_SERVICE} --no-pager --property FragmentPath | cut -d'=' -sf2)
|
||||
readonly CASA_SERVICE_PATH
|
||||
|
||||
CASA_CONF=$( grep -i ExecStart= "${CASA_SERVICE_PATH}" | cut -d'=' -sf2 | cut -d' ' -sf3)
|
||||
if [[ -z "${CASA_CONF}" ]]; then
|
||||
CASA_CONF=/etc/casaos/user-service.conf
|
||||
fi
|
||||
|
||||
CASA_DB_PATH=$( (grep -i dbpath "${CASA_CONF}" || echo "/var/lib/casaos/db") | cut -d'=' -sf2 | xargs )
|
||||
readonly CASA_DB_PATH
|
||||
|
||||
CASA_DB_FILE=${CASA_DB_PATH}/user-service.db
|
||||
|
||||
readonly aCOLOUR=(
|
||||
'\e[38;5;154m' # green | Lines, bullets and separators
|
||||
'\e[1m' # Bold white | Main descriptions
|
||||
'\e[90m' # Grey | Credits
|
||||
'\e[91m' # Red | Update notifications Alert
|
||||
'\e[33m' # Yellow | Emphasis
|
||||
)
|
||||
|
||||
Show() {
|
||||
# OK
|
||||
if (($1 == 0)); then
|
||||
echo -e "${aCOLOUR[2]}[$COLOUR_RESET${aCOLOUR[0]} OK $COLOUR_RESET${aCOLOUR[2]}]$COLOUR_RESET $2"
|
||||
# FAILED
|
||||
elif (($1 == 1)); then
|
||||
echo -e "${aCOLOUR[2]}[$COLOUR_RESET${aCOLOUR[3]}FAILED$COLOUR_RESET${aCOLOUR[2]}]$COLOUR_RESET $2"
|
||||
# INFO
|
||||
elif (($1 == 2)); then
|
||||
echo -e "${aCOLOUR[2]}[$COLOUR_RESET${aCOLOUR[0]} INFO $COLOUR_RESET${aCOLOUR[2]}]$COLOUR_RESET $2"
|
||||
# NOTICE
|
||||
elif (($1 == 3)); then
|
||||
echo -e "${aCOLOUR[2]}[$COLOUR_RESET${aCOLOUR[4]}NOTICE$COLOUR_RESET${aCOLOUR[2]}]$COLOUR_RESET $2"
|
||||
fi
|
||||
}
|
||||
|
||||
Warn() {
|
||||
echo -e "${aCOLOUR[3]}$1$COLOUR_RESET"
|
||||
}
|
||||
|
||||
trap 'onCtrlC' INT
|
||||
onCtrlC() {
|
||||
echo -e "${COLOUR_RESET}"
|
||||
exit 1
|
||||
}
|
||||
|
||||
if [[ ! -x "$(command -v ${CASA_EXEC})" ]]; then
|
||||
Show 2 "${CASA_EXEC} is not detected, exit the script."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
while true; do
|
||||
echo -n -e " ${aCOLOUR[4]}Do you want delete user database? Y/n :${COLOUR_RESET}"
|
||||
read -r input
|
||||
case $input in
|
||||
[yY][eE][sS] | [yY])
|
||||
REMOVE_USER_DATABASE=true
|
||||
break
|
||||
;;
|
||||
[nN][oO] | [nN])
|
||||
REMOVE_USER_DATABASE=false
|
||||
break
|
||||
;;
|
||||
*)
|
||||
echo -e " ${aCOLOUR[3]}Invalid input, please try again.${COLOUR_RESET}"
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
while true; do
|
||||
echo -n -e " ${aCOLOUR[4]}Do you want delete user directory? Y/n :${COLOUR_RESET}"
|
||||
read -r input
|
||||
case $input in
|
||||
[yY][eE][sS] | [yY])
|
||||
REMOVE_USER_DIRECTORY=true
|
||||
break
|
||||
;;
|
||||
[nN][oO] | [nN])
|
||||
REMOVE_USER_DIRECTORY=false
|
||||
break
|
||||
;;
|
||||
*)
|
||||
echo -e " ${aCOLOUR[3]}Invalid input, please try again.${COLOUR_RESET}"
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
Show 2 "Stopping ${CASA_SERVICE}..."
|
||||
systemctl disable --now "${CASA_SERVICE}" || Show 3 "Failed to disable ${CASA_SERVICE}"
|
||||
|
||||
rm -rvf "$(which ${CASA_EXEC})" || Show 3 "Failed to remove ${CASA_EXEC}"
|
||||
rm -rvf "${CASA_CONF}" || Show 3 "Failed to remove ${CASA_CONF}"
|
||||
|
||||
if [[ "${REMOVE_USER_DATABASE}" == true ]]; then
|
||||
rm -rvf "${CASA_DB_FILE}" || Show 3 "Failed to remove ${CASA_DB_FILE}"
|
||||
fi
|
||||
|
||||
if [[ "${REMOVE_USER_DIRECTORY}" == true ]]; then
|
||||
Show 2 "Removing user directories..."
|
||||
rm -rvf /var/lib/casaos/[1-9]*
|
||||
fi
|
||||
+1
@@ -0,0 +1 @@
|
||||
../cleanup-user-service.sh
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -e
|
||||
|
||||
readonly CASA_EXEC=casaos-user-service
|
||||
readonly CASA_SERVICE=casaos-user-service.service
|
||||
|
||||
CASA_SERVICE_PATH=$(systemctl show ${CASA_SERVICE} --no-pager --property FragmentPath | cut -d'=' -sf2)
|
||||
readonly CASA_SERVICE_PATH
|
||||
|
||||
CASA_CONF=$( grep -i ExecStart= "${CASA_SERVICE_PATH}" | cut -d'=' -sf2 | cut -d' ' -sf3)
|
||||
if [[ -z "${CASA_CONF}" ]]; then
|
||||
CASA_CONF=/etc/casaos/user-service.conf
|
||||
fi
|
||||
|
||||
CASA_DB_PATH=$( (grep -i dbpath "${CASA_CONF}" || echo "/var/lib/casaos/db") | cut -d'=' -sf2 | xargs )
|
||||
readonly CASA_DB_PATH
|
||||
|
||||
CASA_DB_FILE=${CASA_DB_PATH}/user-service.db
|
||||
|
||||
readonly aCOLOUR=(
|
||||
'\e[38;5;154m' # green | Lines, bullets and separators
|
||||
'\e[1m' # Bold white | Main descriptions
|
||||
'\e[90m' # Grey | Credits
|
||||
'\e[91m' # Red | Update notifications Alert
|
||||
'\e[33m' # Yellow | Emphasis
|
||||
)
|
||||
|
||||
Show() {
|
||||
# OK
|
||||
if (($1 == 0)); then
|
||||
echo -e "${aCOLOUR[2]}[$COLOUR_RESET${aCOLOUR[0]} OK $COLOUR_RESET${aCOLOUR[2]}]$COLOUR_RESET $2"
|
||||
# FAILED
|
||||
elif (($1 == 1)); then
|
||||
echo -e "${aCOLOUR[2]}[$COLOUR_RESET${aCOLOUR[3]}FAILED$COLOUR_RESET${aCOLOUR[2]}]$COLOUR_RESET $2"
|
||||
# INFO
|
||||
elif (($1 == 2)); then
|
||||
echo -e "${aCOLOUR[2]}[$COLOUR_RESET${aCOLOUR[0]} INFO $COLOUR_RESET${aCOLOUR[2]}]$COLOUR_RESET $2"
|
||||
# NOTICE
|
||||
elif (($1 == 3)); then
|
||||
echo -e "${aCOLOUR[2]}[$COLOUR_RESET${aCOLOUR[4]}NOTICE$COLOUR_RESET${aCOLOUR[2]}]$COLOUR_RESET $2"
|
||||
fi
|
||||
}
|
||||
|
||||
Warn() {
|
||||
echo -e "${aCOLOUR[3]}$1$COLOUR_RESET"
|
||||
}
|
||||
|
||||
trap 'onCtrlC' INT
|
||||
onCtrlC() {
|
||||
echo -e "${COLOUR_RESET}"
|
||||
exit 1
|
||||
}
|
||||
|
||||
if [[ ! -x "$(command -v ${CASA_EXEC})" ]]; then
|
||||
Show 2 "${CASA_EXEC} is not detected, exit the script."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
while true; do
|
||||
echo -n -e " ${aCOLOUR[4]}Do you want delete user database? Y/n :${COLOUR_RESET}"
|
||||
read -r input
|
||||
case $input in
|
||||
[yY][eE][sS] | [yY])
|
||||
REMOVE_USER_DATABASE=true
|
||||
break
|
||||
;;
|
||||
[nN][oO] | [nN])
|
||||
REMOVE_USER_DATABASE=false
|
||||
break
|
||||
;;
|
||||
*)
|
||||
echo -e " ${aCOLOUR[3]}Invalid input, please try again.${COLOUR_RESET}"
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
while true; do
|
||||
echo -n -e " ${aCOLOUR[4]}Do you want delete user directory? Y/n :${COLOUR_RESET}"
|
||||
read -r input
|
||||
case $input in
|
||||
[yY][eE][sS] | [yY])
|
||||
REMOVE_USER_DIRECTORY=true
|
||||
break
|
||||
;;
|
||||
[nN][oO] | [nN])
|
||||
REMOVE_USER_DIRECTORY=false
|
||||
break
|
||||
;;
|
||||
*)
|
||||
echo -e " ${aCOLOUR[3]}Invalid input, please try again.${COLOUR_RESET}"
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
Show 2 "Stopping ${CASA_SERVICE}..."
|
||||
systemctl disable --now "${CASA_SERVICE}" || Show 3 "Failed to disable ${CASA_SERVICE}"
|
||||
|
||||
rm -rvf "$(which ${CASA_EXEC})" || Show 3 "Failed to remove ${CASA_EXEC}"
|
||||
rm -rvf "${CASA_CONF}" || Show 3 "Failed to remove ${CASA_CONF}"
|
||||
|
||||
if [[ "${REMOVE_USER_DATABASE}" == true ]]; then
|
||||
rm -rvf "${CASA_DB_FILE}" || Show 3 "Failed to remove ${CASA_DB_FILE}"
|
||||
fi
|
||||
|
||||
if [[ "${REMOVE_USER_DIRECTORY}" == true ]]; then
|
||||
Show 2 "Removing user directories..."
|
||||
rm -rvf /var/lib/casaos/[1-9]*
|
||||
fi
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../debian/cleanup-user-service.sh
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../../debian/bullseye/cleanup-user-service.sh
|
||||
@@ -6,9 +6,9 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
interfaces "github.com/KaySar12/NextZen-Common"
|
||||
"github.com/KaySar12/NextZen-Common/utils/systemctl"
|
||||
"github.com/KaySar12/NextZen-UserService/common"
|
||||
interfaces "github.com/IceWhaleTech/CasaOS-Common"
|
||||
"github.com/IceWhaleTech/CasaOS-Common/utils/systemctl"
|
||||
"github.com/IceWhaleTech/CasaOS-UserService/common"
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
interfaces "github.com/KaySar12/NextZen-Common"
|
||||
interfaces "github.com/IceWhaleTech/CasaOS-Common"
|
||||
)
|
||||
|
||||
type migrationTool struct{}
|
||||
|
||||
+2
-1
@@ -1,3 +1,4 @@
|
||||
package common
|
||||
|
||||
const Version = "0.4.4"
|
||||
const Version = "1.3.0"
|
||||
const SERVICENAME = "CasaOS-UserService"
|
||||
|
||||
Vendored
+1
-1
@@ -1 +1 @@
|
||||
[{"name":"build/sysroot/usr/bin/casaos-user-service","path":"dist/casaos-user-service-amd64_linux_amd64_v1/build/sysroot/usr/bin/casaos-user-service","goos":"linux","goarch":"amd64","goamd64":"v1","internal_type":4,"type":"Binary","extra":{"Binary":"casaos-user-service","Ext":"","ID":"casaos-user-service-amd64"}}]
|
||||
[{"name":"metadata.json","path":"dist/metadata.json","internal_type":30,"type":"Metadata"},{"name":"build/sysroot/usr/bin/casaos-user-service","path":"dist/casaos-user-service-amd64_linux_amd64_v1/build/sysroot/usr/bin/casaos-user-service","goos":"linux","goarch":"amd64","goamd64":"v1","internal_type":4,"type":"Binary","extra":{"Binary":"casaos-user-service","Ext":"","ID":"casaos-user-service-amd64"}}]
|
||||
Vendored
Regular → Executable
BIN
Binary file not shown.
Vendored
+4
-1
@@ -67,6 +67,7 @@ changelog:
|
||||
- '^docs:'
|
||||
- '^test:'
|
||||
sort: asc
|
||||
format: '{{ .SHA }}: {{ .Message }} ({{ with .AuthorUsername }}@{{ . }}{{ else }}{{ .AuthorName }} <{{ .AuthorEmail }}>{{ end }})'
|
||||
dist: dist
|
||||
env_files:
|
||||
github_token: ~/.config/goreleaser/github_token
|
||||
@@ -115,7 +116,7 @@ announce:
|
||||
linkedin:
|
||||
message_template: '{{ .ProjectName }} {{ .Tag }} is out! Check it out at {{ .ReleaseURL }}'
|
||||
telegram:
|
||||
message_template: '{{ .ProjectName }} {{ mdv2escape .Tag }} is out! Check it out at {{ mdv2escape .ReleaseURL }}'
|
||||
message_template: '{{ mdv2escape .ProjectName }} {{ mdv2escape .Tag }} is out{{ mdv2escape "!" }} Check it out at {{ mdv2escape .ReleaseURL }}'
|
||||
parse_mode: MarkdownV2
|
||||
webhook:
|
||||
message_template: '{ "message": "{{ .ProjectName }} {{ .Tag }} is out! Check it out at {{ .ReleaseURL }}"}'
|
||||
@@ -123,6 +124,8 @@ announce:
|
||||
opencollective:
|
||||
title_template: '{{ .Tag }}'
|
||||
message_template: '{{ .ProjectName }} {{ .Tag }} is out!<br/>Check it out at <a href="{{ .ReleaseURL }}">{{ .ReleaseURL }}</a>'
|
||||
bluesky:
|
||||
message_template: '{{ .ProjectName }} {{ .Tag }} is out! Check it out at {{ .ReleaseURL }}'
|
||||
git:
|
||||
tag_sort: -version:refname
|
||||
github_urls:
|
||||
|
||||
Vendored
+1
-1
@@ -1 +1 @@
|
||||
{"project_name":"casaos-user-service","tag":"v1.0.1","previous_tag":"","version":"1.0.2","commit":"e002bab12a5ce37a0636709986e161f0e84f2eeb","date":"2024-02-21T12:02:47.525580972+07:00","runtime":{"goos":"linux","goarch":"amd64"}}
|
||||
{"project_name":"casaos-user-service","tag":"v1.0.0","previous_tag":"","version":"1.0.1","commit":"75abc7e65122c0822a9663fe8d1db31e91816479","date":"2024-07-10T14:28:43.76387852+07:00","runtime":{"goos":"linux","goarch":"amd64"}}
|
||||
@@ -1,9 +1,9 @@
|
||||
module github.com/KaySar12/NextZen-UserService
|
||||
module github.com/IceWhaleTech/CasaOS-UserService
|
||||
|
||||
go 1.20
|
||||
|
||||
require (
|
||||
github.com/KaySar12/NextZen-Common v1.0.1
|
||||
github.com/IceWhaleTech/CasaOS-Common v0.4.8-alpha12
|
||||
github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf
|
||||
github.com/deepmap/oapi-codegen v1.12.4
|
||||
github.com/getkin/kin-openapi v0.117.0
|
||||
@@ -15,6 +15,7 @@ require (
|
||||
github.com/tidwall/gjson v1.14.4
|
||||
go.uber.org/zap v1.24.0
|
||||
golang.org/x/net v0.17.0
|
||||
golang.org/x/time v0.3.0
|
||||
gopkg.in/ini.v1 v1.67.0
|
||||
gorm.io/gorm v1.25.0
|
||||
)
|
||||
@@ -75,7 +76,6 @@ require (
|
||||
golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1 // indirect
|
||||
golang.org/x/sys v0.14.0 // indirect
|
||||
golang.org/x/text v0.13.0 // indirect
|
||||
golang.org/x/time v0.3.0 // indirect
|
||||
google.golang.org/protobuf v1.30.0 // indirect
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
github.com/KaySar12/NextZen-Common v1.0.1 h1:w+QTKRmXJBmru3Ig4x142k6c7oD6ZTMF13Q0Fu19bGo=
|
||||
github.com/KaySar12/NextZen-Common v1.0.1/go.mod h1:7AnhDlcVN9Dusql3aFy7y7TcyoKO3Pb9n/r0krTAWsw=
|
||||
github.com/IceWhaleTech/CasaOS-Common v0.4.8-alpha12 h1:TikSpmsMOxKufqoq8Q4K3PLh8zIKFrRtLH4JDIG+910=
|
||||
github.com/IceWhaleTech/CasaOS-Common v0.4.8-alpha12/go.mod h1:2IuYyy5qW1BE6jqC6M+tOU+WtUec1K565rLATBJ9p/0=
|
||||
github.com/RaveNoX/go-jsoncommentstrip v1.0.0/go.mod h1:78ihd09MekBnJnxpICcwzCMzGrKSKYe4AqU6PDYYpjk=
|
||||
github.com/apapsch/go-jsonmerge/v2 v2.0.0 h1:axGnT1gRIfimI7gJifB699GoE/oq+F2MU7Dml6nw9rQ=
|
||||
github.com/apapsch/go-jsonmerge/v2 v2.0.0/go.mod h1:lvDnEdqiQrp0O42VQGgmlKpxL1AP2+08jFMw88y4klk=
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
_ "embed"
|
||||
"flag"
|
||||
"fmt"
|
||||
@@ -13,18 +14,19 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/KaySar12/NextZen-Common/external"
|
||||
"github.com/KaySar12/NextZen-Common/model"
|
||||
util_http "github.com/KaySar12/NextZen-Common/utils/http"
|
||||
"github.com/KaySar12/NextZen-Common/utils/jwt"
|
||||
"github.com/KaySar12/NextZen-Common/utils/logger"
|
||||
"github.com/KaySar12/NextZen-UserService/common"
|
||||
"github.com/KaySar12/NextZen-UserService/pkg/config"
|
||||
"github.com/KaySar12/NextZen-UserService/pkg/sqlite"
|
||||
"github.com/KaySar12/NextZen-UserService/pkg/utils/encryption"
|
||||
"github.com/KaySar12/NextZen-UserService/pkg/utils/random"
|
||||
"github.com/KaySar12/NextZen-UserService/route"
|
||||
"github.com/KaySar12/NextZen-UserService/service"
|
||||
"github.com/IceWhaleTech/CasaOS-Common/external"
|
||||
"github.com/IceWhaleTech/CasaOS-Common/model"
|
||||
util_http "github.com/IceWhaleTech/CasaOS-Common/utils/http"
|
||||
"github.com/IceWhaleTech/CasaOS-Common/utils/jwt"
|
||||
"github.com/IceWhaleTech/CasaOS-Common/utils/logger"
|
||||
"github.com/IceWhaleTech/CasaOS-UserService/codegen/message_bus"
|
||||
"github.com/IceWhaleTech/CasaOS-UserService/common"
|
||||
"github.com/IceWhaleTech/CasaOS-UserService/pkg/config"
|
||||
"github.com/IceWhaleTech/CasaOS-UserService/pkg/sqlite"
|
||||
"github.com/IceWhaleTech/CasaOS-UserService/pkg/utils/encryption"
|
||||
"github.com/IceWhaleTech/CasaOS-UserService/pkg/utils/random"
|
||||
"github.com/IceWhaleTech/CasaOS-UserService/route"
|
||||
"github.com/IceWhaleTech/CasaOS-UserService/service"
|
||||
"github.com/coreos/go-systemd/daemon"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
@@ -99,7 +101,6 @@ func main() {
|
||||
v1Router := route.InitRouter()
|
||||
v2Router := route.InitV2Router()
|
||||
v2DocRouter := route.InitV2DocRouter(_docHTML, _docYAML)
|
||||
|
||||
_, publicKey := service.MyService.User().GetKeyPair()
|
||||
|
||||
jswkJSON, err := jwt.GenerateJwksJSON(publicKey)
|
||||
@@ -154,6 +155,23 @@ func main() {
|
||||
go route.EventListen()
|
||||
logger.Info("User service is listening...", zap.Any("address", listener.Addr().String()), zap.String("filepath", addressFilePath))
|
||||
|
||||
var events []message_bus.EventType
|
||||
events = append(events, message_bus.EventType{Name: "zimaos:user:save_config", SourceID: common.SERVICENAME, PropertyTypeList: []message_bus.PropertyType{}})
|
||||
// register at message bus
|
||||
for i := 0; i < 10; i++ {
|
||||
response, err := service.MyService.MessageBus().RegisterEventTypesWithResponse(context.Background(), events)
|
||||
if err != nil {
|
||||
logger.Error("error when trying to register one or more event types - some event type will not be discoverable", zap.Error(err))
|
||||
}
|
||||
if response != nil && response.StatusCode() != http.StatusOK {
|
||||
logger.Error("error when trying to register one or more event types - some event type will not be discoverable", zap.String("status", response.Status()), zap.String("body", string(response.Body)))
|
||||
}
|
||||
if response.StatusCode() == http.StatusOK {
|
||||
break
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
|
||||
s := &http.Server{
|
||||
Handler: mux,
|
||||
ReadHeaderTimeout: 5 * time.Second, // fix G112: Potential slowloris attack (see https://github.com/securego/gosec)
|
||||
|
||||
@@ -10,6 +10,8 @@ type APPModel struct {
|
||||
LogFileExt string
|
||||
UserDataPath string
|
||||
DBPath string
|
||||
OMVServer string
|
||||
SecretKey string
|
||||
}
|
||||
|
||||
type Result struct {
|
||||
|
||||
+1
-1
@@ -9,7 +9,7 @@
|
||||
"publish": "npm publish --access public",
|
||||
"start": "yarn generate:ts && yarn build"
|
||||
},
|
||||
"homepage": "https://github.com/KaySar12/NextZen-UserService#readme",
|
||||
"homepage": "https://github.com/IceWhaleTech/CasaOS-UserService#readme",
|
||||
"description": "Casaos-Localstorage Typescript+Axios SDK",
|
||||
"keywords": [
|
||||
"CasaOS-UserService",
|
||||
|
||||
+4
-2
@@ -5,8 +5,8 @@ import (
|
||||
"log"
|
||||
"os"
|
||||
|
||||
"github.com/KaySar12/NextZen-Common/utils/constants"
|
||||
"github.com/KaySar12/NextZen-UserService/model"
|
||||
"github.com/IceWhaleTech/CasaOS-Common/utils/constants"
|
||||
"github.com/IceWhaleTech/CasaOS-UserService/model"
|
||||
"gopkg.in/ini.v1"
|
||||
)
|
||||
|
||||
@@ -23,6 +23,8 @@ var (
|
||||
LogPath: constants.DefaultLogPath,
|
||||
LogSaveName: "user",
|
||||
LogFileExt: "log",
|
||||
OMVServer: constants.DefaultOMVServer,
|
||||
SecretKey: constants.DefaultSecretKey,
|
||||
}
|
||||
|
||||
Cfg *ini.File
|
||||
|
||||
+4
-4
@@ -12,10 +12,10 @@ package sqlite
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/KaySar12/NextZen-Common/utils/logger"
|
||||
"github.com/KaySar12/NextZen-UserService/model"
|
||||
"github.com/KaySar12/NextZen-UserService/pkg/utils/file"
|
||||
model2 "github.com/KaySar12/NextZen-UserService/service/model"
|
||||
"github.com/IceWhaleTech/CasaOS-Common/utils/logger"
|
||||
"github.com/IceWhaleTech/CasaOS-UserService/model"
|
||||
"github.com/IceWhaleTech/CasaOS-UserService/pkg/utils/file"
|
||||
model2 "github.com/IceWhaleTech/CasaOS-UserService/service/model"
|
||||
"github.com/glebarez/sqlite"
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
|
||||
@@ -10,8 +10,20 @@
|
||||
package encryption
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/md5"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
|
||||
"github.com/IceWhaleTech/CasaOS-UserService/pkg/config"
|
||||
)
|
||||
|
||||
var (
|
||||
// We're using a 32 byte long secret key.
|
||||
// This is probably something you generate first
|
||||
// then put into and environment variable.
|
||||
secretKey string = config.AppInfo.SecretKey
|
||||
)
|
||||
|
||||
func GetMD5ByStr(str string) string {
|
||||
@@ -19,3 +31,54 @@ func GetMD5ByStr(str string) string {
|
||||
h.Write([]byte(str))
|
||||
return hex.EncodeToString(h.Sum(nil))
|
||||
}
|
||||
|
||||
func Encrypt(plaintext string) string {
|
||||
aes, err := aes.NewCipher([]byte(secretKey))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
gcm, err := cipher.NewGCM(aes)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// We need a 12-byte nonce for GCM (modifiable if you use cipher.NewGCMWithNonceSize())
|
||||
// A nonce should always be randomly generated for every encryption.
|
||||
nonce := make([]byte, gcm.NonceSize())
|
||||
_, err = rand.Read(nonce)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// ciphertext here is actually nonce+ciphertext
|
||||
// So that when we decrypt, just knowing the nonce size
|
||||
// is enough to separate it from the ciphertext.
|
||||
ciphertext := gcm.Seal(nonce, nonce, []byte(plaintext), nil)
|
||||
|
||||
return string(ciphertext)
|
||||
}
|
||||
|
||||
func Decrypt(ciphertext string) string {
|
||||
aes, err := aes.NewCipher([]byte(secretKey))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
gcm, err := cipher.NewGCM(aes)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// Since we know the ciphertext is actually nonce+ciphertext
|
||||
// And len(nonce) == NonceSize(). We can separate the two.
|
||||
nonceSize := gcm.NonceSize()
|
||||
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
|
||||
|
||||
plaintext, err := gcm.Open(nil, []byte(nonce), []byte(ciphertext), nil)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
return string(plaintext)
|
||||
}
|
||||
|
||||
@@ -7,12 +7,12 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/KaySar12/NextZen-Common/external"
|
||||
"github.com/KaySar12/NextZen-Common/utils/logger"
|
||||
message_bus "github.com/KaySar12/NextZen-UserService/codegen/message_bus"
|
||||
"github.com/KaySar12/NextZen-UserService/model"
|
||||
"github.com/KaySar12/NextZen-UserService/pkg/config"
|
||||
"github.com/KaySar12/NextZen-UserService/service"
|
||||
"github.com/IceWhaleTech/CasaOS-Common/external"
|
||||
"github.com/IceWhaleTech/CasaOS-Common/utils/logger"
|
||||
message_bus "github.com/IceWhaleTech/CasaOS-UserService/codegen/message_bus"
|
||||
"github.com/IceWhaleTech/CasaOS-UserService/model"
|
||||
"github.com/IceWhaleTech/CasaOS-UserService/pkg/config"
|
||||
"github.com/IceWhaleTech/CasaOS-UserService/service"
|
||||
"go.uber.org/zap"
|
||||
"golang.org/x/net/websocket"
|
||||
)
|
||||
|
||||
+8
-6
@@ -4,10 +4,10 @@ import (
|
||||
"crypto/ecdsa"
|
||||
"os"
|
||||
|
||||
"github.com/KaySar12/NextZen-Common/middleware"
|
||||
"github.com/KaySar12/NextZen-Common/utils/jwt"
|
||||
v1 "github.com/KaySar12/NextZen-UserService/route/v1"
|
||||
"github.com/KaySar12/NextZen-UserService/service"
|
||||
"github.com/IceWhaleTech/CasaOS-Common/middleware"
|
||||
"github.com/IceWhaleTech/CasaOS-Common/utils/jwt"
|
||||
v1 "github.com/IceWhaleTech/CasaOS-UserService/route/v1"
|
||||
"github.com/IceWhaleTech/CasaOS-UserService/service"
|
||||
"github.com/gin-contrib/gzip"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
@@ -27,11 +27,13 @@ func InitRouter() *gin.Engine {
|
||||
|
||||
r.POST("/v1/users/register", v1.PostUserRegister)
|
||||
r.POST("/v1/users/login", v1.PostUserLogin)
|
||||
r.POST("/v1/users/omvlogin", v1.PostOMVLogin)
|
||||
r.POST("/v1/users/logout", v1.PostLogout)
|
||||
r.GET("/v1/users/name", v1.GetUserAllUsername) // all/name
|
||||
r.POST("/v1/users/refresh", v1.PostUserRefreshToken)
|
||||
// No short-term modifications
|
||||
r.GET("/v1/users/image", v1.GetUserImage)
|
||||
|
||||
r.GET("/v1/users/:username", v1.GetUserInfoByUsername)
|
||||
r.GET("/v1/users/status", v1.GetUserStatus) // init/check
|
||||
|
||||
v1Group := r.Group("/v1")
|
||||
@@ -63,7 +65,7 @@ func InitRouter() *gin.Engine {
|
||||
v1UsersGroup.GET("/avatar", v1.GetUserAvatar)
|
||||
|
||||
v1UsersGroup.DELETE("/:id", v1.DeleteUser)
|
||||
v1UsersGroup.GET("/:username", v1.GetUserInfoByUsername)
|
||||
// v1UsersGroup.GET("/:username", v1.GetUserInfoByUsername)
|
||||
v1UsersGroup.DELETE("", v1.DeleteUserAll)
|
||||
}
|
||||
}
|
||||
|
||||
+224
-35
@@ -1,8 +1,10 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ecdsa"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
json2 "encoding/json"
|
||||
"image"
|
||||
"image/png"
|
||||
@@ -13,27 +15,53 @@ import (
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/KaySar12/NextZen-Common/utils/common_err"
|
||||
"github.com/KaySar12/NextZen-Common/utils/jwt"
|
||||
"github.com/KaySar12/NextZen-Common/utils/logger"
|
||||
"github.com/KaySar12/NextZen-UserService/model"
|
||||
"github.com/KaySar12/NextZen-UserService/model/system_model"
|
||||
"github.com/KaySar12/NextZen-UserService/pkg/config"
|
||||
"github.com/KaySar12/NextZen-UserService/pkg/utils/encryption"
|
||||
"github.com/KaySar12/NextZen-UserService/pkg/utils/file"
|
||||
model2 "github.com/KaySar12/NextZen-UserService/service/model"
|
||||
"github.com/IceWhaleTech/CasaOS-Common/external"
|
||||
"github.com/IceWhaleTech/CasaOS-Common/utils/common_err"
|
||||
"github.com/IceWhaleTech/CasaOS-Common/utils/jwt"
|
||||
"github.com/IceWhaleTech/CasaOS-Common/utils/logger"
|
||||
"github.com/IceWhaleTech/CasaOS-UserService/common"
|
||||
"github.com/IceWhaleTech/CasaOS-UserService/model"
|
||||
"github.com/IceWhaleTech/CasaOS-UserService/model/system_model"
|
||||
"github.com/IceWhaleTech/CasaOS-UserService/pkg/config"
|
||||
"github.com/IceWhaleTech/CasaOS-UserService/pkg/utils/encryption"
|
||||
"github.com/IceWhaleTech/CasaOS-UserService/pkg/utils/file"
|
||||
model2 "github.com/IceWhaleTech/CasaOS-UserService/service/model"
|
||||
uuid "github.com/satori/go.uuid"
|
||||
"github.com/tidwall/gjson"
|
||||
"go.uber.org/zap"
|
||||
"golang.org/x/time/rate"
|
||||
|
||||
"github.com/KaySar12/NextZen-UserService/service"
|
||||
"github.com/IceWhaleTech/CasaOS-UserService/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type OMVLogin struct {
|
||||
Response struct {
|
||||
Authenticated bool `json:"authenticated"`
|
||||
Username string `json:"username"`
|
||||
Permissions struct {
|
||||
Role string `json:"role"`
|
||||
} `json:"permissions"`
|
||||
SessionID string `json:"sessionid"`
|
||||
} `json:"response"`
|
||||
Error interface{} `json:"error"`
|
||||
}
|
||||
type OMVUser struct {
|
||||
Response struct {
|
||||
Authenticated bool `json:"authenticated"`
|
||||
Username string `json:"username"`
|
||||
Permissions struct {
|
||||
Role string `json:"role"`
|
||||
} `json:"permissions"`
|
||||
} `json:"response"`
|
||||
Error interface{} `json:"error"`
|
||||
}
|
||||
|
||||
// @Summary register user
|
||||
// @Router /user/register/ [post]
|
||||
func PostUserRegister(c *gin.Context) {
|
||||
@@ -43,6 +71,7 @@ func PostUserRegister(c *gin.Context) {
|
||||
username := json["username"]
|
||||
pwd := json["password"]
|
||||
key := json["key"]
|
||||
role := json["role"]
|
||||
if _, ok := service.UserRegisterHash[key]; !ok {
|
||||
c.JSON(common_err.CLIENT_ERROR,
|
||||
model.Result{Success: common_err.KEY_NOT_EXIST, Message: common_err.GetMsg(common_err.KEY_NOT_EXIST)})
|
||||
@@ -69,8 +98,7 @@ func PostUserRegister(c *gin.Context) {
|
||||
user := model2.UserDBModel{}
|
||||
user.Username = username
|
||||
user.Password = encryption.GetMD5ByStr(pwd)
|
||||
user.Role = "admin"
|
||||
|
||||
user.Role = role
|
||||
user = service.MyService.User().CreateUser(user)
|
||||
if user.Id == 0 {
|
||||
c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SERVICE_ERROR, Message: common_err.GetMsg(common_err.SERVICE_ERROR)})
|
||||
@@ -81,6 +109,8 @@ func PostUserRegister(c *gin.Context) {
|
||||
c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
|
||||
}
|
||||
|
||||
var limiter = rate.NewLimiter(rate.Every(time.Minute), 5)
|
||||
|
||||
// @Summary login
|
||||
// @Produce application/json
|
||||
// @Accept application/json
|
||||
@@ -90,11 +120,18 @@ func PostUserRegister(c *gin.Context) {
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /user/login [post]
|
||||
func PostUserLogin(c *gin.Context) {
|
||||
if !limiter.Allow() {
|
||||
c.JSON(common_err.TOO_MANY_REQUEST,
|
||||
model.Result{
|
||||
Success: common_err.TOO_MANY_LOGIN_REQUESTS,
|
||||
Message: common_err.GetMsg(common_err.TOO_MANY_LOGIN_REQUESTS),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
json := make(map[string]string)
|
||||
c.ShouldBind(&json)
|
||||
|
||||
username := json["username"]
|
||||
|
||||
password := json["password"]
|
||||
// check params is empty
|
||||
if len(username) == 0 || len(password) == 0 {
|
||||
@@ -108,26 +145,28 @@ func PostUserLogin(c *gin.Context) {
|
||||
user := service.MyService.User().GetUserAllInfoByName(username)
|
||||
if user.Id == 0 {
|
||||
c.JSON(common_err.CLIENT_ERROR,
|
||||
model.Result{Success: common_err.USER_NOT_EXIST, Message: common_err.GetMsg(common_err.USER_NOT_EXIST)})
|
||||
model.Result{Success: common_err.USER_NOT_EXIST_OR_PWD_INVALID, Message: common_err.GetMsg(common_err.USER_NOT_EXIST_OR_PWD_INVALID)})
|
||||
return
|
||||
}
|
||||
if user.Password != encryption.GetMD5ByStr(password) {
|
||||
c.JSON(common_err.CLIENT_ERROR,
|
||||
model.Result{Success: common_err.PWD_INVALID, Message: common_err.GetMsg(common_err.PWD_INVALID)})
|
||||
model.Result{Success: common_err.USER_NOT_EXIST_OR_PWD_INVALID, Message: common_err.GetMsg(common_err.USER_NOT_EXIST_OR_PWD_INVALID)})
|
||||
return
|
||||
}
|
||||
// clean limit
|
||||
limiter = rate.NewLimiter(rate.Every(time.Minute), 5)
|
||||
|
||||
privateKey, _ := service.MyService.User().GetKeyPair()
|
||||
|
||||
token := system_model.VerifyInformation{}
|
||||
|
||||
accessToken, err := jwt.GetAccessToken(user.Username, privateKey, user.Id)
|
||||
accessToken, err := jwt.GetAccessToken(username, privateKey, user.Id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Result{Success: common_err.SERVICE_ERROR, Message: err.Error()})
|
||||
}
|
||||
token.AccessToken = accessToken
|
||||
|
||||
refreshToken, err := jwt.GetRefreshToken(user.Username, privateKey, user.Id)
|
||||
refreshToken, err := jwt.GetRefreshToken(username, privateKey, user.Id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Result{Success: common_err.SERVICE_ERROR, Message: err.Error()})
|
||||
}
|
||||
@@ -149,6 +188,101 @@ func PostUserLogin(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// @Summary login user to openmediavault
|
||||
// @Produce application/json
|
||||
// @Tags user
|
||||
// @Param username password
|
||||
// @Security SessionID
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /users/omvLogin [post]
|
||||
func PostOMVLogin(c *gin.Context) {
|
||||
if !limiter.Allow() {
|
||||
c.JSON(common_err.TOO_MANY_REQUEST,
|
||||
model.Result{
|
||||
Success: common_err.TOO_MANY_LOGIN_REQUESTS,
|
||||
Message: common_err.GetMsg(common_err.TOO_MANY_LOGIN_REQUESTS),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
json := make(map[string]string)
|
||||
c.ShouldBind(&json)
|
||||
username := json["username"]
|
||||
password := json["password"]
|
||||
res, cookies := service.MyService.OMV().LoginSession(username, password)
|
||||
var resData OMVLogin
|
||||
err := json2.Unmarshal([]byte(res), &resData)
|
||||
|
||||
if err != nil {
|
||||
log.Printf("Error getting user: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
if !resData.Response.Authenticated {
|
||||
c.JSON(common_err.CLIENT_ERROR,
|
||||
model.Result{Success: common_err.USER_NOT_EXIST_OR_PWD_INVALID, Message: common_err.GetMsg(common_err.USER_NOT_EXIST_OR_PWD_INVALID)})
|
||||
return
|
||||
}
|
||||
|
||||
getUser, err := service.MyService.OMV().AuthUser(username, password, resData.Response.SessionID)
|
||||
if err != nil {
|
||||
// Handle the error, for example, log it or return it
|
||||
log.Printf("Error getting user: %v", err)
|
||||
return // or handle it in a way that fits your application's error handling strategy
|
||||
}
|
||||
|
||||
var userData OMVUser
|
||||
err = json2.Unmarshal([]byte(getUser), &userData)
|
||||
|
||||
if err != nil {
|
||||
// Handle the error, for example, log it or return it
|
||||
log.Printf("Error getting user: %v", err)
|
||||
return // or handle it in a way that fits your application's error handling strategy
|
||||
}
|
||||
|
||||
if isEmpty(userData.Response) {
|
||||
c.JSON(common_err.CLIENT_ERROR,
|
||||
model.Result{
|
||||
Success: common_err.USER_NOT_EXIST_OR_PWD_INVALID,
|
||||
Message: common_err.GetMsg(common_err.USER_NOT_EXIST_OR_PWD_INVALID)})
|
||||
return
|
||||
}
|
||||
// cookie_value, err := c.Cookie("sessionID")
|
||||
// decrypt := encryption.Decrypt(cookie_value)
|
||||
// fmt.Printf(decrypt)
|
||||
// sessionId := encryption.Encrypt(resData.Response.SessionID)
|
||||
for _, cookie := range cookies {
|
||||
c.SetCookie(cookie.Name, cookie.Value, 3600, "/", "", false, true)
|
||||
}
|
||||
c.JSON(common_err.SUCCESS,
|
||||
model.Result{
|
||||
Success: common_err.SUCCESS,
|
||||
Message: common_err.GetMsg(common_err.SUCCESS),
|
||||
Data: userData,
|
||||
})
|
||||
|
||||
}
|
||||
func PostLogout(c *gin.Context) {
|
||||
cookies := c.Request.Cookies()
|
||||
for _, cookie := range cookies {
|
||||
// Set the cookie to expire immediately
|
||||
c.SetCookie(cookie.Name, "", -1, "/", "", false, true)
|
||||
}
|
||||
c.JSON(common_err.SUCCESS,
|
||||
model.Result{
|
||||
Success: common_err.SUCCESS,
|
||||
Message: common_err.GetMsg(common_err.SUCCESS),
|
||||
})
|
||||
}
|
||||
|
||||
func isEmpty(obj interface{}) bool {
|
||||
jsonData, err := json.Marshal(obj)
|
||||
if err != nil && string(jsonData) == "{}" {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// @Summary edit user head
|
||||
// @Produce application/json
|
||||
// @Accept multipart/form-data
|
||||
@@ -255,7 +389,7 @@ func PutUserInfo(c *gin.Context) {
|
||||
user := service.MyService.User().GetUserInfoById(id)
|
||||
if user.Id == 0 {
|
||||
c.JSON(common_err.SERVICE_ERROR,
|
||||
model.Result{Success: common_err.USER_NOT_EXIST, Message: common_err.GetMsg(common_err.USER_NOT_EXIST)})
|
||||
model.Result{Success: common_err.USER_NOT_EXIST_OR_PWD_INVALID, Message: common_err.GetMsg(common_err.USER_NOT_EXIST_OR_PWD_INVALID)})
|
||||
return
|
||||
}
|
||||
if len(json.Username) > 0 {
|
||||
@@ -411,7 +545,12 @@ func GetUserInfoByUsername(c *gin.Context) {
|
||||
}
|
||||
user := service.MyService.User().GetUserInfoByUserName(username)
|
||||
if user.Id == 0 {
|
||||
c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.USER_NOT_EXIST, Message: common_err.GetMsg(common_err.USER_NOT_EXIST)})
|
||||
c.JSON(common_err.SUCCESS,
|
||||
model.Result{
|
||||
Success: common_err.SUCCESS,
|
||||
Message: common_err.GetMsg(common_err.USER_NOT_EXIST),
|
||||
Data: nil,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -507,6 +646,20 @@ func PostUserCustomConf(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if name == "system" {
|
||||
dataMap := make(map[string]string, 1)
|
||||
dataMap["system"] = string(data)
|
||||
response, err := service.MyService.MessageBus().PublishEventWithResponse(context.Background(), common.SERVICENAME, "zimaos:user:save_config", dataMap)
|
||||
if err != nil {
|
||||
logger.Error("failed to publish event to message bus", zap.Error(err), zap.Any("event", string(data)))
|
||||
return
|
||||
}
|
||||
if response.StatusCode() != http.StatusOK {
|
||||
logger.Error("failed to publish event to message bus", zap.String("status", response.Status()), zap.Any("response", response))
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: json2.RawMessage(string(data))})
|
||||
}
|
||||
|
||||
@@ -658,23 +811,35 @@ func GetUserImage(c *gin.Context) {
|
||||
c.JSON(http.StatusNotFound, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
|
||||
return
|
||||
}
|
||||
if !file.Exists(filePath) {
|
||||
absFilePath, err := filepath.Abs(filepath.Clean(filePath))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
|
||||
return
|
||||
}
|
||||
if !file.Exists(absFilePath) {
|
||||
c.JSON(http.StatusNotFound, model.Result{Success: common_err.FILE_DOES_NOT_EXIST, Message: common_err.GetMsg(common_err.FILE_DOES_NOT_EXIST)})
|
||||
return
|
||||
}
|
||||
if !strings.Contains(filePath, config.AppInfo.UserDataPath) {
|
||||
if !strings.Contains(absFilePath, config.AppInfo.UserDataPath) {
|
||||
c.JSON(http.StatusNotFound, model.Result{Success: common_err.INSUFFICIENT_PERMISSIONS, Message: common_err.GetMsg(common_err.INSUFFICIENT_PERMISSIONS)})
|
||||
return
|
||||
}
|
||||
|
||||
fileTmp, _ := os.Open(filePath)
|
||||
defer fileTmp.Close()
|
||||
matched, err := regexp.MatchString(`^/var/lib/casaos/\d`, absFilePath)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, model.Result{Success: common_err.INSUFFICIENT_PERMISSIONS, Message: common_err.GetMsg(common_err.INSUFFICIENT_PERMISSIONS)})
|
||||
return
|
||||
}
|
||||
if !matched {
|
||||
c.JSON(http.StatusNotFound, model.Result{Success: common_err.INSUFFICIENT_PERMISSIONS, Message: common_err.GetMsg(common_err.INSUFFICIENT_PERMISSIONS)})
|
||||
return
|
||||
}
|
||||
|
||||
fileName := path.Base(filePath)
|
||||
fileName := path.Base(absFilePath)
|
||||
|
||||
// @tiger - RESTful 规范下不应该返回文件本身内容,而是返回文件的静态URL,由前端去解析
|
||||
c.Header("Content-Disposition", "attachment; filename*=utf-8''"+url2.PathEscape(fileName))
|
||||
c.File(filePath)
|
||||
c.File(absFilePath)
|
||||
}
|
||||
|
||||
func DeleteUserImage(c *gin.Context) {
|
||||
@@ -764,18 +929,42 @@ func DeleteUserAll(c *gin.Context) {
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /sys/init/check [get]
|
||||
// func GetUserStatus(c *gin.Context) {
|
||||
// data := make(map[string]interface{}, 2)
|
||||
|
||||
// if service.MyService.User().GetUserCount() > 0 {
|
||||
// data["initialized"] = true
|
||||
// data["key"] = ""
|
||||
// } else {
|
||||
// key := uuid.NewV4().String()
|
||||
// service.UserRegisterHash[key] = key
|
||||
// data["key"] = key
|
||||
// data["initialized"] = false
|
||||
// }
|
||||
// gpus, err := external.NvidiaGPUInfoList()
|
||||
// if err != nil {
|
||||
// logger.Error("NvidiaGPUInfoList error", zap.Error(err))
|
||||
// }
|
||||
// data["gpus"] = len(gpus)
|
||||
// c.JSON(common_err.SUCCESS,
|
||||
// model.Result{
|
||||
// Success: common_err.SUCCESS,
|
||||
// Message: common_err.GetMsg(common_err.SUCCESS),
|
||||
// Data: data,
|
||||
// })
|
||||
// }
|
||||
|
||||
func GetUserStatus(c *gin.Context) {
|
||||
data := make(map[string]interface{}, 2)
|
||||
|
||||
if service.MyService.User().GetUserCount() > 0 {
|
||||
data["initialized"] = true
|
||||
data["key"] = ""
|
||||
} else {
|
||||
key := uuid.NewV4().String()
|
||||
service.UserRegisterHash[key] = key
|
||||
data["key"] = key
|
||||
data["initialized"] = false
|
||||
key := uuid.NewV4().String()
|
||||
service.UserRegisterHash[key] = key
|
||||
data["key"] = key
|
||||
data["initialized"] = true
|
||||
gpus, err := external.NvidiaGPUInfoList()
|
||||
if err != nil {
|
||||
logger.Error("NvidiaGPUInfoList error", zap.Error(err))
|
||||
}
|
||||
data["gpus"] = len(gpus)
|
||||
c.JSON(common_err.SUCCESS,
|
||||
model.Result{
|
||||
Success: common_err.SUCCESS,
|
||||
|
||||
+4
-4
@@ -7,10 +7,10 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/KaySar12/NextZen-Common/utils/jwt"
|
||||
codegen "github.com/KaySar12/NextZen-UserService/codegen/user_service"
|
||||
v2 "github.com/KaySar12/NextZen-UserService/route/v2"
|
||||
"github.com/KaySar12/NextZen-UserService/service"
|
||||
"github.com/IceWhaleTech/CasaOS-Common/utils/jwt"
|
||||
codegen "github.com/IceWhaleTech/CasaOS-UserService/codegen/user_service"
|
||||
v2 "github.com/IceWhaleTech/CasaOS-UserService/route/v2"
|
||||
"github.com/IceWhaleTech/CasaOS-UserService/service"
|
||||
"github.com/deepmap/oapi-codegen/pkg/middleware"
|
||||
"github.com/getkin/kin-openapi/openapi3"
|
||||
"github.com/getkin/kin-openapi/openapi3filter"
|
||||
|
||||
@@ -3,8 +3,8 @@ package v2
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
codegen "github.com/KaySar12/NextZen-UserService/codegen/user_service"
|
||||
"github.com/KaySar12/NextZen-UserService/service"
|
||||
codegen "github.com/IceWhaleTech/CasaOS-UserService/codegen/user_service"
|
||||
"github.com/IceWhaleTech/CasaOS-UserService/service"
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
package v2
|
||||
|
||||
import codegen "github.com/KaySar12/NextZen-UserService/codegen/user_service"
|
||||
import codegen "github.com/IceWhaleTech/CasaOS-UserService/codegen/user_service"
|
||||
|
||||
type UserService struct{}
|
||||
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ package service
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/KaySar12/NextZen-UserService/model"
|
||||
"github.com/IceWhaleTech/CasaOS-UserService/model"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ package model
|
||||
|
||||
import "time"
|
||||
|
||||
//Soon to be removed
|
||||
// Soon to be removed
|
||||
type UserDBModel struct {
|
||||
Id int `gorm:"column:id;primary_key" json:"id"`
|
||||
Username string `json:"username"`
|
||||
|
||||
+167
@@ -0,0 +1,167 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
"github.com/IceWhaleTech/CasaOS-UserService/pkg/config"
|
||||
"github.com/IceWhaleTech/CasaOS-UserService/service/model"
|
||||
)
|
||||
|
||||
type OMVService interface {
|
||||
LoginSession(userName string, password string) (string, []*http.Cookie)
|
||||
Logout(sessionID string) (string, error)
|
||||
GetUser(username string, sessionID string) (string, error)
|
||||
AuthUser(username string, password string, sessionID string) (string, error)
|
||||
SetUser(m model.UserDBModel) model.UserDBModel
|
||||
ApplyChange()
|
||||
}
|
||||
type omvService struct {
|
||||
}
|
||||
|
||||
// AuthUser implements OMVService.
|
||||
|
||||
func (o *omvService) LoginSession(username string, password string) (string, []*http.Cookie) {
|
||||
postBody, _ := json.Marshal(map[string]interface{}{
|
||||
"service": "session",
|
||||
"method": "login",
|
||||
"params": map[string]string{
|
||||
"username": username,
|
||||
"password": password,
|
||||
},
|
||||
})
|
||||
responseBody := bytes.NewBuffer(postBody)
|
||||
response, err := http.Post(config.AppInfo.OMVServer, "application/json", responseBody)
|
||||
cookies := response.Cookies()
|
||||
if err != nil {
|
||||
fmt.Print(err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
responseData, err := io.ReadAll(response.Body)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
return string(responseData), cookies
|
||||
}
|
||||
func (o *omvService) Logout(sessionID string) (string, error) {
|
||||
postBody, _ := json.Marshal(map[string]interface{}{
|
||||
"service": "UserMgmt",
|
||||
"method": "logout",
|
||||
"params": nil,
|
||||
})
|
||||
responseBody := bytes.NewBuffer(postBody)
|
||||
req, err := http.NewRequest("POST", config.AppInfo.OMVServer, responseBody)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error creating request: %v", err)
|
||||
}
|
||||
req.Header.Set("X-OPENMEDIAVAULT-SESSIONID", sessionID) // Set session ID header
|
||||
client := &http.Client{}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error making request: %v", err)
|
||||
}
|
||||
defer resp.Body.Close() // Ensure the response body is closed
|
||||
// Check for HTTP errors
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("HTTP error: %s", resp.Status)
|
||||
}
|
||||
|
||||
// Read the response body
|
||||
responseData, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error reading response body: %v", err)
|
||||
}
|
||||
|
||||
return string(responseData), nil
|
||||
}
|
||||
func (o *omvService) AuthUser(username string, password string, sessionID string) (string, error) {
|
||||
postBody, _ := json.Marshal(map[string]interface{}{
|
||||
"service": "session",
|
||||
"method": "login",
|
||||
"params": map[string]string{
|
||||
"username": username,
|
||||
"password": password,
|
||||
},
|
||||
})
|
||||
responseBody := bytes.NewBuffer(postBody)
|
||||
req, err := http.NewRequest("POST", config.AppInfo.OMVServer, responseBody)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error creating request: %v", err)
|
||||
}
|
||||
req.Header.Set("X-OPENMEDIAVAULT-SESSIONID", sessionID) // Set session ID header
|
||||
// Send the request
|
||||
client := &http.Client{}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error making request: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
// Check for HTTP errors
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("HTTP error: %s", resp.Status)
|
||||
}
|
||||
// Read the response body
|
||||
responseData, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error reading response body: %v", err)
|
||||
}
|
||||
|
||||
return string(responseData), nil
|
||||
}
|
||||
func (o *omvService) GetUser(username string, sessionID string) (string, error) {
|
||||
// Prepare the RPC request
|
||||
postBody, _ := json.Marshal(map[string]interface{}{
|
||||
"service": "UserMgmt",
|
||||
"method": "getUser",
|
||||
"params": map[string]string{
|
||||
"name": username,
|
||||
},
|
||||
})
|
||||
responseBody := bytes.NewBuffer(postBody)
|
||||
|
||||
// Create HTTP request and set session ID header
|
||||
req, err := http.NewRequest("POST", config.AppInfo.OMVServer, responseBody)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error creating request: %v", err)
|
||||
}
|
||||
req.Header.Set("X-OPENMEDIAVAULT-SESSIONID", sessionID) // Set session ID header
|
||||
|
||||
// Send the request
|
||||
client := &http.Client{}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error making request: %v", err)
|
||||
}
|
||||
defer resp.Body.Close() // Ensure the response body is closed
|
||||
|
||||
// Check for HTTP errors
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("HTTP error: %s", resp.Status)
|
||||
}
|
||||
|
||||
// Read the response body
|
||||
responseData, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error reading response body: %v", err)
|
||||
}
|
||||
|
||||
return string(responseData), nil
|
||||
}
|
||||
|
||||
func (o *omvService) SetUser(m model.UserDBModel) model.UserDBModel {
|
||||
// Implement SetUser logic here
|
||||
return m // Assuming m is the modified user
|
||||
}
|
||||
|
||||
func (o *omvService) ApplyChange() {
|
||||
// Implement ApplyChange logic here
|
||||
}
|
||||
|
||||
func NewOMVService() OMVService {
|
||||
return &omvService{}
|
||||
}
|
||||
+29
-1
@@ -1,7 +1,9 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"github.com/KaySar12/NextZen-Common/external"
|
||||
"github.com/IceWhaleTech/CasaOS-Common/external"
|
||||
"github.com/IceWhaleTech/CasaOS-UserService/codegen/message_bus"
|
||||
"github.com/IceWhaleTech/CasaOS-UserService/pkg/config"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
@@ -10,7 +12,9 @@ var MyService Repository
|
||||
type Repository interface {
|
||||
Gateway() external.ManagementService
|
||||
User() UserService
|
||||
MessageBus() *message_bus.ClientWithResponses
|
||||
Event() EventService
|
||||
OMV() OMVService
|
||||
}
|
||||
|
||||
func NewService(db *gorm.DB, RuntimePath string) Repository {
|
||||
@@ -24,6 +28,7 @@ func NewService(db *gorm.DB, RuntimePath string) Repository {
|
||||
gateway: gatewayManagement,
|
||||
user: NewUserService(db),
|
||||
event: NewEventService(db),
|
||||
omv: NewOMVService(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,6 +36,7 @@ type store struct {
|
||||
gateway external.ManagementService
|
||||
user UserService
|
||||
event EventService
|
||||
omv OMVService
|
||||
}
|
||||
|
||||
func (c *store) Event() EventService {
|
||||
@@ -43,3 +49,25 @@ func (c *store) Gateway() external.ManagementService {
|
||||
func (c *store) User() UserService {
|
||||
return c.user
|
||||
}
|
||||
func (c *store) OMV() OMVService {
|
||||
return c.omv
|
||||
}
|
||||
func (c *store) MessageBus() *message_bus.ClientWithResponses {
|
||||
client, _ := message_bus.NewClientWithResponses("", func(c *message_bus.Client) error {
|
||||
// error will never be returned, as we always want to return a client, even with wrong address,
|
||||
// in order to avoid panic.
|
||||
//
|
||||
// If we don't avoid panic, message bus becomes a hard dependency, which is not what we want.
|
||||
|
||||
messageBusAddress, err := external.GetMessageBusAddress(config.CommonInfo.RuntimePath)
|
||||
if err != nil {
|
||||
c.Server = "message bus address not found"
|
||||
return nil
|
||||
}
|
||||
|
||||
c.Server = messageBusAddress
|
||||
return nil
|
||||
})
|
||||
|
||||
return client
|
||||
}
|
||||
|
||||
+3
-3
@@ -15,9 +15,9 @@ import (
|
||||
"mime/multipart"
|
||||
"os"
|
||||
|
||||
"github.com/KaySar12/NextZen-Common/utils/jwt"
|
||||
"github.com/KaySar12/NextZen-Common/utils/logger"
|
||||
"github.com/KaySar12/NextZen-UserService/service/model"
|
||||
"github.com/IceWhaleTech/CasaOS-Common/utils/jwt"
|
||||
"github.com/IceWhaleTech/CasaOS-Common/utils/logger"
|
||||
"github.com/IceWhaleTech/CasaOS-UserService/service/model"
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user