Coder Social home page Coder Social logo

Comments (8)

pcantrell avatar pcantrell commented on May 22, 2024

Making this circuit work as you describe, where it retries automatically and you never see the auth failure, isn't really workable with the Siesta API as it stands.

You can do something close to what you want, if:

  1. you’re willing to see the auth error first and then see the refreshed data, and
  2. you only want to retry load requests (not POST etc).

Here’s a sketch:

configure {
  $0.config.beforeStartingRequest { resource, request in
    request.onFailure { error in
      if isAuthError(error) {
        doAuthorization() {
          resource.loadIfNeeded()
        }
      }
    }
  }
}

That would clearly need cleaning up and building out. Hopefully it helps.

from siesta.

pcantrell avatar pcantrell commented on May 22, 2024

(And I should clarify: isAuthError() and doAuthorization() are hypotherical methods that you would write, and doAuthorization() calls the given closure on success.)

from siesta.

vdka avatar vdka commented on May 22, 2024

It would be nice to be able to do something like this:

public static func configureMe() {
  service.configure("/me") {
    $0.config.beforeStartingRequest { (resource, request) in
      guard API.isAuthed else {
        switch API.refreshToken {
        case let refreshToken?:
          request.pause() // Stop the request from going out until we are possibly authed.
          API.login(refreshToken: refreshToken).onCompletion { response in
            guard case .Success = response else {
              request.cancel(API.Error.requiresAuth)
              return
            }
            request.resume() // We are now authed and the request may proceed.
          }
        case nil:
          request.cancel(API.Error.requiresAuth)
        }
      }
    }
  }
}

What are your thoughts on a system like this?

from siesta.

pcantrell avatar pcantrell commented on May 22, 2024

Auto-reuath and auto-refresh would certainly have widespread appeal. @vdka, I could imagine something along those lines. Instead of request.pause(), I’d first investigate some framework-provided mechanism for letting beforeStartingRequest replace the request wholesale.

from siesta.

jordanpwood avatar jordanpwood commented on May 22, 2024

I'm doing some initial evaluation of Siesta to handle an API with this exact issue. @vdka, can I ask, what approach did you end up with?

from siesta.

vdka avatar vdka commented on May 22, 2024

I haven't tackled the issue just yet @jordanpwood but I will in the next couple days, then report back.

from siesta.

vdka avatar vdka commented on May 22, 2024

The following should work, it doesn't do pre-auth for individual requests but it definitely could be made to. You will need some method of finding the expiration time of your tokens for this method (we are using a JWT which encodes expiration time)

final class API {

  static var service = Service()

  // ...

  static func login(username username: String, password: String) -> Request {

    let request = service.resource(.Auth)
      .request(.POST, json: ["grant_type": "password", "username": username, "password": password, "application_id": clientId])
      .onSuccess { entity in
        let json = entity.json

        guard let token = json["token"].string else {
          fatalError() // handle this better
        }

        guard let refreshToken = json["refresh_token"].string else {
          fatalError() // handle this better
        }

        API.token = token
        API.refreshToken = refreshToken
    }

    return request
  }

  static func login(refreshToken refreshToken: String) -> Request {

    let request = service.resource(.Auth)
      .request(.POST, json: ["grant_type": "refresh_token", "refresh_token": refreshToken, "application_id": clientId])
      .onSuccess { entity in
        let json = entity.json
        guard let token = json["token"].string else {
          fatalError()
        }

        guard let refreshToken = json["refresh_token"].string else {
          fatalError()
        }

        API.token = token
        API.refreshToken = refreshToken
    }

    return request
  }

  public static var token: String? {
    didSet {
      service.invalidateConfiguration()
      service.wipeResources()

      guard let token = token else { return }

      let jwt = try? JWTDecode.decode(token)

      tokenExpiry = jwt?.expiresAt
    }
  }

  public private(set) static var tokenExpiry: NSDate? {
    didSet {
      guard let tokenExpiry = tokenExpiry else { return }

      let timeToExpire = abs(tokenExpiry.timeIntervalSinceDate(NSDate()))

      // Somewhat before the expiration happens
      let timeToRefresh = NSDate(timeInterval: timeToExpire * 0.9, sinceDate: NSDate())

      log.info("Token refresh scheduled for \(timeToRefresh.descriptionWithLocale(NSLocale.currentLocale()))")

      NSTimer.after(timeToRefresh.timeIntervalSinceNow) {

        log.info("attempting auto token refresh")

        guard let refreshToken = API.refreshToken else { 
          log.warning("No refresh token set. Cannot auto-refresh") 
          return
        }

        API.login(refreshToken: refreshToken)
          .onSuccess { _ in log.info("Token refresh successful!") }
          .onFailure { log.error("Token refresh failed with \($0)") }
      }
    }
  }
}

from siesta.

pcantrell avatar pcantrell commented on May 22, 2024

I think #98 resolved this. If it didn’t, feel free to reopen.

from siesta.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.