Skip to content

Add DELETE /tokens/current endpoint #2676

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 6, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions src/controllers/token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use crate::schema::api_tokens;
use crate::util::read_fill;
use crate::views::EncodableApiTokenWithToken;

use conduit::{Body, Response};
use serde_json as json;

/// Handles the `GET /me/tokens` route.
Expand Down Expand Up @@ -108,3 +109,18 @@ pub fn revoke(req: &mut dyn RequestExt) -> EndpointResult {
struct R {}
Ok(req.json(&R {}))
}

/// Handles the `DELETE /tokens/current` route.
pub fn revoke_current(req: &mut dyn RequestExt) -> EndpointResult {
let authenticated_user = req.authenticate()?;
let api_token_id = authenticated_user
.api_token_id()
.ok_or_else(|| bad_request("token not provided"))?;

let conn = req.db_conn()?;
diesel::update(api_tokens::table.filter(api_tokens::id.eq(api_token_id)))
.set(api_tokens::revoked.eq(true))
.execute(&*conn)?;

Ok(Response::builder().status(204).body(Body::empty()).unwrap())
}
1 change: 1 addition & 0 deletions src/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ pub fn build_router(app: &App) -> RouteBuilder {
api_router.get("/me/tokens", C(token::list));
api_router.put("/me/tokens", C(token::new));
api_router.delete("/me/tokens/:id", C(token::revoke));
api_router.delete("/tokens/current", C(token::revoke_current));
api_router.get(
"/me/crate_owner_invitations",
C(crate_owner_invitation::list),
Expand Down
68 changes: 68 additions & 0 deletions src/tests/token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,74 @@ fn revoke_token_success() {
});
}

#[test]
fn revoke_current_token_success() {
let (app, _, user, token) = TestApp::init().with_token();

// Ensure that the token currently exists in the database
app.db(|conn| {
let tokens: Vec<ApiToken> = assert_ok!(ApiToken::belonging_to(user.as_model())
.filter(api_tokens::revoked.eq(false))
.load(conn));
assert_eq!(tokens.len(), 1);
assert_eq!(tokens[0].name, token.as_model().name);
});

// Revoke the token
let response = token.delete::<()>("/api/v1/tokens/current");
assert_eq!(response.status(), StatusCode::NO_CONTENT);

// Ensure that the token was removed from the database
app.db(|conn| {
let tokens: Vec<ApiToken> = assert_ok!(ApiToken::belonging_to(user.as_model())
.filter(api_tokens::revoked.eq(false))
.load(conn));
assert_eq!(tokens.len(), 0);
});
}

#[test]
fn revoke_current_token_without_auth() {
let (_, anon) = TestApp::init().empty();

let response = anon.delete::<()>("/api/v1/tokens/current");
assert_eq!(response.status(), StatusCode::FORBIDDEN);
assert_eq!(
response.json(),
json!({ "errors": [{ "detail": "must be logged in to perform that action" }] })
);
}

#[test]
fn revoke_current_token_with_cookie_user() {
let (app, _, user, token) = TestApp::init().with_token();

// Ensure that the token currently exists in the database
app.db(|conn| {
let tokens: Vec<ApiToken> = assert_ok!(ApiToken::belonging_to(user.as_model())
.filter(api_tokens::revoked.eq(false))
.load(conn));
assert_eq!(tokens.len(), 1);
assert_eq!(tokens[0].name, token.as_model().name);
});

// Revoke the token
let response = user.delete::<()>("/api/v1/tokens/current");
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
assert_eq!(
response.json(),
json!({ "errors": [{ "detail": "token not provided" }] })
);

// Ensure that the token still exists in the database after the failed request
app.db(|conn| {
let tokens: Vec<ApiToken> = assert_ok!(ApiToken::belonging_to(user.as_model())
.filter(api_tokens::revoked.eq(false))
.load(conn));
assert_eq!(tokens.len(), 1);
});
}

#[test]
fn using_token_updates_last_used_at() {
let url = "/api/v1/me";
Expand Down