Class: GrowwMcp::Auth

Inherits:
Object
  • Object
show all
Defined in:
lib/groww_mcp/auth.rb

Constant Summary collapse

TOKEN_ENDPOINT =
"/v1/token/api/access"
BASE_URL =
"https://api.groww.in"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeAuth

Returns a new instance of Auth.



15
16
17
18
# File 'lib/groww_mcp/auth.rb', line 15

def initialize
  @access_token = nil
  @token_expiry = nil
end

Instance Attribute Details

#access_tokenObject (readonly)

Returns the value of attribute access_token.



13
14
15
# File 'lib/groww_mcp/auth.rb', line 13

def access_token
  @access_token
end

#token_expiryObject (readonly)

Returns the value of attribute token_expiry.



13
14
15
# File 'lib/groww_mcp/auth.rb', line 13

def token_expiry
  @token_expiry
end

Instance Method Details

#authenticate!Object

Authenticate using the best available method Priority: Direct token > TOTP > API Key + Secret



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/groww_mcp/auth.rb', line 22

def authenticate!
  if ENV["GROWW_ACCESS_TOKEN"] && !ENV["GROWW_ACCESS_TOKEN"].empty?
    @access_token = ENV["GROWW_ACCESS_TOKEN"]
    @token_expiry = nil # Unknown expiry for manual tokens
    log "Authenticated with direct access token"
  elsif ENV["GROWW_TOTP_KEY"] && ENV["GROWW_TOTP_SECRET"]
    authenticate_totp!
  elsif ENV["GROWW_API_KEY"] && ENV["GROWW_API_SECRET"]
    authenticate_approval!
  else
    raise AuthError, "No credentials configured. Set GROWW_TOTP_KEY + GROWW_TOTP_SECRET (recommended), " \
                     "or GROWW_API_KEY + GROWW_API_SECRET, or GROWW_ACCESS_TOKEN in your .env file."
  end

  @access_token
end

#ensure_token!Object

Ensure we have a valid token, refresh if needed



48
49
50
51
# File 'lib/groww_mcp/auth.rb', line 48

def ensure_token!
  authenticate! unless token_valid?
  @access_token
end

#invalidate!Object

Drop the cached token so the next ensure_token! re-authenticates. Called by the client when the API returns 401 (stale/expired token).



55
56
57
58
# File 'lib/groww_mcp/auth.rb', line 55

def invalidate!
  @access_token = nil
  @token_expiry = nil
end

#token_valid?Boolean

Check if token needs refresh (expired or expiring in 5 minutes)

Returns:

  • (Boolean)


40
41
42
43
44
45
# File 'lib/groww_mcp/auth.rb', line 40

def token_valid?
  return false unless @access_token
  return true unless @token_expiry # Manual tokens — assume valid

  Time.now < (@token_expiry - 300) # 5 minute buffer
end