Best Testkube code snippet using client.Abort
authenticator.go
Source:authenticator.go
...136 _ = oauth2.WriteBearerError(w, oauth2.ServerError(""))137 })138 // parse bearer token139 tk, err := oauth2.ParseBearerToken(r)140 xo.AbortIf(err)141 // parse token142 key, err := a.policy.Verify(rcx, tk)143 if heat.ErrExpiredToken.Is(err) {144 xo.Abort(oauth2.InvalidToken("expired bearer token"))145 } else if err != nil {146 xo.Abort(oauth2.InvalidToken("malformed bearer token"))147 }148 // prepare context149 ctx := &Context{150 Context: rcx,151 Request: r,152 writer: w,153 Tracer: tracer,154 }155 // get token156 accessToken := a.getToken(ctx, key.Base.ID)157 if accessToken == nil {158 xo.Abort(oauth2.InvalidToken("unknown bearer token"))159 }160 // get token data161 data := accessToken.GetTokenData()162 // validate token type163 if data.Type != AccessToken {164 xo.Abort(oauth2.InvalidToken("invalid bearer token type"))165 }166 // validate expiration167 if data.ExpiresAt.Before(time.Now()) {168 xo.Abort(oauth2.InvalidToken("expired access token"))169 }170 // validate scope171 if !data.Scope.Includes(scope) {172 xo.Abort(oauth2.InsufficientScope(scope))173 }174 // create new context with access token175 rcx = context.WithValue(rcx, AccessTokenContextKey, accessToken)176 // call next handler if client should not be loaded177 if !loadClient {178 // call next handler179 next.ServeHTTP(w, r.WithContext(rcx))180 return181 }182 // get client183 client := a.getFirstClient(ctx, data.ClientID)184 if client == nil {185 xo.Abort(xo.F("missing client"))186 }187 // create new context with client188 rcx = context.WithValue(rcx, ClientContextKey, client)189 // call next handler if resource owner does not exist or should not190 // be loaded191 if data.ResourceOwnerID == nil || !loadResourceOwner {192 // call next handler193 next.ServeHTTP(w, r.WithContext(rcx))194 return195 }196 // get resource owner197 resourceOwner := a.getFirstResourceOwner(ctx, client, *data.ResourceOwnerID)198 if resourceOwner == nil {199 xo.Abort(oauth2.InvalidToken("missing resource owner"))200 }201 // create new context with resource owner202 rcx = context.WithValue(rcx, ResourceOwnerContextKey, resourceOwner)203 // call next handler204 next.ServeHTTP(w, r.WithContext(rcx))205 })206 }207}208func (a *Authenticator) authorizationEndpoint(ctx *Context) {209 // trace210 ctx.Tracer.Push("flame/Authenticator.authorizationEndpoint")211 defer ctx.Tracer.Pop()212 // parse authorization request213 req, err := oauth2.ParseAuthorizationRequest(ctx.Request)214 xo.AbortIf(err)215 // make sure the response type is known216 if !oauth2.KnownResponseType(req.ResponseType) {217 xo.Abort(oauth2.InvalidRequest("unknown response type"))218 }219 // get client220 client := a.findFirstClient(ctx, req.ClientID)221 if client == nil {222 xo.Abort(oauth2.InvalidClient("unknown client"))223 }224 // validate redirect URI225 req.RedirectURI, err = a.policy.RedirectURIValidator(ctx, client, req.RedirectURI)226 if ErrInvalidRedirectURI.Is(err) {227 xo.Abort(oauth2.InvalidRequest("invalid redirect uri"))228 } else if err != nil {229 xo.Abort(err)230 }231 // get grants232 ctx.grants, err = a.policy.Grants(ctx, client)233 xo.AbortIf(err)234 /* client is valid */235 // validate response type236 if req.ResponseType == oauth2.TokenResponseType && !ctx.grants.Implicit {237 xo.Abort(oauth2.UnsupportedResponseType(""))238 } else if req.ResponseType == oauth2.CodeResponseType && !ctx.grants.AuthorizationCode {239 xo.Abort(oauth2.UnsupportedResponseType(""))240 }241 // prepare abort method242 abort := func(err *oauth2.Error) {243 xo.Abort(err.SetRedirect(req.RedirectURI, req.State, req.ResponseType == oauth2.TokenResponseType))244 }245 // check request method246 if ctx.Request.Method == "GET" {247 // get approval url248 url, err := a.policy.ApprovalURL(ctx, client)249 if err != nil {250 xo.Abort(err)251 } else if url == "" {252 abort(oauth2.InvalidRequest("unsupported request method"))253 }254 // prepare params255 params := map[string]string{}256 for name, values := range ctx.Request.URL.Query() {257 params[name] = values[0]258 }259 // perform redirect260 xo.AbortIf(oauth2.WriteRedirect(ctx.writer, url, params, false))261 return262 }263 // get access token264 token := ctx.Request.Form.Get("access_token")265 if token == "" {266 abort(oauth2.AccessDenied("missing access token"))267 }268 // parse token269 key, err := a.policy.Verify(ctx, token)270 if heat.ErrExpiredToken.Is(err) {271 abort(oauth2.AccessDenied("expired access token"))272 } else if err != nil {273 abort(oauth2.AccessDenied("invalid access token"))274 }275 // get token276 accessToken := a.getToken(ctx, key.Base.ID)277 if accessToken == nil {278 abort(oauth2.AccessDenied("unknown access token"))279 }280 // get token data281 data := accessToken.GetTokenData()282 // validate token type283 if data.Type != AccessToken {284 abort(oauth2.AccessDenied("invalid access token type"))285 }286 // validate expiration287 if data.ExpiresAt.Before(time.Now()) {288 abort(oauth2.AccessDenied("expired access token"))289 }290 // check resource owner291 if data.ResourceOwnerID == nil {292 abort(oauth2.AccessDenied("missing resource owner"))293 }294 // get resource owner295 resourceOwner := a.getFirstResourceOwner(ctx, client, *data.ResourceOwnerID)296 if resourceOwner == nil {297 abort(oauth2.AccessDenied("unknown resource owner"))298 }299 // validate & grant scope300 scope, err := a.policy.ApproveStrategy(ctx, client, resourceOwner, accessToken, req.Scope)301 if ErrApprovalRejected.Is(err) {302 abort(oauth2.AccessDenied("approval rejected"))303 } else if ErrInvalidScope.Is(err) {304 abort(oauth2.InvalidScope(""))305 } else if err != nil {306 xo.Abort(err)307 }308 // triage based on response type309 switch req.ResponseType {310 case oauth2.TokenResponseType:311 // issue access token312 res := a.issueTokens(ctx, false, scope, req.RedirectURI, client, resourceOwner)313 res.SetRedirect(req.RedirectURI, req.State)314 // write response315 xo.AbortIf(oauth2.WriteTokenResponse(ctx.writer, res))316 case oauth2.CodeResponseType:317 // issue authorization code318 res := a.issueCode(ctx, scope, req.RedirectURI, client, resourceOwner)319 res.State = req.State320 // write response321 xo.AbortIf(oauth2.WriteCodeResponse(ctx.writer, res))322 }323}324func (a *Authenticator) tokenEndpoint(ctx *Context) {325 // trace326 ctx.Tracer.Push("flame/Authenticator.tokenEndpoint")327 defer ctx.Tracer.Pop()328 // parse token request329 req, err := oauth2.ParseTokenRequest(ctx.Request)330 xo.AbortIf(err)331 // make sure the grant type is known332 if !oauth2.KnownGrantType(req.GrantType) {333 xo.Abort(oauth2.InvalidRequest("unknown grant type"))334 }335 // get client336 client := a.findFirstClient(ctx, req.ClientID)337 if client == nil {338 xo.Abort(oauth2.InvalidClient("unknown client"))339 }340 // get grants341 ctx.grants, err = a.policy.Grants(ctx, client)342 xo.AbortIf(err)343 // handle grant type344 switch req.GrantType {345 case oauth2.PasswordGrantType:346 // check availability347 if !ctx.grants.Password {348 xo.Abort(oauth2.UnsupportedGrantType(""))349 }350 // handle resource owner password credentials grant351 a.handleResourceOwnerPasswordCredentialsGrant(ctx, req, client)352 case oauth2.ClientCredentialsGrantType:353 // check availability354 if !ctx.grants.ClientCredentials {355 xo.Abort(oauth2.UnsupportedGrantType(""))356 }357 // handle client credentials grant358 a.handleClientCredentialsGrant(ctx, req, client)359 case oauth2.RefreshTokenGrantType:360 // check availability361 if !ctx.grants.RefreshToken {362 xo.Abort(oauth2.UnsupportedGrantType(""))363 }364 // handle refresh token grant365 a.handleRefreshTokenGrant(ctx, req, client)366 case oauth2.AuthorizationCodeGrantType:367 // check availability368 if !ctx.grants.AuthorizationCode {369 xo.Abort(oauth2.UnsupportedGrantType(""))370 }371 // handle authorization code grant372 a.handleAuthorizationCodeGrant(ctx, req, client)373 }374}375func (a *Authenticator) handleResourceOwnerPasswordCredentialsGrant(ctx *Context, req *oauth2.TokenRequest, client Client) {376 // trace377 ctx.Tracer.Push("flame/Authenticator.handleResourceOwnerPasswordCredentialsGrant")378 defer ctx.Tracer.Pop()379 // authenticate client if confidential380 if client.IsConfidential() && !client.ValidSecret(req.ClientSecret) {381 xo.Abort(oauth2.InvalidClient("unknown client"))382 }383 // get resource owner384 resourceOwner := a.findFirstResourceOwner(ctx, client, req.Username)385 if resourceOwner == nil {386 xo.Abort(oauth2.AccessDenied("")) // never expose reason!387 }388 // authenticate resource owner389 if !resourceOwner.ValidPassword(req.Password) {390 xo.Abort(oauth2.AccessDenied("")) // never expose reason!391 }392 // validate & grant scope393 scope, err := a.policy.GrantStrategy(ctx, client, resourceOwner, req.Scope)394 if ErrGrantRejected.Is(err) {395 xo.Abort(oauth2.AccessDenied("")) // never expose reason!396 } else if ErrInvalidScope.Is(err) {397 xo.Abort(oauth2.InvalidScope(""))398 } else if err != nil {399 xo.Abort(err)400 }401 // issue access token402 res := a.issueTokens(ctx, true, scope, "", client, resourceOwner)403 // write response404 xo.AbortIf(oauth2.WriteTokenResponse(ctx.writer, res))405}406func (a *Authenticator) handleClientCredentialsGrant(ctx *Context, req *oauth2.TokenRequest, client Client) {407 // trace408 ctx.Tracer.Push("flame/Authenticator.handleClientCredentialsGrant")409 defer ctx.Tracer.Pop()410 // check confidentiality411 if !client.IsConfidential() {412 xo.Abort(oauth2.InvalidClient("non confidential client"))413 }414 // authenticate client415 if !client.ValidSecret(req.ClientSecret) {416 xo.Abort(oauth2.InvalidClient("unknown client"))417 }418 // validate & grant scope419 scope, err := a.policy.GrantStrategy(ctx, client, nil, req.Scope)420 if ErrGrantRejected.Is(err) {421 xo.Abort(oauth2.AccessDenied("grant rejected"))422 } else if ErrInvalidScope.Is(err) {423 xo.Abort(oauth2.InvalidScope(""))424 } else if err != nil {425 xo.Abort(err)426 }427 // issue access token428 res := a.issueTokens(ctx, true, scope, "", client, nil)429 // write response430 xo.AbortIf(oauth2.WriteTokenResponse(ctx.writer, res))431}432func (a *Authenticator) handleRefreshTokenGrant(ctx *Context, req *oauth2.TokenRequest, client Client) {433 // trace434 ctx.Tracer.Push("flame/Authenticator.handleRefreshTokenGrant")435 defer ctx.Tracer.Pop()436 // authenticate client if confidential437 if client.IsConfidential() && !client.ValidSecret(req.ClientSecret) {438 xo.Abort(oauth2.InvalidClient("unknown client"))439 }440 // parse token441 key, err := a.policy.Verify(ctx, req.RefreshToken)442 if heat.ErrExpiredToken.Is(err) {443 xo.Abort(oauth2.InvalidGrant("expired refresh token"))444 } else if err != nil {445 xo.Abort(oauth2.InvalidRequest("malformed refresh token"))446 }447 // get stored refresh token by signature448 rt := a.getToken(ctx, key.Base.ID)449 if rt == nil {450 xo.Abort(oauth2.InvalidGrant("unknown refresh token"))451 }452 // get token data453 data := rt.GetTokenData()454 // validate type455 if data.Type != RefreshToken {456 xo.Abort(oauth2.InvalidGrant("invalid refresh token type"))457 }458 // validate expiration459 if data.ExpiresAt.Before(time.Now()) {460 xo.Abort(oauth2.InvalidGrant("expired refresh token"))461 }462 // validate ownership463 if data.ClientID != client.ID() {464 xo.Abort(oauth2.InvalidGrant("invalid refresh token ownership"))465 }466 // inherit scope from stored refresh token467 if req.Scope.Empty() {468 req.Scope = data.Scope469 }470 // validate scope - a missing scope is always included471 if !data.Scope.Includes(req.Scope) {472 xo.Abort(oauth2.InvalidScope("scope exceeds the originally granted scope"))473 }474 // get resource owner475 var ro ResourceOwner476 if data.ResourceOwnerID != nil {477 ro = a.getFirstResourceOwner(ctx, client, *data.ResourceOwnerID)478 }479 // issue tokens480 res := a.issueTokens(ctx, true, req.Scope, data.RedirectURI, client, ro)481 // delete refresh token482 a.deleteToken(ctx, rt.ID())483 // write response484 xo.AbortIf(oauth2.WriteTokenResponse(ctx.writer, res))485}486func (a *Authenticator) handleAuthorizationCodeGrant(ctx *Context, req *oauth2.TokenRequest, client Client) {487 // trace488 ctx.Tracer.Push("flame/Authenticator.handleAuthorizationCodeGrant")489 defer ctx.Tracer.Pop()490 // authenticate client if confidential491 if client.IsConfidential() && !client.ValidSecret(req.ClientSecret) {492 xo.Abort(oauth2.InvalidClient("unknown client"))493 }494 // parse authorization code495 key, err := a.policy.Verify(ctx, req.Code)496 if heat.ErrExpiredToken.Is(err) {497 xo.Abort(oauth2.InvalidGrant("expired authorization code"))498 } else if err != nil {499 xo.Abort(oauth2.InvalidRequest("malformed authorization code"))500 }501 // TODO: We should revoke all descending tokens if a code is reused.502 // get stored authorization code by signature503 code := a.getToken(ctx, key.Base.ID)504 if code == nil {505 xo.Abort(oauth2.InvalidGrant("unknown authorization code"))506 }507 // get token data508 data := code.GetTokenData()509 // validate type510 if data.Type != AuthorizationCode {511 xo.Abort(oauth2.InvalidGrant("invalid authorization code type"))512 }513 // validate expiration514 if data.ExpiresAt.Before(time.Now()) {515 xo.Abort(oauth2.InvalidGrant("expired authorization code"))516 }517 // validate ownership518 if data.ClientID != client.ID() {519 xo.Abort(oauth2.InvalidGrant("invalid authorization code ownership"))520 }521 // validate redirect URI522 req.RedirectURI, err = a.policy.RedirectURIValidator(ctx, client, req.RedirectURI)523 if ErrInvalidRedirectURI.Is(err) {524 xo.Abort(oauth2.InvalidRequest("invalid redirect uri"))525 } else if err != nil {526 xo.Abort(err)527 }528 // compare redirect URIs529 if data.RedirectURI != req.RedirectURI {530 xo.Abort(oauth2.InvalidGrant("redirect uri mismatch"))531 }532 // inherit scope from stored authorization code533 if req.Scope.Empty() {534 req.Scope = data.Scope535 }536 // validate scope - a missing scope is always included537 if !data.Scope.Includes(req.Scope) {538 xo.Abort(oauth2.InvalidScope("scope exceeds the originally granted scope"))539 }540 // get resource owner541 var ro ResourceOwner542 if data.ResourceOwnerID != nil {543 ro = a.getFirstResourceOwner(ctx, client, *data.ResourceOwnerID)544 }545 // issue tokens546 res := a.issueTokens(ctx, true, req.Scope, data.RedirectURI, client, ro)547 // delete authorization code548 a.deleteToken(ctx, code.ID())549 // write response550 xo.AbortIf(oauth2.WriteTokenResponse(ctx.writer, res))551}552func (a *Authenticator) revocationEndpoint(ctx *Context) {553 // trace554 ctx.Tracer.Push("flame/Authenticator.revocationEndpoint")555 defer ctx.Tracer.Pop()556 // parse authorization request557 req, err := oauth2.ParseRevocationRequest(ctx.Request)558 xo.AbortIf(err)559 // check token type hint560 if req.TokenTypeHint != "" && !oauth2.KnownTokenType(req.TokenTypeHint) {561 xo.Abort(oauth2.UnsupportedTokenType(""))562 }563 // get client564 client := a.findFirstClient(ctx, req.ClientID)565 if client == nil {566 xo.Abort(oauth2.InvalidClient("unknown client"))567 }568 // authenticate client if confidential569 if client.IsConfidential() && !client.ValidSecret(req.ClientSecret) {570 xo.Abort(oauth2.InvalidClient("unknown client"))571 }572 // parse token573 key, err := a.policy.Verify(ctx, req.Token)574 if heat.ErrExpiredToken.Is(err) {575 ctx.writer.WriteHeader(http.StatusOK)576 return577 } else if err != nil {578 xo.Abort(oauth2.InvalidRequest("malformed token"))579 }580 // get token581 token := a.getToken(ctx, key.Base.ID)582 if token != nil {583 // get data584 data := token.GetTokenData()585 // check ownership586 if data.ClientID != client.ID() {587 xo.Abort(oauth2.InvalidClient("wrong client"))588 return589 }590 // delete token591 a.deleteToken(ctx, key.Base.ID)592 }593 // write header594 ctx.writer.WriteHeader(http.StatusOK)595}596func (a *Authenticator) introspectionEndpoint(ctx *Context) {597 // trace598 ctx.Tracer.Push("flame/Authenticator.introspectionEndpoint")599 defer ctx.Tracer.Pop()600 // parse introspection request601 req, err := oauth2.ParseIntrospectionRequest(ctx.Request)602 xo.AbortIf(err)603 // check token type hint604 if req.TokenTypeHint != "" && !oauth2.KnownTokenType(req.TokenTypeHint) {605 xo.Abort(oauth2.UnsupportedTokenType(""))606 }607 // get client608 client := a.findFirstClient(ctx, req.ClientID)609 if client == nil {610 xo.Abort(oauth2.InvalidClient("unknown client"))611 }612 // authenticate client if confidential613 if client.IsConfidential() && !client.ValidSecret(req.ClientSecret) {614 xo.Abort(oauth2.InvalidClient("unknown client"))615 }616 // parse token617 key, err := a.policy.Verify(ctx, req.Token)618 if heat.ErrExpiredToken.Is(err) {619 xo.AbortIf(oauth2.WriteIntrospectionResponse(ctx.writer, &oauth2.IntrospectionResponse{}))620 return621 } else if err != nil {622 xo.Abort(oauth2.InvalidRequest("malformed token"))623 }624 // prepare response625 res := &oauth2.IntrospectionResponse{}626 // get token627 token := a.getToken(ctx, key.Base.ID)628 if token != nil {629 // get data630 data := token.GetTokenData()631 // check ownership632 if data.ClientID != client.ID() {633 xo.Abort(oauth2.InvalidClient("wrong client"))634 return635 }636 // get resource owner637 var resourceOwner ResourceOwner638 if data.ResourceOwnerID != nil {639 resourceOwner = a.getFirstResourceOwner(ctx, client, *data.ResourceOwnerID)640 }641 // get validity642 expired := data.ExpiresAt.Before(time.Now())643 // set response if valid and can be introspected644 if !expired && (data.Type == AccessToken || data.Type == RefreshToken) {645 res.Active = true646 res.Scope = data.Scope647 res.ClientID = data.ClientID.Hex()648 if data.ResourceOwnerID != nil {649 res.Username = data.ResourceOwnerID.Hex()650 }651 res.TokenType = oauth2.AccessToken652 if data.Type == RefreshToken {653 res.TokenType = oauth2.RefreshToken654 }655 res.ExpiresAt = data.ExpiresAt.Unix()656 res.IssuedAt = token.ID().Timestamp().Unix()657 res.Identifier = token.ID().Hex()658 res.Extra = a.policy.TokenData(client, resourceOwner, token)659 }660 }661 // write response662 xo.AbortIf(oauth2.WriteIntrospectionResponse(ctx.writer, res))663}664func (a *Authenticator) issueTokens(ctx *Context, refreshable bool, scope oauth2.Scope, redirectURI string, client Client, resourceOwner ResourceOwner) *oauth2.TokenResponse {665 // trace666 ctx.Tracer.Push("flame/Authenticator.issueTokens")667 defer ctx.Tracer.Pop()668 // prepare expiration669 atExpiry := time.Now().Add(a.policy.AccessTokenLifespan)670 rtExpiry := time.Now().Add(a.policy.RefreshTokenLifespan)671 // save access token672 at := a.saveToken(ctx, AccessToken, scope, atExpiry, redirectURI, client, resourceOwner)673 // generate new access token674 atSignature, err := a.policy.Issue(ctx, at, client, resourceOwner)675 xo.AbortIf(err)676 // prepare response677 res := oauth2.NewBearerTokenResponse(atSignature, int(a.policy.AccessTokenLifespan/time.Second))678 // set granted scope679 res.Scope = scope680 // issue a refresh token if requested681 if refreshable && ctx.grants.RefreshToken {682 // save refresh token683 rt := a.saveToken(ctx, RefreshToken, scope, rtExpiry, redirectURI, client, resourceOwner)684 // generate new refresh token685 rtSignature, err := a.policy.Issue(ctx, rt, client, resourceOwner)686 xo.AbortIf(err)687 // set refresh token688 res.RefreshToken = rtSignature689 }690 return res691}692func (a *Authenticator) issueCode(ctx *Context, scope oauth2.Scope, redirectURI string, client Client, resourceOwner ResourceOwner) *oauth2.CodeResponse {693 // trace694 ctx.Tracer.Push("flame/Authenticator.issueCode")695 defer ctx.Tracer.Pop()696 // prepare expiration697 expiry := time.Now().Add(a.policy.AuthorizationCodeLifespan)698 // save authorization code699 code := a.saveToken(ctx, AuthorizationCode, scope, expiry, redirectURI, client, resourceOwner)700 // generate new access token701 signature, err := a.policy.Issue(ctx, code, client, resourceOwner)702 xo.AbortIf(err)703 // prepare response704 res := oauth2.NewCodeResponse(signature, redirectURI, "")705 return res706}707func (a *Authenticator) findFirstClient(ctx *Context, id string) Client {708 // trace709 ctx.Tracer.Push("flame/Authenticator.findFirstClient")710 defer ctx.Tracer.Pop()711 // check all available models in order712 for _, model := range a.policy.Clients {713 c := a.findClient(ctx, model, id)714 if c != nil {715 return c716 }717 }718 return nil719}720func (a *Authenticator) findClient(ctx *Context, model Client, id string) Client {721 // trace722 ctx.Tracer.Push("flame/Authenticator.findClient")723 defer ctx.Tracer.Pop()724 // prepare client725 client := coal.GetMeta(model).Make().(Client)726 // use tagged field if present727 var filters []bson.M728 idField := coal.L(model, "flame-client-id", false)729 if idField != "" {730 filters = []bson.M{731 {idField: id},732 }733 } else if coal.IsHex(id) {734 filters = []bson.M{735 {"_id": coal.MustFromHex(id)},736 }737 } else {738 xo.Abort(xo.F("unable to determine client id field"))739 }740 // add additional filter if provided741 if a.policy.ClientFilter != nil {742 // run filter function743 filter, err := a.policy.ClientFilter(ctx, model)744 if ErrInvalidFilter.Is(err) {745 xo.Abort(oauth2.InvalidRequest("invalid filter"))746 } else if err != nil {747 xo.Abort(err)748 }749 // add filter if present750 if filter != nil {751 filters = append(filters, filter)752 }753 }754 // fetch client755 found, err := a.store.M(model).FindFirst(ctx, client, bson.M{756 "$and": filters,757 }, nil, 0, false)758 xo.AbortIf(err)759 if !found {760 return nil761 }762 return client763}764func (a *Authenticator) getFirstClient(ctx *Context, id coal.ID) Client {765 // trace766 ctx.Tracer.Push("flame/Authenticator.getFirstClient")767 defer ctx.Tracer.Pop()768 // check all available models in order769 for _, model := range a.policy.Clients {770 c := a.getClient(ctx, model, id)771 if c != nil {772 return c773 }774 }775 return nil776}777func (a *Authenticator) getClient(ctx *Context, model Client, id coal.ID) Client {778 // trace779 ctx.Tracer.Push("flame/Authenticator.getClient")780 defer ctx.Tracer.Pop()781 // prepare client782 client := coal.GetMeta(model).Make().(Client)783 // fetch client784 found, err := a.store.M(model).Find(ctx, client, id, false)785 xo.AbortIf(err)786 if !found {787 return nil788 }789 return client790}791func (a *Authenticator) findFirstResourceOwner(ctx *Context, client Client, id string) ResourceOwner {792 // trace793 ctx.Tracer.Push("flame/Authenticator.findFirstResourceOwner")794 defer ctx.Tracer.Pop()795 // get resource owners796 resourceOwners, err := a.policy.ResourceOwners(ctx, client)797 xo.AbortIf(err)798 // check all available models in order799 for _, model := range resourceOwners {800 ro := a.findResourceOwner(ctx, client, model, id)801 if ro != nil {802 return ro803 }804 }805 return nil806}807func (a *Authenticator) findResourceOwner(ctx *Context, client Client, model ResourceOwner, id string) ResourceOwner {808 // trace809 ctx.Tracer.Push("flame/Authenticator.findResourceOwner")810 defer ctx.Tracer.Pop()811 // prepare resource owner812 resourceOwner := coal.GetMeta(model).Make().(ResourceOwner)813 // use tagged field if present814 var filters []bson.M815 idField := coal.L(model, "flame-resource-owner-id", false)816 if idField != "" {817 filters = []bson.M{818 {idField: id},819 }820 } else if coal.IsHex(id) {821 filters = []bson.M{822 {"_id": coal.MustFromHex(id)},823 }824 } else {825 xo.Abort(xo.F("unable to determine resource owner id field"))826 }827 // add additional filter if provided828 if a.policy.ResourceOwnerFilter != nil {829 // run filter function830 filter, err := a.policy.ResourceOwnerFilter(ctx, client, model)831 if ErrInvalidFilter.Is(err) {832 xo.Abort(oauth2.InvalidRequest("invalid filter"))833 } else if err != nil {834 xo.Abort(err)835 }836 // add filter if present837 if filter != nil {838 filters = append(filters, filter)839 }840 }841 // fetch resource owner842 found, err := a.store.M(model).FindFirst(ctx, resourceOwner, bson.M{843 "$and": filters,844 }, nil, 0, false)845 xo.AbortIf(err)846 if !found {847 return nil848 }849 return resourceOwner850}851func (a *Authenticator) getFirstResourceOwner(ctx *Context, client Client, id coal.ID) ResourceOwner {852 // trace853 ctx.Tracer.Push("flame/Authenticator.getFirstResourceOwner")854 defer ctx.Tracer.Pop()855 // get resource owners856 resourceOwners, err := a.policy.ResourceOwners(ctx, client)857 xo.AbortIf(err)858 // check all available models in order859 for _, model := range resourceOwners {860 ro := a.getResourceOwner(ctx, model, id)861 if ro != nil {862 return ro863 }864 }865 return nil866}867func (a *Authenticator) getResourceOwner(ctx *Context, model ResourceOwner, id coal.ID) ResourceOwner {868 // trace869 ctx.Tracer.Push("flame/Authenticator.getResourceOwner")870 defer ctx.Tracer.Pop()871 // prepare object872 resourceOwner := coal.GetMeta(model).Make().(ResourceOwner)873 // fetch resource owner874 found, err := a.store.M(model).Find(ctx, resourceOwner, id, false)875 xo.AbortIf(err)876 if !found {877 return nil878 }879 return resourceOwner880}881func (a *Authenticator) getToken(ctx *Context, id coal.ID) GenericToken {882 // trace883 ctx.Tracer.Push("flame/Authenticator.getToken")884 defer ctx.Tracer.Pop()885 // prepare object886 token := coal.GetMeta(a.policy.Token).Make().(GenericToken)887 // fetch token888 found, err := a.store.M(token).Find(ctx, token, id, false)889 xo.AbortIf(err)890 if !found {891 return nil892 }893 return token894}895func (a *Authenticator) saveToken(ctx *Context, typ TokenType, scope []string, expiresAt time.Time, redirectURI string, client Client, resourceOwner ResourceOwner) GenericToken {896 // trace897 ctx.Tracer.Push("flame/Authenticator.saveToken")898 defer ctx.Tracer.Pop()899 // create token with id900 token := coal.GetMeta(a.policy.Token).Make().(GenericToken)901 token.GetBase().DocID = coal.New()902 // get resource owner id903 var roID *coal.ID904 if resourceOwner != nil {905 roID = stick.P(resourceOwner.ID())906 }907 // set token data908 token.SetTokenData(TokenData{909 Type: typ,910 Scope: scope,911 ExpiresAt: expiresAt,912 RedirectURI: redirectURI,913 Client: client,914 ResourceOwner: resourceOwner,915 ClientID: client.ID(),916 ResourceOwnerID: roID,917 })918 // save token919 xo.AbortIf(a.store.M(token).Insert(ctx, token))920 return token921}922func (a *Authenticator) deleteToken(ctx *Context, id coal.ID) {923 // trace924 ctx.Tracer.Push("flame/Authenticator.deleteToken")925 defer ctx.Tracer.Pop()926 // delete token927 _, err := a.store.M(a.policy.Token).Delete(ctx, nil, id)928 xo.AbortIf(err)929}...
client_session.go
Source:client_session.go
...20// ErrNoTransactStarted is returned if a transaction operation is called when no transaction has started.21var ErrNoTransactStarted = errors.New("no transaction started")22// ErrTransactInProgress is returned if startTransaction() is called when a transaction is in progress.23var ErrTransactInProgress = errors.New("transaction already in progress")24// ErrAbortAfterCommit is returned when abort is called after a commit.25var ErrAbortAfterCommit = errors.New("cannot call abortTransaction after calling commitTransaction")26// ErrAbortTwice is returned if abort is called after transaction is already aborted.27var ErrAbortTwice = errors.New("cannot call abortTransaction twice")28// ErrCommitAfterAbort is returned if commit is called after an abort.29var ErrCommitAfterAbort = errors.New("cannot call commitTransaction after calling abortTransaction")30// ErrUnackWCUnsupported is returned if an unacknowledged write concern is supported for a transaciton.31var ErrUnackWCUnsupported = errors.New("transactions do not support unacknowledged write concerns")32// Type describes the type of the session33type Type uint834// These constants are the valid types for a client session.35const (36 Explicit Type = iota37 Implicit38)39// State indicates the state of the FSM.40type state uint841// Client Session states42const (43 None state = iota44 Starting45 InProgress46 Committed47 Aborted48)49// Client is a session for clients to run commands.50type Client struct {51 *Server52 ClientID uuid.UUID53 ClusterTime bson.Raw54 Consistent bool // causal consistency55 OperationTime *primitive.Timestamp56 SessionType Type57 Terminated bool58 RetryingCommit bool59 Committing bool60 Aborting bool61 RetryWrite bool62 RetryRead bool63 // options for the current transaction64 // most recently set by transactionopt65 CurrentRc *readconcern.ReadConcern66 CurrentRp *readpref.ReadPref67 CurrentWc *writeconcern.WriteConcern68 CurrentMct *time.Duration69 // default transaction options70 transactionRc *readconcern.ReadConcern71 transactionRp *readpref.ReadPref72 transactionWc *writeconcern.WriteConcern73 transactionMaxCommitTime *time.Duration74 pool *Pool75 state state76 PinnedServer *description.Server77 RecoveryToken bson.Raw78}79func getClusterTime(clusterTime bson.Raw) (uint32, uint32) {80 if clusterTime == nil {81 return 0, 082 }83 clusterTimeVal, err := clusterTime.LookupErr("$clusterTime")84 if err != nil {85 return 0, 086 }87 timestampVal, err := bson.Raw(clusterTimeVal.Value).LookupErr("clusterTime")88 if err != nil {89 return 0, 090 }91 return timestampVal.Timestamp()92}93// MaxClusterTime compares 2 clusterTime documents and returns the document representing the highest cluster time.94func MaxClusterTime(ct1, ct2 bson.Raw) bson.Raw {95 epoch1, ord1 := getClusterTime(ct1)96 epoch2, ord2 := getClusterTime(ct2)97 if epoch1 > epoch2 {98 return ct199 } else if epoch1 < epoch2 {100 return ct2101 } else if ord1 > ord2 {102 return ct1103 } else if ord1 < ord2 {104 return ct2105 }106 return ct1107}108// NewClientSession creates a Client.109func NewClientSession(pool *Pool, clientID uuid.UUID, sessionType Type, opts ...*ClientOptions) (*Client, error) {110 c := &Client{111 Consistent: true, // set default112 ClientID: clientID,113 SessionType: sessionType,114 pool: pool,115 }116 mergedOpts := mergeClientOptions(opts...)117 if mergedOpts.CausalConsistency != nil {118 c.Consistent = *mergedOpts.CausalConsistency119 }120 if mergedOpts.DefaultReadPreference != nil {121 c.transactionRp = mergedOpts.DefaultReadPreference122 }123 if mergedOpts.DefaultReadConcern != nil {124 c.transactionRc = mergedOpts.DefaultReadConcern125 }126 if mergedOpts.DefaultWriteConcern != nil {127 c.transactionWc = mergedOpts.DefaultWriteConcern128 }129 if mergedOpts.DefaultMaxCommitTime != nil {130 c.transactionMaxCommitTime = mergedOpts.DefaultMaxCommitTime131 }132 servSess, err := pool.GetSession()133 if err != nil {134 return nil, err135 }136 c.Server = servSess137 return c, nil138}139// AdvanceClusterTime updates the session's cluster time.140func (c *Client) AdvanceClusterTime(clusterTime bson.Raw) error {141 if c.Terminated {142 return ErrSessionEnded143 }144 c.ClusterTime = MaxClusterTime(c.ClusterTime, clusterTime)145 return nil146}147// AdvanceOperationTime updates the session's operation time.148func (c *Client) AdvanceOperationTime(opTime *primitive.Timestamp) error {149 if c.Terminated {150 return ErrSessionEnded151 }152 if c.OperationTime == nil {153 c.OperationTime = opTime154 return nil155 }156 if opTime.T > c.OperationTime.T {157 c.OperationTime = opTime158 } else if (opTime.T == c.OperationTime.T) && (opTime.I > c.OperationTime.I) {159 c.OperationTime = opTime160 }161 return nil162}163// UpdateUseTime sets the session's last used time to the current time. This must be called whenever the session is164// used to send a command to the server to ensure that the session is not prematurely marked expired in the driver's165// session pool. If the session has already been ended, this method will return ErrSessionEnded.166func (c *Client) UpdateUseTime() error {167 if c.Terminated {168 return ErrSessionEnded169 }170 c.updateUseTime()171 return nil172}173// UpdateRecoveryToken updates the session's recovery token from the server response.174func (c *Client) UpdateRecoveryToken(response bson.Raw) {175 if c == nil {176 return177 }178 token, err := response.LookupErr("recoveryToken")179 if err != nil {180 return181 }182 c.RecoveryToken = token.Document()183}184// ClearPinnedServer sets the PinnedServer to nil.185func (c *Client) ClearPinnedServer() {186 if c != nil {187 c.PinnedServer = nil188 }189}190// EndSession ends the session.191func (c *Client) EndSession() {192 if c.Terminated {193 return194 }195 c.Terminated = true196 c.pool.ReturnSession(c.Server)197 return198}199// TransactionInProgress returns true if the client session is in an active transaction.200func (c *Client) TransactionInProgress() bool {201 return c.state == InProgress202}203// TransactionStarting returns true if the client session is starting a transaction.204func (c *Client) TransactionStarting() bool {205 return c.state == Starting206}207// TransactionRunning returns true if the client session has started the transaction208// and it hasn't been committed or aborted209func (c *Client) TransactionRunning() bool {210 return c != nil && (c.state == Starting || c.state == InProgress)211}212// TransactionCommitted returns true of the client session just committed a transaciton.213func (c *Client) TransactionCommitted() bool {214 return c.state == Committed215}216// CheckStartTransaction checks to see if allowed to start transaction and returns217// an error if not allowed218func (c *Client) CheckStartTransaction() error {219 if c.state == InProgress || c.state == Starting {220 return ErrTransactInProgress221 }222 return nil223}224// StartTransaction initializes the transaction options and advances the state machine.225// It does not contact the server to start the transaction.226func (c *Client) StartTransaction(opts *TransactionOptions) error {227 err := c.CheckStartTransaction()228 if err != nil {229 return err230 }231 c.IncrementTxnNumber()232 c.RetryingCommit = false233 if opts != nil {234 c.CurrentRc = opts.ReadConcern235 c.CurrentRp = opts.ReadPreference236 c.CurrentWc = opts.WriteConcern237 c.CurrentMct = opts.MaxCommitTime238 }239 if c.CurrentRc == nil {240 c.CurrentRc = c.transactionRc241 }242 if c.CurrentRp == nil {243 c.CurrentRp = c.transactionRp244 }245 if c.CurrentWc == nil {246 c.CurrentWc = c.transactionWc247 }248 if c.CurrentMct == nil {249 c.CurrentMct = c.transactionMaxCommitTime250 }251 if !writeconcern.AckWrite(c.CurrentWc) {252 c.clearTransactionOpts()253 return ErrUnackWCUnsupported254 }255 c.state = Starting256 c.PinnedServer = nil257 return nil258}259// CheckCommitTransaction checks to see if allowed to commit transaction and returns260// an error if not allowed.261func (c *Client) CheckCommitTransaction() error {262 if c.state == None {263 return ErrNoTransactStarted264 } else if c.state == Aborted {265 return ErrCommitAfterAbort266 }267 return nil268}269// CommitTransaction updates the state for a successfully committed transaction and returns270// an error if not permissible. It does not actually perform the commit.271func (c *Client) CommitTransaction() error {272 err := c.CheckCommitTransaction()273 if err != nil {274 return err275 }276 c.state = Committed277 return nil278}279// UpdateCommitTransactionWriteConcern will set the write concern to majority and potentially set a280// w timeout of 10 seconds. This should be called after a commit transaction operation fails with a281// retryable error or after a successful commit transaction operation.282func (c *Client) UpdateCommitTransactionWriteConcern() {283 wc := c.CurrentWc284 timeout := 10 * time.Second285 if wc != nil && wc.GetWTimeout() != 0 {286 timeout = wc.GetWTimeout()287 }288 c.CurrentWc = wc.WithOptions(writeconcern.WMajority(), writeconcern.WTimeout(timeout))289}290// CheckAbortTransaction checks to see if allowed to abort transaction and returns291// an error if not allowed.292func (c *Client) CheckAbortTransaction() error {293 if c.state == None {294 return ErrNoTransactStarted295 } else if c.state == Committed {296 return ErrAbortAfterCommit297 } else if c.state == Aborted {298 return ErrAbortTwice299 }300 return nil301}302// AbortTransaction updates the state for a successfully aborted transaction and returns303// an error if not permissible. It does not actually perform the abort.304func (c *Client) AbortTransaction() error {305 err := c.CheckAbortTransaction()306 if err != nil {307 return err308 }309 c.state = Aborted310 c.clearTransactionOpts()311 return nil312}313// ApplyCommand advances the state machine upon command execution.314func (c *Client) ApplyCommand(desc description.Server) {315 if c.Committing {316 // Do not change state if committing after already committed317 return318 }319 if c.state == Starting {320 c.state = InProgress321 // If this is in a transaction and the server is a mongos, pin it322 if desc.Kind == description.Mongos {323 c.PinnedServer = &desc324 }325 } else if c.state == Committed || c.state == Aborted {326 c.clearTransactionOpts()327 c.state = None328 }329}330func (c *Client) clearTransactionOpts() {331 c.RetryingCommit = false332 c.Aborting = false333 c.Committing = false334 c.CurrentWc = nil335 c.CurrentRp = nil336 c.CurrentRc = nil337 c.PinnedServer = nil338 c.RecoveryToken = nil339}...
relay.go
Source:relay.go
...36 SessionProxyResponderClient: protos.NewSessionProxyResponderClient(conn),37 conn: conn,38 }, nil39}40type CloseableAbortSessionResponderClient struct {41 protos.AbortSessionResponderClient42 conn *grpc.ClientConn43}44func (client *CloseableAbortSessionResponderClient) Close() {45 client.conn.Close()46}47// GetAbortSessionResponderClient returns a client to the local abort session client. To avoid leaking48// connections, defer Close() on the returned client.49func GetAbortSessionResponderClient(50 cloudRegistry service_registry.GatewayRegistry) (*CloseableAbortSessionResponderClient, error) {51 conn, err := cloudRegistry.GetCloudConnection(feg_relay.ServiceName)52 if err != nil {53 return nil, fmt.Errorf("Failed to connect to gw relay: %s", err)54 }55 return &CloseableAbortSessionResponderClient{56 AbortSessionResponderClient: protos.NewAbortSessionResponderClient(conn),57 conn: conn,58 }, nil59}60func GetIMSIFromSessionID(sessionID string) (string, error) {61 split := strings.Split(sessionID, "-")62 if len(split) < 2 {63 return "", fmt.Errorf("Session ID %s does not match format 'IMSI-RandNum'", sessionID)64 }65 return split[0], nil66}...
Abort
Using AI Code Generation
1import (2func main() {3 client := &http.Client{}4 if err != nil {5 fmt.Println(err)6 }7 resp, err := client.Do(req)8 if err != nil {9 fmt.Println(err)10 }11 defer resp.Body.Close()12 fmt.Println("response Status:", resp.Status)13 fmt.Println("response Headers:", resp.Header)14}15response Headers: map[Content-Type:[text/html; charset=utf-8] Date:[Tue, 20 Mar 2018 14:11:02 GMT] Content-Length:[2996] Server:[gws]]16import (17func main() {18 client := &http.Client{}19 if err != nil {20 fmt.Println(err)21 }22 defer resp.Body.Close()23 body, err := ioutil.ReadAll(resp.Body)24 if err != nil {25 fmt.Println(err)26 }27 fmt.Println(string(body))28}
Abort
Using AI Code Generation
1import (2func main() {3 client := &http.Client{4 }5 if err != nil {6 fmt.Println(err)7 }8 res, err := client.Do(req)9 if err != nil {10 fmt.Println(err)11 }12 fmt.Println(res.Status)13}
Abort
Using AI Code Generation
1import (2func main() {3 client := http.Client{4 }5 if err != nil {6 fmt.Println(err)7 }8 resp, err := client.Do(req)9 if err != nil {10 fmt.Println(err)11 }12 defer resp.Body.Close()13 fmt.Println(resp.StatusCode)14}15import (16func main() {17 client := http.Client{18 }19 if err != nil {20 fmt.Println(err)21 }22 ctx, cancel := context.WithTimeout(context.Background(), time.Second)23 defer cancel()24 req = req.WithContext(ctx)25 resp, err := client.Do(req)26 if err != nil {27 fmt.Println(err)28 }29 defer resp.Body.Close()30 fmt.Println(resp.StatusCode)31}32import (33func main() {34 client := http.Client{35 }36 if err != nil {37 fmt.Println(err)38 }39 ctx, cancel := context.WithCancel(context.Background())40 defer cancel()41 req = req.WithContext(ctx)42 resp, err := client.Do(req
Abort
Using AI Code Generation
1import (2func main() {3 if err != nil {4 fmt.Println(err)5 }6 client := &http.Client{}7 ch := make(chan *http.Response)8 go func() {9 resp, err := client.Do(req)10 if err != nil {11 fmt.Println(err)12 }13 }()14 select {15 fmt.Println(resp)16 case <-time.After(1 * time.Second):17 client.Abort()18 }19}20import (21func main() {22 if err != nil {23 fmt.Println(err)24 }25 client := &http.Client{}26 ch := make(chan *http.Response)27 go func() {28 resp, err := client.Do(req)29 if err != nil {30 fmt.Println(err)31 }32 }()33 select {
Abort
Using AI Code Generation
1import (2func main() {3 if err != nil {4 fmt.Println(err)5 }6 client := &http.Client{}7 ch := make(chan *http.Response)8 go func() {9 resp, err := client.Do(req)10 if err != nil {11 fmt.Println(err)12 }13 }()14 select {15 fmt.Println(resp.Status)16 case <-time.After(1 * time.Second):17 client.Abort()18 fmt.Println("Request Aborted")19 }20}
Abort
Using AI Code Generation
1import (2func main() {3 client := &fasthttp.Client{4 }5 req, resp := fasthttp.AcquireRequest(), fasthttp.AcquireResponse()6 req.Header.SetMethod("GET")7 err := client.DoTimeout(req, resp, 1000)8 if err != nil {9 log.Fatal(err)10 }11 fmt.Println(resp)12}13import (14func main() {15 client := &fasthttp.Client{16 }17 req, resp := fasthttp.AcquireRequest(), fasthttp.AcquireResponse()18 req.Header.SetMethod("GET")19 err := client.Do(req, resp)20 if err != nil {21 log.Fatal(err)22 }23 fmt.Println(resp)24}25import (26func main() {27 client := &fasthttp.Client{28 }29 req, resp := fasthttp.AcquireRequest(), fasthttp.AcquireResponse()30 req.Header.SetMethod("GET")31 err := client.DoDeadline(req, resp, time.Now().Add(1000*time.Millisecond))32 if err != nil {33 log.Fatal(err)34 }35 fmt.Println(resp)36}37import (38func main() {39 client := &fasthttp.Client{40 }41 req, resp := fasthttp.AcquireRequest(), fasthttp.AcquireResponse()42 req.Header.SetMethod("GET")43 err := client.DoTimeout(req, resp, 1000)44 if err != nil {45 log.Fatal(err)
Abort
Using AI Code Generation
1import (2func main() {3 req, res := fasthttp.AcquireRequest(), fasthttp.AcquireResponse()4 defer fasthttp.ReleaseRequest(req)5 defer fasthttp.ReleaseResponse(res)6 client := &fasthttp.Client{}7 client.Do(req, res)8 fmt.Println(res.StatusCode())9 client.Abort()10}11func (c *Client) Get(dst []byte, host string) error12import (13func main() {14 client := &fasthttp.Client{}15 fmt.Println(resp)16}17func (c *Client) Head(dst []byte, host string) error18import (
Abort
Using AI Code Generation
1import (2func main() {3 client, _ := elasticsearch.NewDefaultClient()4 client.Abort()5 fmt.Println("Abort method called")6}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!