mirror of
https://github.com/lejianwen/rustdesk-api.git
synced 2026-02-13 01:30:53 +00:00
Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
65f0a9e3cf | ||
|
|
77836a4e56 | ||
|
|
09f8316bf1 | ||
|
|
c52706e621 | ||
|
|
17dcff4f43 | ||
|
|
0b39c4e104 | ||
|
|
ee176b314e | ||
|
|
1ffc9c4a5b | ||
|
|
1257246552 |
@@ -42,11 +42,11 @@ RUN if [ "$COUNTRY" = "CN" ] ; then \
|
|||||||
fi && \
|
fi && \
|
||||||
apk update && apk add --no-cache git
|
apk update && apk add --no-cache git
|
||||||
|
|
||||||
ARG FREONTEND_GIT_REPO=https://github.com/lejianwen/rustdesk-api-web.git
|
ARG FRONTEND_GIT_REPO=https://github.com/lejianwen/rustdesk-api-web.git
|
||||||
ARG FRONTEND_GIT_BRANCH=master
|
ARG FRONTEND_GIT_BRANCH=master
|
||||||
# Clone the frontend repository
|
# Clone the frontend repository
|
||||||
|
|
||||||
RUN git clone -b $FRONTEND_GIT_BRANCH $FREONTEND_GIT_REPO .
|
RUN git clone -b $FRONTEND_GIT_BRANCH $FRONTEND_GIT_REPO .
|
||||||
|
|
||||||
# Install required tools without caching index to minimize image size
|
# Install required tools without caching index to minimize image size
|
||||||
RUN if [ "$COUNTRY" = "CN" ] ; then \
|
RUN if [ "$COUNTRY" = "CN" ] ; then \
|
||||||
@@ -91,4 +91,4 @@ VOLUME /app/data
|
|||||||
EXPOSE 21114
|
EXPOSE 21114
|
||||||
|
|
||||||
# Define the command to run the application
|
# Define the command to run the application
|
||||||
CMD ["./apimain"]
|
CMD ["./apimain"]
|
||||||
|
|||||||
@@ -255,6 +255,12 @@
|
|||||||
#或者使用generate_api.go生成api并运行
|
#或者使用generate_api.go生成api并运行
|
||||||
go generate generate_api.go
|
go generate generate_api.go
|
||||||
```
|
```
|
||||||
|
> 注意:使用 `go run` 或编译后的二进制时,当前目录下必须存在 `conf` 和 `resources`
|
||||||
|
> 目录。如果在其他目录运行,可通过 `-c` 和环境变量
|
||||||
|
> `RUSTDESK_API_GIN_RESOURCES_PATH` 指定绝对路径,例如:
|
||||||
|
> ```bash
|
||||||
|
> RUSTDESK_API_GIN_RESOURCES_PATH=/opt/rustdesk-api/resources ./apimain -c /opt/rustdesk-api/conf/config.yaml
|
||||||
|
> ```
|
||||||
5. 编译,如果想自己编译,先cd到项目根目录,然后windows下直接运行`build.bat`,linux下运行`build.sh`,编译后会在`release`
|
5. 编译,如果想自己编译,先cd到项目根目录,然后windows下直接运行`build.bat`,linux下运行`build.sh`,编译后会在`release`
|
||||||
目录下生成对应的可执行文件。直接运行编译后的可执行文件即可。
|
目录下生成对应的可执行文件。直接运行编译后的可执行文件即可。
|
||||||
|
|
||||||
|
|||||||
18
README_EN.md
18
README_EN.md
@@ -164,7 +164,8 @@ The table below does not list all configurations. Please refer to the configurat
|
|||||||
| RUSTDESK_API_APP_DISABLE_PWD_LOGIN | disable password login | `false` |
|
| RUSTDESK_API_APP_DISABLE_PWD_LOGIN | disable password login | `false` |
|
||||||
| RUSTDESK_API_APP_REGISTER_STATUS | register user default status ; 1 enabled , 2 disabled ; default 1 | `1` |
|
| RUSTDESK_API_APP_REGISTER_STATUS | register user default status ; 1 enabled , 2 disabled ; default 1 | `1` |
|
||||||
| RUSTDESK_API_APP_CAPTCHA_THRESHOLD | captcha threshold; -1 disabled, 0 always enable, >0 threshold ;default `3` | `3` |
|
| RUSTDESK_API_APP_CAPTCHA_THRESHOLD | captcha threshold; -1 disabled, 0 always enable, >0 threshold ;default `3` | `3` |
|
||||||
| RUSTDESK_API_APP_BAN_THRESHOLD | ban ip threshold; 0 disabled, >0 threshold ; default `0` | `0` |
|
| RUSTDESK_API_APP_BAN_THRESHOLD | ban ip threshold; 0 disabled, >0 threshold ; default `0`
|
||||||
|
| `0` |
|
||||||
| ----- ADMIN Configuration----- | ---------- | ---------- |
|
| ----- ADMIN Configuration----- | ---------- | ---------- |
|
||||||
| RUSTDESK_API_ADMIN_TITLE | Admin Title | `RustDesk Api Admin` |
|
| RUSTDESK_API_ADMIN_TITLE | Admin Title | `RustDesk Api Admin` |
|
||||||
| RUSTDESK_API_ADMIN_HELLO | Admin welcome message, you can use `html` | |
|
| RUSTDESK_API_ADMIN_HELLO | Admin welcome message, you can use `html` | |
|
||||||
@@ -251,10 +252,17 @@ Download the release from [release](https://github.com/lejianwen/rustdesk-api/re
|
|||||||
4. Run:
|
4. Run:
|
||||||
```bash
|
```bash
|
||||||
# Run directly
|
# Run directly
|
||||||
go run cmd/apimain.go
|
go run cmd/apimain.go
|
||||||
# Or generate and run the API using generate_api.go
|
# Or generate and run the API using generate_api.go
|
||||||
go generate generate_api.go
|
go generate generate_api.go
|
||||||
```
|
```
|
||||||
|
> **Note:** When using `go run` or the compiled binary, the `conf` and `resources`
|
||||||
|
> directories must exist relative to the current working directory. If you run
|
||||||
|
> the program from another location, specify absolute paths with `-c` and the
|
||||||
|
> `RUSTDESK_API_GIN_RESOURCES_PATH` environment variable. Example:
|
||||||
|
> ```bash
|
||||||
|
> RUSTDESK_API_GIN_RESOURCES_PATH=/opt/rustdesk-api/resources ./apimain -c /opt/rustdesk-api/conf/config.yaml
|
||||||
|
> ```
|
||||||
|
|
||||||
5. To compile, change to the project root directory. For Windows, run `build.bat`, and for Linux, run `build.sh`. After
|
5. To compile, change to the project root directory. For Windows, run `build.bat`, and for Linux, run `build.sh`. After
|
||||||
compiling, the corresponding executables will be generated in the `release` directory. Run the compiled executables
|
compiling, the corresponding executables will be generated in the `release` directory. Run the compiled executables
|
||||||
|
|||||||
@@ -2,6 +2,10 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/go-redis/redis/v8"
|
"github.com/go-redis/redis/v8"
|
||||||
"github.com/lejianwen/rustdesk-api/v2/config"
|
"github.com/lejianwen/rustdesk-api/v2/config"
|
||||||
"github.com/lejianwen/rustdesk-api/v2/global"
|
"github.com/lejianwen/rustdesk-api/v2/global"
|
||||||
@@ -17,11 +21,10 @@ import (
|
|||||||
"github.com/lejianwen/rustdesk-api/v2/utils"
|
"github.com/lejianwen/rustdesk-api/v2/utils"
|
||||||
"github.com/nicksnyder/go-i18n/v2/i18n"
|
"github.com/nicksnyder/go-i18n/v2/i18n"
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
"os"
|
|
||||||
"strconv"
|
|
||||||
"time"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const DatabaseVersion = 264
|
||||||
|
|
||||||
// @title 管理系统API
|
// @title 管理系统API
|
||||||
// @version 1.0
|
// @version 1.0
|
||||||
// @description 接口
|
// @description 接口
|
||||||
@@ -210,7 +213,7 @@ func InitGlobal() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func DatabaseAutoUpdate() {
|
func DatabaseAutoUpdate() {
|
||||||
version := 262
|
version := DatabaseVersion
|
||||||
|
|
||||||
db := global.DB
|
db := global.DB
|
||||||
|
|
||||||
@@ -342,7 +345,11 @@ func Migrate(version uint) {
|
|||||||
// 生成随机密码
|
// 生成随机密码
|
||||||
pwd := utils.RandomString(8)
|
pwd := utils.RandomString(8)
|
||||||
global.Logger.Info("Admin Password Is: ", pwd)
|
global.Logger.Info("Admin Password Is: ", pwd)
|
||||||
admin.Password = service.AllService.UserService.EncryptPassword(pwd)
|
var err error
|
||||||
|
admin.Password, err = utils.EncryptPassword(pwd)
|
||||||
|
if err != nil {
|
||||||
|
global.Logger.Fatalf("failed to generate admin password: %v", err)
|
||||||
|
}
|
||||||
global.DB.Create(admin)
|
global.DB.Create(admin)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,24 +3,20 @@ package config
|
|||||||
type GithubOauth struct {
|
type GithubOauth struct {
|
||||||
ClientId string `mapstructure:"client-id"`
|
ClientId string `mapstructure:"client-id"`
|
||||||
ClientSecret string `mapstructure:"client-secret"`
|
ClientSecret string `mapstructure:"client-secret"`
|
||||||
RedirectUrl string `mapstructure:"redirect-url"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type GoogleOauth struct {
|
type GoogleOauth struct {
|
||||||
ClientId string `mapstructure:"client-id"`
|
ClientId string `mapstructure:"client-id"`
|
||||||
ClientSecret string `mapstructure:"client-secret"`
|
ClientSecret string `mapstructure:"client-secret"`
|
||||||
RedirectUrl string `mapstructure:"redirect-url"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type OidcOauth struct {
|
type OidcOauth struct {
|
||||||
Issuer string `mapstructure:"issuer"`
|
Issuer string `mapstructure:"issuer"`
|
||||||
ClientId string `mapstructure:"client-id"`
|
ClientId string `mapstructure:"client-id"`
|
||||||
ClientSecret string `mapstructure:"client-secret"`
|
ClientSecret string `mapstructure:"client-secret"`
|
||||||
RedirectUrl string `mapstructure:"redirect-url"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type LinuxdoOauth struct {
|
type LinuxdoOauth struct {
|
||||||
ClientId string `mapstructure:"client-id"`
|
ClientId string `mapstructure:"client-id"`
|
||||||
ClientSecret string `mapstructure:"client-secret"`
|
ClientSecret string `mapstructure:"client-secret"`
|
||||||
RedirectUrl string `mapstructure:"redirect-url"`
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ services:
|
|||||||
dockerfile: Dockerfile.dev
|
dockerfile: Dockerfile.dev
|
||||||
args:
|
args:
|
||||||
COUNTRY: CN
|
COUNTRY: CN
|
||||||
FREONTEND_GIT_REPO: https://github.com/lejianwen/rustdesk-api-web.git
|
FRONTEND_GIT_REPO: https://github.com/lejianwen/rustdesk-api-web.git
|
||||||
FRONTEND_GIT_BRANCH: master
|
FRONTEND_GIT_BRANCH: master
|
||||||
# image: lejianwen/rustdesk-api
|
# image: lejianwen/rustdesk-api
|
||||||
container_name: rustdesk-api
|
container_name: rustdesk-api
|
||||||
@@ -21,4 +21,4 @@ services:
|
|||||||
- ./data/rustdesk/api:/app/data #将数据库挂载出来方便备份
|
- ./data/rustdesk/api:/app/data #将数据库挂载出来方便备份
|
||||||
- ./conf:/app/conf # config
|
- ./conf:/app/conf # config
|
||||||
# - ./resources:/app/resources # 静态资源
|
# - ./resources:/app/resources # 静态资源
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|||||||
@@ -5569,8 +5569,7 @@ const docTemplateadmin = `{
|
|||||||
"required": [
|
"required": [
|
||||||
"client_id",
|
"client_id",
|
||||||
"client_secret",
|
"client_secret",
|
||||||
"oauth_type",
|
"oauth_type"
|
||||||
"redirect_url"
|
|
||||||
],
|
],
|
||||||
"properties": {
|
"properties": {
|
||||||
"auto_register": {
|
"auto_register": {
|
||||||
@@ -5600,9 +5599,6 @@ const docTemplateadmin = `{
|
|||||||
"pkce_method": {
|
"pkce_method": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
"redirect_url": {
|
|
||||||
"type": "string"
|
|
||||||
},
|
|
||||||
"scopes": {
|
"scopes": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
}
|
}
|
||||||
@@ -6296,9 +6292,6 @@ const docTemplateadmin = `{
|
|||||||
"pkce_method": {
|
"pkce_method": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
"redirect_url": {
|
|
||||||
"type": "string"
|
|
||||||
},
|
|
||||||
"scopes": {
|
"scopes": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -5562,8 +5562,7 @@
|
|||||||
"required": [
|
"required": [
|
||||||
"client_id",
|
"client_id",
|
||||||
"client_secret",
|
"client_secret",
|
||||||
"oauth_type",
|
"oauth_type"
|
||||||
"redirect_url"
|
|
||||||
],
|
],
|
||||||
"properties": {
|
"properties": {
|
||||||
"auto_register": {
|
"auto_register": {
|
||||||
@@ -5593,9 +5592,6 @@
|
|||||||
"pkce_method": {
|
"pkce_method": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
"redirect_url": {
|
|
||||||
"type": "string"
|
|
||||||
},
|
|
||||||
"scopes": {
|
"scopes": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
}
|
}
|
||||||
@@ -6289,9 +6285,6 @@
|
|||||||
"pkce_method": {
|
"pkce_method": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
"redirect_url": {
|
|
||||||
"type": "string"
|
|
||||||
},
|
|
||||||
"scopes": {
|
"scopes": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
@@ -6595,4 +6588,4 @@
|
|||||||
"in": "header"
|
"in": "header"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -143,15 +143,12 @@ definitions:
|
|||||||
type: boolean
|
type: boolean
|
||||||
pkce_method:
|
pkce_method:
|
||||||
type: string
|
type: string
|
||||||
redirect_url:
|
|
||||||
type: string
|
|
||||||
scopes:
|
scopes:
|
||||||
type: string
|
type: string
|
||||||
required:
|
required:
|
||||||
- client_id
|
- client_id
|
||||||
- client_secret
|
- client_secret
|
||||||
- oauth_type
|
- oauth_type
|
||||||
- redirect_url
|
|
||||||
type: object
|
type: object
|
||||||
admin.PeerBatchDeleteForm:
|
admin.PeerBatchDeleteForm:
|
||||||
properties:
|
properties:
|
||||||
@@ -611,8 +608,6 @@ definitions:
|
|||||||
type: boolean
|
type: boolean
|
||||||
pkce_method:
|
pkce_method:
|
||||||
type: string
|
type: string
|
||||||
redirect_url:
|
|
||||||
type: string
|
|
||||||
scopes:
|
scopes:
|
||||||
type: string
|
type: string
|
||||||
updated_at:
|
updated_at:
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ func (f *File) Notify(c *gin.Context) {
|
|||||||
|
|
||||||
res := global.Oss.Verify(c.Request)
|
res := global.Oss.Verify(c.Request)
|
||||||
if !res {
|
if !res {
|
||||||
response.Fail(c, 101, "权限错误")
|
response.Fail(c, 101, response.TranslateMsg(c, "NoAccess"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
fm := &FileBack{}
|
fm := &FileBack{}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package admin
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/lejianwen/rustdesk-api/v2/global"
|
"github.com/lejianwen/rustdesk-api/v2/global"
|
||||||
"github.com/lejianwen/rustdesk-api/v2/http/controller/api"
|
"github.com/lejianwen/rustdesk-api/v2/http/controller/api"
|
||||||
@@ -188,7 +189,7 @@ func (ct *Login) OidcAuth(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
err, state, verifier, nonce, url := service.AllService.OauthService.BeginAuth(f.Op)
|
err, state, verifier, nonce, url := service.AllService.OauthService.BeginAuth(c, f.Op)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
response.Error(c, response.TranslateMsg(c, err.Error()))
|
response.Error(c, response.TranslateMsg(c, err.Error()))
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -1,13 +1,14 @@
|
|||||||
package admin
|
package admin
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"strconv"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/lejianwen/rustdesk-api/v2/global"
|
"github.com/lejianwen/rustdesk-api/v2/global"
|
||||||
"github.com/lejianwen/rustdesk-api/v2/http/request/admin"
|
"github.com/lejianwen/rustdesk-api/v2/http/request/admin"
|
||||||
adminReq "github.com/lejianwen/rustdesk-api/v2/http/request/admin"
|
adminReq "github.com/lejianwen/rustdesk-api/v2/http/request/admin"
|
||||||
"github.com/lejianwen/rustdesk-api/v2/http/response"
|
"github.com/lejianwen/rustdesk-api/v2/http/response"
|
||||||
"github.com/lejianwen/rustdesk-api/v2/service"
|
"github.com/lejianwen/rustdesk-api/v2/service"
|
||||||
"strconv"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type Oauth struct {
|
type Oauth struct {
|
||||||
@@ -43,7 +44,7 @@ func (o *Oauth) ToBind(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
err, state, verifier, nonce, url := service.AllService.OauthService.BeginAuth(f.Op)
|
err, state, verifier, nonce, url := service.AllService.OauthService.BeginAuth(c, f.Op)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
response.Error(c, response.TranslateMsg(c, err.Error()))
|
response.Error(c, response.TranslateMsg(c, err.Error()))
|
||||||
return
|
return
|
||||||
@@ -68,16 +69,16 @@ func (o *Oauth) Confirm(c *gin.Context) {
|
|||||||
j := &adminReq.OauthConfirmForm{}
|
j := &adminReq.OauthConfirmForm{}
|
||||||
err := c.ShouldBindJSON(j)
|
err := c.ShouldBindJSON(j)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
response.Fail(c, 101, "参数错误"+err.Error())
|
response.Fail(c, 101, response.TranslateMsg(c, "ParamsError")+err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if j.Code == "" {
|
if j.Code == "" {
|
||||||
response.Fail(c, 101, "参数错误: code 不存在")
|
response.Fail(c, 101, response.TranslateMsg(c, "ParamsError"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
v := service.AllService.OauthService.GetOauthCache(j.Code)
|
v := service.AllService.OauthService.GetOauthCache(j.Code)
|
||||||
if v == nil {
|
if v == nil {
|
||||||
response.Fail(c, 101, "授权已过期")
|
response.Fail(c, 101, response.TranslateMsg(c, "OauthExpired"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
u := service.AllService.UserService.CurUser(c)
|
u := service.AllService.UserService.CurUser(c)
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import (
|
|||||||
adResp "github.com/lejianwen/rustdesk-api/v2/http/response/admin"
|
adResp "github.com/lejianwen/rustdesk-api/v2/http/response/admin"
|
||||||
"github.com/lejianwen/rustdesk-api/v2/model"
|
"github.com/lejianwen/rustdesk-api/v2/model"
|
||||||
"github.com/lejianwen/rustdesk-api/v2/service"
|
"github.com/lejianwen/rustdesk-api/v2/service"
|
||||||
|
"github.com/lejianwen/rustdesk-api/v2/utils"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
"strconv"
|
"strconv"
|
||||||
)
|
)
|
||||||
@@ -243,11 +244,10 @@ func (ct *User) ChangeCurPwd(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
u := service.AllService.UserService.CurUser(c)
|
u := service.AllService.UserService.CurUser(c)
|
||||||
// If the password is not empty, the old password is verified
|
// Verify the old password only when the account already has one set
|
||||||
// otherwise, the old password is not verified
|
|
||||||
if !service.AllService.UserService.IsPasswordEmptyByUser(u) {
|
if !service.AllService.UserService.IsPasswordEmptyByUser(u) {
|
||||||
oldPwd := service.AllService.UserService.EncryptPassword(f.OldPassword)
|
ok, _, err := utils.VerifyPassword(u.Password, f.OldPassword)
|
||||||
if u.Password != oldPwd {
|
if err != nil || !ok {
|
||||||
response.Fail(c, 101, response.TranslateMsg(c, "OldPasswordError"))
|
response.Fail(c, 101, response.TranslateMsg(c, "OldPasswordError"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
package api
|
package api
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/lejianwen/rustdesk-api/v2/global"
|
"github.com/lejianwen/rustdesk-api/v2/global"
|
||||||
"github.com/lejianwen/rustdesk-api/v2/http/request/api"
|
"github.com/lejianwen/rustdesk-api/v2/http/request/api"
|
||||||
@@ -10,7 +12,6 @@ import (
|
|||||||
"github.com/lejianwen/rustdesk-api/v2/service"
|
"github.com/lejianwen/rustdesk-api/v2/service"
|
||||||
"github.com/lejianwen/rustdesk-api/v2/utils"
|
"github.com/lejianwen/rustdesk-api/v2/utils"
|
||||||
"github.com/nicksnyder/go-i18n/v2/i18n"
|
"github.com/nicksnyder/go-i18n/v2/i18n"
|
||||||
"net/http"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type Oauth struct {
|
type Oauth struct {
|
||||||
@@ -35,7 +36,7 @@ func (o *Oauth) OidcAuth(c *gin.Context) {
|
|||||||
|
|
||||||
oauthService := service.AllService.OauthService
|
oauthService := service.AllService.OauthService
|
||||||
|
|
||||||
err, state, verifier, nonce, url := oauthService.BeginAuth(f.Op)
|
err, state, verifier, nonce, url := oauthService.BeginAuth(c, f.Op)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
response.Error(c, response.TranslateMsg(c, err.Error()))
|
response.Error(c, response.TranslateMsg(c, err.Error()))
|
||||||
return
|
return
|
||||||
@@ -169,7 +170,7 @@ func (o *Oauth) OauthCallback(c *gin.Context) {
|
|||||||
var user *model.User
|
var user *model.User
|
||||||
// 获取用户信息
|
// 获取用户信息
|
||||||
code := c.Query("code")
|
code := c.Query("code")
|
||||||
err, oauthUser := oauthService.Callback(code, verifier, op, nonce)
|
err, oauthUser := oauthService.Callback(c, code, verifier, op, nonce)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.HTML(http.StatusOK, "oauth_fail.html", gin.H{
|
c.HTML(http.StatusOK, "oauth_fail.html", gin.H{
|
||||||
"message": "OauthFailed",
|
"message": "OauthFailed",
|
||||||
@@ -225,8 +226,7 @@ func (o *Oauth) OauthCallback(c *gin.Context) {
|
|||||||
if !*oauthConfig.AutoRegister {
|
if !*oauthConfig.AutoRegister {
|
||||||
//c.String(http.StatusInternalServerError, "还未绑定用户,请先绑定")
|
//c.String(http.StatusInternalServerError, "还未绑定用户,请先绑定")
|
||||||
oauthCache.UpdateFromOauthUser(oauthUser)
|
oauthCache.UpdateFromOauthUser(oauthUser)
|
||||||
url := global.Config.Rustdesk.ApiServer + "/_admin/#/oauth/bind/" + cacheKey
|
c.Redirect(http.StatusFound, "/_admin/#/oauth/bind/"+cacheKey)
|
||||||
c.Redirect(http.StatusFound, url)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -251,8 +251,7 @@ func (o *Oauth) OauthCallback(c *gin.Context) {
|
|||||||
Type: model.LoginLogTypeOauth,
|
Type: model.LoginLogTypeOauth,
|
||||||
Platform: oauthService.DeviceOs,
|
Platform: oauthService.DeviceOs,
|
||||||
})*/
|
})*/
|
||||||
url := global.Config.Rustdesk.ApiServer + "/_admin/#/"
|
c.Redirect(http.StatusFound, "/_admin/#/")
|
||||||
c.Redirect(http.StatusFound, url)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
c.HTML(http.StatusOK, "oauth_success.html", gin.H{
|
c.HTML(http.StatusOK, "oauth_success.html", gin.H{
|
||||||
|
|||||||
@@ -13,13 +13,13 @@ func BackendUserAuth() gin.HandlerFunc {
|
|||||||
//测试先关闭
|
//测试先关闭
|
||||||
token := c.GetHeader("api-token")
|
token := c.GetHeader("api-token")
|
||||||
if token == "" {
|
if token == "" {
|
||||||
response.Fail(c, 403, "请先登录")
|
response.Fail(c, 403, response.TranslateMsg(c, "NeedLogin"))
|
||||||
c.Abort()
|
c.Abort()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
user, ut := service.AllService.UserService.InfoByAccessToken(token)
|
user, ut := service.AllService.UserService.InfoByAccessToken(token)
|
||||||
if user.Id == 0 {
|
if user.Id == 0 {
|
||||||
response.Fail(c, 403, "请先登录")
|
response.Fail(c, 403, response.TranslateMsg(c, "NeedLogin"))
|
||||||
c.Abort()
|
c.Abort()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ func AdminPrivilege() gin.HandlerFunc {
|
|||||||
u := service.AllService.UserService.CurUser(c)
|
u := service.AllService.UserService.CurUser(c)
|
||||||
|
|
||||||
if !service.AllService.UserService.IsAdmin(u) {
|
if !service.AllService.UserService.IsAdmin(u) {
|
||||||
response.Fail(c, 403, "无权限")
|
response.Fail(c, 403, response.TranslateMsg(c, "NoAccess"))
|
||||||
c.Abort()
|
c.Abort()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,18 +12,18 @@ func JwtAuth() gin.HandlerFunc {
|
|||||||
//测试先关闭
|
//测试先关闭
|
||||||
token := c.GetHeader("api-token")
|
token := c.GetHeader("api-token")
|
||||||
if token == "" {
|
if token == "" {
|
||||||
response.Fail(c, 403, "请先登录")
|
response.Fail(c, 403, response.TranslateMsg(c, "NeedLogin"))
|
||||||
c.Abort()
|
c.Abort()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
uid, err := global.Jwt.ParseToken(token)
|
uid, err := global.Jwt.ParseToken(token)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
response.Fail(c, 403, "请先登录")
|
response.Fail(c, 403, response.TranslateMsg(c, "NeedLogin"))
|
||||||
c.Abort()
|
c.Abort()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if uid == 0 {
|
if uid == 0 {
|
||||||
response.Fail(c, 403, "请先登录")
|
response.Fail(c, 403, response.TranslateMsg(c, "NeedLogin"))
|
||||||
c.Abort()
|
c.Abort()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -34,12 +34,12 @@ func JwtAuth() gin.HandlerFunc {
|
|||||||
// Username: "测试用户",
|
// Username: "测试用户",
|
||||||
//}
|
//}
|
||||||
if user.Id == 0 {
|
if user.Id == 0 {
|
||||||
response.Fail(c, 403, "请先登录")
|
response.Fail(c, 403, response.TranslateMsg(c, "NeedLogin"))
|
||||||
c.Abort()
|
c.Abort()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if !service.AllService.UserService.CheckUserEnable(user) {
|
if !service.AllService.UserService.CheckUserEnable(user) {
|
||||||
response.Fail(c, 101, "你已被禁用")
|
response.Fail(c, 101, response.TranslateMsg(c, "Banned"))
|
||||||
c.Abort()
|
c.Abort()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,7 +22,6 @@ type OauthForm struct {
|
|||||||
Scopes string `json:"scopes" validate:"omitempty"`
|
Scopes string `json:"scopes" validate:"omitempty"`
|
||||||
ClientId string `json:"client_id" validate:"required"`
|
ClientId string `json:"client_id" validate:"required"`
|
||||||
ClientSecret string `json:"client_secret" validate:"required"`
|
ClientSecret string `json:"client_secret" validate:"required"`
|
||||||
RedirectUrl string `json:"redirect_url" validate:"required"`
|
|
||||||
AutoRegister *bool `json:"auto_register"`
|
AutoRegister *bool `json:"auto_register"`
|
||||||
PkceEnable *bool `json:"pkce_enable"`
|
PkceEnable *bool `json:"pkce_enable"`
|
||||||
PkceMethod string `json:"pkce_method"`
|
PkceMethod string `json:"pkce_method"`
|
||||||
@@ -34,7 +33,6 @@ func (of *OauthForm) ToOauth() *model.Oauth {
|
|||||||
OauthType: of.OauthType,
|
OauthType: of.OauthType,
|
||||||
ClientId: of.ClientId,
|
ClientId: of.ClientId,
|
||||||
ClientSecret: of.ClientSecret,
|
ClientSecret: of.ClientSecret,
|
||||||
RedirectUrl: of.RedirectUrl,
|
|
||||||
AutoRegister: of.AutoRegister,
|
AutoRegister: of.AutoRegister,
|
||||||
Issuer: of.Issuer,
|
Issuer: of.Issuer,
|
||||||
Scopes: of.Scopes,
|
Scopes: of.Scopes,
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ type UserForm struct {
|
|||||||
GroupId uint `json:"group_id" validate:"required"`
|
GroupId uint `json:"group_id" validate:"required"`
|
||||||
IsAdmin *bool `json:"is_admin" `
|
IsAdmin *bool `json:"is_admin" `
|
||||||
Status model.StatusCode `json:"status" validate:"required,gte=0"`
|
Status model.StatusCode `json:"status" validate:"required,gte=0"`
|
||||||
|
Remark string `json:"remark"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (uf *UserForm) FromUser(user *model.User) *UserForm {
|
func (uf *UserForm) FromUser(user *model.User) *UserForm {
|
||||||
@@ -25,6 +26,7 @@ func (uf *UserForm) FromUser(user *model.User) *UserForm {
|
|||||||
uf.GroupId = user.GroupId
|
uf.GroupId = user.GroupId
|
||||||
uf.IsAdmin = user.IsAdmin
|
uf.IsAdmin = user.IsAdmin
|
||||||
uf.Status = user.Status
|
uf.Status = user.Status
|
||||||
|
uf.Remark = user.Remark
|
||||||
return uf
|
return uf
|
||||||
}
|
}
|
||||||
func (uf *UserForm) ToUser() *model.User {
|
func (uf *UserForm) ToUser() *model.User {
|
||||||
@@ -37,6 +39,7 @@ func (uf *UserForm) ToUser() *model.User {
|
|||||||
user.GroupId = uf.GroupId
|
user.GroupId = uf.GroupId
|
||||||
user.IsAdmin = uf.IsAdmin
|
user.IsAdmin = uf.IsAdmin
|
||||||
user.Status = uf.Status
|
user.Status = uf.Status
|
||||||
|
user.Remark = uf.Remark
|
||||||
return user
|
return user
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -30,9 +30,9 @@ func ValidateOauthType(oauthType string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const (
|
const (
|
||||||
UserEndpointGithub string = "https://api.github.com/user"
|
UserEndpointGithub string = "https://api.github.com/user"
|
||||||
UserEndpointLinuxdo string = "https://connect.linux.do/api/user"
|
UserEndpointLinuxdo string = "https://connect.linux.do/api/user"
|
||||||
IssuerGoogle string = "https://accounts.google.com"
|
IssuerGoogle string = "https://accounts.google.com"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Oauth struct {
|
type Oauth struct {
|
||||||
@@ -41,12 +41,11 @@ type Oauth struct {
|
|||||||
OauthType string `json:"oauth_type"`
|
OauthType string `json:"oauth_type"`
|
||||||
ClientId string `json:"client_id"`
|
ClientId string `json:"client_id"`
|
||||||
ClientSecret string `json:"client_secret"`
|
ClientSecret string `json:"client_secret"`
|
||||||
RedirectUrl string `json:"redirect_url"`
|
|
||||||
AutoRegister *bool `json:"auto_register"`
|
AutoRegister *bool `json:"auto_register"`
|
||||||
Scopes string `json:"scopes"`
|
Scopes string `json:"scopes"`
|
||||||
Issuer string `json:"issuer"`
|
Issuer string `json:"issuer"`
|
||||||
PkceEnable *bool `json:"pkce_enable"`
|
PkceEnable *bool `json:"pkce_enable"`
|
||||||
PkceMethod string `json:"pkce_method"`
|
PkceMethod string `json:"pkce_method"`
|
||||||
TimeModel
|
TimeModel
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ type User struct {
|
|||||||
GroupId uint `json:"group_id" gorm:"default:0;not null;index"`
|
GroupId uint `json:"group_id" gorm:"default:0;not null;index"`
|
||||||
IsAdmin *bool `json:"is_admin" gorm:"default:0;not null;"`
|
IsAdmin *bool `json:"is_admin" gorm:"default:0;not null;"`
|
||||||
Status StatusCode `json:"status" gorm:"default:1;not null;"`
|
Status StatusCode `json:"status" gorm:"default:1;not null;"`
|
||||||
|
Remark string `json:"remark" gorm:"default:'';not null;"`
|
||||||
TimeModel
|
TimeModel
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -33,6 +33,11 @@ description = "No access."
|
|||||||
one = "No access."
|
one = "No access."
|
||||||
other = "No access."
|
other = "No access."
|
||||||
|
|
||||||
|
[NeedLogin]
|
||||||
|
description = "Need login."
|
||||||
|
one = "Please log in first."
|
||||||
|
other = "Please log in first."
|
||||||
|
|
||||||
[UsernameOrPasswordError]
|
[UsernameOrPasswordError]
|
||||||
description = "Username or password error."
|
description = "Username or password error."
|
||||||
one = "Username or password error."
|
one = "Username or password error."
|
||||||
|
|||||||
@@ -33,6 +33,11 @@ description = "No access."
|
|||||||
one = "Sin acceso."
|
one = "Sin acceso."
|
||||||
other = "Sin acceso."
|
other = "Sin acceso."
|
||||||
|
|
||||||
|
[NeedLogin]
|
||||||
|
description = "Need login."
|
||||||
|
one = "Por favor inicie sesión primero."
|
||||||
|
other = "Por favor inicie sesión primero."
|
||||||
|
|
||||||
[UsernameOrPasswordError]
|
[UsernameOrPasswordError]
|
||||||
description = "Username or password error."
|
description = "Username or password error."
|
||||||
one = "Error de usuario o contraseña."
|
one = "Error de usuario o contraseña."
|
||||||
|
|||||||
@@ -33,6 +33,11 @@ description = "No access."
|
|||||||
one = "Aucun d'access."
|
one = "Aucun d'access."
|
||||||
other = "Aucun d'access."
|
other = "Aucun d'access."
|
||||||
|
|
||||||
|
[NeedLogin]
|
||||||
|
description = "Need login."
|
||||||
|
one = "Veuillez d'abord vous connecter."
|
||||||
|
other = "Veuillez d'abord vous connecter."
|
||||||
|
|
||||||
[UsernameOrPasswordError]
|
[UsernameOrPasswordError]
|
||||||
description = "Username or password error."
|
description = "Username or password error."
|
||||||
one = "Nom d'utilisateur ou de mot de passe incorrect."
|
one = "Nom d'utilisateur ou de mot de passe incorrect."
|
||||||
@@ -161,4 +166,4 @@ other = "Banni."
|
|||||||
[RegisterSuccessWaitAdminConfirm]
|
[RegisterSuccessWaitAdminConfirm]
|
||||||
description = "Register success wait admin confirm."
|
description = "Register success wait admin confirm."
|
||||||
one = "Inscription réussie, veuillez attendre la confirmation de l'administrateur."
|
one = "Inscription réussie, veuillez attendre la confirmation de l'administrateur."
|
||||||
other = "Inscription réussie, veuillez attendre la confirmation de l'administrateur."
|
other = "Inscription réussie, veuillez attendre la confirmation de l'administrateur."
|
||||||
|
|||||||
@@ -33,6 +33,11 @@ description = "No access."
|
|||||||
one = "접근할 수 없습니다."
|
one = "접근할 수 없습니다."
|
||||||
other = "접근할 수 없습니다."
|
other = "접근할 수 없습니다."
|
||||||
|
|
||||||
|
[NeedLogin]
|
||||||
|
description = "Need login."
|
||||||
|
one = "먼저 로그인해주세요."
|
||||||
|
other = "먼저 로그인해주세요."
|
||||||
|
|
||||||
[UsernameOrPasswordError]
|
[UsernameOrPasswordError]
|
||||||
description = "Username or password error."
|
description = "Username or password error."
|
||||||
one = "사용자 이름이나 비밀번호가 올바르지 않습니다."
|
one = "사용자 이름이나 비밀번호가 올바르지 않습니다."
|
||||||
|
|||||||
@@ -33,6 +33,11 @@ description = "No access."
|
|||||||
one = "Нет доступа."
|
one = "Нет доступа."
|
||||||
other = "Нет доступа."
|
other = "Нет доступа."
|
||||||
|
|
||||||
|
[NeedLogin]
|
||||||
|
description = "Need login."
|
||||||
|
one = "Пожалуйста, войдите в систему."
|
||||||
|
other = "Пожалуйста, войдите в систему."
|
||||||
|
|
||||||
[UsernameOrPasswordError]
|
[UsernameOrPasswordError]
|
||||||
description = "Username or password error."
|
description = "Username or password error."
|
||||||
one = "Неправильное имя пользователя или пароль."
|
one = "Неправильное имя пользователя или пароль."
|
||||||
@@ -161,4 +166,4 @@ other = "Заблокировано."
|
|||||||
[RegisterSuccessWaitAdminConfirm]
|
[RegisterSuccessWaitAdminConfirm]
|
||||||
description = "Register success wait admin confirm."
|
description = "Register success wait admin confirm."
|
||||||
one = "Регистрация прошла успешно, ожидайте подтверждения администратора."
|
one = "Регистрация прошла успешно, ожидайте подтверждения администратора."
|
||||||
other = "Регистрация прошла успешно, ожидайте подтверждения администратора."
|
other = "Регистрация прошла успешно, ожидайте подтверждения администратора."
|
||||||
|
|||||||
@@ -33,6 +33,11 @@ description = "No access."
|
|||||||
one = "无权限。"
|
one = "无权限。"
|
||||||
other = "无权限。"
|
other = "无权限。"
|
||||||
|
|
||||||
|
[NeedLogin]
|
||||||
|
description = "Need login."
|
||||||
|
one = "请先登录。"
|
||||||
|
other = "请先登录。"
|
||||||
|
|
||||||
[UsernameOrPasswordError]
|
[UsernameOrPasswordError]
|
||||||
description = "Username or password error."
|
description = "Username or password error."
|
||||||
one = "用户名或密码错误。"
|
one = "用户名或密码错误。"
|
||||||
|
|||||||
@@ -33,6 +33,11 @@ description = "No access."
|
|||||||
one = "無許可權。"
|
one = "無許可權。"
|
||||||
other = "無許可權。"
|
other = "無許可權。"
|
||||||
|
|
||||||
|
[NeedLogin]
|
||||||
|
description = "Need login."
|
||||||
|
one = "請先登入。"
|
||||||
|
other = "請先登入。"
|
||||||
|
|
||||||
[UsernameOrPasswordError]
|
[UsernameOrPasswordError]
|
||||||
description = "Username or password error."
|
description = "Username or password error."
|
||||||
one = "使用者名稱或密碼錯誤。"
|
one = "使用者名稱或密碼錯誤。"
|
||||||
|
|||||||
@@ -4,11 +4,14 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
|
|
||||||
"github.com/coreos/go-oidc/v3/oidc"
|
"github.com/coreos/go-oidc/v3/oidc"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/lejianwen/rustdesk-api/v2/model"
|
"github.com/lejianwen/rustdesk-api/v2/model"
|
||||||
"github.com/lejianwen/rustdesk-api/v2/utils"
|
"github.com/lejianwen/rustdesk-api/v2/utils"
|
||||||
"golang.org/x/oauth2"
|
"golang.org/x/oauth2"
|
||||||
"golang.org/x/oauth2/github"
|
"golang.org/x/oauth2/github"
|
||||||
|
|
||||||
// "golang.org/x/oauth2/google"
|
// "golang.org/x/oauth2/google"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
// "io"
|
// "io"
|
||||||
@@ -93,16 +96,20 @@ func (os *OauthService) DeleteOauthCache(key string) {
|
|||||||
OauthCache.Delete(key)
|
OauthCache.Delete(key)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (os *OauthService) BeginAuth(op string) (error error, state, verifier, nonce, url string) {
|
func (os *OauthService) BeginAuth(c *gin.Context, op string) (error error, state, verifier, nonce, url string) {
|
||||||
state = utils.RandomString(10) + strconv.FormatInt(time.Now().Unix(), 10)
|
state = utils.RandomString(10) + strconv.FormatInt(time.Now().Unix(), 10)
|
||||||
verifier = ""
|
verifier = ""
|
||||||
nonce = ""
|
nonce = ""
|
||||||
if op == model.OauthTypeWebauth {
|
if op == model.OauthTypeWebauth {
|
||||||
url = Config.Rustdesk.ApiServer + "/_admin/#/oauth/" + state
|
host := c.GetHeader("Origin")
|
||||||
|
if host == "" {
|
||||||
|
host = Config.Rustdesk.ApiServer
|
||||||
|
}
|
||||||
|
url = host + "/_admin/#/oauth/" + state
|
||||||
//url = "http://localhost:8888/_admin/#/oauth/" + code
|
//url = "http://localhost:8888/_admin/#/oauth/" + code
|
||||||
return nil, state, verifier, nonce, url
|
return nil, state, verifier, nonce, url
|
||||||
}
|
}
|
||||||
err, oauthInfo, oauthConfig, _ := os.GetOauthConfig(op)
|
err, oauthInfo, oauthConfig, _ := os.GetOauthConfig(c, op)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
extras := make([]oauth2.AuthCodeOption, 0, 3)
|
extras := make([]oauth2.AuthCodeOption, 0, 3)
|
||||||
|
|
||||||
@@ -167,20 +174,20 @@ func (os *OauthService) LinuxdoProvider() *oidc.Provider {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// GetOauthConfig retrieves the OAuth2 configuration based on the provider name
|
// GetOauthConfig retrieves the OAuth2 configuration based on the provider name
|
||||||
func (os *OauthService) GetOauthConfig(op string) (err error, oauthInfo *model.Oauth, oauthConfig *oauth2.Config, provider *oidc.Provider) {
|
func (os *OauthService) GetOauthConfig(c *gin.Context, op string) (err error, oauthInfo *model.Oauth, oauthConfig *oauth2.Config, provider *oidc.Provider) {
|
||||||
//err, oauthInfo, oauthConfig = os.getOauthConfigGeneral(op)
|
//err, oauthInfo, oauthConfig = os.getOauthConfigGeneral(op)
|
||||||
oauthInfo = os.InfoByOp(op)
|
oauthInfo = os.InfoByOp(op)
|
||||||
if oauthInfo.Id == 0 || oauthInfo.ClientId == "" || oauthInfo.ClientSecret == "" {
|
if oauthInfo.Id == 0 || oauthInfo.ClientId == "" || oauthInfo.ClientSecret == "" {
|
||||||
return errors.New("ConfigNotFound"), nil, nil, nil
|
return errors.New("ConfigNotFound"), nil, nil, nil
|
||||||
}
|
}
|
||||||
// If the redirect URL is empty, use the default redirect URL
|
host := c.GetHeader("Origin")
|
||||||
if oauthInfo.RedirectUrl == "" {
|
if host == "" {
|
||||||
oauthInfo.RedirectUrl = Config.Rustdesk.ApiServer + "/api/oidc/callback"
|
host = Config.Rustdesk.ApiServer
|
||||||
}
|
}
|
||||||
oauthConfig = &oauth2.Config{
|
oauthConfig = &oauth2.Config{
|
||||||
ClientID: oauthInfo.ClientId,
|
ClientID: oauthInfo.ClientId,
|
||||||
ClientSecret: oauthInfo.ClientSecret,
|
ClientSecret: oauthInfo.ClientSecret,
|
||||||
RedirectURL: oauthInfo.RedirectUrl,
|
RedirectURL: host + "/api/oidc/callback",
|
||||||
}
|
}
|
||||||
|
|
||||||
// Maybe should validate the oauthConfig here
|
// Maybe should validate the oauthConfig here
|
||||||
@@ -335,8 +342,8 @@ func (os *OauthService) oidcCallback(oauthConfig *oauth2.Config, provider *oidc.
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Callback: Get user information by code and op(Oauth provider)
|
// Callback: Get user information by code and op(Oauth provider)
|
||||||
func (os *OauthService) Callback(code, verifier, op, nonce string) (err error, oauthUser *model.OauthUser) {
|
func (os *OauthService) Callback(c *gin.Context, code, verifier, op, nonce string) (err error, oauthUser *model.OauthUser) {
|
||||||
err, oauthInfo, oauthConfig, provider := os.GetOauthConfig(op)
|
err, oauthInfo, oauthConfig, provider := os.GetOauthConfig(c, op)
|
||||||
// oauthType is already validated in GetOauthConfig
|
// oauthType is already validated in GetOauthConfig
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err, nil
|
return err, nil
|
||||||
|
|||||||
@@ -2,14 +2,14 @@ package service
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"github.com/lejianwen/rustdesk-api/v2/model"
|
|
||||||
"github.com/lejianwen/rustdesk-api/v2/utils"
|
|
||||||
"math/rand"
|
"math/rand"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/lejianwen/rustdesk-api/v2/model"
|
||||||
|
"github.com/lejianwen/rustdesk-api/v2/utils"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -55,7 +55,18 @@ func (us *UserService) InfoByUsernamePassword(username, password string) *model.
|
|||||||
Logger.Warn("Fallback to local database")
|
Logger.Warn("Fallback to local database")
|
||||||
}
|
}
|
||||||
u := &model.User{}
|
u := &model.User{}
|
||||||
DB.Where("username = ? and password = ?", username, us.EncryptPassword(password)).First(u)
|
DB.Where("username = ?", username).First(u)
|
||||||
|
if u.Id == 0 {
|
||||||
|
return u
|
||||||
|
}
|
||||||
|
ok, newHash, err := utils.VerifyPassword(u.Password, password)
|
||||||
|
if err != nil || !ok {
|
||||||
|
return &model.User{}
|
||||||
|
}
|
||||||
|
if newHash != "" {
|
||||||
|
DB.Model(u).Update("password", newHash)
|
||||||
|
u.Password = newHash
|
||||||
|
}
|
||||||
return u
|
return u
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -151,11 +162,6 @@ func (us *UserService) ListIdAndNameByGroupId(groupId uint) (res []*model.User)
|
|||||||
return res
|
return res
|
||||||
}
|
}
|
||||||
|
|
||||||
// EncryptPassword 加密密码
|
|
||||||
func (us *UserService) EncryptPassword(password string) string {
|
|
||||||
return utils.Md5(password + "rustdesk-api")
|
|
||||||
}
|
|
||||||
|
|
||||||
// CheckUserEnable 判断用户是否禁用
|
// CheckUserEnable 判断用户是否禁用
|
||||||
func (us *UserService) CheckUserEnable(u *model.User) bool {
|
func (us *UserService) CheckUserEnable(u *model.User) bool {
|
||||||
return u.Status == model.COMMON_STATUS_ENABLE
|
return u.Status == model.COMMON_STATUS_ENABLE
|
||||||
@@ -168,7 +174,11 @@ func (us *UserService) Create(u *model.User) error {
|
|||||||
return errors.New("UsernameExists")
|
return errors.New("UsernameExists")
|
||||||
}
|
}
|
||||||
u.Username = us.formatUsername(u.Username)
|
u.Username = us.formatUsername(u.Username)
|
||||||
u.Password = us.EncryptPassword(u.Password)
|
var err error
|
||||||
|
u.Password, err = utils.EncryptPassword(u.Password)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
res := DB.Create(u).Error
|
res := DB.Create(u).Error
|
||||||
return res
|
return res
|
||||||
}
|
}
|
||||||
@@ -268,8 +278,12 @@ func (us *UserService) FlushTokenByUuids(uuids []string) error {
|
|||||||
|
|
||||||
// UpdatePassword 更新密码
|
// UpdatePassword 更新密码
|
||||||
func (us *UserService) UpdatePassword(u *model.User, password string) error {
|
func (us *UserService) UpdatePassword(u *model.User, password string) error {
|
||||||
u.Password = us.EncryptPassword(password)
|
var err error
|
||||||
err := DB.Model(u).Update("password", u.Password).Error
|
u.Password, err = utils.EncryptPassword(password)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
err = DB.Model(u).Update("password", u.Password).Error
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -486,8 +500,9 @@ func (us *UserService) RefreshAccessToken(ut *model.UserToken) {
|
|||||||
ut.ExpiredAt = us.UserTokenExpireTimestamp()
|
ut.ExpiredAt = us.UserTokenExpireTimestamp()
|
||||||
DB.Model(ut).Update("expired_at", ut.ExpiredAt)
|
DB.Model(ut).Update("expired_at", ut.ExpiredAt)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (us *UserService) AutoRefreshAccessToken(ut *model.UserToken) {
|
func (us *UserService) AutoRefreshAccessToken(ut *model.UserToken) {
|
||||||
if ut.ExpiredAt-time.Now().Unix() < 86400 {
|
if ut.ExpiredAt-time.Now().Unix() < Config.App.TokenExpire.Milliseconds()/3000 {
|
||||||
us.RefreshAccessToken(ut)
|
us.RefreshAccessToken(ut)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
42
utils/password.go
Normal file
42
utils/password.go
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
package utils
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
)
|
||||||
|
|
||||||
|
// EncryptPassword hashes the input password using bcrypt.
|
||||||
|
// An error is returned if hashing fails.
|
||||||
|
func EncryptPassword(password string) (string, error) {
|
||||||
|
bs, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return string(bs), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// VerifyPassword checks the input password against the stored hash.
|
||||||
|
// When a legacy MD5 hash is provided, the password is rehashed with bcrypt
|
||||||
|
// and the new hash is returned. Any internal bcrypt error is returned.
|
||||||
|
func VerifyPassword(hash, input string) (bool, string, error) {
|
||||||
|
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(input))
|
||||||
|
if err == nil {
|
||||||
|
return true, "", nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var invalidPrefixErr bcrypt.InvalidHashPrefixError
|
||||||
|
if errors.As(err, &invalidPrefixErr) || errors.Is(err, bcrypt.ErrHashTooShort) {
|
||||||
|
// Try fallback to legacy MD5 hash verification
|
||||||
|
if hash == Md5(input+"rustdesk-api") {
|
||||||
|
newHash, err2 := bcrypt.GenerateFromPassword([]byte(input), bcrypt.DefaultCost)
|
||||||
|
if err2 != nil {
|
||||||
|
return true, "", err2
|
||||||
|
}
|
||||||
|
return true, string(newHash), nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if errors.Is(err, bcrypt.ErrMismatchedHashAndPassword) {
|
||||||
|
return false, "", nil
|
||||||
|
}
|
||||||
|
return false, "", err
|
||||||
|
}
|
||||||
40
utils/password_test.go
Normal file
40
utils/password_test.go
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
package utils
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestVerifyPasswordMD5(t *testing.T) {
|
||||||
|
hash := Md5("secret" + "rustdesk-api")
|
||||||
|
ok, newHash, err := VerifyPassword(hash, "secret")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("md5 verify failed: %v", err)
|
||||||
|
}
|
||||||
|
if !ok || newHash == "" {
|
||||||
|
t.Fatalf("md5 migration failed")
|
||||||
|
}
|
||||||
|
if bcrypt.CompareHashAndPassword([]byte(newHash), []byte("secret")) != nil {
|
||||||
|
t.Fatalf("invalid rehash")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestVerifyPasswordBcrypt(t *testing.T) {
|
||||||
|
b, _ := bcrypt.GenerateFromPassword([]byte("pass"), bcrypt.DefaultCost)
|
||||||
|
ok, newHash, err := VerifyPassword(string(b), "pass")
|
||||||
|
if err != nil || !ok || newHash != "" {
|
||||||
|
t.Fatalf("bcrypt verify failed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestVerifyPasswordMigrate(t *testing.T) {
|
||||||
|
md5hash := Md5("mypass" + "rustdesk-api")
|
||||||
|
ok, newHash, err := VerifyPassword(md5hash, "mypass")
|
||||||
|
if err != nil || !ok || newHash == "" {
|
||||||
|
t.Fatalf("expected bcrypt rehash")
|
||||||
|
}
|
||||||
|
if bcrypt.CompareHashAndPassword([]byte(newHash), []byte("mypass")) != nil {
|
||||||
|
t.Fatalf("rehash not valid bcrypt")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,9 +2,9 @@ package utils
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/md5"
|
"crypto/md5"
|
||||||
|
crand "crypto/rand"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"math/rand"
|
|
||||||
"reflect"
|
"reflect"
|
||||||
"runtime/debug"
|
"runtime/debug"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -69,8 +69,12 @@ func RandomString(n int) string {
|
|||||||
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
||||||
length := len(letterBytes)
|
length := len(letterBytes)
|
||||||
b := make([]byte, n)
|
b := make([]byte, n)
|
||||||
for i := range b {
|
randomBytes := make([]byte, n)
|
||||||
b[i] = letterBytes[rand.Intn(length)]
|
if _, err := crand.Read(randomBytes); err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
for i, rb := range randomBytes {
|
||||||
|
b[i] = letterBytes[int(rb)%length]
|
||||||
}
|
}
|
||||||
return string(b)
|
return string(b)
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user