Skip to content

Commit

Permalink
Expose CSRF#getToken method (#335)
Browse files Browse the repository at this point in the history
  • Loading branch information
sergiodxa authored Apr 8, 2024
1 parent 753ee6e commit ec995bc
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/server/csrf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,26 @@ export class CSRF {
return [token, signature].join(".");
}

/**
* Get the existing token from the cookie or generate a new one if it doesn't
* exist.
* @param requestOrHeaders A request or headers object from which we can
* get the cookie to get the existing token.
* @param bytes The number of bytes used to generate the token.
* @returns The existing token if it exists in the cookie, otherwise a new
* token.
*/
async getToken(
requestOrHeaders: Request | Headers = new Headers(),
bytes = 32,
) {
let headers = getHeaders(requestOrHeaders);
let existingToken = await this.cookie.parse(headers.get("cookie"));
let token =
typeof existingToken === "string" ? existingToken : this.generate(bytes);
return token;
}

/**
* Generates a token and serialize it into the cookie.
* @param requestOrHeaders A request or headers object from which we can
Expand Down

0 comments on commit ec995bc

Please sign in to comment.