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

cypress login with next-auth #23

Merged
merged 2 commits into from
Nov 15, 2023
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
42 changes: 42 additions & 0 deletions app/NavBar.cy.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import NavBar from './NavBar'
import {SessionProvider} from 'next-auth/react'
import session from '@fixtures/auth-session.json'

describe('<NavBar />', () => {
it('should show loading and Sign in', () => {
cy.intercept(
{
method: 'GET',
url: '**/api/auth/session',
},
{statusCode: 400},
)
cy.mount(
<SessionProvider>
<NavBar />
</SessionProvider>,
)

cy.getByCy('login').should('be.visible')
})

it('should show user name when authenticated, and not show after sign out', () => {
cy.intercept(
{
method: 'GET',
url: '**/api/auth/session',
},
{fixture: 'auth-session.json', statusCode: 200},
)
cy.mount(
<SessionProvider>
<NavBar />
</SessionProvider>,
)

cy.getByCy('login').should('not.exist')

cy.getByCy('logout').click()
cy.location('pathname').should('eq', '/api/auth/signout')
})
})
39 changes: 28 additions & 11 deletions app/NavBar.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
'use client'
import Link from 'next/link'
import {useSession} from 'next-auth/react'
import {AiFillBug} from 'react-icons/ai'
import {usePathname} from 'next/navigation'
import classnames from 'classnames'
import {Box} from '@radix-ui/themes'

export default function NavBar() {
const {status, data: session} = useSession()
// we want to highlight the active link, so we need usePathname
const currentPath = usePathname()

Expand All @@ -17,21 +20,35 @@ export default function NavBar() {
<Link href="/">
<AiFillBug />
</Link>

<ul className="flex space-x-6">
{links.map(({label, href}) => (
<Link
href={href}
key={label}
className={classnames({
'text-zinc-900': href === currentPath,
'text-zinc-500': href !== currentPath,
'hover:text-zinc-800 transition-colors': true, // always there
})}
>
{label}
</Link>
<li key={label}>
<Link
href={href}
className={classnames({
'text-zinc-900': href === currentPath,
'text-zinc-500': href !== currentPath,
'hover:text-zinc-800 transition-colors': true, // always there
})}
>
{label}
</Link>
</li>
))}
</ul>
<Box>
{status === 'authenticated' && (
<Link data-cy="logout" href="/api/auth/signout">
Log out
</Link>
)}
{status === 'unauthenticated' && (
<Link data-cy="login" href="/api/auth/signin">
Login
</Link>
)}
</Box>
</nav>
)
}
15 changes: 0 additions & 15 deletions app/api/auth/[...nextauth]/authOptions.ts

This file was deleted.

17 changes: 15 additions & 2 deletions app/api/auth/[...nextauth]/route.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,20 @@
import NextAuth from 'next-auth'
import {authOptions} from './authOptions'
import GoogleProvider from 'next-auth/providers/google'
import {PrismaAdapter} from '@next-auth/prisma-adapter'
import {prisma} from '@/prisma/client'

const handler = NextAuth(authOptions)
const handler = NextAuth({
adapter: PrismaAdapter(prisma),
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
}),
],
session: {
strategy: 'jwt',
},
})

// any GET or POST will get handled by the NextAuth handler
export {handler as GET, handler as POST}
Expand Down
10 changes: 10 additions & 0 deletions app/auth/Provider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
'use client'
import {SessionProvider} from 'next-auth/react'

export default function AuthProvider({
children,
}: {
readonly children: React.ReactNode
}) {
return <SessionProvider>{children}</SessionProvider>
}
21 changes: 14 additions & 7 deletions app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {Inter} from 'next/font/google'
import {Container, Theme} from '@radix-ui/themes'

import NavBar from './NavBar'
import AuthProvider from './auth/Provider'

const inter = Inter({subsets: ['latin'], variable: '--font-inter'})

Expand All @@ -15,16 +16,22 @@ export const metadata: Metadata = {
description: 'Generated by create next app',
}

export default function RootLayout({children}: {children: React.ReactNode}) {
export default function RootLayout({
children,
}: {
readonly children: React.ReactNode
}) {
return (
<html lang="en">
<body className={inter.variable}>
<Theme appearance="light" accentColor="violet">
<NavBar />
<main className="p-5">
<Container>{children}</Container>
</main>
</Theme>
<AuthProvider>
<Theme appearance="light" accentColor="violet">
<NavBar />
<main className="p-5">
<Container>{children}</Container>
</main>
</Theme>
</AuthProvider>
</body>
</html>
)
Expand Down
10 changes: 10 additions & 0 deletions cypress.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,16 @@ declare global {

/** Deletes all issues */
cleanUpIssues()

/**
* Logs-in user by using Google API request
*/
googleLogin(): Chainable<Response>

/**
* Stubs login via fixture, to get past the auth wall
*/
stubLogin(): void
}
}
}
11 changes: 11 additions & 0 deletions cypress/e2e/login.cy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
describe('Login', () => {
it('should stubLogin', () => {
cy.stubLogin()
cy.getByCy('logout').should('be.visible')
})

it('should googleLogin', () => {
cy.googleLogin()
cy.getByCy('logout').should('be.visible')
})
})
8 changes: 8 additions & 0 deletions cypress/fixtures/auth-session.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"user": {
"name": "Murat Ozcan",
"email": "next.app.mosh@gmail.com",
"image": "https://lh3.googleusercontent.com/a/ACg8ocLFX3ZmZsILarbdRhYk_ISWE2QjlIBZci1W3F6KemHy=s96-c"
},
"expires": "3000-11-12T14:16:09.957Z"
}
40 changes: 40 additions & 0 deletions cypress/support/e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,43 @@
import './commands'
import '@bahmutov/cy-api'
import 'cypress-map'
import 'cypress-v10-preserve-cookie'

Cypress.Commands.add('googleLogin', () => {
cy.log('Logging in to Google')

return cy
.request({
method: 'POST',
url: 'https://www.googleapis.com/oauth2/v4/token',
body: {
grant_type: 'refresh_token',
client_id: Cypress.env('GOOGLE_CLIENT_ID'),
client_secret: Cypress.env('GOOGLE_CLIENT_SECRET'),
refresh_token: Cypress.env('GOOGLE_REFRESH_TOKEN'),
},
})
.its('body.id_token')
.then(id_token => {
cy.setCookie('next-auth.session-token', id_token)
cy.preserveCookieOnce('next-auth.session-token')
// on visit, the cookie is cleared after the next-auth call
// since we already have the cookie set, we can stub out the next-auth call
cy.intercept('/api/auth/session', {status: 200}).as('next-auth-stub')
return cy.visit('/')
})
})

Cypress.Commands.add('stubLogin', () => {
cy.intercept('/api/auth/session', {fixture: 'auth-session.json'}).as(
'session',
)

cy.setCookie(
'next-auth.session-token',
'a valid cookie from your browser session',
)
// cy.preserveCookieOnce('next-auth.session-token') // works without this, for now
cy.visit('/')
cy.wait('@session')
})
18 changes: 14 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@
"@types/react-dom": "18.2.7",
"autoprefixer": "^10.4.16",
"cy-spok": "^1.6.2",
"cypress": "^13.4.0",
"cypress": "^13.5.0",
"cypress-v10-preserve-cookie": "^1.2.1",
"cypress-map": "^1.21.1",
"dotenv": "^16.3.1",
"eslint": "8.49.0",
Expand Down