diff --git a/authz/authz.go b/authz/authz.go index aa36cbe7a465..2473d9c757d0 100644 --- a/authz/authz.go +++ b/authz/authz.go @@ -68,7 +68,7 @@ m = (r.subOwner == p.subOwner || p.subOwner == "*") && \ Enforcer.ClearPolicy() - //if len(Enforcer.GetPolicy()) == 0 { + // if len(Enforcer.GetPolicy()) == 0 { if true { ruleText := ` p, built-in, *, *, *, *, * diff --git a/captcha/aliyun.go b/captcha/aliyun.go index 59a8a33cb292..086abd6e3076 100644 --- a/captcha/aliyun.go +++ b/captcha/aliyun.go @@ -31,8 +31,7 @@ import ( const AliyunCaptchaVerifyUrl = "http://afs.aliyuncs.com" -type AliyunCaptchaProvider struct { -} +type AliyunCaptchaProvider struct{} func NewAliyunCaptchaProvider() *AliyunCaptchaProvider { captcha := &AliyunCaptchaProvider{} diff --git a/captcha/default.go b/captcha/default.go index f739a84020c9..d3c2037c9a33 100644 --- a/captcha/default.go +++ b/captcha/default.go @@ -16,8 +16,7 @@ package captcha import "github.com/casdoor/casdoor/object" -type DefaultCaptchaProvider struct { -} +type DefaultCaptchaProvider struct{} func NewDefaultCaptchaProvider() *DefaultCaptchaProvider { captcha := &DefaultCaptchaProvider{} diff --git a/captcha/geetest.go b/captcha/geetest.go index d1c4de05083b..3c9b2607b04f 100644 --- a/captcha/geetest.go +++ b/captcha/geetest.go @@ -28,8 +28,7 @@ import ( const GEETESTCaptchaVerifyUrl = "http://gcaptcha4.geetest.com/validate" -type GEETESTCaptchaProvider struct { -} +type GEETESTCaptchaProvider struct{} func NewGEETESTCaptchaProvider() *GEETESTCaptchaProvider { captcha := &GEETESTCaptchaProvider{} diff --git a/captcha/hcaptcha.go b/captcha/hcaptcha.go index a86dd488207d..52f2aa135c8b 100644 --- a/captcha/hcaptcha.go +++ b/captcha/hcaptcha.go @@ -25,8 +25,7 @@ import ( const HCaptchaVerifyUrl = "https://hcaptcha.com/siteverify" -type HCaptchaProvider struct { -} +type HCaptchaProvider struct{} func NewHCaptchaProvider() *HCaptchaProvider { captcha := &HCaptchaProvider{} diff --git a/captcha/recaptcha.go b/captcha/recaptcha.go index 04dbf8ea8aff..90f3b4176385 100644 --- a/captcha/recaptcha.go +++ b/captcha/recaptcha.go @@ -25,8 +25,7 @@ import ( const ReCaptchaVerifyUrl = "https://recaptcha.net/recaptcha/api/siteverify" -type ReCaptchaProvider struct { -} +type ReCaptchaProvider struct{} func NewReCaptchaProvider() *ReCaptchaProvider { captcha := &ReCaptchaProvider{} diff --git a/conf/conf.go b/conf/conf.go index 7088c67691d5..9f2afd0e547a 100644 --- a/conf/conf.go +++ b/conf/conf.go @@ -48,8 +48,8 @@ func GetConfigInt64(key string) (int64, error) { } func init() { - //this array contains the beego configuration items that may be modified via env - var presetConfigItems = []string{"httpport", "appname"} + // this array contains the beego configuration items that may be modified via env + presetConfigItems := []string{"httpport", "appname"} for _, key := range presetConfigItems { if value, ok := os.LookupEnv(key); ok { beego.AppConfig.Set(key, value) diff --git a/conf/conf_test.go b/conf/conf_test.go index 24ccdabe7a63..ed9f9a636f35 100644 --- a/conf/conf_test.go +++ b/conf/conf_test.go @@ -32,7 +32,7 @@ func TestGetConfString(t *testing.T) { {"Should be return value", "key", "value"}, } - //do some set up job + // do some set up job os.Setenv("appname", "casbin") os.Setenv("key", "value") @@ -58,7 +58,7 @@ func TestGetConfInt(t *testing.T) { {"Should be return 8000", "verificationCodeTimeout", 10}, } - //do some set up job + // do some set up job os.Setenv("httpport", "8001") err := beego.LoadAppConfig("ini", "app.conf") diff --git a/controllers/auth.go b/controllers/auth.go index e498cbfcae2b..e200f3f450cd 100644 --- a/controllers/auth.go +++ b/controllers/auth.go @@ -44,7 +44,6 @@ func tokenToResponse(token *object.Token) *Response { return &Response{Status: "error", Msg: "fail to get accessToken", Data: token.AccessToken} } return &Response{Status: "ok", Msg: "", Data: token.AccessToken} - } // HandleLoggedIn ... @@ -86,7 +85,7 @@ func (c *ApiController) HandleLoggedIn(application *object.Application, user *ob // The prompt page needs the user to be signed in c.SetSessionUsername(userId) } - } else if form.Type == ResponseTypeToken || form.Type == ResponseTypeIdToken { //implicit flow + } else if form.Type == ResponseTypeToken || form.Type == ResponseTypeIdToken { // implicit flow if !object.IsGrantTypeValid(form.Type, application.GrantTypes) { resp = &Response{Status: "error", Msg: fmt.Sprintf("error: grant_type: %s is not supported in this application", form.Type), Data: ""} } else { @@ -94,7 +93,6 @@ func (c *ApiController) HandleLoggedIn(application *object.Application, user *ob token, _ := object.GetTokenByUser(application, user, scope, c.Ctx.Request.Host) resp = tokenToResponse(token) } - } else if form.Type == ResponseTypeSaml { // saml flow res, redirectUrl, err := object.GetSamlResponse(application, user, form.SamlRequest, c.Ctx.Request.Host) if err != nil { @@ -103,7 +101,7 @@ func (c *ApiController) HandleLoggedIn(application *object.Application, user *ob } resp = &Response{Status: "ok", Msg: "", Data: res, Data2: redirectUrl} } else if form.Type == ResponseTypeCas { - //not oauth but CAS SSO protocol + // not oauth but CAS SSO protocol service := c.Input().Get("service") resp = wrapErrorResponse(nil) if service != "" { @@ -430,7 +428,7 @@ func (c *ApiController) Login() { } else if provider.Category == "SAML" { resp = &Response{Status: "error", Msg: "The account does not exist"} } - //resp = &Response{Status: "ok", Msg: "", Data: res} + // resp = &Response{Status: "ok", Msg: "", Data: res} } else { // form.Method != "signup" userId := c.GetSessionUsername() if userId == "" { diff --git a/controllers/cas.go b/controllers/cas.go index 75595c568481..d6a6a16e2a95 100644 --- a/controllers/cas.go +++ b/controllers/cas.go @@ -44,14 +44,13 @@ func (c *RootController) CasValidate() { return } if ok, response, issuedService, _ := object.GetCasTokenByTicket(ticket); ok { - //check whether service is the one for which we previously issued token + // check whether service is the one for which we previously issued token if issuedService == service { c.Ctx.Output.Body([]byte(fmt.Sprintf("yes\n%s\n", response.User))) return } - } - //token not found + // token not found c.Ctx.Output.Body([]byte("no\n")) } @@ -83,39 +82,39 @@ func (c *RootController) CasP3ServiceAndProxyValidate() { Xmlns: "http://www.yale.edu/tp/cas", } - //check whether all required parameters are met + // check whether all required parameters are met if service == "" || ticket == "" { c.sendCasAuthenticationResponseErr(InvalidRequest, "service and ticket must exist", format) return } ok, response, issuedService, userId := object.GetCasTokenByTicket(ticket) - //find the token + // find the token if ok { - //check whether service is the one for which we previously issued token + // check whether service is the one for which we previously issued token if strings.HasPrefix(service, issuedService) { serviceResponse.Success = response } else { - //service not match + // service not match c.sendCasAuthenticationResponseErr(InvalidService, fmt.Sprintf("service %s and %s does not match", service, issuedService), format) return } } else { - //token not found + // token not found c.sendCasAuthenticationResponseErr(InvalidTicket, fmt.Sprintf("Ticket %s not recognized", ticket), format) return } if pgtUrl != "" && serviceResponse.Failure == nil { - //that means we are in proxy web flow + // that means we are in proxy web flow pgt := object.StoreCasTokenForPgt(serviceResponse.Success, service, userId) pgtiou := serviceResponse.Success.ProxyGrantingTicket - //todo: check whether it is https + // todo: check whether it is https pgtUrlObj, err := url.Parse(pgtUrl) if pgtUrlObj.Scheme != "https" { c.sendCasAuthenticationResponseErr(InvalidProxyCallback, "callback is not https", format) return } - //make a request to pgturl passing pgt and pgtiou + // make a request to pgturl passing pgt and pgtiou if err != nil { c.sendCasAuthenticationResponseErr(InteralError, err.Error(), format) return @@ -133,7 +132,7 @@ func (c *RootController) CasP3ServiceAndProxyValidate() { resp, err := http.DefaultClient.Do(request) if err != nil || !(resp.StatusCode >= 200 && resp.StatusCode < 400) { - //failed to send request + // failed to send request c.sendCasAuthenticationResponseErr(InvalidProxyCallback, err.Error(), format) return } @@ -184,7 +183,6 @@ func (c *RootController) CasProxy() { c.Data["xml"] = serviceResponse c.ServeXML() } - } func (c *RootController) SamlValidate() { diff --git a/controllers/ldap.go b/controllers/ldap.go index 3dec945f79b3..9f715fca470a 100644 --- a/controllers/ldap.go +++ b/controllers/ldap.go @@ -30,7 +30,7 @@ type LdapServer struct { } type LdapResp struct { - //Groups []LdapRespGroup `json:"groups"` + // Groups []LdapRespGroup `json:"groups"` Users []object.LdapRespUser `json:"users"` } @@ -88,7 +88,7 @@ func (c *ApiController) GetLdapUser() { Uid: user.Uid, Cn: user.Cn, GroupId: user.GidNumber, - //GroupName: groupsMap[user.GidNumber].Cn, + // GroupName: groupsMap[user.GidNumber].Cn, Uuid: user.Uuid, Email: util.GetMaxLenStr(user.Mail, user.Email, user.EmailAddress), Phone: util.GetMaxLenStr(user.TelephoneNumber, user.Mobile, user.MobileTelephoneNumber), diff --git a/controllers/provider.go b/controllers/provider.go index 1d0dc76d342e..6959157537e8 100644 --- a/controllers/provider.go +++ b/controllers/provider.go @@ -16,6 +16,7 @@ package controllers import ( "encoding/json" + "github.com/astaxie/beego/utils/pagination" "github.com/casdoor/casdoor/object" "github.com/casdoor/casdoor/util" diff --git a/controllers/syncer.go b/controllers/syncer.go index 6d4fc31c9925..f8b442f5b2b1 100644 --- a/controllers/syncer.go +++ b/controllers/syncer.go @@ -16,6 +16,7 @@ package controllers import ( "encoding/json" + "github.com/astaxie/beego/utils/pagination" "github.com/casdoor/casdoor/object" "github.com/casdoor/casdoor/util" diff --git a/cred/argon2id.go b/cred/argon2id.go index b9c13c4b9b21..089153c17f76 100644 --- a/cred/argon2id.go +++ b/cred/argon2id.go @@ -24,7 +24,6 @@ func NewArgon2idCredManager() *Argon2idCredManager { } func (cm *Argon2idCredManager) GetHashedPassword(password string, userSalt string, organizationSalt string) string { - hash, err := argon2id.CreateHash(password, argon2id.DefaultParams) if err != nil { return "" diff --git a/cred/pbkdf2-salt.go b/cred/pbkdf2-salt.go index c12e2ef21319..3b8df52d533b 100644 --- a/cred/pbkdf2-salt.go +++ b/cred/pbkdf2-salt.go @@ -17,6 +17,7 @@ package cred import ( "crypto/sha256" "encoding/base64" + "golang.org/x/crypto/pbkdf2" ) @@ -36,4 +37,4 @@ func (cm *Pbkdf2SaltCredManager) GetHashedPassword(password string, userSalt str func (cm *Pbkdf2SaltCredManager) IsPasswordCorrect(plainPwd string, hashedPwd string, userSalt string, organizationSalt string) bool { return hashedPwd == cm.GetHashedPassword(plainPwd, userSalt, organizationSalt) -} \ No newline at end of file +} diff --git a/idp/adfs.go b/idp/adfs.go index 6e01fa40cdf3..3cc69a0a7e4e 100644 --- a/idp/adfs.go +++ b/idp/adfs.go @@ -59,12 +59,12 @@ func (idp *AdfsIdProvider) SetHttpClient(client *http.Client) { } func (idp *AdfsIdProvider) getConfig(hostUrl string) *oauth2.Config { - var endpoint = oauth2.Endpoint{ + endpoint := oauth2.Endpoint{ AuthURL: fmt.Sprintf("%s/adfs/oauth2/authorize", hostUrl), TokenURL: fmt.Sprintf("%s/adfs/oauth2/token", hostUrl), } - var config = &oauth2.Config{ + config := &oauth2.Config{ Endpoint: endpoint, } diff --git a/idp/alipay.go b/idp/alipay.go index e918eb8bde99..60d65f30f238 100644 --- a/idp/alipay.go +++ b/idp/alipay.go @@ -56,12 +56,12 @@ func (idp *AlipayIdProvider) SetHttpClient(client *http.Client) { // getConfig return a point of Config, which describes a typical 3-legged OAuth2 flow func (idp *AlipayIdProvider) getConfig(clientId string, clientSecret string, redirectUrl string) *oauth2.Config { - var endpoint = oauth2.Endpoint{ + endpoint := oauth2.Endpoint{ AuthURL: "https://openauth.alipay.com/oauth2/publicAppAuthorize.htm", TokenURL: "https://openapi.alipay.com/gateway.do", } - var config = &oauth2.Config{ + config := &oauth2.Config{ Scopes: []string{"", ""}, Endpoint: endpoint, ClientID: clientId, @@ -206,7 +206,6 @@ func (idp *AlipayIdProvider) postWithBody(body interface{}, targetUrl string) ([ return nil, err } data, err := ioutil.ReadAll(resp.Body) - if err != nil { return nil, err } diff --git a/idp/baidu.go b/idp/baidu.go index f44040b429a1..27bb5772eb1b 100644 --- a/idp/baidu.go +++ b/idp/baidu.go @@ -46,12 +46,12 @@ func (idp *BaiduIdProvider) SetHttpClient(client *http.Client) { } func (idp *BaiduIdProvider) getConfig() *oauth2.Config { - var endpoint = oauth2.Endpoint{ + endpoint := oauth2.Endpoint{ AuthURL: "https://openapi.baidu.com/oauth/2.0/authorize", TokenURL: "https://openapi.baidu.com/oauth/2.0/token", } - var config = &oauth2.Config{ + config := &oauth2.Config{ Scopes: []string{"email"}, Endpoint: endpoint, } diff --git a/idp/bilibili.go b/idp/bilibili.go index c921f5265a45..6cce62159ee6 100644 --- a/idp/bilibili.go +++ b/idp/bilibili.go @@ -47,12 +47,12 @@ func (idp *BilibiliIdProvider) SetHttpClient(client *http.Client) { // getConfig return a point of Config, which describes a typical 3-legged OAuth2 flow func (idp *BilibiliIdProvider) getConfig(clientId string, clientSecret string, redirectUrl string) *oauth2.Config { - var endpoint = oauth2.Endpoint{ + endpoint := oauth2.Endpoint{ TokenURL: "https://api.bilibili.com/x/account-oauth2/v1/token", AuthURL: "http://member.bilibili.com/arcopen/fn/user/account/info", } - var config = &oauth2.Config{ + config := &oauth2.Config{ Scopes: []string{"", ""}, Endpoint: endpoint, ClientID: clientId, @@ -104,7 +104,6 @@ func (idp *BilibiliIdProvider) GetToken(code string) (*oauth2.Token, error) { } data, err := idp.postWithBody(pTokenParams, idp.Config.Endpoint.TokenURL) - if err != nil { return nil, err } @@ -167,7 +166,6 @@ func (idp *BilibiliIdProvider) GetUserInfo(token *oauth2.Token) (*UserInfo, erro userInfoUrl := fmt.Sprintf("%s?%s", idp.Config.Endpoint.AuthURL, params.Encode()) resp, err := idp.Client.Get(userInfoUrl) - if err != nil { return nil, err } diff --git a/idp/casdoor.go b/idp/casdoor.go index 8d91b32a308c..308b435dfaea 100644 --- a/idp/casdoor.go +++ b/idp/casdoor.go @@ -72,7 +72,6 @@ func (idp *CasdoorIdProvider) GetToken(code string) (*oauth2.Token, error) { } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) - if err != nil { return nil, err } @@ -82,7 +81,7 @@ func (idp *CasdoorIdProvider) GetToken(code string) (*oauth2.Token, error) { return nil, err } - //check if token is expired + // check if token is expired if pToken.ExpiresIn <= 0 { return nil, fmt.Errorf("%s", pToken.AccessToken) } @@ -91,7 +90,6 @@ func (idp *CasdoorIdProvider) GetToken(code string) (*oauth2.Token, error) { Expiry: time.Unix(time.Now().Unix()+int64(pToken.ExpiresIn), 0), } return token, nil - } /* @@ -125,7 +123,7 @@ func (idp *CasdoorIdProvider) GetUserInfo(token *oauth2.Token) (*UserInfo, error if err != nil { return nil, err } - //add accesstoken to bearer token + // add accesstoken to bearer token request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", accessToken)) resp, err := idp.Client.Do(request) if err != nil { @@ -155,5 +153,4 @@ func (idp *CasdoorIdProvider) GetUserInfo(token *oauth2.Token) (*UserInfo, error AvatarUrl: cdUserinfo.AvatarUrl, } return userInfo, nil - } diff --git a/idp/custom.go b/idp/custom.go index f523fa747e5f..1c307efef009 100644 --- a/idp/custom.go +++ b/idp/custom.go @@ -36,7 +36,7 @@ func NewCustomIdProvider(clientId string, clientSecret string, redirectUrl strin idp := &CustomIdProvider{} idp.UserInfoUrl = userInfoUrl - var config = &oauth2.Config{ + config := &oauth2.Config{ ClientID: clientId, ClientSecret: clientSecret, RedirectURL: redirectUrl, @@ -76,7 +76,7 @@ func (idp *CustomIdProvider) GetUserInfo(token *oauth2.Token) (*UserInfo, error) if err != nil { return nil, err } - //add accessToken to request header + // add accessToken to request header request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", accessToken)) resp, err := idp.Client.Do(request) if err != nil { diff --git a/idp/dingtalk.go b/idp/dingtalk.go index ff663cd6699b..b79b286b29ec 100644 --- a/idp/dingtalk.go +++ b/idp/dingtalk.go @@ -48,12 +48,12 @@ func (idp *DingTalkIdProvider) SetHttpClient(client *http.Client) { // getConfig return a point of Config, which describes a typical 3-legged OAuth2 flow func (idp *DingTalkIdProvider) getConfig(clientId string, clientSecret string, redirectUrl string) *oauth2.Config { - var endpoint = oauth2.Endpoint{ + endpoint := oauth2.Endpoint{ AuthURL: "https://api.dingtalk.com/v1.0/contact/users/me", TokenURL: "https://api.dingtalk.com/v1.0/oauth2/userAccessToken", } - var config = &oauth2.Config{ + config := &oauth2.Config{ // DingTalk not allow to set scopes,here it is just a placeholder, // convenient to use later Scopes: []string{"", ""}, diff --git a/idp/douyin.go b/idp/douyin.go index bd66d08f760a..fa43e6927358 100644 --- a/idp/douyin.go +++ b/idp/douyin.go @@ -42,12 +42,12 @@ func (idp *DouyinIdProvider) SetHttpClient(client *http.Client) { } func (idp *DouyinIdProvider) getConfig(clientId string, clientSecret string, redirectUrl string) *oauth2.Config { - var endpoint = oauth2.Endpoint{ + endpoint := oauth2.Endpoint{ TokenURL: "https://open.douyin.com/oauth/access_token", AuthURL: "https://open.douyin.com/platform/oauth/connect", } - var config = &oauth2.Config{ + config := &oauth2.Config{ Scopes: []string{"user_info"}, Endpoint: endpoint, ClientID: clientId, diff --git a/idp/facebook.go b/idp/facebook.go index 07d3ec41edd0..622fa465d96c 100644 --- a/idp/facebook.go +++ b/idp/facebook.go @@ -46,11 +46,11 @@ func (idp *FacebookIdProvider) SetHttpClient(client *http.Client) { // getConfig return a point of Config, which describes a typical 3-legged OAuth2 flow func (idp *FacebookIdProvider) getConfig(clientId string, clientSecret string, redirectUrl string) *oauth2.Config { - var endpoint = oauth2.Endpoint{ + endpoint := oauth2.Endpoint{ TokenURL: "https://graph.facebook.com/oauth/access_token", } - var config = &oauth2.Config{ + config := &oauth2.Config{ Scopes: []string{"email,public_profile"}, Endpoint: endpoint, ClientID: clientId, @@ -62,9 +62,9 @@ func (idp *FacebookIdProvider) getConfig(clientId string, clientSecret string, r } type FacebookAccessToken struct { - AccessToken string `json:"access_token"` //Interface call credentials - TokenType string `json:"token_type"` //Access token type - ExpiresIn int64 `json:"expires_in"` //access_token interface call credential timeout time, unit (seconds) + AccessToken string `json:"access_token"` // Interface call credentials + TokenType string `json:"token_type"` // Access token type + ExpiresIn int64 `json:"expires_in"` // access_token interface call credential timeout time, unit (seconds) } type FacebookCheckToken struct { diff --git a/idp/gitee.go b/idp/gitee.go index c7896d24ee6c..af55eb512c1d 100644 --- a/idp/gitee.go +++ b/idp/gitee.go @@ -49,11 +49,11 @@ func (idp *GiteeIdProvider) SetHttpClient(client *http.Client) { // getConfig return a point of Config, which describes a typical 3-legged OAuth2 flow func (idp *GiteeIdProvider) getConfig(clientId string, clientSecret string, redirectUrl string) *oauth2.Config { - var endpoint = oauth2.Endpoint{ + endpoint := oauth2.Endpoint{ TokenURL: "https://gitee.com/oauth/token", } - var config = &oauth2.Config{ + config := &oauth2.Config{ Scopes: []string{"user_info emails"}, Endpoint: endpoint, diff --git a/idp/github.go b/idp/github.go index f2b274a0b763..57e0ad5d111f 100644 --- a/idp/github.go +++ b/idp/github.go @@ -49,12 +49,12 @@ func (idp *GithubIdProvider) SetHttpClient(client *http.Client) { } func (idp *GithubIdProvider) getConfig() *oauth2.Config { - var endpoint = oauth2.Endpoint{ + endpoint := oauth2.Endpoint{ AuthURL: "https://github.com/login/oauth/authorize", TokenURL: "https://github.com/login/oauth/access_token", } - var config = &oauth2.Config{ + config := &oauth2.Config{ Scopes: []string{"user:email", "read:user"}, Endpoint: endpoint, } @@ -93,7 +93,6 @@ func (idp *GithubIdProvider) GetToken(code string) (*oauth2.Token, error) { } return token, nil - } //{ diff --git a/idp/gitlab.go b/idp/gitlab.go index 14ba8bd2bb2f..0d03d2a40a74 100644 --- a/idp/gitlab.go +++ b/idp/gitlab.go @@ -46,11 +46,11 @@ func (idp *GitlabIdProvider) SetHttpClient(client *http.Client) { // getConfig return a point of Config, which describes a typical 3-legged OAuth2 flow func (idp *GitlabIdProvider) getConfig(clientId string, clientSecret string, redirectUrl string) *oauth2.Config { - var endpoint = oauth2.Endpoint{ + endpoint := oauth2.Endpoint{ TokenURL: "https://gitlab.com/oauth/token", } - var config = &oauth2.Config{ + config := &oauth2.Config{ Scopes: []string{"read_user+profile"}, Endpoint: endpoint, ClientID: clientId, diff --git a/idp/google.go b/idp/google.go index d4fbb1e02e9c..604fd8256b3c 100644 --- a/idp/google.go +++ b/idp/google.go @@ -47,12 +47,12 @@ func (idp *GoogleIdProvider) SetHttpClient(client *http.Client) { } func (idp *GoogleIdProvider) getConfig() *oauth2.Config { - var endpoint = oauth2.Endpoint{ + endpoint := oauth2.Endpoint{ AuthURL: "https://accounts.google.com/o/oauth2/auth", TokenURL: "https://accounts.google.com/o/oauth2/token", } - var config = &oauth2.Config{ + config := &oauth2.Config{ Scopes: []string{"profile", "email"}, Endpoint: endpoint, } diff --git a/idp/goth.go b/idp/goth.go index bce99230f085..d40b647bed07 100644 --- a/idp/goth.go +++ b/idp/goth.go @@ -207,7 +207,7 @@ func NewGothIdProvider(providerType string, clientId string, clientSecret string return &idp } -//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 +// 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") idpClient.Set(reflect.ValueOf(client)) @@ -225,8 +225,8 @@ func (idp *GothIdProvider) GetToken(code string) (*oauth2.Token, error) { return nil, err } } else { - //Need to construct variables supported by goth - //to call the function to obtain accessToken + // Need to construct variables supported by goth + // to call the function to obtain accessToken value = url.Values{} value.Add("code", code) } @@ -235,7 +235,7 @@ func (idp *GothIdProvider) GetToken(code string) (*oauth2.Token, error) { return nil, err } - //Get ExpiresAt's value + // Get ExpiresAt's value valueOfExpire := reflect.ValueOf(idp.Session).Elem().FieldByName("ExpiresAt") if valueOfExpire.IsValid() { expireAt = valueOfExpire.Interface().(time.Time) @@ -264,8 +264,8 @@ func getUser(gothUser goth.User, provider string) *UserInfo { Email: gothUser.Email, AvatarUrl: gothUser.AvatarURL, } - //Some idp return an empty Name - //so construct the Name with firstname and lastname or nickname + // Some idp return an empty Name + // so construct the Name with firstname and lastname or nickname if user.Username == "" { if gothUser.FirstName != "" && gothUser.LastName != "" { user.Username = getName(gothUser.FirstName, gothUser.LastName) diff --git a/idp/infoflow_internal.go b/idp/infoflow_internal.go index b7d7f4e84d0a..b896b1079b20 100644 --- a/idp/infoflow_internal.go +++ b/idp/infoflow_internal.go @@ -43,7 +43,7 @@ func (idp *InfoflowInternalIdProvider) SetHttpClient(client *http.Client) { } func (idp *InfoflowInternalIdProvider) getConfig(clientId string, clientSecret string, redirectUrl string) *oauth2.Config { - var config = &oauth2.Config{ + config := &oauth2.Config{ ClientID: clientId, ClientSecret: clientSecret, RedirectURL: redirectUrl, @@ -139,7 +139,7 @@ type InfoflowInternalUserInfo struct { // 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 + // Get userid first accessToken := token.AccessToken code := token.Extra("code").(string) resp, err := idp.Client.Get(fmt.Sprintf("https://qy.im.baidu.com/api/user/getuserinfo?access_token=%s&code=%s&agentid=%s", accessToken, code, idp.AgentId)) @@ -159,7 +159,7 @@ func (idp *InfoflowInternalIdProvider) GetUserInfo(token *oauth2.Token) (*UserIn if userResp.Errcode != 0 { return nil, fmt.Errorf("userIdResp.Errcode = %d, userIdResp.Errmsg = %s", userResp.Errcode, userResp.Errmsg) } - //Use userid and accesstoken to get user information + // Use userid and accesstoken to get user information resp, err = idp.Client.Get(fmt.Sprintf("https://api.im.baidu.com/api/user/get?access_token=%s&userid=%s", accessToken, userResp.UserId)) if err != nil { return nil, err diff --git a/idp/infoflow_third_party.go b/idp/infoflow_third_party.go index 6999f1935931..4d31cb9659cb 100644 --- a/idp/infoflow_third_party.go +++ b/idp/infoflow_third_party.go @@ -47,7 +47,7 @@ func (idp *InfoflowIdProvider) SetHttpClient(client *http.Client) { } func (idp *InfoflowIdProvider) getConfig(clientId string, clientSecret string, redirectUrl string) *oauth2.Config { - var config = &oauth2.Config{ + config := &oauth2.Config{ ClientID: clientId, ClientSecret: clientSecret, RedirectURL: redirectUrl, @@ -136,7 +136,7 @@ type InfoflowUserInfo struct { // 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 + // Get userid first accessToken := token.AccessToken code := token.Extra("code").(string) resp, err := idp.Client.Get(fmt.Sprintf("https://api.im.baidu.com/api/user/getuserinfo?access_token=%s&code=%s&agentid=%s", accessToken, code, idp.AgentId)) @@ -156,7 +156,7 @@ func (idp *InfoflowIdProvider) GetUserInfo(token *oauth2.Token) (*UserInfo, erro if userResp.Errcode != 0 { return nil, fmt.Errorf("userIdResp.Errcode = %d, userIdResp.Errmsg = %s", userResp.Errcode, userResp.Errmsg) } - //Use userid and accesstoken to get user information + // Use userid and accesstoken to get user information resp, err = idp.Client.Get(fmt.Sprintf("https://api.im.baidu.com/api/user/get?access_token=%s&userid=%s", accessToken, userResp.UserId)) if err != nil { return nil, err diff --git a/idp/lark.go b/idp/lark.go index d21fc53e2a9a..61fbd74d37c4 100644 --- a/idp/lark.go +++ b/idp/lark.go @@ -45,11 +45,11 @@ func (idp *LarkIdProvider) SetHttpClient(client *http.Client) { // getConfig return a point of Config, which describes a typical 3-legged OAuth2 flow func (idp *LarkIdProvider) getConfig(clientId string, clientSecret string, redirectUrl string) *oauth2.Config { - var endpoint = oauth2.Endpoint{ + endpoint := oauth2.Endpoint{ TokenURL: "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal", } - var config = &oauth2.Config{ + config := &oauth2.Config{ Scopes: []string{}, Endpoint: endpoint, ClientID: clientId, diff --git a/idp/linkedin.go b/idp/linkedin.go index 60f75432f90c..7442e6c2c154 100644 --- a/idp/linkedin.go +++ b/idp/linkedin.go @@ -47,11 +47,11 @@ func (idp *LinkedInIdProvider) SetHttpClient(client *http.Client) { // getConfig return a point of Config, which describes a typical 3-legged OAuth2 flow func (idp *LinkedInIdProvider) getConfig(clientId string, clientSecret string, redirectUrl string) *oauth2.Config { - var endpoint = oauth2.Endpoint{ + endpoint := oauth2.Endpoint{ TokenURL: "https://www.linkedIn.com/oauth/v2/accessToken", } - var config = &oauth2.Config{ + config := &oauth2.Config{ Scopes: []string{"email,public_profile"}, Endpoint: endpoint, ClientID: clientId, @@ -63,8 +63,8 @@ func (idp *LinkedInIdProvider) getConfig(clientId string, clientSecret string, r } type LinkedInAccessToken struct { - AccessToken string `json:"access_token"` //Interface call credentials - ExpiresIn int64 `json:"expires_in"` //access_token interface call credential timeout time, unit (seconds) + AccessToken string `json:"access_token"` // Interface call credentials + ExpiresIn int64 `json:"expires_in"` // access_token interface call credential timeout time, unit (seconds) } // GetToken use code get access_token (*operation of getting code ought to be done in front) diff --git a/idp/okta.go b/idp/okta.go index 70e60d5bae61..b8dfec50af3f 100644 --- a/idp/okta.go +++ b/idp/okta.go @@ -48,12 +48,12 @@ func (idp *OktaIdProvider) SetHttpClient(client *http.Client) { } func (idp *OktaIdProvider) getConfig(hostUrl string, clientId string, clientSecret string, redirectUrl string) *oauth2.Config { - var endpoint = oauth2.Endpoint{ + endpoint := oauth2.Endpoint{ TokenURL: fmt.Sprintf("%s/v1/token", hostUrl), AuthURL: fmt.Sprintf("%s/v1/authorize", hostUrl), } - var config = &oauth2.Config{ + config := &oauth2.Config{ // openid is required for authentication requests // get more details via: https://developer.okta.com/docs/reference/api/oidc/#reserved-scopes Scopes: []string{"openid", "profile", "email"}, diff --git a/idp/qq.go b/idp/qq.go index e8063a8e7389..b803c3408006 100644 --- a/idp/qq.go +++ b/idp/qq.go @@ -48,11 +48,11 @@ func (idp *QqIdProvider) SetHttpClient(client *http.Client) { } func (idp *QqIdProvider) getConfig() *oauth2.Config { - var endpoint = oauth2.Endpoint{ + endpoint := oauth2.Endpoint{ TokenURL: "https://graph.qq.com/oauth2.0/token", } - var config = &oauth2.Config{ + config := &oauth2.Config{ Scopes: []string{"get_user_info"}, Endpoint: endpoint, } diff --git a/idp/wechat.go b/idp/wechat.go index 727ad7cc9ed4..6e1fe3599366 100644 --- a/idp/wechat.go +++ b/idp/wechat.go @@ -47,11 +47,11 @@ func (idp *WeChatIdProvider) SetHttpClient(client *http.Client) { // getConfig return a point of Config, which describes a typical 3-legged OAuth2 flow func (idp *WeChatIdProvider) getConfig(clientId string, clientSecret string, redirectUrl string) *oauth2.Config { - var endpoint = oauth2.Endpoint{ + endpoint := oauth2.Endpoint{ TokenURL: "https://graph.qq.com/oauth2.0/token", } - var config = &oauth2.Config{ + config := &oauth2.Config{ Scopes: []string{"snsapi_login"}, Endpoint: endpoint, ClientID: clientId, @@ -63,12 +63,12 @@ func (idp *WeChatIdProvider) getConfig(clientId string, clientSecret string, red } type WechatAccessToken struct { - AccessToken string `json:"access_token"` //Interface call credentials - ExpiresIn int64 `json:"expires_in"` //access_token interface call credential timeout time, unit (seconds) - RefreshToken string `json:"refresh_token"` //User refresh access_token - Openid string `json:"openid"` //Unique ID of authorized user - Scope string `json:"scope"` //The scope of user authorization, separated by commas. (,) - Unionid string `json:"unionid"` //This field will appear if and only if the website application has been authorized by the user's UserInfo. + AccessToken string `json:"access_token"` // Interface call credentials + ExpiresIn int64 `json:"expires_in"` // access_token interface call credential timeout time, unit (seconds) + RefreshToken string `json:"refresh_token"` // User refresh access_token + Openid string `json:"openid"` // Unique ID of authorized user + Scope string `json:"scope"` // The scope of user authorization, separated by commas. (,) + Unionid string `json:"unionid"` // This field will appear if and only if the website application has been authorized by the user's UserInfo. } // GetToken use code get access_token (*operation of getting code ought to be done in front) diff --git a/idp/wechat_miniprogram.go b/idp/wechat_miniprogram.go index dd9de6c19b72..ce83bb4dfbb1 100644 --- a/idp/wechat_miniprogram.go +++ b/idp/wechat_miniprogram.go @@ -42,7 +42,7 @@ func (idp *WeChatMiniProgramIdProvider) SetHttpClient(client *http.Client) { } func (idp *WeChatMiniProgramIdProvider) getConfig(clientId string, clientSecret string) *oauth2.Config { - var config = &oauth2.Config{ + config := &oauth2.Config{ ClientID: clientId, ClientSecret: clientSecret, } @@ -78,5 +78,4 @@ func (idp *WeChatMiniProgramIdProvider) GetSessionByCode(code string) (*WeChatMi return nil, fmt.Errorf("err: %s", session.Errmsg) } return &session, nil - } diff --git a/idp/wecom_internal.go b/idp/wecom_internal.go index ee12b0860da3..1a8b511e276a 100644 --- a/idp/wecom_internal.go +++ b/idp/wecom_internal.go @@ -24,7 +24,7 @@ import ( "golang.org/x/oauth2" ) -//This idp is using wecom internal application api as idp +// This idp is using wecom internal application api as idp type WeComInternalIdProvider struct { Client *http.Client Config *oauth2.Config @@ -44,7 +44,7 @@ func (idp *WeComInternalIdProvider) SetHttpClient(client *http.Client) { } func (idp *WeComInternalIdProvider) getConfig(clientId string, clientSecret string, redirectUrl string) *oauth2.Config { - var config = &oauth2.Config{ + config := &oauth2.Config{ ClientID: clientId, ClientSecret: clientSecret, RedirectURL: redirectUrl, @@ -115,7 +115,7 @@ type WecomInternalUserInfo struct { } func (idp *WeComInternalIdProvider) GetUserInfo(token *oauth2.Token) (*UserInfo, error) { - //Get userid first + // Get userid first accessToken := token.AccessToken code := token.Extra("code").(string) resp, err := idp.Client.Get(fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=%s&code=%s", accessToken, code)) @@ -138,7 +138,7 @@ func (idp *WeComInternalIdProvider) GetUserInfo(token *oauth2.Token) (*UserInfo, if userResp.OpenId != "" { return nil, fmt.Errorf("not an internal user") } - //Use userid and accesstoken to get user information + // Use userid and accesstoken to get user information resp, err = idp.Client.Get(fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=%s&userid=%s", accessToken, userResp.UserId)) if err != nil { return nil, err diff --git a/idp/wecom_third_party.go b/idp/wecom_third_party.go index 3f5ac9a2e20c..651fafb5b4a7 100644 --- a/idp/wecom_third_party.go +++ b/idp/wecom_third_party.go @@ -46,11 +46,11 @@ func (idp *WeComIdProvider) SetHttpClient(client *http.Client) { // getConfig return a point of Config, which describes a typical 3-legged OAuth2 flow func (idp *WeComIdProvider) getConfig(clientId string, clientSecret string, redirectUrl string) *oauth2.Config { - var endpoint = oauth2.Endpoint{ + endpoint := oauth2.Endpoint{ TokenURL: "https://graph.qq.com/oauth2.0/token", } - var config = &oauth2.Config{ + config := &oauth2.Config{ Scopes: []string{"snsapi_login"}, Endpoint: endpoint, ClientID: clientId, diff --git a/idp/weibo.go b/idp/weibo.go index fce2fa6de8c8..1a8ce8d2c8dd 100644 --- a/idp/weibo.go +++ b/idp/weibo.go @@ -48,11 +48,11 @@ func (idp *WeiBoIdProvider) SetHttpClient(client *http.Client) { // getConfig return a point of Config, which describes a typical 3-legged OAuth2 flow func (idp *WeiBoIdProvider) getConfig(clientId string, clientSecret string, redirectUrl string) *oauth2.Config { - var endpoint = oauth2.Endpoint{ + endpoint := oauth2.Endpoint{ TokenURL: "https://api.weibo.com/oauth2/access_token", } - var config = &oauth2.Config{ + config := &oauth2.Config{ Scopes: []string{""}, Endpoint: endpoint, ClientID: clientId, diff --git a/main.go b/main.go index 5a6dd032bbae..f565663fc4e1 100644 --- a/main.go +++ b/main.go @@ -42,9 +42,9 @@ func main() { proxy.InitHttpClient() authz.InitAuthz() - util.SafeGoroutine(func() {object.RunSyncUsersJob()}) + util.SafeGoroutine(func() { object.RunSyncUsersJob() }) - //beego.DelStaticPath("/static") + // beego.DelStaticPath("/static") beego.SetStaticPath("/static", "web/build/static") beego.BConfig.WebConfig.DirectoryIndex = true beego.SetStaticPath("/swagger", "swagger") @@ -66,14 +66,14 @@ func main() { beego.BConfig.WebConfig.Session.SessionProviderConfig = conf.GetConfigString("redisEndpoint") } beego.BConfig.WebConfig.Session.SessionCookieLifeTime = 3600 * 24 * 30 - //beego.BConfig.WebConfig.Session.SessionCookieSameSite = http.SameSiteNoneMode + // beego.BConfig.WebConfig.Session.SessionCookieSameSite = http.SameSiteNoneMode err := logs.SetLogger("file", `{"filename":"logs/casdoor.log","maxdays":99999,"perm":"0770"}`) if err != nil { panic(err) } port := beego.AppConfig.DefaultInt("httpport", 8000) - //logs.SetLevel(logs.LevelInformational) + // logs.SetLevel(logs.LevelInformational) logs.SetLogFuncCall(false) beego.Run(fmt.Sprintf(":%v", port)) } diff --git a/object/application.go b/object/application.go index d2e3a2d1e3c2..03e5eab8b983 100644 --- a/object/application.go +++ b/object/application.go @@ -317,7 +317,7 @@ func (application *Application) GetId() string { } func CheckRedirectUriValid(application *Application, redirectUri string) bool { - var validUri = false + validUri := false for _, tmpUri := range application.RedirectUris { if strings.Contains(redirectUri, tmpUri) { validUri = true diff --git a/object/check.go b/object/check.go index f1694e3ccce0..41cb277e3ccc 100644 --- a/object/check.go +++ b/object/check.go @@ -182,7 +182,7 @@ func CheckUserPassword(organization string, username string, password string) (* } if user.Ldap != "" { - //ONLY for ldap users + // ONLY for ldap users return checkLdapUserPassword(user, password) } else { msg := CheckPassword(user, password) diff --git a/object/ldap.go b/object/ldap.go index 670005e595ee..1e08754e2147 100644 --- a/object/ldap.go +++ b/object/ldap.go @@ -56,7 +56,7 @@ type ldapUser struct { Uid string Cn string GidNumber string - //Gcn string + // Gcn string Uuid string Mail string Email string @@ -73,7 +73,7 @@ type LdapRespUser struct { Uid string `json:"uid"` Cn string `json:"cn"` GroupId string `json:"groupId"` - //GroupName string `json:"groupName"` + // GroupName string `json:"groupName"` Uuid string `json:"uuid"` Email string `json:"email"` Phone string `json:"phone"` @@ -208,11 +208,15 @@ func GetLdapConn(host string, port int, adminUser string, adminPasswd string) (* func (l *ldapConn) GetLdapUsers(baseDn string) ([]ldapUser, error) { SearchFilter := "(objectClass=posixAccount)" - SearchAttributes := []string{"uidNumber", "uid", "cn", "gidNumber", "entryUUID", "mail", "email", - "emailAddress", "telephoneNumber", "mobile", "mobileTelephoneNumber", "registeredAddress", "postalAddress"} + SearchAttributes := []string{ + "uidNumber", "uid", "cn", "gidNumber", "entryUUID", "mail", "email", + "emailAddress", "telephoneNumber", "mobile", "mobileTelephoneNumber", "registeredAddress", "postalAddress", + } SearchFilterMsAD := "(objectClass=user)" - SearchAttributesMsAD := []string{"uidNumber", "sAMAccountName", "cn", "gidNumber", "entryUUID", "mail", "email", - "emailAddress", "telephoneNumber", "mobile", "mobileTelephoneNumber", "registeredAddress", "postalAddress"} + SearchAttributesMsAD := []string{ + "uidNumber", "sAMAccountName", "cn", "gidNumber", "entryUUID", "mail", "email", + "emailAddress", "telephoneNumber", "mobile", "mobileTelephoneNumber", "registeredAddress", "postalAddress", + } var searchReq *goldap.SearchRequest if l.IsAD { searchReq = goldap.NewSearchRequest(baseDn, @@ -459,7 +463,7 @@ func CheckLdapUuidExist(owner string, uuids []string) []string { } } - for uuid, _ := range existUuidSet { + for uuid := range existUuidSet { existUuids = append(existUuids, uuid) } return existUuids diff --git a/object/ldap_autosync.go b/object/ldap_autosync.go index 164df166a7c6..46e6ec25d3fe 100644 --- a/object/ldap_autosync.go +++ b/object/ldap_autosync.go @@ -31,7 +31,7 @@ func GetLdapAutoSynchronizer() *LdapAutoSynchronizer { return globalLdapAutoSynchronizer } -//start autosync for specified ldap, old existing autosync goroutine will be ceased +// start autosync for specified ldap, old existing autosync goroutine will be ceased func (l *LdapAutoSynchronizer) StartAutoSync(ldapId string) error { l.Lock() defer l.Unlock() @@ -48,7 +48,7 @@ func (l *LdapAutoSynchronizer) StartAutoSync(ldapId string) error { stopChan := make(chan struct{}) l.ldapIdToStopChan[ldapId] = stopChan logs.Info(fmt.Sprintf("autoSync started for %s", ldap.Id)) - util.SafeGoroutine(func() {l.syncRoutine(ldap, stopChan)}) + util.SafeGoroutine(func() { l.syncRoutine(ldap, stopChan) }) return nil } @@ -61,7 +61,7 @@ func (l *LdapAutoSynchronizer) StopAutoSync(ldapId string) { } } -//autosync goroutine +// autosync goroutine func (l *LdapAutoSynchronizer) syncRoutine(ldap *Ldap, stopChan chan struct{}) { ticker := time.NewTicker(time.Duration(ldap.AutoSync) * time.Minute) defer ticker.Stop() @@ -74,7 +74,7 @@ func (l *LdapAutoSynchronizer) syncRoutine(ldap *Ldap, stopChan chan struct{}) { } UpdateLdapSyncTime(ldap.Id) - //fetch all users + // fetch all users conn, err := GetLdapConn(ldap.Host, ldap.Port, ldap.Admin, ldap.Passwd) if err != nil { logs.Warning(fmt.Sprintf("autoSync failed for %s, error %s", ldap.Id, err)) @@ -93,10 +93,9 @@ func (l *LdapAutoSynchronizer) syncRoutine(ldap *Ldap, stopChan chan struct{}) { logs.Info(fmt.Sprintf("ldap autosync success, %d new users, %d existing users", len(users)-len(*existed), len(*existed))) } } - } -//start all autosync goroutine for existing ldap servers in each organizations +// start all autosync goroutine for existing ldap servers in each organizations func (l *LdapAutoSynchronizer) LdapAutoSynchronizerStartUpAll() { organizations := []*Organization{} err := adapter.Engine.Desc("created_time").Find(&organizations) diff --git a/object/model.go b/object/model.go index 1a8a9c817dd6..b04872fc3274 100644 --- a/object/model.go +++ b/object/model.go @@ -27,8 +27,8 @@ type Model struct { CreatedTime string `xorm:"varchar(100)" json:"createdTime"` DisplayName string `xorm:"varchar(100)" json:"displayName"` - ModelText string `xorm:"mediumtext" json:"modelText"` - IsEnabled bool `json:"isEnabled"` + ModelText string `xorm:"mediumtext" json:"modelText"` + IsEnabled bool `json:"isEnabled"` } func GetModelCount(owner, field, value string) int { diff --git a/object/oidc_discovery.go b/object/oidc_discovery.go index b9f2d54e8d96..456cc47e3e60 100644 --- a/object/oidc_discovery.go +++ b/object/oidc_discovery.go @@ -93,9 +93,9 @@ func GetOidcDiscovery(host string) OidcDiscovery { func GetJsonWebKeySet() (jose.JSONWebKeySet, error) { certs := GetCerts("admin") jwks := jose.JSONWebKeySet{} - //follows the protocol rfc 7517(draft) - //link here: https://self-issued.info/docs/draft-ietf-jose-json-web-key.html - //or https://datatracker.ietf.org/doc/html/draft-ietf-jose-json-web-key + // follows the protocol rfc 7517(draft) + // link here: https://self-issued.info/docs/draft-ietf-jose-json-web-key.html + // or https://datatracker.ietf.org/doc/html/draft-ietf-jose-json-web-key for _, cert := range certs { certPemBlock := []byte(cert.Certificate) certDerBlock, _ := pem.Decode(certPemBlock) diff --git a/object/record.go b/object/record.go index 01d454d62532..6f0b440c4b32 100644 --- a/object/record.go +++ b/object/record.go @@ -29,7 +29,7 @@ func init() { var err error logPostOnly, err = conf.GetConfigBool("logPostOnly") if err != nil { - //panic(err) + // panic(err) } } diff --git a/object/resource.go b/object/resource.go index 914ceeb87dfb..8d605444d9a6 100644 --- a/object/resource.go +++ b/object/resource.go @@ -110,7 +110,7 @@ func UpdateResource(id string, resource *Resource) bool { panic(err) } - //return affected != 0 + // return affected != 0 return true } diff --git a/object/saml_idp.go b/object/saml_idp.go index 3b276c141f2f..1576202118cc 100644 --- a/object/saml_idp.go +++ b/object/saml_idp.go @@ -35,7 +35,7 @@ import ( uuid "github.com/satori/go.uuid" ) -//returns a saml2 response +// 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{ Space: "samlp", @@ -100,7 +100,6 @@ func NewSamlResponse(user *User, host string, certificate string, destination st displayName.CreateElement("saml:AttributeValue").CreateAttr("xsi:type", "xs:string").Element().SetText(user.DisplayName) return samlResponse, nil - } type X509Key struct { @@ -114,7 +113,7 @@ func (x X509Key) GetKeyPair() (privateKey *rsa.PrivateKey, cert []byte, err erro return privateKey, cert, err } -//SAML METADATA +// SAML METADATA type IdpEntityDescriptor struct { XMLName xml.Name `xml:"EntityDescriptor"` DS string `xml:"xmlns:ds,attr"` @@ -299,7 +298,7 @@ func NewSamlResponse11(user *User, requestID string, host string) *etree.Element Space: "samlp", Tag: "Response", } - //create samlresponse + // create samlresponse samlResponse.CreateAttr("xmlns:samlp", "urn:oasis:names:tc:SAML:1.0:protocol") samlResponse.CreateAttr("MajorVersion", "1") samlResponse.CreateAttr("MinorVersion", "1") @@ -315,7 +314,7 @@ func NewSamlResponse11(user *User, requestID string, host string) *etree.Element samlResponse.CreateElement("samlp:Status").CreateElement("samlp:StatusCode").CreateAttr("Value", "samlp:Success") - //create assertion which is inside the response + // create assertion which is inside the response assertion := samlResponse.CreateElement("saml:Assertion") assertion.CreateAttr("xmlns:saml", "urn:oasis:names:tc:SAML:1.0:assertion") assertion.CreateAttr("MajorVersion", "1") @@ -328,19 +327,19 @@ func NewSamlResponse11(user *User, requestID string, host string) *etree.Element condition.CreateAttr("NotBefore", now) condition.CreateAttr("NotOnOrAfter", expireTime) - //AuthenticationStatement inside assertion + // AuthenticationStatement inside assertion authenticationStatement := assertion.CreateElement("saml:AuthenticationStatement") authenticationStatement.CreateAttr("AuthenticationMethod", "urn:oasis:names:tc:SAML:1.0:am:password") authenticationStatement.CreateAttr("AuthenticationInstant", now) - //subject inside AuthenticationStatement + // subject inside AuthenticationStatement subject := assertion.CreateElement("saml:Subject") - //nameIdentifier inside subject + // nameIdentifier inside subject nameIdentifier := subject.CreateElement("saml:NameIdentifier") - //nameIdentifier.CreateAttr("Format", "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress") + // nameIdentifier.CreateAttr("Format", "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress") nameIdentifier.SetText(user.Name) - //subjectConfirmation inside subject + // subjectConfirmation inside subject subjectConfirmation := subject.CreateElement("saml:SubjectConfirmation") subjectConfirmation.CreateElement("saml:ConfirmationMethod").SetText("urn:oasis:names:tc:SAML:1.0:cm:artifact") diff --git a/object/storage.go b/object/storage.go index b2caf234feaa..d1e877541cca 100644 --- a/object/storage.go +++ b/object/storage.go @@ -31,7 +31,7 @@ func init() { var err error isCloudIntranet, err = conf.GetConfigBool("isCloudIntranet") if err != nil { - //panic(err) + // panic(err) } } diff --git a/object/token.go b/object/token.go index 6704474910e6..ee3b5f3d8802 100644 --- a/object/token.go +++ b/object/token.go @@ -220,7 +220,7 @@ func DeleteTokenByAceessToken(accessToken string) (bool, *Application) { } func GetTokenByAccessToken(accessToken string) *Token { - //Check if the accessToken is in the database + // Check if the accessToken is in the database token := Token{AccessToken: accessToken} existed, err := adapter.Engine.Get(&token) if err != nil || !existed { @@ -330,7 +330,7 @@ func GetOAuthToken(grantType string, clientId string, clientSecret string, code } } - //Check if grantType is allowed in the current application + // Check if grantType is allowed in the current application if !IsGrantTypeValid(grantType, application.GrantTypes) && tag == "" { return &TokenError{ @@ -688,7 +688,7 @@ func GetWechatMiniProgramToken(application *Application, code string, host strin ErrorDescription: "the application does not allow to sign up new account", } } - //Add new user + // Add new user var name string if username != "" { name = username @@ -729,7 +729,7 @@ func GetWechatMiniProgramToken(application *Application, code string, host strin Application: application.Name, Organization: user.Owner, User: user.Name, - Code: session.SessionKey, //a trick, because miniprogram does not use the code, so use the code field to save the session_key + Code: session.SessionKey, // a trick, because miniprogram does not use the code, so use the code field to save the session_key AccessToken: accessToken, RefreshToken: refreshToken, ExpiresIn: application.ExpireInHours * 60, diff --git a/object/token_cas.go b/object/token_cas.go index 04b9a48cf53b..cf28b39d3d02 100644 --- a/object/token_cas.go +++ b/object/token_cas.go @@ -88,7 +88,7 @@ type CasAnyAttribute struct { type CasAuthenticationSuccessWrapper struct { AuthenticationSuccess *CasAuthenticationSuccess // the token we issued - Service string //to which service this token is issued + Service string // to which service this token is issued UserId string } @@ -116,10 +116,10 @@ type Saml11AssertionArtifact struct { InnerXML string `xml:",innerxml"` } -//st is short for service ticket +// st is short for service ticket var stToServiceResponse sync.Map -//pgt is short for proxy granting ticket +// pgt is short for proxy granting ticket var pgtToServiceResponse sync.Map func StoreCasTokenForPgt(token *CasAuthenticationSuccess, service, userId string) string { @@ -262,12 +262,11 @@ func GetValidationBySaml(samlRequest string, host string) (string, string, error return "", "", fmt.Errorf("err: %s", err.Error()) } return xmlStr, service, nil - } func (c *CasAuthenticationSuccess) DeepCopy() CasAuthenticationSuccess { res := *c - //copy proxy + // copy proxy if c.Proxies != nil { tmp := c.Proxies.DeepCopy() res.Proxies = &tmp @@ -307,7 +306,6 @@ func (c *CasAttributes) DeepCopy() CasAttributes { res.ExtraAttributes[i] = &tmp } return res - } func (c *CasUserAttributes) DeepCopy() CasUserAttributes { @@ -316,11 +314,11 @@ func (c *CasUserAttributes) DeepCopy() CasUserAttributes { Attributes: make([]*CasNamedAttribute, len(c.Attributes)), } for i, a := range c.AnyAttributes { - var tmp = *a + tmp := *a res.AnyAttributes[i] = &tmp } for i, a := range c.Attributes { - var tmp = *a + tmp := *a res.Attributes[i] = &tmp } return res diff --git a/pp/alipay.go b/pp/alipay.go index 05b3b2f1ae8e..326e3a79abca 100644 --- a/pp/alipay.go +++ b/pp/alipay.go @@ -46,7 +46,7 @@ func NewAlipayPaymentProvider(appId string, appCertificate string, appPrivateKey } func (pp *AlipayPaymentProvider) Pay(providerName string, productName string, payerName string, paymentName string, productDisplayName string, price float64, returnUrl string, notifyUrl string) (string, error) { - //pp.Client.DebugSwitch = gopay.DebugOn + // pp.Client.DebugSwitch = gopay.DebugOn bm := gopay.BodyMap{} diff --git a/proxy/proxy.go b/proxy/proxy.go index ff89b1ae5de9..9069f8ccbacb 100644 --- a/proxy/proxy.go +++ b/proxy/proxy.go @@ -25,8 +25,10 @@ import ( "golang.org/x/net/proxy" ) -var DefaultHttpClient *http.Client -var ProxyHttpClient *http.Client +var ( + DefaultHttpClient *http.Client + ProxyHttpClient *http.Client +) func InitHttpClient() { // not use proxy diff --git a/routers/authz_filter.go b/routers/authz_filter.go index d3a7b4166d3e..031c22513448 100644 --- a/routers/authz_filter.go +++ b/routers/authz_filter.go @@ -78,7 +78,7 @@ func getObject(ctx *context.Context) (string, string) { var obj Object err := json.Unmarshal(body, &obj) if err != nil { - //panic(err) + // panic(err) return "", "" } diff --git a/routers/auto_signin_filter.go b/routers/auto_signin_filter.go index bc65f6ce405e..bbe863128f94 100644 --- a/routers/auto_signin_filter.go +++ b/routers/auto_signin_filter.go @@ -71,5 +71,4 @@ func AutoSigninFilter(ctx *context.Context) { setSessionUser(ctx, userId) return } - } diff --git a/routers/router.go b/routers/router.go index b3a7c29261f5..2a963795d2ba 100644 --- a/routers/router.go +++ b/routers/router.go @@ -30,19 +30,18 @@ func init() { } func initAPI() { - ns := - beego.NewNamespace("/", - beego.NSNamespace("/api", - beego.NSInclude( - &controllers.ApiController{}, - ), + ns := beego.NewNamespace("/", + beego.NSNamespace("/api", + beego.NSInclude( + &controllers.ApiController{}, ), - beego.NSNamespace("", - beego.NSInclude( - &controllers.RootController{}, - ), + ), + beego.NSNamespace("", + beego.NSInclude( + &controllers.RootController{}, ), - ) + ), + ) beego.AddNamespace(ns) beego.Router("/api/signup", &controllers.ApiController{}, "POST:Signup") @@ -195,5 +194,4 @@ func initAPI() { beego.Router("/api/webauthn/signup/finish", &controllers.ApiController{}, "Post:WebAuthnSignupFinish") beego.Router("/api/webauthn/signin/begin", &controllers.ApiController{}, "Get:WebAuthnSigninBegin") beego.Router("/api/webauthn/signin/finish", &controllers.ApiController{}, "Post:WebAuthnSigninFinish") - } diff --git a/util/log.go b/util/log.go index 1a60f92e3b08..5e99f9873320 100644 --- a/util/log.go +++ b/util/log.go @@ -32,7 +32,7 @@ func GetIPInfo(clientIP string) string { res := "" for i := range ips { ip := strings.TrimSpace(ips[i]) - //desc := GetDescFromIP(ip) + // desc := GetDescFromIP(ip) ipstr := fmt.Sprintf("%s: %s", ip, "") if i != len(ips)-1 { res += ipstr + " -> " diff --git a/util/regex.go b/util/regex.go index fdb6ef2424a4..bceaedb15c1a 100644 --- a/util/regex.go +++ b/util/regex.go @@ -19,8 +19,10 @@ import ( "regexp" ) -var rePhoneCn *regexp.Regexp -var rePhone *regexp.Regexp +var ( + rePhoneCn *regexp.Regexp + rePhone *regexp.Regexp +) func init() { // https://learnku.com/articles/31543 diff --git a/util/string.go b/util/string.go index 8f6019231231..076f1c627c04 100644 --- a/util/string.go +++ b/util/string.go @@ -69,7 +69,7 @@ func BoolToString(b bool) string { return "0" } -//CamelToSnakeCase This function transform camelcase in snakecase LoremIpsum in lorem_ipsum +// CamelToSnakeCase This function transform camelcase in snakecase LoremIpsum in lorem_ipsum func CamelToSnakeCase(camel string) string { var buf bytes.Buffer for _, c := range camel { @@ -177,7 +177,7 @@ func ReadStringFromPath(path string) string { } func WriteStringToPath(s string, path string) { - err := ioutil.WriteFile(path, []byte(s), 0644) + err := ioutil.WriteFile(path, []byte(s), 0o644) if err != nil { panic(err) } diff --git a/util/string_test.go b/util/string_test.go index 2af356bd0116..143d6fc90da1 100644 --- a/util/string_test.go +++ b/util/string_test.go @@ -15,9 +15,10 @@ package util import ( + "testing" + "github.com/google/uuid" "github.com/stretchr/testify/assert" - "testing" ) func TestParseInt(t *testing.T) { @@ -245,4 +246,3 @@ func TestSnakeString(t *testing.T) { }) } } - diff --git a/util/time_test.go b/util/time_test.go index 5736a924c5f3..801b60d784fe 100644 --- a/util/time_test.go +++ b/util/time_test.go @@ -31,7 +31,6 @@ func Test_GetCurrentTime(t *testing.T) { types := reflect.TypeOf(test).Kind() assert.Equal(t, types, reflect.String, "GetCurrentUnixTime should be return string") - } func Test_GetCurrentUnixTime_Shoud_Return_String(t *testing.T) { @@ -41,7 +40,6 @@ func Test_GetCurrentUnixTime_Shoud_Return_String(t *testing.T) { } func Test_IsTokenExpired(t *testing.T) { - type input struct { createdTime string expiresIn int