Commit 46d2537d authored by ibuler's avatar ibuler

[Update] 修改结构

parent f8bee143
......@@ -17,17 +17,25 @@ import (
type Client struct {
Timeout time.Duration
Headers map[string]string
BaseHost string
basicAuth []string
authorization string
cookie map[string]string
http *http.Client
UrlParsers []UrlParser
}
func NewClient() *Client {
type UrlParser interface {
parse(url string, params ...map[string]string) string
}
func NewClient(timeout time.Duration) *Client {
headers := make(map[string]string, 1)
client := http.DefaultClient
client.Timeout = timeout * time.Second
return &Client{
Timeout: 30,
Timeout: timeout * time.Second,
Headers: headers,
http: client,
cookie: make(map[string]string, 0),
}
}
......@@ -54,44 +62,49 @@ func (c *Client) marshalData(data interface{}) (reader io.Reader, error error) {
return
}
func (c *Client) ParseUrl(url string) string {
return url
}
func (c *Client) ConstructUrl(url string) string {
if c.BaseHost != "" {
url = strings.TrimRight(c.BaseHost, "/") + url
func (c *Client) ParseUrlQuery(url string, query map[string]string) string {
var paramSlice []string
for k, v := range query {
paramSlice = append(paramSlice, fmt.Sprintf("%s=%s", k, v))
}
param := strings.Join(paramSlice, "&")
if strings.Contains(url, "?") {
url += "&" + param
} else {
url += "?" + param
}
return url
}
func (c *Client) NewRequest(method, url string, body interface{}) (req *http.Request, err error) {
url = c.ConstructUrl(url)
reader, err := c.marshalData(body)
if err != nil {
return
func (c *Client) ParseUrl(url string, params ...map[string]string) string {
if len(params) == 1 {
url = c.ParseUrlQuery(url, params[0])
}
for _, parser := range c.UrlParsers {
url = parser.parse(url, params...)
}
return http.NewRequest(method, url, reader)
return url
}
// Do wrapper http.Client Do() for using auth and error handle
func (c *Client) Do(req *http.Request, res interface{}) (err error) {
// Custom our client
client := http.DefaultClient
client.Timeout = c.Timeout * time.Second
func (c *Client) SetAuthHeader(r *http.Request, params ...map[string]string) {
if len(c.basicAuth) == 2 {
req.SetBasicAuth(c.basicAuth[0], c.basicAuth[1])
r.SetBasicAuth(c.basicAuth[0], c.basicAuth[1])
return
}
if c.authorization != "" {
req.Header.Add("Authorization", c.authorization)
r.Header.Add("Authorization", c.authorization)
return
}
if len(c.cookie) != 0 {
cookie := make([]string, 0)
for k, v := range c.cookie {
cookie = append(cookie, fmt.Sprintf("%s=%s", k, v))
}
req.Header.Add("Cookie", strings.Join(cookie, ";"))
r.Header.Add("Cookie", strings.Join(cookie, ";"))
}
}
func (c *Client) SetReqHeaders(req *http.Request, params ...map[string]string) {
if len(c.Headers) != 0 {
for k, v := range c.Headers {
req.Header.Set(k, v)
......@@ -101,9 +114,26 @@ func (c *Client) Do(req *http.Request, res interface{}) (err error) {
req.Header.Set("Content-Type", "application/json")
}
req.Header.Set("User-Agent", "coco-client")
c.SetAuthHeader(req)
}
func (c *Client) NewRequest(method, url string, body interface{}, params ...map[string]string) (req *http.Request, err error) {
url = c.ParseUrl(url, params...)
reader, err := c.marshalData(body)
if err != nil {
return
}
req, err = http.NewRequest(method, url, reader)
c.SetReqHeaders(req, params...)
return req, err
}
// Request it
resp, err := client.Do(req)
// Do wrapper http.Client Do() for using auth and error handle
// params:
// 1. query string if set {"name": "ibuler"}
func (c *Client) Do(method, url string, data, res interface{}, params ...map[string]string) (err error) {
req, err := c.NewRequest(method, url, data, params...)
resp, err := c.http.Do(req)
if err != nil {
return
}
......@@ -111,7 +141,8 @@ func (c *Client) Do(req *http.Request, res interface{}) (err error) {
body, err := ioutil.ReadAll(resp.Body)
if resp.StatusCode >= 400 {
err = errors.New(fmt.Sprintf("%s %s failed, get code: %d, %s", req.Method, req.URL, resp.StatusCode, string(body)))
msg := fmt.Sprintf("%s %s failed, get code: %d, %s", req.Method, req.URL, resp.StatusCode, string(body))
err = errors.New(msg)
return
}
......@@ -119,65 +150,32 @@ func (c *Client) Do(req *http.Request, res interface{}) (err error) {
if res != nil {
err = json.Unmarshal(body, res)
if err != nil {
msg := fmt.Sprintf("Failed %s %s, unmarshal `%s` response failed", req.Method, req.URL, string(body)[:50])
return errors.New(msg)
msg := fmt.Sprintf("%s %s failed, unmarshal `%s` response failed", req.Method, req.URL, string(body)[:50])
err = errors.New(msg)
return
}
}
return nil
return
}
func (c *Client) Get(url string, res interface{}, params ...map[string]string) (err error) {
if len(params) == 1 {
paramSlice := make([]string, 1)
for k, v := range params[0] {
paramSlice = append(paramSlice, fmt.Sprintf("%s=%s", k, v))
}
param := strings.Join(paramSlice, "&")
if strings.Contains(url, "?") {
url += "&" + param
} else {
url += "?" + param
}
}
req, err := c.NewRequest("GET", url, nil)
if err != nil {
return
}
err = c.Do(req, res)
return err
return c.Do("GET", url, nil, res, params...)
}
func (c *Client) Post(url string, data interface{}, res interface{}) (err error) {
req, err := c.NewRequest("POST", url, data)
if err != nil {
return
}
err = c.Do(req, res)
return err
return c.Do("POST", url, data, res)
}
func (c *Client) Delete(url string, res interface{}) (err error) {
req, err := c.NewRequest("DELETE", url, nil)
err = c.Do(req, res)
return err
return c.Do("DELETE", url, nil, res)
}
func (c *Client) Put(url string, data interface{}, res interface{}) (err error) {
req, err := c.NewRequest("PUT", url, data)
if err != nil {
return
}
err = c.Do(req, res)
return err
return c.Do("PUT", url, data, res)
}
func (c *Client) Patch(url string, data interface{}, res interface{}) (err error) {
req, err := c.NewRequest("PATCH", url, data)
if err != nil {
return
}
err = c.Do(req, res)
return err
return c.Do("PATCH", url, data, res)
}
func (c *Client) PostForm(url string, data interface{}, res interface{}) (err error) {
......@@ -196,7 +194,7 @@ func (c *Client) PostForm(url string, data interface{}, res interface{}) (err er
default:
attr, err := json.Marshal(val.Field(i).Interface())
if err != nil {
return err
return nil
}
v = string(attr)
}
......@@ -207,6 +205,5 @@ func (c *Client) PostForm(url string, data interface{}, res interface{}) (err er
reader := strings.NewReader(values.Encode())
req, err := http.NewRequest("POST", url, reader)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
err = c.Do(req, res)
return err
return nil
}
......@@ -26,29 +26,24 @@ var user = User{ID: 2, Name: "Jumpserver", Age: 5}
var userDeleteUrl = fmt.Sprintf("%s/%d", usersUrl, user.ID)
func TestClient_Do(t *testing.T) {
c := NewClient()
req, err := http.NewRequest("GET", usersUrl, nil)
if err != nil {
t.Error("Failed NewRequest() ...")
}
err = c.Do(req, nil)
c := NewClient(10)
err := c.Do("GET", usersUrl, nil, nil)
if err == nil {
t.Error("Failed Do(), want get err but not")
}
c.SetBasicAuth(username, password)
var res []User
err = c.Do(req, &res)
err = c.Do("GET", usersUrl, nil, &res)
if err != nil {
t.Errorf("Failed Do(), %s", err.Error())
t.Errorf("Failed Do() error: %s", err.Error())
}
if len(res) != 2 {
t.Errorf("User not equal 2")
t.Errorf("User not equal 2: %d", len(res))
}
}
func TestClient_Get(t *testing.T) {
c := NewClient()
c := NewClient(10)
err := c.Get(usersUrl, nil)
if err == nil {
t.Errorf("Failed Get(%s): want get err but not", usersUrl)
......@@ -61,7 +56,7 @@ func TestClient_Get(t *testing.T) {
}
func TestClient_Post(t *testing.T) {
c := NewClient()
c := NewClient(10)
var userCreated User
err := c.Post(usersUrl, user, &userCreated)
if err != nil {
......@@ -73,7 +68,7 @@ func TestClient_Post(t *testing.T) {
}
func TestClient_Put(t *testing.T) {
c := NewClient()
c := NewClient(10)
var userUpdated User
err := c.Put(usersUrl, user, &userUpdated)
if err != nil {
......@@ -85,7 +80,7 @@ func TestClient_Put(t *testing.T) {
}
func TestClient_Delete(t *testing.T) {
c := NewClient()
c := NewClient(10)
c.SetBasicAuth(username, password)
err := c.Delete(userDeleteUrl, nil)
if err != nil {
......
package service
import (
"cocogo/pkg/logger"
"errors"
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"strings"
"cocogo/pkg/common"
)
var (
AccessKeyNotFound = errors.New("access key not found")
AccessKeyFileNotFound = errors.New("access key file not found")
AccessKeyInvalid = errors.New("access key not valid")
)
type AccessKey struct {
Id string
Secret string
Id string
Secret string
Path string
Context string
}
func (ak *AccessKey) Signature(date string) string {
func (ak AccessKey) Sign() string {
date := common.HTTPGMTDate()
signature := common.MakeSignature(ak.Secret, date)
return fmt.Sprintf("Sign %s:%s", ak.Id, signature)
}
// LoadAccessKey 加载AccessKey用来与 Core Api 交互
func (s *Service) LoadAccessKey() {
/*
1. 查看配置文件是否包含accessKey,解析不正确则退出程序
2. 检查是否已经注册过accessKey,
1)已经注册过则进行解析,解析不正确则退出程序
2)未注册则新注册
*/
if s.Conf.AccessKey != "" {
fmt.Println(s.Conf.AccessKey)
keyAndSecret := strings.Split(s.Conf.AccessKey, ":")
if len(keyAndSecret) == 2 {
s.auth = accessAuth{
accessKey: keyAndSecret[0],
accessSecret: keyAndSecret[1],
}
} else {
fmt.Println("ACCESS_KEY format err")
os.Exit(1)
}
return
func (ak *AccessKey) LoadAccessKeyFromStr(key string) error {
if key == "" {
return AccessKeyNotFound
}
keySlice := strings.Split(strings.TrimSpace(key), ":")
if len(ak.Context) != 2 {
return AccessKeyInvalid
}
var configPath string
ak.Id = keySlice[0]
ak.Secret = keySlice[1]
return nil
}
if !path.IsAbs(s.Conf.AccessKeyFile) {
configPath = filepath.Join(s.Conf.RootPath, s.Conf.AccessKeyFile)
} else {
configPath = s.Conf.AccessKeyFile
func (ak *AccessKey) LoadAccessKeyFromFile(keyPath string) error {
if keyPath == "" {
return AccessKeyNotFound
}
_, err := os.Stat(configPath)
_, err := os.Stat(keyPath)
if err != nil {
if os.IsNotExist(err) {
fmt.Println("Do not have access key, register it!")
err := s.registerTerminalAndSave()
if err != nil {
log.Info("register Failed:", err)
os.Exit(1)
}
return
} else {
fmt.Println("sys err:", err)
os.Exit(1)
}
return AccessKeyFileNotFound
}
buf, err := ioutil.ReadFile(keyPath)
if err != nil {
msg := fmt.Sprintf("read access key failed: %s", err)
return errors.New(msg)
}
return ak.LoadAccessKeyFromStr(string(buf))
}
buf, err := ioutil.ReadFile(configPath)
func (ak *AccessKey) SaveToFile() error {
return nil
}
func (ak *AccessKey) Register(times int) error {
return nil
}
// LoadAccessKey 加载AccessKey用来与 Core Api 交互
func (ak *AccessKey) Load() (err error) {
err = ak.LoadAccessKeyFromStr(ak.Context)
if err == nil {
return
}
err = ak.LoadAccessKeyFromFile(ak.Path)
if err == nil {
return
}
err = ak.Register(10)
if err != nil {
fmt.Println("read Access key Failed:", err)
os.Exit(1)
msg := "register access key failed"
logger.Error(msg)
return errors.New(msg)
}
keyAndSecret := strings.Split(string(buf), ":")
if len(keyAndSecret) == 2 {
s.auth = accessAuth{
accessKey: keyAndSecret[0],
accessSecret: keyAndSecret[1],
}
} else {
fmt.Println("ACCESS_KEY format err")
os.Exit(1)
err = ak.SaveToFile()
if err != nil {
msg := fmt.Sprintf("save to access key to file error: %s", err)
logger.Error(msg)
return errors.New(msg)
}
return nil
}
package service
import (
"encoding/json"
"fmt"
"cocogo/pkg/model"
)
func (s *Service) GetSystemUserAssetAuthInfo(systemUserID, assetID string) (authInfo model.SystemUserAuthInfo, err error) {
url := fmt.Sprintf("%s%s", s.Conf.CoreHost,
fmt.Sprintf(SystemUserAssetAuthUrl, systemUserID, assetID),
)
buf, err := s.SendHTTPRequest("GET", url, nil)
if err != nil {
log.Info("get User Assets Groups err:", err)
return authInfo, err
}
err = json.Unmarshal(buf, &authInfo)
if err != nil {
log.Info(err)
return authInfo, err
}
return authInfo, err
}
func (s *Service) GetSystemUserAuthInfo(systemUserID string) {
url := fmt.Sprintf("%s%s", s.Conf.CoreHost,
fmt.Sprintf(SystemUserAuthUrl, systemUserID))
buf, err := s.SendHTTPRequest("GET", url, nil)
if err != nil {
log.Info("get User Assets Groups err:", err)
return
}
//err = json.Unmarshal(buf, &authInfo)
fmt.Printf("%s", buf)
if err != nil {
log.Info(err)
return
}
return
}
//
//func GetSystemUserAssetAuthInfo(systemUserID, assetID string) (authInfo model.SystemUserAuthInfo, err error) {
//
//
// err = json.Unmarshal(buf, &authInfo)
// if err != nil {
// log.Info(err)
// return authInfo, err
// }
// return authInfo, err
//
//}
//
//func (s *Service) GetSystemUserAuthInfo(systemUserID string) {
//
// url := fmt.Sprintf("%s%s", s.Conf.CoreHost,
// fmt.Sprintf(SystemUserAuthUrl, systemUserID))
// buf, err := s.SendHTTPRequest("GET", url, nil)
// if err != nil {
// log.Info("get User Assets Groups err:", err)
// return
// }
// //err = json.Unmarshal(buf, &authInfo)
// fmt.Printf("%s", buf)
// if err != nil {
// log.Info(err)
// return
// }
// return
//
//}
package service
import (
"cocogo/pkg/model"
"net/http"
"path"
"path/filepath"
"strings"
"cocogo/pkg/common"
"cocogo/pkg/config"
)
type ClientAuth interface {
Sign() string
}
type WrapperClient struct {
*common.Client
Auth ClientAuth
BaseHost string
}
func (c *WrapperClient) SetAuthHeader(r *http.Request) {
if c.Auth != nil {
signature := c.Auth.Sign()
r.Header.Add("Authorization", signature)
}
}
func (c *WrapperClient) ExpandUrl(url string, query map[string]string) string {
}
func (c *WrapperClient) ParseUrl(url string, params ...map[string]string) string {
var newUrl = ""
if url, ok := urls[url]; ok {
newUrl = url
}
if c.BaseHost != "" {
newUrl = strings.TrimRight(c.BaseHost, "/") + newUrl
}
if len(params) == 1 {
url = c.ParseUrlQuery(url, params[0])
}
if len(params) == 2 {
url =
}
return newUrl
}
func (c *WrapperClient) LoadAuth() error {
keyPath := config.Conf.AccessKeyFile
if !path.IsAbs(config.Conf.AccessKeyFile) {
keyPath = filepath.Join(config.Conf.RootPath, keyPath)
}
ak := AccessKey{Context: config.Conf.AccessKey, Path: keyPath}
err := ak.Load()
if err != nil {
return err
}
c.Auth = ak
return nil
}
func (c *WrapperClient) CheckAuth() error {
var user model.User
err := c.Get("UserProfileUrl", &user)
if err != nil {
return err
}
return nil
}
package service
import (
"os"
"cocogo/pkg/logger"
)
var client = WrapperClient{}
func init() {
err := client.LoadAuth()
if err != nil {
logger.Error("Load client access key error: %s", err)
os.Exit(10)
}
err = client.CheckAuth()
if err != nil {
logger.Error("Check client auth error: %s", err)
os.Exit(11)
}
}
package service
import (
"cocogo/pkg/model"
"encoding/json"
"fmt"
)
func (s *Service) GetUserAssets(uid string) (resp []model.Asset, err error) {
url := fmt.Sprintf("%s%s", s.Conf.CoreHost, fmt.Sprintf(UserAssetsUrl, uid))
buf, err := s.SendHTTPRequest("GET", url, nil)
if err != nil {
log.Info("get User Assets err:", err)
return resp, err
}
err = json.Unmarshal(buf, &resp)
if err != nil {
log.Info(err)
return resp, err
}
return resp, nil
}
func (s *Service) GetUserAssetNodes(uid string) ([]model.AssetNode, error) {
var resp []model.AssetNode
url := fmt.Sprintf("%s%s", s.Conf.CoreHost, fmt.Sprintf(UserNodesAssetsUrl, uid))
buf, err := s.SendHTTPRequest("GET", url, nil)
if err != nil {
log.Info("get User Assets Groups err:", err)
return resp, err
}
err = json.Unmarshal(buf, &resp)
if err != nil {
log.Info(err)
return resp, err
}
return resp, err
}
func (s *Service) ValidateUserAssetPermission(userID, systemUserID, AssetID string) bool {
// cache_policy 0:不使用缓存 1:使用缓存 2: 刷新缓存
baseUrl, _ := neturl.Parse(fmt.Sprintf("%s%s", s.Conf.CoreHost, ValidateUserAssetPermission))
params := neturl.Values{}
params.Add("user_id", userID)
params.Add("asset_id", AssetID)
params.Add("system_user_id", systemUserID)
params.Add("cache_policy", "1")
baseUrl.RawQuery = params.Encode()
buf, err := s.SendHTTPRequest("GET", baseUrl.String(), nil)
if err != nil {
log.Error("Check User Asset Permission err:", err)
return false
}
var res struct {
Msg bool `json:"msg"'`
}
if err = json.Unmarshal(buf, &res); err != nil {
return false
}
return res.Msg
}
//
//func (s *Service) GetUserAssets(uid string) (resp []model.Asset, err error) {
//
// url := fmt.Sprintf("%s%s", s.Conf.CoreHost, fmt.Sprintf(UserAssetsUrl, uid))
//
// buf, err := s.SendHTTPRequest("GET", url, nil)
// if err != nil {
// log.Info("get User Assets err:", err)
// return resp, err
// }
// err = json.Unmarshal(buf, &resp)
// if err != nil {
// log.Info(err)
// return resp, err
// }
// return resp, nil
//
//}
//
//func (s *Service) GetUserAssetNodes(uid string) ([]model.AssetNode, error) {
//
// var resp []model.AssetNode
//
// url := fmt.Sprintf("%s%s", s.Conf.CoreHost, fmt.Sprintf(UserNodesAssetsUrl, uid))
//
// buf, err := s.SendHTTPRequest("GET", url, nil)
// if err != nil {
// log.Info("get User Assets Groups err:", err)
// return resp, err
// }
// err = json.Unmarshal(buf, &resp)
// if err != nil {
// log.Info(err)
// return resp, err
// }
// return resp, err
//}
//
//func (s *Service) ValidateUserAssetPermission(userID, systemUserID, AssetID string) bool {
// // cache_policy 0:不使用缓存 1:使用缓存 2: 刷新缓存
//
// baseUrl, _ := neturl.Parse(fmt.Sprintf("%s%s", s.Conf.CoreHost, ValidateUserAssetPermission))
// params := neturl.Values{}
// params.Add("user_id", userID)
// params.Add("asset_id", AssetID)
// params.Add("system_user_id", systemUserID)
// params.Add("cache_policy", "1")
//
// baseUrl.RawQuery = params.Encode()
// buf, err := s.SendHTTPRequest("GET", baseUrl.String(), nil)
// if err != nil {
// log.Error("Check User Asset Permission err:", err)
// return false
// }
// var res struct {
// Msg bool `json:"msg"'`
// }
// if err = json.Unmarshal(buf, &res); err != nil {
// return false
// }
// return res.Msg
//}
This diff is collapsed.
package service
import (
"bytes"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
)
func (s *Service) PushSessionReplay(gZipFile, sessionID string) error {
fp, err := os.Open(gZipFile)
if err != nil {
return err
}
defer fp.Close()
fi, err := fp.Stat()
if err != nil {
return err
}
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile("file", fi.Name())
if err != nil {
return err
}
_, _ = io.Copy(part, fp)
err = writer.Close() // close writer before POST request
if err != nil {
return err
}
url := fmt.Sprintf("%s%s", s.Conf.CoreHost, fmt.Sprintf(SessionReplay, sessionID))
req, err := http.NewRequest("POST", url, body)
currentDate := HTTPGMTDate()
req.Header.Add("Content-Type", writer.FormDataContentType())
req.Header.Set("Date", currentDate)
req.Header.Set("Authorization", s.auth.Signature(currentDate))
resp, err := s.http.Do(req)
defer resp.Body.Close()
if err != nil {
log.Info("Send HTTP Request failed:", err)
return err
}
log.Info("PushSessionReplay:", err)
return err
}
func (s *Service) CreateSession(data []byte) bool {
url := fmt.Sprintf("%s%s", s.Conf.CoreHost, SessionList)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(data))
req.Header.Set("Content-Type", "application/json")
currentDate := HTTPGMTDate()
req.Header.Set("Date", currentDate)
req.Header.Set("Authorization", s.auth.Signature(currentDate))
resp, err := s.http.Do(req)
defer resp.Body.Close()
if err != nil {
log.Error("create Session err: ", err)
return false
}
if resp.StatusCode == 201 {
log.Info("create Session 201")
return true
}
return false
}
func (s *Service) FinishSession(id string, jsonData []byte) bool {
url := fmt.Sprintf("%s%s", s.Conf.CoreHost, fmt.Sprintf(SessionDetail, id))
res, err := s.SendHTTPRequest("PATCH", url, jsonData)
fmt.Printf("%s", res)
if err != nil {
log.Error(err)
return false
}
return true
}
func (s *Service) FinishReply(id string) bool {
data := map[string]bool{"has_replay": true}
jsonData, _ := json.Marshal(data)
url := fmt.Sprintf("%s%s", s.Conf.CoreHost, fmt.Sprintf(SessionDetail, id))
_, err := s.SendHTTPRequest("PATCH", url, jsonData)
if err != nil {
log.Error(err)
return false
}
return true
}
//
//func (s *Service) PushSessionReplay(gZipFile, sessionID string) error {
// fp, err := os.Open(gZipFile)
// if err != nil {
// return err
// }
// defer fp.Close()
// fi, err := fp.Stat()
// if err != nil {
// return err
// }
//
// body := &bytes.Buffer{}
// writer := multipart.NewWriter(body)
// part, err := writer.CreateFormFile("file", fi.Name())
// if err != nil {
// return err
// }
// _, _ = io.Copy(part, fp)
// err = writer.Close() // close writer before POST request
// if err != nil {
// return err
// }
//
// url := fmt.Sprintf("%s%s", s.Conf.CoreHost, fmt.Sprintf(SessionReplay, sessionID))
// req, err := http.NewRequest("POST", url, body)
// currentDate := HTTPGMTDate()
// req.Header.Add("Content-Type", writer.FormDataContentType())
// req.Header.Set("Date", currentDate)
// req.Header.Set("Authorization", s.auth.Signature(currentDate))
// resp, err := s.http.Do(req)
// defer resp.Body.Close()
// if err != nil {
// log.Info("Send HTTP Request failed:", err)
// return err
// }
//
// log.Info("PushSessionReplay:", err)
// return err
//}
//
//func (s *Service) CreateSession(data []byte) bool {
// url := fmt.Sprintf("%s%s", s.Conf.CoreHost, SessionList)
//
// req, err := http.NewRequest("POST", url, bytes.NewBuffer(data))
// req.Header.Set("Content-Type", "application/json")
// currentDate := HTTPGMTDate()
// req.Header.Set("Date", currentDate)
// req.Header.Set("Authorization", s.auth.Signature(currentDate))
// resp, err := s.http.Do(req)
// defer resp.Body.Close()
// if err != nil {
// log.Error("create Session err: ", err)
// return false
// }
// if resp.StatusCode == 201 {
// log.Info("create Session 201")
// return true
// }
// return false
//
//}
//
//func (s *Service) FinishSession(id string, jsonData []byte) bool {
//
// url := fmt.Sprintf("%s%s", s.Conf.CoreHost, fmt.Sprintf(SessionDetail, id))
// res, err := s.SendHTTPRequest("PATCH", url, jsonData)
// fmt.Printf("%s", res)
// if err != nil {
// log.Error(err)
// return false
// }
// return true
//}
//
//func (s *Service) FinishReply(id string) bool {
// data := map[string]bool{"has_replay": true}
// jsonData, _ := json.Marshal(data)
// url := fmt.Sprintf("%s%s", s.Conf.CoreHost, fmt.Sprintf(SessionDetail, id))
// _, err := s.SendHTTPRequest("PATCH", url, jsonData)
// if err != nil {
// log.Error(err)
// return false
// }
// return true
//}
//
//func (s *Service) LoadTerminalConfig() {
// url := fmt.Sprintf("%s%s", s.Conf.CoreHost, TerminalConfigUrl)
// req, err := http.NewRequest(http.MethodGet, url, nil)
// if err != nil {
// log.Info(err)
// }
// currentDate := HTTPGMTDate()
// req.Header.Set("Content-Type", "application/json")
// req.Header.Set("Date", currentDate)
// req.Header.Set("Authorization", s.auth.Signature(currentDate))
// resp, err := s.http.Do(req)
// if err != nil {
// log.Info("client http request failed:", err)
// }
//
// defer resp.Body.Close()
// body, err := ioutil.ReadAll(resp.Body)
// if err != nil {
// log.Info("Read response Body err:", err)
// return
// }
// fmt.Printf("%s\n", body)
// resBody := config.TerminalConfig{}
// err = json.Unmarshal(body, &resBody)
// if err != nil {
// log.Info("json.Unmarshal", err)
// return
// }
// s.Conf.TermConfig = &resBody
// fmt.Println(resBody)
//
//}
package service
//
//func (s *Service) CheckAuth(username, password, publicKey, remoteAddr, loginType string) (model.User, error) {
// /*
// {
// 'token': '0191970b1f5b414bbae42ec8fbb2a2ad',
// 'user':{'id': '34987591-bf75-4e5f-a102-6d59a1103431',
// 'name': 'softwareuser1', 'username': 'softwareuser1',
// 'email': 'xplz@hotmail.com',
// 'groups': ['bdc861f9-f476-4554-9bd4-13c3112e469d'],
// 'groups_display': '研发组', 'role': 'User',
// 'role_display': '用户', 'avatar_url': '/static/img/avatar/user.png',
// 'wechat': '', 'phone': None, 'otp_level': 0, 'comment': '',
// 'source': 'local', 'source_display': 'Local', 'is_valid': True,
// 'is_expired': False, 'is_active': True, 'created_by': 'admin',
// 'is_first_login': True, 'date_password_last_updated': '2019-03-08 11:47:04 +0800',
// 'date_expired': '2089-02-18 09:37:00 +0800'}}
// */
//
// postMap := map[string]string{
// "username": username,
// "password": password,
// "public_key": publicKey,
// "remote_addr": remoteAddr,
// "login_type": loginType,
// }
//
// data, err := json.Marshal(postMap)
// if err != nil {
// log.Info(err)
// return model.User{}, err
// }
//
// url := fmt.Sprintf("%s%s", s.Conf.CoreHost, UserAuthUrl)
// body, err := s.SendHTTPRequest(http.MethodPost, url, data)
//
// if err != nil {
// log.Info("read body failed:", err)
// return model.User{}, err
// }
// var result struct {
// Token string `json:"token"`
// User model.User `json:"user"`
// }
//
// err = json.Unmarshal(body, &result)
// if err != nil {
// log.Info("json decode failed:", err)
// return model.User{}, err
// }
//
// return result.User, nil
//}
//
//func (s *Service) CheckSSHPassword(ctx ssh.Context, password string) bool {
//
// username := ctx.User()
// remoteAddr := ctx.RemoteAddr().String()
// authUser, err := s.CheckAuth(username, password, "", remoteAddr, "T")
// if err != nil {
// return false
// }
// ctx.SetValue("LoginUser", authUser)
// return true
//}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment