7 Commits

Author SHA1 Message Date
hoangvv 5f1a220316 update 2024-07-10 14:39:12 +07:00
hoangvv 75abc7e651 update 2024-07-10 12:14:25 +07:00
hoangvv 465e77832e update 2024-07-05 18:35:54 +07:00
hoangvv 219fa12590 update code 2024-07-04 12:19:44 +07:00
hoangvv dd3a9ebea4 omv intergration 2024-07-03 17:58:27 +07:00
hoangvv f0d6780c12 update 2024-07-01 11:56:38 +07:00
hoangvv 2e845d29b7 suppport multiple users 2024-07-01 04:01:09 +07:00
14 changed files with 384 additions and 14 deletions
+7
View File
@@ -27,3 +27,10 @@ dist/
.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
@@ -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
+1 -1
View File
@@ -1,4 +1,4 @@
package common
const Version = "0.4.8"
const Version = "1.3.0"
const SERVICENAME = "CasaOS-UserService"
+1 -1
View File
@@ -1 +1 @@
{"project_name":"casaos-user-service","tag":"v1.0.0","previous_tag":"","version":"1.0.1","commit":"cd28792c154027bebe695a5be5eef33d65dce067","date":"2024-06-29T11:38:52.713569836+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
View File
@@ -101,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)
+2
View File
@@ -10,6 +10,8 @@ type APPModel struct {
LogFileExt string
UserDataPath string
DBPath string
OMVServer string
SecretKey string
}
type Result struct {
+2
View File
@@ -23,6 +23,8 @@ var (
LogPath: constants.DefaultLogPath,
LogSaveName: "user",
LogFileExt: "log",
OMVServer: constants.DefaultOMVServer,
SecretKey: constants.DefaultSecretKey,
}
Cfg *ini.File
+63
View File
@@ -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)
}
+4 -2
View File
@@ -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)
}
}
+128 -8
View File
@@ -4,6 +4,7 @@ import (
"context"
"crypto/ecdsa"
"encoding/base64"
"encoding/json"
json2 "encoding/json"
"image"
"image/png"
@@ -39,6 +40,28 @@ import (
"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) {
@@ -48,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)})
@@ -74,8 +98,7 @@ func PostUserRegister(c *gin.Context) {
user := model2.UserDBModel{}
user.Username = username
user.Password = encryption.GetMD5ByStr(pwd)
user.Role = "admin"
// user.Role = "user"
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)})
@@ -108,9 +131,7 @@ func PostUserLogin(c *gin.Context) {
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 {
@@ -132,7 +153,6 @@ func PostUserLogin(c *gin.Context) {
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)
@@ -140,13 +160,13 @@ func PostUserLogin(c *gin.Context) {
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()})
}
@@ -168,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
@@ -430,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
}
+1 -1
View File
@@ -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
View File
@@ -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{}
}
+6
View File
@@ -14,6 +14,7 @@ type Repository interface {
User() UserService
MessageBus() *message_bus.ClientWithResponses
Event() EventService
OMV() OMVService
}
func NewService(db *gorm.DB, RuntimePath string) Repository {
@@ -27,6 +28,7 @@ func NewService(db *gorm.DB, RuntimePath string) Repository {
gateway: gatewayManagement,
user: NewUserService(db),
event: NewEventService(db),
omv: NewOMVService(),
}
}
@@ -34,6 +36,7 @@ type store struct {
gateway external.ManagementService
user UserService
event EventService
omv OMVService
}
func (c *store) Event() EventService {
@@ -46,6 +49,9 @@ 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,