Skip to content

Commit

Permalink
Fix(csrf): Attach csrf-token to the HTML form
Browse files Browse the repository at this point in the history
Signed-off-by: Kaung Zin Hein <[email protected]>
  • Loading branch information
Zen-cronic committed Oct 4, 2024
1 parent 8e7545d commit 08dc771
Show file tree
Hide file tree
Showing 4 changed files with 8 additions and 10 deletions.
4 changes: 2 additions & 2 deletions src/changepassword/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ class ChangePasswordController extends Controller {

async get(ctx: Context) {

const csrfToken = await ctx.getCsrf();
ctx.response.type = 'text/html';
ctx.response.body = changePasswordForm(ctx.query.msg, ctx.query.error);

ctx.response.body = changePasswordForm(ctx.query.msg, ctx.query.error, csrfToken);
}

async post(ctx: Context<any>) {
Expand Down
3 changes: 2 additions & 1 deletion src/changepassword/formats/html.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { render } from '../../templates.js';

export function changePasswordForm(msg: string, error: string) {
export function changePasswordForm(msg: string, error: string, csrfToken: string) {

return render('changepassword', {
title: 'Change Password',
msg: msg,
error: error,
action: '/change-password',
csrfToken: csrfToken,
});

}
9 changes: 2 additions & 7 deletions src/middleware/csrf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const safePaths = [

export default function(): Middleware {

return async (ctx, next) => {
return (ctx, next) => {

/**
* There's 2 ways a user might be authenticated, via a session cookie or
Expand All @@ -21,12 +21,7 @@ export default function(): Middleware {
if (!ctx.session.user) return next();

if (!safeMethods.includes(ctx.method) && !safePaths.includes(ctx.path)) {
if(ctx.path === '/change-password'){
ctx.validateCsrf(await ctx.getCsrf());
}
else{
ctx.validateCsrf();
}
ctx.validateCsrf();
}

delete ctx.request.body?.['csrf-token'];
Expand Down
2 changes: 2 additions & 0 deletions templates/changepassword.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
<p class="form-options"><a href="/">Cancel</a></p>
</fieldset>

<input type="hidden" name="csrf-token" value="{{ csrfToken }}" />

{{#each hiddenFields}}
<input type="hidden" name="{{@key}}" value="{{this}}" />
{{/each}}
Expand Down

0 comments on commit 08dc771

Please sign in to comment.