auth.go 6.9 KB
Newer Older
Y
Your Name 已提交
1 2 3
package console_sqlite3

import (
Y
Your Name 已提交
4
	"database/sql"
Y
Your Name 已提交
5 6 7
	"encoding/json"
	"time"

Y
Your Name 已提交
8
	"github.com/eolinker/goku-api-gateway/server/dao"
Y
Your Name 已提交
9

Y
Your Name 已提交
10
	log "github.com/eolinker/goku-api-gateway/goku-log"
Y
Your Name 已提交
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
)

type basicAuthConf struct {
	UserName       string `json:"userName"`
	Password       string `json:"password"`
	HideCredential bool   `json:"hideCredential"`
	Remark         string `json:"remark"`
}

//APIKeyConf apiKey配置
type APIKeyConf struct {
	APIKey         string `json:"Apikey"`
	TokenPlace     string `json:"tokenPlace"`
	HideCredential bool   `json:"hideCredential"`
	Remark         string `json:"remark"`
}

//OAuth2GlobalConf oauth2配置
type OAuth2GlobalConf struct {
	oauth2Conf
	Oauth2CredentialList []*oauth2Credential `json:"oauth2CredentialList"`
}

type oauth2Conf struct {
	Scopes                        []string `json:"scopes"`                        //scopes = { required = false, type = "array" },
	MandatoryScope                bool     `json:"mandatoryScope"`                //mandatory_scope = { required = true, type = "boolean", default = false, func = check_mandatory_scope },
	TokenExpiration               int      `json:"tokenExpiration"`               //token_expiration = { required = true, type = "number", default = 7200 },
	EnableAuthorizationCode       bool     `json:"enableAuthorizationCode"`       //enable_authorization_code = { required = true, type = "boolean", default = false },
	EnableImplicitGrant           bool     `json:"enableImplicitGrant"`           //enable_implicit_grant = { required = true, type = "boolean", default = false },
	EnableClientCredentials       bool     `json:"enableClientCredentials"`       //enable_client_credentials = { required = true, type = "boolean", default = false },
	HideCredentials               bool     `json:"hideCredentials"`               //hide_credentials = { type = "boolean", default = false },
	AcceptHTTPIfAlreadyTerminated bool     `json:"acceptHttpIfAlreadyTerminated"` //accept_http_if_already_terminated = { required = false, type = "boolean", default = false },
	RefreshTokenTTL               int      `json:"refreshTokenTTL"`               //refresh_token_ttl = {required = true, type = "number", default = 1209600} -- original hardcoded value - 14 days
}

type jwtCredential struct {
	ISS          string `json:"iss"`
	Secret       string `json:"secret"`
	RsaPublicKey string `json:"rsaPublicKey"`
	Algorithm    string `json:"algorithm"`
	Remark       string `json:"remark"`
}

type jwtConf struct {
	SignatureIsBase64 bool            `json:"signatureIsBase64"`
	ClaimsToVerify    []string        `json:"claimsToVerify"`
	RunOnPreflight    bool            `json:"runOnPreflight"`
	JwtCredentials    []jwtCredential `json:"jwtCredentials"`
	HideCredentials   bool            `json:"hideCredentials"`
}

type oauth2Credential struct {
	CredentialID string `json:"credentialID"`
	ClientID     string `json:"clientID"`
	ClientSecret string `json:"clientSecret"`
	RedirectURI  string `json:"redirectURI"`
	Remark       string `json:"remark"`
}

Y
Your Name 已提交
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
//AuthDao AuthDao
type AuthDao struct {
	db *sql.DB
}

//NewAuthDao new AuthDao
func NewAuthDao() *AuthDao {
	return &AuthDao{}
}

//Create create
func (d *AuthDao) Create(db *sql.DB) (interface{}, error) {

	d.db = db

	var i dao.AuthDao = d

	return &i, nil
}

