Class: Kabk::Auth::JwtStrategy

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

Overview

A pluggable JWT authentication strategy for Kabk

Instance Method Summary collapse

Constructor Details

#initialize(secret:, default_exp: 86400) ⇒ JwtStrategy

You should initialize this with your application's JWT secret



11
12
13
14
# File 'lib/kabk/auth/jwt_strategy.rb', line 11

def initialize(secret:, default_exp: 86400)
  @secret = secret
  @default_exp = default_exp
end

Instance Method Details

#login(username, password) {|username, password| ... } ⇒ Object

Validates user credentials and returns tokens and user context In a real app, this should check against the DB.

Parameters:

  • username (String)
  • password (String)

Yields:

  • (username, password)

    Should yield and return user data if valid, or nil

Raises:



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

def (username, password, &block)
  user_data = yield(username, password)
  raise UnauthorizedError, "Invalid credentials" unless user_data

  access_token = generate_token({ user_id: user_data[:id], type: 'access' }, @default_exp)
  refresh_token = generate_token({ user_id: user_data[:id], type: 'refresh' }, @default_exp * 7)

  {
    success: true,
    message: "Authentication successful",
    data: {
      token_type: "Bearer",
      access_token: access_token,
      refresh_token: refresh_token,
      expires_in: @default_exp,
      user: user_data
    }
  }
end

#refresh(refresh_token) ⇒ Object

Refresh an access token using a refresh token

Raises:



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/kabk/auth/jwt_strategy.rb', line 49

def refresh(refresh_token)
  payload = decode_token!(refresh_token)
  raise UnauthorizedError, "Invalid token type" unless payload["type"] == "refresh"

  access_token = generate_token({ user_id: payload["user_id"], type: 'access' }, @default_exp)
  new_refresh_token = generate_token({ user_id: payload["user_id"], type: 'refresh' }, @default_exp * 7)

  {
    success: true,
    data: {
      token_type: "Bearer",
      access_token: access_token,
      refresh_token: new_refresh_token,
      expires_in: @default_exp
    }
  }
end

#verify_access_token!(token) ⇒ Object

Verifies an access token and returns decoded payload

Raises:



42
43
44
45
46
# File 'lib/kabk/auth/jwt_strategy.rb', line 42

def verify_access_token!(token)
  payload = decode_token!(token)
  raise UnauthorizedError, "Invalid token type" unless payload["type"] == "access"
  payload
end