diff --git a/captcha/aliyun.go b/captcha/aliyun.go index 086abd6e3076..17695ce8ec3d 100644 --- a/captcha/aliyun.go +++ b/captcha/aliyun.go @@ -18,7 +18,7 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" + "io" "net/http" "net/url" "sort" @@ -80,7 +80,7 @@ func (captcha *AliyunCaptchaProvider) VerifyCaptcha(token, clientSecret string) } defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return false, err } diff --git a/captcha/geetest.go b/captcha/geetest.go index 3c9b2607b04f..bd48c8e462ac 100644 --- a/captcha/geetest.go +++ b/captcha/geetest.go @@ -18,7 +18,7 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" + "io" "net/http" "net/url" "time" @@ -58,7 +58,7 @@ func (captcha *GEETESTCaptchaProvider) VerifyCaptcha(token, clientSecret string) } defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return false, err } diff --git a/captcha/hcaptcha.go b/captcha/hcaptcha.go index 52f2aa135c8b..f7f5198bc83e 100644 --- a/captcha/hcaptcha.go +++ b/captcha/hcaptcha.go @@ -17,7 +17,7 @@ package captcha import ( "encoding/json" "errors" - "io/ioutil" + "io" "net/http" "net/url" "strings" @@ -43,7 +43,7 @@ func (captcha *HCaptchaProvider) VerifyCaptcha(token, clientSecret string) (bool } defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return false, err } diff --git a/captcha/recaptcha.go b/captcha/recaptcha.go index 90f3b4176385..84d32e3c1650 100644 --- a/captcha/recaptcha.go +++ b/captcha/recaptcha.go @@ -17,7 +17,7 @@ package captcha import ( "encoding/json" "errors" - "io/ioutil" + "io" "net/http" "net/url" "strings" @@ -43,7 +43,7 @@ func (captcha *ReCaptchaProvider) VerifyCaptcha(token, clientSecret string) (boo } defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return false, err } diff --git a/controllers/account.go b/controllers/account.go index 40a170597d58..33ba7ad20353 100644 --- a/controllers/account.go +++ b/controllers/account.go @@ -274,6 +274,7 @@ func (c *ApiController) GetAccount() { c.ServeJSON() } +// GetUserinfo // UserInfo // @Title UserInfo // @Tag Account API diff --git a/controllers/auth.go b/controllers/auth.go index e200f3f450cd..2050d0cd88ac 100644 --- a/controllers/auth.go +++ b/controllers/auth.go @@ -118,7 +118,7 @@ func (c *ApiController) HandleLoggedIn(application *object.Application, user *ob } } else { - resp = wrapErrorResponse(fmt.Errorf("Unknown response type: %s", form.Type)) + resp = wrapErrorResponse(fmt.Errorf("unknown response type: %s", form.Type)) } // if user did not check auto signin diff --git a/controllers/base.go b/controllers/base.go index bbbacf631c72..893f84ead801 100644 --- a/controllers/base.go +++ b/controllers/base.go @@ -23,11 +23,13 @@ import ( "github.com/casdoor/casdoor/util" ) +// ApiController // controller for handlers under /api uri type ApiController struct { beego.Controller } +// RootController // controller for handlers directly under / (root) type RootController struct { ApiController diff --git a/controllers/cas.go b/controllers/cas.go index d6a6a16e2a95..37f433b3db37 100644 --- a/controllers/cas.go +++ b/controllers/cas.go @@ -31,7 +31,7 @@ const ( InvalidProxyCallback string = "INVALID_PROXY_CALLBACK" InvalidTicket string = "INVALID_TICKET" InvalidService string = "INVALID_SERVICE" - InteralError string = "INTERNAL_ERROR" + InternalError string = "INTERNAL_ERROR" UnauthorizedService string = "UNAUTHORIZED_SERVICE" ) @@ -116,7 +116,7 @@ func (c *RootController) CasP3ServiceAndProxyValidate() { } // make a request to pgturl passing pgt and pgtiou if err != nil { - c.sendCasAuthenticationResponseErr(InteralError, err.Error(), format) + c.sendCasAuthenticationResponseErr(InternalError, err.Error(), format) return } param := pgtUrlObj.Query() @@ -126,7 +126,7 @@ func (c *RootController) CasP3ServiceAndProxyValidate() { request, err := http.NewRequest("GET", pgtUrlObj.String(), nil) if err != nil { - c.sendCasAuthenticationResponseErr(InteralError, err.Error(), format) + c.sendCasAuthenticationResponseErr(InternalError, err.Error(), format) return } @@ -214,7 +214,7 @@ func (c *RootController) SamlValidate() { return } - envelopReponse := struct { + envelopResponse := struct { XMLName xml.Name `xml:"SOAP-ENV:Envelope"` Xmlns string `xml:"xmlns:SOAP-ENV"` Body struct { @@ -222,15 +222,15 @@ func (c *RootController) SamlValidate() { Content string `xml:",innerxml"` } }{} - envelopReponse.Xmlns = "http://schemas.xmlsoap.org/soap/envelope/" - envelopReponse.Body.Content = response + envelopResponse.Xmlns = "http://schemas.xmlsoap.org/soap/envelope/" + envelopResponse.Body.Content = response - data, err := xml.Marshal(envelopReponse) + data, err := xml.Marshal(envelopResponse) if err != nil { c.ResponseError(err.Error()) return } - c.Ctx.Output.Body([]byte(data)) + c.Ctx.Output.Body(data) } func (c *RootController) sendCasProxyResponseErr(code, msg, format string) { diff --git a/controllers/cert.go b/controllers/cert.go index fe16a9025817..361312e5dd84 100644 --- a/controllers/cert.go +++ b/controllers/cert.go @@ -48,6 +48,7 @@ func (c *ApiController) GetCerts() { } } +// GetCert // @Title GetCert // @Tag Cert API // @Description get cert @@ -61,6 +62,7 @@ func (c *ApiController) GetCert() { c.ServeJSON() } +// UpdateCert // @Title UpdateCert // @Tag Cert API // @Description update cert @@ -81,6 +83,7 @@ func (c *ApiController) UpdateCert() { c.ServeJSON() } +// AddCert // @Title AddCert // @Tag Cert API // @Description add cert @@ -98,6 +101,7 @@ func (c *ApiController) AddCert() { c.ServeJSON() } +// DeleteCert // @Title DeleteCert // @Tag Cert API // @Description delete cert diff --git a/controllers/ldap.go b/controllers/ldap.go index 9f715fca470a..9aa96c2aa845 100644 --- a/controllers/ldap.go +++ b/controllers/ldap.go @@ -44,6 +44,7 @@ type LdapSyncResp struct { Failed []object.LdapRespUser `json:"failed"` } +// GetLdapUser // @Tag Account API // @Title GetLdapser // @router /get-ldap-user [post] @@ -100,6 +101,7 @@ func (c *ApiController) GetLdapUser() { c.ServeJSON() } +// GetLdaps // @Tag Account API // @Title GetLdaps // @router /get-ldaps [post] @@ -110,6 +112,7 @@ func (c *ApiController) GetLdaps() { c.ServeJSON() } +// GetLdap // @Tag Account API // @Title GetLdap // @router /get-ldap [post] @@ -125,6 +128,7 @@ func (c *ApiController) GetLdap() { c.ServeJSON() } +// AddLdap // @Tag Account API // @Title AddLdap // @router /add-ldap [post] @@ -159,6 +163,7 @@ func (c *ApiController) AddLdap() { c.ServeJSON() } +// UpdateLdap // @Tag Account API // @Title UpdateLdap // @router /update-ldap [post] @@ -186,6 +191,7 @@ func (c *ApiController) UpdateLdap() { c.ServeJSON() } +// DeleteLdap // @Tag Account API // @Title DeleteLdap // @router /delete-ldap [post] @@ -201,6 +207,7 @@ func (c *ApiController) DeleteLdap() { c.ServeJSON() } +// SyncLdapUsers // @Tag Account API // @Title SyncLdapUsers // @router /sync-ldap-users [post] @@ -223,6 +230,7 @@ func (c *ApiController) SyncLdapUsers() { c.ServeJSON() } +// CheckLdapUsersExist // @Tag Account API // @Title CheckLdapUserExist // @router /check-ldap-users-exist [post] diff --git a/controllers/oidc_discovery.go b/controllers/oidc_discovery.go index 3a27c68e7f6f..8986c80f68dc 100644 --- a/controllers/oidc_discovery.go +++ b/controllers/oidc_discovery.go @@ -16,6 +16,7 @@ package controllers import "github.com/casdoor/casdoor/object" +// GetOidcDiscovery // @Title GetOidcDiscovery // @Tag OIDC API // @Description Get Oidc Discovery @@ -27,6 +28,7 @@ func (c *RootController) GetOidcDiscovery() { c.ServeJSON() } +// GetJwks // @Title GetJwks // @Tag OIDC API // @Success 200 {object} jose.JSONWebKey diff --git a/controllers/payment.go b/controllers/payment.go index b3c7fb02075d..596d2809844f 100644 --- a/controllers/payment.go +++ b/controllers/payment.go @@ -67,6 +67,7 @@ func (c *ApiController) GetUserPayments() { c.ResponseOk(payments) } +// GetPayment // @Title GetPayment // @Tag Payment API // @Description get payment @@ -80,6 +81,7 @@ func (c *ApiController) GetPayment() { c.ServeJSON() } +// UpdatePayment // @Title UpdatePayment // @Tag Payment API // @Description update payment @@ -100,6 +102,7 @@ func (c *ApiController) UpdatePayment() { c.ServeJSON() } +// AddPayment // @Title AddPayment // @Tag Payment API // @Description add payment @@ -117,6 +120,7 @@ func (c *ApiController) AddPayment() { c.ServeJSON() } +// DeletePayment // @Title DeletePayment // @Tag Payment API // @Description delete payment @@ -134,6 +138,7 @@ func (c *ApiController) DeletePayment() { c.ServeJSON() } +// NotifyPayment // @Title NotifyPayment // @Tag Payment API // @Description notify payment @@ -159,6 +164,7 @@ func (c *ApiController) NotifyPayment() { } } +// InvoicePayment // @Title InvoicePayment // @Tag Payment API // @Description invoice payment diff --git a/controllers/permission.go b/controllers/permission.go index d7606609c120..8f3cdafca2bf 100644 --- a/controllers/permission.go +++ b/controllers/permission.go @@ -48,6 +48,7 @@ func (c *ApiController) GetPermissions() { } } +// GetPermission // @Title GetPermission // @Tag Permission API // @Description get permission @@ -61,6 +62,7 @@ func (c *ApiController) GetPermission() { c.ServeJSON() } +// UpdatePermission // @Title UpdatePermission // @Tag Permission API // @Description update permission @@ -81,6 +83,7 @@ func (c *ApiController) UpdatePermission() { c.ServeJSON() } +// AddPermission // @Title AddPermission // @Tag Permission API // @Description add permission @@ -98,6 +101,7 @@ func (c *ApiController) AddPermission() { c.ServeJSON() } +// DeletePermission // @Title DeletePermission // @Tag Permission API // @Description delete permission diff --git a/controllers/product.go b/controllers/product.go index 2e2a7c4fa76b..a267ddd33efc 100644 --- a/controllers/product.go +++ b/controllers/product.go @@ -49,6 +49,7 @@ func (c *ApiController) GetProducts() { } } +// GetProduct // @Title GetProduct // @Tag Product API // @Description get product @@ -65,6 +66,7 @@ func (c *ApiController) GetProduct() { c.ServeJSON() } +// UpdateProduct // @Title UpdateProduct // @Tag Product API // @Description update product @@ -85,6 +87,7 @@ func (c *ApiController) UpdateProduct() { c.ServeJSON() } +// AddProduct // @Title AddProduct // @Tag Product API // @Description add product @@ -102,6 +105,7 @@ func (c *ApiController) AddProduct() { c.ServeJSON() } +// DeleteProduct // @Title DeleteProduct // @Tag Product API // @Description delete product @@ -119,6 +123,7 @@ func (c *ApiController) DeleteProduct() { c.ServeJSON() } +// BuyProduct // @Title BuyProduct // @Tag Product API // @Description buy product diff --git a/controllers/provider.go b/controllers/provider.go index 6959157537e8..ec4c73d24768 100644 --- a/controllers/provider.go +++ b/controllers/provider.go @@ -48,6 +48,7 @@ func (c *ApiController) GetProviders() { } } +// GetProvider // @Title GetProvider // @Tag Provider API // @Description get provider @@ -61,6 +62,7 @@ func (c *ApiController) GetProvider() { c.ServeJSON() } +// UpdateProvider // @Title UpdateProvider // @Tag Provider API // @Description update provider @@ -81,6 +83,7 @@ func (c *ApiController) UpdateProvider() { c.ServeJSON() } +// AddProvider // @Title AddProvider // @Tag Provider API // @Description add provider @@ -98,6 +101,7 @@ func (c *ApiController) AddProvider() { c.ServeJSON() } +// DeleteProvider // @Title DeleteProvider // @Tag Provider API // @Description delete provider diff --git a/controllers/resource.go b/controllers/resource.go index 382555bc3d99..55d8da5e827f 100644 --- a/controllers/resource.go +++ b/controllers/resource.go @@ -27,6 +27,7 @@ import ( "github.com/casdoor/casdoor/util" ) +// GetResources // @router /get-resources [get] // @Tag Resource API // @Title GetResources @@ -50,6 +51,7 @@ func (c *ApiController) GetResources() { } } +// GetResource // @Tag Resource API // @Title GetResource // @router /get-resource [get] @@ -60,6 +62,7 @@ func (c *ApiController) GetResource() { c.ServeJSON() } +// UpdateResource // @Tag Resource API // @Title UpdateResource // @router /update-resource [post] @@ -76,6 +79,7 @@ func (c *ApiController) UpdateResource() { c.ServeJSON() } +// AddResource // @Tag Resource API // @Title AddResource // @router /add-resource [post] @@ -90,6 +94,7 @@ func (c *ApiController) AddResource() { c.ServeJSON() } +// DeleteResource // @Tag Resource API // @Title DeleteResource // @router /delete-resource [post] @@ -115,6 +120,7 @@ func (c *ApiController) DeleteResource() { c.ServeJSON() } +// UploadResource // @Tag Resource API // @Title UploadResource // @router /upload-resource [post] diff --git a/controllers/role.go b/controllers/role.go index 56971985068f..ca46a148d73c 100644 --- a/controllers/role.go +++ b/controllers/role.go @@ -48,6 +48,7 @@ func (c *ApiController) GetRoles() { } } +// GetRole // @Title GetRole // @Tag Role API // @Description get role @@ -61,6 +62,7 @@ func (c *ApiController) GetRole() { c.ServeJSON() } +// UpdateRole // @Title UpdateRole // @Tag Role API // @Description update role @@ -81,6 +83,7 @@ func (c *ApiController) UpdateRole() { c.ServeJSON() } +// AddRole // @Title AddRole // @Tag Role API // @Description add role @@ -98,6 +101,7 @@ func (c *ApiController) AddRole() { c.ServeJSON() } +// DeleteRole // @Title DeleteRole // @Tag Role API // @Description delete role diff --git a/controllers/syncer.go b/controllers/syncer.go index f8b442f5b2b1..127d1eef2da9 100644 --- a/controllers/syncer.go +++ b/controllers/syncer.go @@ -48,6 +48,7 @@ func (c *ApiController) GetSyncers() { } } +// GetSyncer // @Title GetSyncer // @Tag Syncer API // @Description get syncer @@ -61,6 +62,7 @@ func (c *ApiController) GetSyncer() { c.ServeJSON() } +// UpdateSyncer // @Title UpdateSyncer // @Tag Syncer API // @Description update syncer @@ -81,6 +83,7 @@ func (c *ApiController) UpdateSyncer() { c.ServeJSON() } +// AddSyncer // @Title AddSyncer // @Tag Syncer API // @Description add syncer @@ -98,6 +101,7 @@ func (c *ApiController) AddSyncer() { c.ServeJSON() } +// DeleteSyncer // @Title DeleteSyncer // @Tag Syncer API // @Description delete syncer @@ -115,6 +119,7 @@ func (c *ApiController) DeleteSyncer() { c.ServeJSON() } +// RunSyncer // @Title RunSyncer // @Tag Syncer API // @Description run syncer diff --git a/controllers/token.go b/controllers/token.go index ab139227b8eb..c859ec3bfb83 100644 --- a/controllers/token.go +++ b/controllers/token.go @@ -255,7 +255,7 @@ func (c *ApiController) RefreshToken() { // @router /login/oauth/logout [get] func (c *ApiController) TokenLogout() { token := c.Input().Get("id_token_hint") - flag, application := object.DeleteTokenByAceessToken(token) + flag, application := object.DeleteTokenByAccessToken(token) redirectUri := c.Input().Get("post_logout_redirect_uri") state := c.Input().Get("state") if application != nil && object.CheckRedirectUriValid(application, redirectUri) { @@ -288,7 +288,7 @@ func (c *ApiController) IntrospectToken() { if clientId == "" || clientSecret == "" { c.ResponseError("empty clientId or clientSecret") c.Data["json"] = &object.TokenError{ - Error: object.INVALID_REQUEST, + Error: object.InvalidRequest, } c.SetTokenErrorHttpStatus() c.ServeJSON() @@ -299,7 +299,7 @@ func (c *ApiController) IntrospectToken() { if application == nil || application.ClientSecret != clientSecret { c.ResponseError("invalid application or wrong clientSecret") c.Data["json"] = &object.TokenError{ - Error: object.INVALID_CLIENT, + Error: object.InvalidClient, } c.SetTokenErrorHttpStatus() return diff --git a/controllers/user.go b/controllers/user.go index 21e05680eef8..7b65c4d7504e 100644 --- a/controllers/user.go +++ b/controllers/user.go @@ -298,6 +298,7 @@ func (c *ApiController) SetPassword() { c.ServeJSON() } +// CheckUserPassword // @Title CheckUserPassword // @router /check-user-password [post] // @Tag User API diff --git a/controllers/util.go b/controllers/util.go index cfb545f40c92..727640042593 100644 --- a/controllers/util.go +++ b/controllers/util.go @@ -55,7 +55,7 @@ func (c *ApiController) ResponseError(error string, data ...interface{}) { func (c *ApiController) SetTokenErrorHttpStatus() { _, ok := c.Data["json"].(*object.TokenError) if ok { - if c.Data["json"].(*object.TokenError).Error == object.INVALID_CLIENT { + if c.Data["json"].(*object.TokenError).Error == object.InvalidClient { c.Ctx.Output.SetStatus(401) c.Ctx.Output.Header("WWW-Authenticate", "Basic realm=\"OAuth2\"") } else { diff --git a/controllers/verification.go b/controllers/verification.go index 7134a17f89df..08a203ce0ac2 100644 --- a/controllers/verification.go +++ b/controllers/verification.go @@ -98,7 +98,7 @@ func (c *ApiController) SendVerificationCode() { return } - sendResp := errors.New("Invalid dest type") + sendResp := errors.New("invalid dest type") if user == nil && checkUser != "" && checkUser != "true" { name := application.Organization diff --git a/controllers/webauthn.go b/controllers/webauthn.go index 474436e26974..d48a63962dc8 100644 --- a/controllers/webauthn.go +++ b/controllers/webauthn.go @@ -16,7 +16,7 @@ package controllers import ( "bytes" - "io/ioutil" + "io" "github.com/casdoor/casdoor/object" "github.com/casdoor/casdoor/util" @@ -24,6 +24,7 @@ import ( "github.com/duo-labs/webauthn/webauthn" ) +// WebAuthnSignupBegin // @Title WebAuthnSignupBegin // @Tag User API // @Description WebAuthn Registration Flow 1st stage @@ -53,6 +54,7 @@ func (c *ApiController) WebAuthnSignupBegin() { c.ServeJSON() } +// WebAuthnSignupFinish // @Title WebAuthnSignupFinish // @Tag User API // @Description WebAuthn Registration Flow 2nd stage @@ -72,7 +74,7 @@ func (c *ApiController) WebAuthnSignupFinish() { c.ResponseError("Please call WebAuthnSignupBegin first") return } - c.Ctx.Request.Body = ioutil.NopCloser(bytes.NewBuffer(c.Ctx.Input.RequestBody)) + c.Ctx.Request.Body = io.NopCloser(bytes.NewBuffer(c.Ctx.Input.RequestBody)) credential, err := webauthnObj.FinishRegistration(user, sessionData, c.Ctx.Request) if err != nil { @@ -84,6 +86,7 @@ func (c *ApiController) WebAuthnSignupFinish() { c.ResponseOk() } +// WebAuthnSigninBegin // @Title WebAuthnSigninBegin // @Tag Login API // @Description WebAuthn Login Flow 1st stage @@ -110,6 +113,7 @@ func (c *ApiController) WebAuthnSigninBegin() { c.ServeJSON() } +// WebAuthnSigninFinish // @Title WebAuthnSigninBegin // @Tag Login API // @Description WebAuthn Login Flow 2nd stage @@ -124,7 +128,7 @@ func (c *ApiController) WebAuthnSigninFinish() { c.ResponseError("Please call WebAuthnSigninBegin first") return } - c.Ctx.Request.Body = ioutil.NopCloser(bytes.NewBuffer(c.Ctx.Input.RequestBody)) + c.Ctx.Request.Body = io.NopCloser(bytes.NewBuffer(c.Ctx.Input.RequestBody)) userId := string(sessionData.UserID) user := object.GetUser(userId) _, err := webauthnObj.FinishLogin(user, sessionData, c.Ctx.Request) diff --git a/controllers/webhook.go b/controllers/webhook.go index c872684f6a36..ecc9ecde7ef7 100644 --- a/controllers/webhook.go +++ b/controllers/webhook.go @@ -48,6 +48,7 @@ func (c *ApiController) GetWebhooks() { } } +// GetWebhook // @Title GetWebhook // @Tag Webhook API // @Description get webhook @@ -61,6 +62,7 @@ func (c *ApiController) GetWebhook() { c.ServeJSON() } +// UpdateWebhook // @Title UpdateWebhook // @Tag Webhook API // @Description update webhook @@ -81,6 +83,7 @@ func (c *ApiController) UpdateWebhook() { c.ServeJSON() } +// AddWebhook // @Title AddWebhook // @Tag Webhook API // @Description add webhook @@ -98,6 +101,7 @@ func (c *ApiController) AddWebhook() { c.ServeJSON() } +// DeleteWebhook // @Title DeleteWebhook // @Tag Webhook API // @Description delete webhook diff --git a/idp/adfs.go b/idp/adfs.go index 3cc69a0a7e4e..d20fe850c309 100644 --- a/idp/adfs.go +++ b/idp/adfs.go @@ -19,7 +19,7 @@ import ( "crypto/tls" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "net/url" "time" @@ -77,6 +77,7 @@ type AdfsToken struct { ErrMsg string `json:"error_description"` } +// GetToken // get more detail via: https://docs.microsoft.com/en-us/windows-server/identity/ad-fs/overview/ad-fs-openid-connect-oauth-flows-scenarios#request-an-access-token func (idp *AdfsIdProvider) GetToken(code string) (*oauth2.Token, error) { payload := url.Values{} @@ -88,7 +89,7 @@ func (idp *AdfsIdProvider) GetToken(code string) (*oauth2.Token, error) { if err != nil { return nil, err } - data, err := ioutil.ReadAll(resp.Body) + data, err := io.ReadAll(resp.Body) if err != nil { return nil, err } @@ -109,6 +110,7 @@ func (idp *AdfsIdProvider) GetToken(code string) (*oauth2.Token, error) { return token, nil } +// GetUserInfo // Since the userinfo endpoint of ADFS only returns sub, // the id_token is used to resolve the userinfo func (idp *AdfsIdProvider) GetUserInfo(token *oauth2.Token) (*UserInfo, error) { @@ -122,10 +124,10 @@ func (idp *AdfsIdProvider) GetUserInfo(token *oauth2.Token) (*UserInfo, error) { } tokenSrc := []byte(token.AccessToken) publicKey, _ := keyset.Keys[0].Materialize() - id_token, _ := jwt.Parse(bytes.NewReader(tokenSrc), jwt.WithVerify(jwa.RS256, publicKey)) - sid, _ := id_token.Get("sid") - upn, _ := id_token.Get("upn") - name, _ := id_token.Get("unique_name") + idToken, _ := jwt.Parse(bytes.NewReader(tokenSrc), jwt.WithVerify(jwa.RS256, publicKey)) + sid, _ := idToken.Get("sid") + upn, _ := idToken.Get("upn") + name, _ := idToken.Get("unique_name") userinfo := &UserInfo{ Id: sid.(string), Username: name.(string), diff --git a/idp/alipay.go b/idp/alipay.go index 60d65f30f238..9056dfc122b7 100644 --- a/idp/alipay.go +++ b/idp/alipay.go @@ -24,7 +24,6 @@ import ( "encoding/json" "encoding/pem" "io" - "io/ioutil" "net/http" "net/url" "sort" @@ -205,7 +204,7 @@ func (idp *AlipayIdProvider) postWithBody(body interface{}, targetUrl string) ([ if err != nil { return nil, err } - data, err := ioutil.ReadAll(resp.Body) + data, err := io.ReadAll(resp.Body) if err != nil { return nil, err } diff --git a/idp/baidu.go b/idp/baidu.go index 27bb5772eb1b..77b891cc0a1f 100644 --- a/idp/baidu.go +++ b/idp/baidu.go @@ -18,7 +18,7 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "golang.org/x/oauth2" @@ -97,7 +97,7 @@ func (idp *BaiduIdProvider) GetUserInfo(token *oauth2.Token) (*UserInfo, error) return nil, err } - data, err := ioutil.ReadAll(resp.Body) + data, err := io.ReadAll(resp.Body) if err != nil { return nil, err } diff --git a/idp/bilibili.go b/idp/bilibili.go index 6cce62159ee6..3f368ed2f9f7 100644 --- a/idp/bilibili.go +++ b/idp/bilibili.go @@ -18,7 +18,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "net/url" "strings" @@ -76,6 +75,7 @@ type BilibiliIdProviderTokenResponse struct { Data BilibiliProviderToken `json:"data"` } +// GetToken /* { "code": 0, @@ -170,7 +170,7 @@ func (idp *BilibiliIdProvider) GetUserInfo(token *oauth2.Token) (*UserInfo, erro return nil, err } - data, err := ioutil.ReadAll(resp.Body) + data, err := io.ReadAll(resp.Body) if err != nil { return nil, err } @@ -204,7 +204,7 @@ func (idp *BilibiliIdProvider) postWithBody(body interface{}, url string) ([]byt if err != nil { return nil, err } - data, err := ioutil.ReadAll(resp.Body) + data, err := io.ReadAll(resp.Body) if err != nil { return nil, err } diff --git a/idp/casdoor.go b/idp/casdoor.go index 308b435dfaea..04a140eefaa8 100644 --- a/idp/casdoor.go +++ b/idp/casdoor.go @@ -17,7 +17,7 @@ package idp import ( "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "net/url" "time" @@ -71,7 +71,7 @@ func (idp *CasdoorIdProvider) GetToken(code string) (*oauth2.Token, error) { return nil, err } defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return nil, err } @@ -131,7 +131,7 @@ func (idp *CasdoorIdProvider) GetUserInfo(token *oauth2.Token) (*UserInfo, error } defer resp.Body.Close() - data, err := ioutil.ReadAll(resp.Body) + data, err := io.ReadAll(resp.Body) if err != nil { return nil, err } diff --git a/idp/custom.go b/idp/custom.go index 1c307efef009..abd517141546 100644 --- a/idp/custom.go +++ b/idp/custom.go @@ -18,7 +18,7 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" _ "net/url" _ "time" @@ -84,7 +84,7 @@ func (idp *CustomIdProvider) GetUserInfo(token *oauth2.Token) (*UserInfo, error) } defer resp.Body.Close() - data, err := ioutil.ReadAll(resp.Body) + data, err := io.ReadAll(resp.Body) if err != nil { return nil, err } diff --git a/idp/dingtalk.go b/idp/dingtalk.go index b79b286b29ec..d17e69fc3854 100644 --- a/idp/dingtalk.go +++ b/idp/dingtalk.go @@ -18,7 +18,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "strings" "time" @@ -101,7 +100,7 @@ func (idp *DingTalkIdProvider) GetToken(code string) (*oauth2.Token, error) { token := &oauth2.Token{ AccessToken: pToken.AccessToken, - Expiry: time.Unix(time.Now().Unix()+int64(pToken.ExpiresIn), 0), + Expiry: time.Unix(time.Now().Unix()+pToken.ExpiresIn, 0), } return token, nil } @@ -145,7 +144,7 @@ func (idp *DingTalkIdProvider) GetUserInfo(token *oauth2.Token) (*UserInfo, erro } defer resp.Body.Close() - data, err := ioutil.ReadAll(resp.Body) + data, err := io.ReadAll(resp.Body) if err != nil { return nil, err } @@ -180,7 +179,7 @@ func (idp *DingTalkIdProvider) postWithBody(body interface{}, url string) ([]byt if err != nil { return nil, err } - data, err := ioutil.ReadAll(resp.Body) + data, err := io.ReadAll(resp.Body) if err != nil { return nil, err } diff --git a/idp/douyin.go b/idp/douyin.go index fa43e6927358..1be7e6993d00 100644 --- a/idp/douyin.go +++ b/idp/douyin.go @@ -18,7 +18,7 @@ import ( "bytes" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "net/url" "time" @@ -98,7 +98,7 @@ func (idp *DouyinIdProvider) GetToken(code string) (*oauth2.Token, error) { if err != nil { return nil, err } - data, err := ioutil.ReadAll(resp.Body) + data, err := io.ReadAll(resp.Body) if err != nil { return nil, err } @@ -177,7 +177,7 @@ func (idp *DouyinIdProvider) GetUserInfo(token *oauth2.Token) (*UserInfo, error) defer resp.Body.Close() - respBody, err := ioutil.ReadAll(resp.Body) + respBody, err := io.ReadAll(resp.Body) if err != nil { return nil, err } diff --git a/idp/facebook.go b/idp/facebook.go index 622fa465d96c..2f8399530273 100644 --- a/idp/facebook.go +++ b/idp/facebook.go @@ -71,6 +71,7 @@ type FacebookCheckToken struct { Data string `json:"data"` } +// FacebookCheckTokenData // Get more detail via: https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow#checktoken type FacebookCheckTokenData struct { UserId string `json:"user_id"` diff --git a/idp/gitee.go b/idp/gitee.go index af55eb512c1d..8688f8353cd4 100644 --- a/idp/gitee.go +++ b/idp/gitee.go @@ -19,7 +19,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "net/url" "strconv" @@ -93,7 +92,7 @@ func (idp *GiteeIdProvider) GetToken(code string) (*oauth2.Token, error) { if err != nil { return nil, err } - rbs, err := ioutil.ReadAll(resp.Body) + rbs, err := io.ReadAll(resp.Body) if err != nil { return nil, err } diff --git a/idp/github.go b/idp/github.go index 57e0ad5d111f..58a233782173 100644 --- a/idp/github.go +++ b/idp/github.go @@ -18,7 +18,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "strconv" "strings" @@ -202,7 +201,7 @@ func (idp *GithubIdProvider) GetUserInfo(token *oauth2.Token) (*UserInfo, error) defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return nil, err } @@ -236,7 +235,7 @@ func (idp *GithubIdProvider) postWithBody(body interface{}, url string) ([]byte, if err != nil { return nil, err } - data, err := ioutil.ReadAll(resp.Body) + data, err := io.ReadAll(resp.Body) if err != nil { return nil, err } diff --git a/idp/gitlab.go b/idp/gitlab.go index 0d03d2a40a74..b5b344b9e173 100644 --- a/idp/gitlab.go +++ b/idp/gitlab.go @@ -17,7 +17,7 @@ package idp import ( "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "net/url" "strconv" @@ -85,7 +85,7 @@ func (idp *GitlabIdProvider) GetToken(code string) (*oauth2.Token, error) { return nil, err } - data, err := ioutil.ReadAll(resp.Body) + data, err := io.ReadAll(resp.Body) if err != nil { return nil, err } @@ -209,7 +209,7 @@ func (idp *GitlabIdProvider) GetUserInfo(token *oauth2.Token) (*UserInfo, error) return nil, err } - data, err := ioutil.ReadAll(resp.Body) + data, err := io.ReadAll(resp.Body) if err != nil { return nil, err } diff --git a/idp/google.go b/idp/google.go index 604fd8256b3c..ca22a690adc9 100644 --- a/idp/google.go +++ b/idp/google.go @@ -19,7 +19,7 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" + "io" "net/http" "golang.org/x/oauth2" @@ -95,7 +95,7 @@ func (idp *GoogleIdProvider) GetUserInfo(token *oauth2.Token) (*UserInfo, error) } defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return nil, err } diff --git a/idp/goth.go b/idp/goth.go index d40b647bed07..5853fb97f2e2 100644 --- a/idp/goth.go +++ b/idp/goth.go @@ -207,6 +207,7 @@ func NewGothIdProvider(providerType string, clientId string, clientSecret string return &idp } +// SetHttpClient // Goth's idp all implement the Client method, but since the goth.Provider interface does not provide to modify idp's client method, reflection is required func (idp *GothIdProvider) SetHttpClient(client *http.Client) { idpClient := reflect.ValueOf(idp.Provider).Elem().FieldByName("HTTPClient") diff --git a/idp/infoflow_internal.go b/idp/infoflow_internal.go index b896b1079b20..c48739828ac5 100644 --- a/idp/infoflow_internal.go +++ b/idp/infoflow_internal.go @@ -17,7 +17,7 @@ package idp import ( "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "golang.org/x/oauth2" @@ -58,6 +58,7 @@ type InfoflowInterToken struct { AccessToken string `json:"access_token"` } +// GetToken // get more detail via: https://qy.baidu.com/doc/index.html#/inner_quickstart/flow?id=%E8%8E%B7%E5%8F%96accesstoken func (idp *InfoflowInternalIdProvider) GetToken(code string) (*oauth2.Token, error) { pTokenParams := &struct { @@ -69,7 +70,7 @@ func (idp *InfoflowInternalIdProvider) GetToken(code string) (*oauth2.Token, err return nil, err } - data, err := ioutil.ReadAll(resp.Body) + data, err := io.ReadAll(resp.Body) if err != nil { return nil, err } @@ -137,6 +138,7 @@ type InfoflowInternalUserInfo struct { Email string `json:"email"` } +// GetUserInfo // get more detail via: https://qy.baidu.com/doc/index.html#/inner_serverapi/contacts?id=%e8%8e%b7%e5%8f%96%e6%88%90%e5%91%98 func (idp *InfoflowInternalIdProvider) GetUserInfo(token *oauth2.Token) (*UserInfo, error) { // Get userid first @@ -147,7 +149,7 @@ func (idp *InfoflowInternalIdProvider) GetUserInfo(token *oauth2.Token) (*UserIn return nil, err } - data, err := ioutil.ReadAll(resp.Body) + data, err := io.ReadAll(resp.Body) if err != nil { return nil, err } @@ -165,7 +167,7 @@ func (idp *InfoflowInternalIdProvider) GetUserInfo(token *oauth2.Token) (*UserIn return nil, err } - data, err = ioutil.ReadAll(resp.Body) + data, err = io.ReadAll(resp.Body) if err != nil { return nil, err } diff --git a/idp/infoflow_third_party.go b/idp/infoflow_third_party.go index 4d31cb9659cb..f67d197b23d2 100644 --- a/idp/infoflow_third_party.go +++ b/idp/infoflow_third_party.go @@ -18,7 +18,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "strings" "time" @@ -63,6 +62,7 @@ type InfoflowToken struct { ExpiresIn int `json:"expires_in"` } +// GetToken // get more detail via: https://qy.baidu.com/doc/index.html#/third_serverapi/authority func (idp *InfoflowIdProvider) GetToken(code string) (*oauth2.Token, error) { pTokenParams := &struct { @@ -134,6 +134,7 @@ type InfoflowUserInfo struct { Email string `json:"email"` } +// GetUserInfo // get more detail via: https://qy.baidu.com/doc/index.html#/third_serverapi/contacts?id=%e8%8e%b7%e5%8f%96%e6%88%90%e5%91%98 func (idp *InfoflowIdProvider) GetUserInfo(token *oauth2.Token) (*UserInfo, error) { // Get userid first @@ -144,7 +145,7 @@ func (idp *InfoflowIdProvider) GetUserInfo(token *oauth2.Token) (*UserInfo, erro return nil, err } - data, err := ioutil.ReadAll(resp.Body) + data, err := io.ReadAll(resp.Body) if err != nil { return nil, err } @@ -162,7 +163,7 @@ func (idp *InfoflowIdProvider) GetUserInfo(token *oauth2.Token) (*UserInfo, erro return nil, err } - data, err = ioutil.ReadAll(resp.Body) + data, err = io.ReadAll(resp.Body) if err != nil { return nil, err } @@ -197,7 +198,7 @@ func (idp *InfoflowIdProvider) postWithBody(body interface{}, url string) ([]byt if err != nil { return nil, err } - data, err := ioutil.ReadAll(resp.Body) + data, err := io.ReadAll(resp.Body) if err != nil { return nil, err } diff --git a/idp/lark.go b/idp/lark.go index 61fbd74d37c4..9c8d18d6d3ea 100644 --- a/idp/lark.go +++ b/idp/lark.go @@ -17,7 +17,6 @@ package idp import ( "encoding/json" "io" - "io/ioutil" "net/http" "strings" "time" @@ -173,7 +172,7 @@ func (idp *LarkIdProvider) GetUserInfo(token *oauth2.Token) (*UserInfo, error) { return nil, err } defer resp.Body.Close() - data, err = ioutil.ReadAll(resp.Body) + data, err = io.ReadAll(resp.Body) if err != nil { return nil, err } @@ -204,7 +203,7 @@ func (idp *LarkIdProvider) postWithBody(body interface{}, url string) ([]byte, e if err != nil { return nil, err } - data, err := ioutil.ReadAll(resp.Body) + data, err := io.ReadAll(resp.Body) if err != nil { return nil, err } diff --git a/idp/linkedin.go b/idp/linkedin.go index 7442e6c2c154..577ecdadb221 100644 --- a/idp/linkedin.go +++ b/idp/linkedin.go @@ -18,7 +18,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "net/url" "strings" @@ -85,7 +84,7 @@ func (idp *LinkedInIdProvider) GetToken(code string) (*oauth2.Token, error) { if err != nil { return nil, err } - rbs, err := ioutil.ReadAll(resp.Body) + rbs, err := io.ReadAll(resp.Body) if err != nil { return nil, err } @@ -323,7 +322,7 @@ func (idp *LinkedInIdProvider) GetUrlRespWithAuthorization(url, token string) ([ } }(resp.Body) - bs, err := ioutil.ReadAll(resp.Body) + bs, err := io.ReadAll(resp.Body) if err != nil { return nil, err } diff --git a/idp/okta.go b/idp/okta.go index b8dfec50af3f..1468094a354c 100644 --- a/idp/okta.go +++ b/idp/okta.go @@ -17,7 +17,7 @@ package idp import ( "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "net/url" "time" @@ -114,7 +114,7 @@ func (idp *OktaIdProvider) GetToken(code string) (*oauth2.Token, error) { if err != nil { return nil, err } - data, err := ioutil.ReadAll(resp.Body) + data, err := io.ReadAll(resp.Body) if err != nil { return nil, err } @@ -178,7 +178,7 @@ func (idp *OktaIdProvider) GetUserInfo(token *oauth2.Token) (*UserInfo, error) { defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return nil, err } diff --git a/idp/qq.go b/idp/qq.go index b803c3408006..aa5f6ac454c2 100644 --- a/idp/qq.go +++ b/idp/qq.go @@ -18,7 +18,7 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" + "io" "net/http" "net/url" "regexp" @@ -75,7 +75,7 @@ func (idp *QqIdProvider) GetToken(code string) (*oauth2.Token, error) { } defer resp.Body.Close() - tokenContent, err := ioutil.ReadAll(resp.Body) + tokenContent, err := io.ReadAll(resp.Body) if err != nil { return nil, err } @@ -148,7 +148,7 @@ func (idp *QqIdProvider) GetUserInfo(token *oauth2.Token) (*UserInfo, error) { } defer resp.Body.Close() - openIdBody, err := ioutil.ReadAll(resp.Body) + openIdBody, err := io.ReadAll(resp.Body) if err != nil { return nil, err } @@ -167,7 +167,7 @@ func (idp *QqIdProvider) GetUserInfo(token *oauth2.Token) (*UserInfo, error) { } defer resp.Body.Close() - userInfoBody, err := ioutil.ReadAll(resp.Body) + userInfoBody, err := io.ReadAll(resp.Body) if err != nil { return nil, err } diff --git a/idp/wechat.go b/idp/wechat.go index 6e1fe3599366..fc27a2546895 100644 --- a/idp/wechat.go +++ b/idp/wechat.go @@ -144,7 +144,7 @@ type WechatUserInfo struct { City string `json:"city"` // City filled in by general user's personal data Province string `json:"province"` // Province filled in by ordinary user's personal information Country string `json:"country"` // Country, such as China is CN - Headimgurl string `json:"headimgurl"` // User avatar, the last value represents the size of the square avatar (there are optional values of 0, 46, 64, 96, 132, 0 represents a 640*640 square avatar), this item is empty when the user does not have a avatar + Headimgurl string `json:"headimgurl"` // User avatar, the last value represents the size of the square avatar (there are optional values of 0, 46, 64, 96, 132, 0 represents a 640*640 square avatar), this item is empty when the user does not have an avatar Privilege []string `json:"privilege"` // User Privilege information, json array, such as Wechat Woka user (chinaunicom) Unionid string `json:"unionid"` // Unified user identification. For an application under a WeChat open platform account, the unionid of the same user is unique. } diff --git a/idp/wechat_miniprogram.go b/idp/wechat_miniprogram.go index ce83bb4dfbb1..9206f2b8e6d5 100644 --- a/idp/wechat_miniprogram.go +++ b/idp/wechat_miniprogram.go @@ -17,7 +17,7 @@ package idp import ( "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "golang.org/x/oauth2" @@ -65,7 +65,7 @@ func (idp *WeChatMiniProgramIdProvider) GetSessionByCode(code string) (*WeChatMi return nil, err } defer sessionResponse.Body.Close() - data, err := ioutil.ReadAll(sessionResponse.Body) + data, err := io.ReadAll(sessionResponse.Body) if err != nil { return nil, err } diff --git a/idp/wecom_internal.go b/idp/wecom_internal.go index 1a8b511e276a..afaddc3222cb 100644 --- a/idp/wecom_internal.go +++ b/idp/wecom_internal.go @@ -17,13 +17,14 @@ package idp import ( "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "time" "golang.org/x/oauth2" ) +// WeComInternalIdProvider // This idp is using wecom internal application api as idp type WeComInternalIdProvider struct { Client *http.Client @@ -72,7 +73,7 @@ func (idp *WeComInternalIdProvider) GetToken(code string) (*oauth2.Token, error) return nil, err } - data, err := ioutil.ReadAll(resp.Body) + data, err := io.ReadAll(resp.Body) if err != nil { return nil, err } @@ -123,7 +124,7 @@ func (idp *WeComInternalIdProvider) GetUserInfo(token *oauth2.Token) (*UserInfo, return nil, err } - data, err := ioutil.ReadAll(resp.Body) + data, err := io.ReadAll(resp.Body) if err != nil { return nil, err } @@ -144,7 +145,7 @@ func (idp *WeComInternalIdProvider) GetUserInfo(token *oauth2.Token) (*UserInfo, return nil, err } - data, err = ioutil.ReadAll(resp.Body) + data, err = io.ReadAll(resp.Body) if err != nil { return nil, err } diff --git a/idp/wecom_third_party.go b/idp/wecom_third_party.go index 651fafb5b4a7..e0e665799ff5 100644 --- a/idp/wecom_third_party.go +++ b/idp/wecom_third_party.go @@ -18,7 +18,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "strings" "time" @@ -195,7 +194,7 @@ func (idp *WeComIdProvider) postWithBody(body interface{}, url string) ([]byte, if err != nil { return nil, err } - data, err := ioutil.ReadAll(resp.Body) + data, err := io.ReadAll(resp.Body) if err != nil { return nil, err } diff --git a/idp/weibo.go b/idp/weibo.go index 1a8ce8d2c8dd..14533b57c747 100644 --- a/idp/weibo.go +++ b/idp/weibo.go @@ -19,7 +19,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "net/url" "strconv" @@ -92,7 +91,7 @@ func (idp *WeiBoIdProvider) GetToken(code string) (*oauth2.Token, error) { return } }(resp.Body) - bs, err := ioutil.ReadAll(resp.Body) + bs, err := io.ReadAll(resp.Body) if err != nil { return nil, err } diff --git a/object/init.go b/object/init.go index 1b25a522db83..d2b09fbce3c3 100644 --- a/object/init.go +++ b/object/init.go @@ -16,7 +16,7 @@ package object import ( "encoding/gob" - "io/ioutil" + "os" "github.com/casdoor/casdoor/util" "github.com/duo-labs/webauthn/webauthn" @@ -158,11 +158,11 @@ func initBuiltInApplication() { func readTokenFromFile() (string, string) { pemPath := "./object/token_jwt_key.pem" keyPath := "./object/token_jwt_key.key" - pem, err := ioutil.ReadFile(pemPath) + pem, err := os.ReadFile(pemPath) if err != nil { return "", "" } - key, err := ioutil.ReadFile(keyPath) + key, err := os.ReadFile(keyPath) if err != nil { return "", "" } diff --git a/object/ldap_autosync.go b/object/ldap_autosync.go index 46e6ec25d3fe..dbc77e8cb687 100644 --- a/object/ldap_autosync.go +++ b/object/ldap_autosync.go @@ -31,6 +31,7 @@ func GetLdapAutoSynchronizer() *LdapAutoSynchronizer { return globalLdapAutoSynchronizer } +// StartAutoSync // start autosync for specified ldap, old existing autosync goroutine will be ceased func (l *LdapAutoSynchronizer) StartAutoSync(ldapId string) error { l.Lock() @@ -95,6 +96,7 @@ func (l *LdapAutoSynchronizer) syncRoutine(ldap *Ldap, stopChan chan struct{}) { } } +// LdapAutoSynchronizerStartUpAll // start all autosync goroutine for existing ldap servers in each organizations func (l *LdapAutoSynchronizer) LdapAutoSynchronizerStartUpAll() { organizations := []*Organization{} diff --git a/object/saml_idp.go b/object/saml_idp.go index 1576202118cc..8e38b9b75852 100644 --- a/object/saml_idp.go +++ b/object/saml_idp.go @@ -35,6 +35,7 @@ import ( uuid "github.com/satori/go.uuid" ) +// NewSamlResponse // returns a saml2 response func NewSamlResponse(user *User, host string, certificate string, destination string, iss string, requestId string, redirectUri []string) (*etree.Element, error) { samlResponse := &etree.Element{ @@ -113,6 +114,7 @@ func (x X509Key) GetKeyPair() (privateKey *rsa.PrivateKey, cert []byte, err erro return privateKey, cert, err } +// IdpEntityDescriptor // SAML METADATA type IdpEntityDescriptor struct { XMLName xml.Name `xml:"EntityDescriptor"` diff --git a/object/saml_sp.go b/object/saml_sp.go index f74d0adc1fd3..334682bff478 100644 --- a/object/saml_sp.go +++ b/object/saml_sp.go @@ -44,7 +44,7 @@ func ParseSamlResponse(samlResponse string, providerType string) (string, error) func GenerateSamlLoginUrl(id, relayState string) (string, string, error) { provider := GetProvider(id) if provider.Category != "SAML" { - return "", "", fmt.Errorf("Provider %s's category is not SAML", provider.Name) + return "", "", fmt.Errorf("provider %s's category is not SAML", provider.Name) } sp, err := buildSp(provider, "") if err != nil { diff --git a/object/token.go b/object/token.go index 06b5eadbdf33..999f10b37444 100644 --- a/object/token.go +++ b/object/token.go @@ -27,14 +27,14 @@ import ( ) const ( - hourSeconds = 3600 - INVALID_REQUEST = "invalid_request" - INVALID_CLIENT = "invalid_client" - INVALID_GRANT = "invalid_grant" - UNAUTHORIZED_CLIENT = "unauthorized_client" - UNSUPPORTED_GRANT_TYPE = "unsupported_grant_type" - INVALID_SCOPE = "invalid_scope" - ENDPOINT_ERROR = "endpoint_error" + hourSeconds = 3600 + InvalidRequest = "invalid_request" + InvalidClient = "invalid_client" + InvalidGrant = "invalid_grant" + UnauthorizedClient = "unauthorized_client" + UnsupportedGrantType = "unsupported_grant_type" + InvalidScope = "invalid_scope" + EndpointError = "endpoint_error" ) type Code struct { @@ -200,7 +200,7 @@ func DeleteToken(token *Token) bool { return affected != 0 } -func DeleteTokenByAceessToken(accessToken string) (bool, *Application) { +func DeleteTokenByAccessToken(accessToken string) (bool, *Application) { token := Token{AccessToken: accessToken} existed, err := adapter.Engine.Get(&token) if err != nil { @@ -325,7 +325,7 @@ func GetOAuthToken(grantType string, clientId string, clientSecret string, code application := GetApplicationByClientId(clientId) if application == nil { return &TokenError{ - Error: INVALID_CLIENT, + Error: InvalidClient, ErrorDescription: "client_id is invalid", } } @@ -334,7 +334,7 @@ func GetOAuthToken(grantType string, clientId string, clientSecret string, code if !IsGrantTypeValid(grantType, application.GrantTypes) && tag == "" { return &TokenError{ - Error: UNSUPPORTED_GRANT_TYPE, + Error: UnsupportedGrantType, ErrorDescription: fmt.Sprintf("grant_type: %s is not supported in this application", grantType), } } @@ -377,20 +377,20 @@ func RefreshToken(grantType string, refreshToken string, scope string, clientId // check parameters if grantType != "refresh_token" { return &TokenError{ - Error: UNSUPPORTED_GRANT_TYPE, + Error: UnsupportedGrantType, ErrorDescription: "grant_type should be refresh_token", } } application := GetApplicationByClientId(clientId) if application == nil { return &TokenError{ - Error: INVALID_CLIENT, + Error: InvalidClient, ErrorDescription: "client_id is invalid", } } if clientSecret != "" && application.ClientSecret != clientSecret { return &TokenError{ - Error: INVALID_CLIENT, + Error: InvalidClient, ErrorDescription: "client_secret is invalid", } } @@ -399,7 +399,7 @@ func RefreshToken(grantType string, refreshToken string, scope string, clientId existed, err := adapter.Engine.Get(&token) if err != nil || !existed { return &TokenError{ - Error: INVALID_GRANT, + Error: InvalidGrant, ErrorDescription: "refresh token is invalid, expired or revoked", } } @@ -408,7 +408,7 @@ func RefreshToken(grantType string, refreshToken string, scope string, clientId _, err = ParseJwtToken(refreshToken, cert) if err != nil { return &TokenError{ - Error: INVALID_GRANT, + Error: InvalidGrant, ErrorDescription: fmt.Sprintf("parse refresh token error: %s", err.Error()), } } @@ -416,14 +416,14 @@ func RefreshToken(grantType string, refreshToken string, scope string, clientId user := getUser(application.Organization, token.User) if user.IsForbidden { return &TokenError{ - Error: INVALID_GRANT, + Error: InvalidGrant, ErrorDescription: "the user is forbidden to sign in, please contact the administrator", } } newAccessToken, newRefreshToken, err := generateJwtToken(application, user, "", scope, host) if err != nil { return &TokenError{ - Error: ENDPOINT_ERROR, + Error: EndpointError, ErrorDescription: fmt.Sprintf("generate jwt token error: %s", err.Error()), } } @@ -464,6 +464,7 @@ func pkceChallenge(verifier string) string { return challenge } +// IsGrantTypeValid // Check if grantType is allowed in the current application // authorization_code is allowed by default func IsGrantTypeValid(method string, grantTypes []string) bool { @@ -478,11 +479,12 @@ func IsGrantTypeValid(method string, grantTypes []string) bool { return false } +// GetAuthorizationCodeToken // Authorization code flow func GetAuthorizationCodeToken(application *Application, clientSecret string, code string, verifier string) (*Token, *TokenError) { if code == "" { return nil, &TokenError{ - Error: INVALID_REQUEST, + Error: InvalidRequest, ErrorDescription: "authorization code should not be empty", } } @@ -490,21 +492,21 @@ func GetAuthorizationCodeToken(application *Application, clientSecret string, co token := getTokenByCode(code) if token == nil { return nil, &TokenError{ - Error: INVALID_GRANT, + Error: InvalidGrant, ErrorDescription: "authorization code is invalid", } } if token.CodeIsUsed { // anti replay attacks return nil, &TokenError{ - Error: INVALID_GRANT, + Error: InvalidGrant, ErrorDescription: "authorization code has been used", } } if token.CodeChallenge != "" && pkceChallenge(verifier) != token.CodeChallenge { return nil, &TokenError{ - Error: INVALID_GRANT, + Error: InvalidGrant, ErrorDescription: "verifier is invalid", } } @@ -514,13 +516,13 @@ func GetAuthorizationCodeToken(application *Application, clientSecret string, co // but if it is provided, it must be accurate. if token.CodeChallenge == "" { return nil, &TokenError{ - Error: INVALID_CLIENT, + Error: InvalidClient, ErrorDescription: "client_secret is invalid", } } else { if clientSecret != "" { return nil, &TokenError{ - Error: INVALID_CLIENT, + Error: InvalidClient, ErrorDescription: "client_secret is invalid", } } @@ -529,7 +531,7 @@ func GetAuthorizationCodeToken(application *Application, clientSecret string, co if application.Name != token.Application { return nil, &TokenError{ - Error: INVALID_GRANT, + Error: InvalidGrant, ErrorDescription: "the token is for wrong application (client_id)", } } @@ -537,39 +539,40 @@ func GetAuthorizationCodeToken(application *Application, clientSecret string, co if time.Now().Unix() > token.CodeExpireIn { // code must be used within 5 minutes return nil, &TokenError{ - Error: INVALID_GRANT, + Error: InvalidGrant, ErrorDescription: "authorization code has expired", } } return token, nil } +// GetPasswordToken // Resource Owner Password Credentials flow func GetPasswordToken(application *Application, username string, password string, scope string, host string) (*Token, *TokenError) { user := getUser(application.Organization, username) if user == nil { return nil, &TokenError{ - Error: INVALID_GRANT, + Error: InvalidGrant, ErrorDescription: "the user does not exist", } } msg := CheckPassword(user, password) if msg != "" { return nil, &TokenError{ - Error: INVALID_GRANT, + Error: InvalidGrant, ErrorDescription: "invalid username or password", } } if user.IsForbidden { return nil, &TokenError{ - Error: INVALID_GRANT, + Error: InvalidGrant, ErrorDescription: "the user is forbidden to sign in, please contact the administrator", } } accessToken, refreshToken, err := generateJwtToken(application, user, "", scope, host) if err != nil { return nil, &TokenError{ - Error: ENDPOINT_ERROR, + Error: EndpointError, ErrorDescription: fmt.Sprintf("generate jwt token error: %s", err.Error()), } } @@ -592,11 +595,12 @@ func GetPasswordToken(application *Application, username string, password string return token, nil } +// GetClientCredentialsToken // Client Credentials flow func GetClientCredentialsToken(application *Application, clientSecret string, scope string, host string) (*Token, *TokenError) { if application.ClientSecret != clientSecret { return nil, &TokenError{ - Error: INVALID_CLIENT, + Error: InvalidClient, ErrorDescription: "client_secret is invalid", } } @@ -608,7 +612,7 @@ func GetClientCredentialsToken(application *Application, clientSecret string, sc accessToken, _, err := generateJwtToken(application, nullUser, "", scope, host) if err != nil { return nil, &TokenError{ - Error: ENDPOINT_ERROR, + Error: EndpointError, ErrorDescription: fmt.Sprintf("generate jwt token error: %s", err.Error()), } } @@ -630,6 +634,7 @@ func GetClientCredentialsToken(application *Application, clientSecret string, sc return token, nil } +// GetTokenByUser // Implicit flow func GetTokenByUser(application *Application, user *User, scope string, host string) (*Token, error) { accessToken, refreshToken, err := generateJwtToken(application, user, "", scope, host) @@ -655,12 +660,13 @@ func GetTokenByUser(application *Application, user *User, scope string, host str return token, nil } +// GetWechatMiniProgramToken // Wechat Mini Program flow func GetWechatMiniProgramToken(application *Application, code string, host string, username string, avatar string) (*Token, *TokenError) { mpProvider := GetWechatMiniProgramProvider(application) if mpProvider == nil { return nil, &TokenError{ - Error: INVALID_CLIENT, + Error: InvalidClient, ErrorDescription: "the application does not support wechat mini program", } } @@ -669,14 +675,14 @@ func GetWechatMiniProgramToken(application *Application, code string, host strin session, err := mpIdp.GetSessionByCode(code) if err != nil { return nil, &TokenError{ - Error: INVALID_GRANT, + Error: InvalidGrant, ErrorDescription: fmt.Sprintf("get wechat mini program session error: %s", err.Error()), } } openId, unionId := session.Openid, session.Unionid if openId == "" && unionId == "" { return nil, &TokenError{ - Error: INVALID_REQUEST, + Error: InvalidRequest, ErrorDescription: "the wechat mini program session is invalid", } } @@ -684,7 +690,7 @@ func GetWechatMiniProgramToken(application *Application, code string, host strin if user == nil { if !application.EnableSignUp { return nil, &TokenError{ - Error: INVALID_GRANT, + Error: InvalidGrant, ErrorDescription: "the application does not allow to sign up new account", } } @@ -710,8 +716,8 @@ func GetWechatMiniProgramToken(application *Application, code string, host strin IsForbidden: false, IsDeleted: false, Properties: map[string]string{ - USER_PROPERTIES_WECHAT_OPEN_ID: openId, - USER_PROPERTIES_WECHAT_UNION_ID: unionId, + UserPropertiesWechatOpenId: openId, + UserPropertiesWechatUnionId: unionId, }, } AddUser(user) @@ -720,7 +726,7 @@ func GetWechatMiniProgramToken(application *Application, code string, host strin accessToken, refreshToken, err := generateJwtToken(application, user, "", "", host) if err != nil { return nil, &TokenError{ - Error: ENDPOINT_ERROR, + Error: EndpointError, ErrorDescription: fmt.Sprintf("generate jwt token error: %s", err.Error()), } } diff --git a/object/token_cas.go b/object/token_cas.go index cf28b39d3d02..6e17dadfe2b8 100644 --- a/object/token_cas.go +++ b/object/token_cas.go @@ -136,6 +136,7 @@ func GenerateId() { panic("unimplemented") } +// GetCasTokenByPgt /** @ret1: whether a token is found @ret2: token, nil if not found @@ -150,6 +151,7 @@ func GetCasTokenByPgt(pgt string) (bool, *CasAuthenticationSuccess, string, stri return false, nil, "", "" } +// GetCasTokenByTicket /** @ret1: whether a token is found @ret2: token, nil if not found @@ -207,6 +209,7 @@ func GenerateCasToken(userId string, service string) (string, error) { } } +// GetValidationBySaml /** @ret1: saml response @ret2: the service URL who requested to issue this token diff --git a/object/user.go b/object/user.go index 4e1eda6be84f..1e92c98129f8 100644 --- a/object/user.go +++ b/object/user.go @@ -25,8 +25,8 @@ import ( ) const ( - USER_PROPERTIES_WECHAT_UNION_ID = "wechatUnionId" - USER_PROPERTIES_WECHAT_OPEN_ID = "wechatOpenId" + UserPropertiesWechatUnionId = "wechatUnionId" + UserPropertiesWechatOpenId = "wechatOpenId" ) type User struct { diff --git a/object/user_webauthn.go b/object/user_webauthn.go index e3c25821801f..7ddf9126868a 100644 --- a/object/user_webauthn.go +++ b/object/user_webauthn.go @@ -50,30 +50,31 @@ func GetWebAuthnObject(host string) *webauthn.WebAuthn { return webAuthn } +// WebAuthnID // implementation of webauthn.User interface -func (u *User) WebAuthnID() []byte { - return []byte(u.GetId()) +func (user *User) WebAuthnID() []byte { + return []byte(user.GetId()) } -func (u *User) WebAuthnName() string { - return u.Name +func (user *User) WebAuthnName() string { + return user.Name } -func (u *User) WebAuthnDisplayName() string { - return u.DisplayName +func (user *User) WebAuthnDisplayName() string { + return user.DisplayName } -func (u *User) WebAuthnCredentials() []webauthn.Credential { - return u.WebauthnCredentials +func (user *User) WebAuthnCredentials() []webauthn.Credential { + return user.WebauthnCredentials } -func (u *User) WebAuthnIcon() string { - return u.Avatar +func (user *User) WebAuthnIcon() string { + return user.Avatar } // CredentialExcludeList returns a CredentialDescriptor array filled with all the user's credentials -func (u *User) CredentialExcludeList() []protocol.CredentialDescriptor { - credentials := u.WebAuthnCredentials() +func (user *User) CredentialExcludeList() []protocol.CredentialDescriptor { + credentials := user.WebAuthnCredentials() credentialExcludeList := []protocol.CredentialDescriptor{} for _, cred := range credentials { descriptor := protocol.CredentialDescriptor{ @@ -86,16 +87,16 @@ func (u *User) CredentialExcludeList() []protocol.CredentialDescriptor { return credentialExcludeList } -func (u *User) AddCredentials(credential webauthn.Credential, isGlobalAdmin bool) bool { - u.WebauthnCredentials = append(u.WebauthnCredentials, credential) - return UpdateUser(u.GetId(), u, []string{"webauthnCredentials"}, isGlobalAdmin) +func (user *User) AddCredentials(credential webauthn.Credential, isGlobalAdmin bool) bool { + user.WebauthnCredentials = append(user.WebauthnCredentials, credential) + return UpdateUser(user.GetId(), user, []string{"webauthnCredentials"}, isGlobalAdmin) } -func (u *User) DeleteCredentials(credentialIdBase64 string) bool { - for i, credential := range u.WebauthnCredentials { +func (user *User) DeleteCredentials(credentialIdBase64 string) bool { + for i, credential := range user.WebauthnCredentials { if base64.StdEncoding.EncodeToString(credential.ID) == credentialIdBase64 { - u.WebauthnCredentials = append(u.WebauthnCredentials[0:i], u.WebauthnCredentials[i+1:]...) - return UpdateUserForAllFields(u.GetId(), u) + user.WebauthnCredentials = append(user.WebauthnCredentials[0:i], user.WebauthnCredentials[i+1:]...) + return UpdateUserForAllFields(user.GetId(), user) } } return false diff --git a/object/verification.go b/object/verification.go index ac491ea44679..8971a2f55e43 100644 --- a/object/verification.go +++ b/object/verification.go @@ -42,7 +42,7 @@ type VerificationRecord struct { func SendVerificationCodeToEmail(organization *Organization, user *User, provider *Provider, remoteAddr string, dest string) error { if provider == nil { - return fmt.Errorf("Please set an Email provider first") + return fmt.Errorf("please set an Email provider first") } sender := organization.DisplayName @@ -60,7 +60,7 @@ func SendVerificationCodeToEmail(organization *Organization, user *User, provide func SendVerificationCodeToPhone(organization *Organization, user *User, provider *Provider, remoteAddr string, dest string) error { if provider == nil { - return errors.New("Please set a SMS provider first") + return errors.New("please set a SMS provider first") } code := getRandomCode(5) @@ -85,7 +85,7 @@ func AddToVerificationRecord(user *User, provider *Provider, remoteAddr, recordT now := time.Now().Unix() if has && now-record.Time < 60 { - return errors.New("You can only send one code in 60s.") + return errors.New("you can only send one code in 60s") } record.Owner = provider.Owner diff --git a/pp/gc.go b/pp/gc.go index d2f3ee29111a..78fd48e93cf5 100644 --- a/pp/gc.go +++ b/pp/gc.go @@ -20,7 +20,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "net/url" "strings" @@ -147,7 +146,7 @@ func (pp *GcPaymentProvider) doPost(postBytes []byte) ([]byte, error) { } }(resp.Body) - respBytes, err := ioutil.ReadAll(resp.Body) + respBytes, err := io.ReadAll(resp.Body) if err != nil { return nil, err } diff --git a/util/string.go b/util/string.go index 076f1c627c04..e2735162d8e6 100644 --- a/util/string.go +++ b/util/string.go @@ -20,7 +20,7 @@ import ( "encoding/hex" "errors" "fmt" - "io/ioutil" + "os" "strconv" "strings" "time" @@ -168,7 +168,7 @@ func GetMinLenStr(strs ...string) string { } func ReadStringFromPath(path string) string { - data, err := ioutil.ReadFile(path) + data, err := os.ReadFile(path) if err != nil { panic(err) } @@ -177,7 +177,7 @@ func ReadStringFromPath(path string) string { } func WriteStringToPath(s string, path string) { - err := ioutil.WriteFile(path, []byte(s), 0o644) + err := os.WriteFile(path, []byte(s), 0o644) if err != nil { panic(err) }