Y
Your Name 已提交
90
//GetAuthStatus 获取认证状态
Y
Your Name 已提交
91 92
func (d *AuthDao) GetAuthStatus(strategyID string) (bool, map[string]interface{}, error) {
	db := d.db
Y
Your Name 已提交
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
	var basicStatus, apikeyStatus int
	sql := `SELECT CASE WHEN goku_plugin.pluginStatus = 0 THEN 0 ELSE goku_conn_plugin_strategy.pluginStatus END AS pluginStatus FROM goku_conn_plugin_strategy INNER JOIN goku_plugin ON goku_plugin.pluginName = goku_conn_plugin_strategy.pluginName WHERE goku_conn_plugin_strategy.pluginName = ? AND goku_conn_plugin_strategy.strategyID = ?;`
	db.QueryRow(sql, "goku-basic_auth", strategyID).Scan(&basicStatus)

	db.QueryRow(sql, "goku-apikey_auth", strategyID).Scan(&apikeyStatus)

	authInfo := map[string]interface{}{
		"basicAuthStatus": basicStatus,
		"apiKeyStatus":    apikeyStatus,
		"jwtStatus":       0,
		"oAuthStatus":     0,
	}
	return true, authInfo, nil
}

//GetAuthInfo 获取认证信息
Y
Your Name 已提交
109 110
func (d *AuthDao) GetAuthInfo(strategyID string) (bool, map[string]interface{}, error) {
	db := d.db
Y
Your Name 已提交
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
	var strategyName, auth string
	sql := "SELECT IFNULL(auth,''),strategyName FROM goku_gateway_strategy WHERE strategyID = ?;"
	err := db.QueryRow(sql, strategyID).Scan(&auth, &strategyName)
	if err != nil {
		return false, make(map[string]interface{}), err
	}
	basicAuthList := make([]basicAuthConf, 0)
	apiKeyList := make([]APIKeyConf, 0)

	var basicConfig, apiKeyConfig string
	sql = `SELECT pluginConfig FROM goku_conn_plugin_strategy WHERE pluginName = ? AND strategyID = ? AND pluginStatus = 1;`
	err = db.QueryRow(sql, "goku-basic_auth", strategyID).Scan(&basicConfig)
	if err == nil {
		if basicConfig != "" {
			json.Unmarshal([]byte(basicConfig), &basicAuthList)
			if err != nil {
				panic(err)
				return false, make(map[string]interface{}), err
			}
		}
	}
	err = db.QueryRow(sql, "goku-apikey_auth", strategyID).Scan(&apiKeyConfig)
	if err == nil {
		if apiKeyConfig != "" {
			err = json.Unmarshal([]byte(apiKeyConfig), &apiKeyList)
			if err != nil {
				panic(err)
				return false, make(map[string]interface{}), err
			}
		}
	}

	authInfo := map[string]interface{}{
		"strategyID":           strategyID,
		"strategyName":         strategyName,
		"auth":                 auth,
		"basicAuthList":        basicAuthList,
		"apiKeyList":           apiKeyList,
		"jwtCredentialList":    make([]interface{}, 0),
		"oauth2CredentialList": make([]interface{}, 0),
	}
	return true, authInfo, nil
}

//EditAuthInfo 编辑认证信息
Y
Your Name 已提交
156 157
func (d *AuthDao) EditAuthInfo(strategyID, strategyName, basicAuthList, apikeyList, jwtCredentialList, oauth2CredentialList string, delClientIDList []string) (bool, error) {
	db := d.db
Y
Your Name 已提交
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
	now := time.Now().Format("2006-01-02 15:04:05")
	sql := "UPDATE goku_gateway_strategy SET strategyName = ? WHERE strategyID = ?;"
	stmt, err := db.Prepare(sql)
	if err != nil {
		return false, err
	}
	defer stmt.Close()
	_, err = stmt.Exec(strategyName, strategyID)
	if err != nil {
		return false, err
	}
	// 设置basic信息
	Tx, _ := db.Begin()
	_, err = Tx.Exec("UPDATE goku_conn_plugin_strategy SET pluginConfig = ?,updateTime = ? WHERE strategyID = ? AND pluginName = ? AND pluginStatus = 1;", basicAuthList, now, strategyID, "goku-basic_auth")
	if err != nil {
		Tx.Rollback()
		return false, err
	}
	_, err = Tx.Exec("UPDATE goku_conn_plugin_strategy SET pluginConfig = ?,updateTime = ? WHERE strategyID = ? AND pluginName = ? AND pluginStatus = 1;", apikeyList, now, strategyID, "goku-apikey_auth")
	if err != nil {
		Tx.Rollback()
		return false, err
	}

	sql = "UPDATE goku_gateway_strategy SET updateTime = ? WHERE strategyID = ?;"
	_, err = Tx.Exec(sql, now, strategyID)
	if err != nil {
		Tx.Rollback()
		return false, err
	}
	err = Tx.Commit()
	if err != nil {
		info := err.Error()
		log.Info(info)
	}
	return true, nil
}