Skip to content

Commit

Permalink
address changes: separate revoke_tokens
Browse files Browse the repository at this point in the history
  • Loading branch information
xihai01 committed Feb 26, 2025
1 parent bb13f87 commit fad4857
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 20 deletions.
4 changes: 2 additions & 2 deletions app/controllers/api/v1/users/sessions_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ def destroy
api_credential = ApiCredential.find_by(refresh_token_digest: Digest::SHA256.hexdigest(refresh_token))
# set api and refresh tokens to nil; otherwise render 401
if api_credential
api_credential.revoke_token("api_token")
api_credential.revoke_token("refresh_token")
api_credential.revoke_api_token
api_credential.revoke_refresh_token
render json: {message: "Signed out successfully."}, status: 200
else
render json: {message: "An error occured when signing out."}, status: 401
Expand Down
17 changes: 6 additions & 11 deletions app/models/api_credential.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,17 +37,12 @@ def is_refresh_token_expired?
refresh_token_expires_at < Time.current
end

# clear tokens
# token argument takes in two strings: api_token and refresh_token
def revoke_token(token)
if (token == "api_token")
update_columns(api_token_digest: nil)
elsif (token == "refresh_token")
update_columns(refresh_token_digest: nil)
else
return nil
end
return token
def revoke_api_token
update_columns(api_token_digest: nil)
end

def revoke_refresh_token
update_columns(refresh_token_digest: nil)
end

private
Expand Down
12 changes: 5 additions & 7 deletions spec/models/api_credential_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -101,23 +101,21 @@
end
end

describe "#revoke_token" do
describe "#revoke_api_token" do
it "sets api token to nil" do
api_token = api_credential.return_new_api_token![:api_token]
api_credential.revoke_token("api_token")
api_credential.revoke_api_token

expect(api_credential.api_token_digest).to be_nil
end
end

describe "#revoke_refresh_token" do
it "sets refresh token to nil" do
refresh_token = api_credential.return_new_refresh_token![:refresh_token]
api_credential.revoke_token("refresh_token")
api_credential.revoke_refresh_token

expect(api_credential.refresh_token_digest).to be_nil
end

it "returns nil if token is not found" do
expect(api_credential.revoke_token("invalid_token")).to be_nil
end
end
end

0 comments on commit fad4857

Please sign in to comment.