Skip to content
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

Feature/tas 8 helper methods for authentication #20

Closed
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
31 changes: 31 additions & 0 deletions .github/workflows/vite.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
name: Atlas 3.0 CI

on:
pull_request:
branches:
- main
- epic/*

jobs:
build:
runs-on: ubuntu-latest
if: github.event.pull_request.draft == false

env:
VITE_IGNORE_MSW: false

steps:
- name: Checkout code
uses: actions/checkout@v4

- name: Setup NodeJS
uses: actions/setup-node@v4
with:
node-version: 20
cache: 'yarn'

- name: Install dependencies
run: yarn

- name: Run Vitest
run: yarn vitest
8 changes: 6 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
"dev": "vite",
"build": "tsc && vite build",
"lint": "eslint --ext .js,.jsx,.ts,.tsx src",
"preview": "vite preview"
"preview": "vite preview",
"test": "vitest"
},
"dependencies": {
"@tanstack/react-query": "^5.18.0",
Expand All @@ -18,6 +19,7 @@
"react-dom": "^18.2.0"
},
"devDependencies": {
"@testing-library/react": "^14.2.1",
"@types/node": "^20.11.13",
"@types/react": "^18.2.43",
"@types/react-dom": "^18.2.17",
Expand All @@ -28,8 +30,10 @@
"eslint-plugin-react": "^7.33.2",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.5",
"jsdom": "^24.0.0",
"typescript": "^5.2.2",
"vite": "^5.0.8"
"vite": "^5.0.8",
"vitest": "^1.2.2"
},
"msw": {
"workerDirectory": [
Expand Down
34 changes: 34 additions & 0 deletions src/api/authentication.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
const BASE_URL = 'https://example.com/auth';
const LOGIN_URL = `${BASE_URL}/login`;
const LOGOUT_URL = `${BASE_URL}/logout`;
Comment on lines +1 to +3
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use resolveURL function from @/src/api/fetch


export const signIn = async (username: string, password: string): Promise<any> => {
const response = await fetch(LOGIN_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

need to set credentials to include to save csrf token

body: JSON.stringify({ username, password }),
});

if (!response.ok) {
throw new Error('Failed to sign in');
}

return response.json();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should return response object and not json

};

export const signOut = async (): Promise<void> => {
const response = await fetch(LOGOUT_URL, {
method: 'POST',
});

if (!response.ok) {
throw new Error('Failed to sign out');
}

// Clear cookies on the client side
document.cookie.split(';').forEach(cookie => {
document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, '=;expires=' + new Date().toUTCString() + ';path=/');
});
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should return response too, in case sign out failed and errors can be handled

};
2 changes: 1 addition & 1 deletion src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ async function enableMocking() {
return
}

const { worker } = await import('./mocks/browser.ts')
const { worker } = await import('./mocks/worker')

return worker.start()
}
Expand Down
33 changes: 33 additions & 0 deletions src/mocks/authentication/auth_handlers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
//src/mocks/authentication/auth_handlers.ts

import { http, HttpResponse } from "msw"
import resolveURL from "../../api/fetch";


export const mockCSRFToken: string = "SUPERSECRETCSRFTOKEN"
export const mockUsername: string = "testuser"
export const mockPassword: string = "mockpassword"

export const auth_handlers = [
http.post(resolveURL("/auth/csrf"), () => {
return new HttpResponse(null, {
headers: {
'Set-Cookie': mockCSRFToken
}
})
}),

http.post(resolveURL("/auth/login"), async ({ cookies, request }) => {
if (!cookies.csrfmiddlewaretoken) return new HttpResponse(null, {status: 403})
if (cookies.csrfmiddlewaretoken !== mockCSRFToken) return new HttpResponse(null, {status: 403})

const data = await request.formData()
if (data.get("username") !== mockUsername || data.get("password") !== mockPassword) return new HttpResponse(null, {status: 403})

return new HttpResponse(null, {
headers: {
'Set-Cookie': mockCSRFToken
}
})
})
]
20 changes: 0 additions & 20 deletions src/mocks/browser.ts

This file was deleted.

21 changes: 21 additions & 0 deletions src/mocks/handlers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
//src/mocks/handlers.ts

import { http, HttpResponse } from "msw"
import resolveURL from "../api/fetch.ts";

import { auth_handlers } from "./authentication/auth_handlers.ts";


const default_handlers = [
http.get(resolveURL('/resource'), () => {
return HttpResponse.json({
result: "Hello World!"
})
})
]


export const handlers = [
...default_handlers,
...auth_handlers
]
5 changes: 5 additions & 0 deletions src/mocks/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { setupServer } from 'msw/node'
import { handlers } from "./handlers";


export const server = setupServer(...handlers)
8 changes: 8 additions & 0 deletions src/mocks/worker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { setupWorker, SetupWorker } from "msw/browser"
import { handlers } from "./handlers.ts"

export const worker: SetupWorker = setupWorker(...handlers)

worker.events.on("request:start", ({ request }) => {
console.log('MSW intercepted: ', request.method, request.url)
})
23 changes: 23 additions & 0 deletions tests/authentication/auth.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { describe, expect, test } from "vitest"
import { getCSRF, signIn, signOut } from "../../src/api/authentication";
import { mockCSRFToken, mockUsername, mockPassword } from "../../src/mocks/authentication/auth_handlers";

describe("authentication helper functions", () => {

test("should get csrf token", async () => {
const response: Response = await getCSRF()
expect(response.headers).toBe({
'Set-Cookie': mockCSRFToken
})
})

test("should be able to sign in", async () => {
const response = await signIn(mockUsername, mockPassword)
expect(response.status).toBe(200)
})

test("should be able to sign out", async () => {
const response = await signOut()
expect(response.status).toBe(200)
})
})
17 changes: 17 additions & 0 deletions tests/test.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import {beforeEach, describe, expect, test } from "vitest"
import {render, screen} from "@testing-library/react"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import App from "../src/App"

const queryClient = new QueryClient()

describe("Vitest Test", () => {

beforeEach(() => {
render(<QueryClientProvider client={queryClient}><App></App></QueryClientProvider>)
})

test("Should show Hello World!", async () => {
expect(await screen.findByText(/Hello World!/)).toBeDefined()
})
})
8 changes: 8 additions & 0 deletions vite.config.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
/// <reference types="vitest" />
/// <reference types="vite/client" />

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
test: {
globals: true,
environment: "jsdom",
setupFiles: ["./vitest.setup.ts"]
}
})
6 changes: 6 additions & 0 deletions vitest.setup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { afterAll, afterEach, beforeAll } from 'vitest'
import { server } from "./src/mocks/server"

beforeAll(() => server.listen({ onUnhandledRequest: 'error' }))
afterAll(() => server.close())
afterEach(() => server.resetHandlers())
Loading
Loading