Skip to content

Commit c15d3ae

Browse files
committed
✨ Implement authentication features: Add login and logout functionality with validation; create login controller, validator, and Inertia pages;
1 parent 56c01df commit c15d3ae

7 files changed

Lines changed: 188 additions & 7 deletions

File tree

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import { loginValidator } from '#validators/login_validator'
2+
import { HttpContext } from '@adonisjs/core/http'
3+
import User from '#models/user'
4+
import { errors } from '@adonisjs/auth'
5+
export default class LoginController {
6+
async show({ inertia }: HttpContext) {
7+
return inertia.render('auth/login')
8+
}
9+
10+
async login({ request, auth, response, session }: HttpContext) {
11+
const data = await loginValidator.validate(request.all())
12+
const user = await User.verifyCredentials(data.email, data.password)
13+
14+
try {
15+
await auth.use('web').login(user)
16+
return response.redirect().toRoute('dashboard')
17+
} catch (error) {
18+
if (error instanceof errors.E_INVALID_CREDENTIALS) {
19+
session.flash('errors', { form: 'Invalid credentials' })
20+
return response.redirect().back()
21+
}
22+
throw error
23+
}
24+
}
25+
26+
async logout({ auth, response }: HttpContext) {
27+
await auth.use('web').logout()
28+
return response.redirect().toRoute('login')
29+
}
30+
}

‎app/validators/login_validator.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import vine from '@vinejs/vine'
2+
3+
/**
4+
* Validates the login action
5+
*/
6+
export const loginValidator = vine.compile(
7+
vine.object({
8+
email: vine.string().email(),
9+
password: vine.string().minLength(6),
10+
remember: vine.boolean().optional(),
11+
})
12+
)

‎config/auth.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,9 @@ const authConfig = defineConfig({
66
default: 'web',
77
guards: {
88
web: sessionGuard({
9-
useRememberMeTokens: false,
9+
useRememberMeTokens: true,
1010
provider: sessionUserProvider({
11-
model: () => import('#models/user')
11+
model: () => import('#models/user'),
1212
}),
1313
}),
1414
},
@@ -25,4 +25,4 @@ declare module '@adonisjs/auth/types' {
2525
}
2626
declare module '@adonisjs/core/types' {
2727
interface EventsList extends InferAuthEvents<Authenticators> {}
28-
}
28+
}

‎config/inertia.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ const inertiaConfig = defineConfig({
1111
* Data that should be shared with all rendered pages
1212
*/
1313
sharedData: {
14+
user: (ctx) => ctx.auth.user,
1415
errors: (ctx) => ctx.inertia.always(() => ctx.session?.flashMessages.get('errors')),
1516
},
1617

@@ -19,12 +20,12 @@ const inertiaConfig = defineConfig({
1920
*/
2021
ssr: {
2122
enabled: true,
22-
entrypoint: 'inertia/app/ssr.tsx'
23-
}
23+
entrypoint: 'inertia/app/ssr.tsx',
24+
},
2425
})
2526

2627
export default inertiaConfig
2728

2829
declare module '@adonisjs/inertia/types' {
2930
export interface SharedProps extends InferSharedProps<typeof inertiaConfig>, PageProps {}
30-
}
31+
}

‎inertia/layouts/app.tsx‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import { PropsWithChildren } from 'react'
2+
import { usePage } from '@inertiajs/react'
3+
4+
export default function AppLayout({ children }: PropsWithChildren) {
5+
const { user } = usePage().props
6+
7+
console.log(user)
8+
9+
return (
10+
<div className="min-h-screen bg-gray-100">
11+
<nav className="bg-white border-b border-gray-100">
12+
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
13+
<div className="flex justify-between h-16">
14+
<div className="flex">
15+
<div className="flex-shrink-0 flex items-center">
16+
<a href="/">JavaScript.cm</a>
17+
</div>
18+
</div>
19+
20+
{false && (
21+
<div className="flex items-center">
22+
<form action="/logout" method="post">
23+
<button type="submit" className="text-gray-600 hover:text-gray-900">
24+
Logout
25+
</button>
26+
</form>
27+
</div>
28+
)}
29+
</div>
30+
</div>
31+
</nav>
32+
33+
<main>{children}</main>
34+
</div>
35+
)
36+
}

‎inertia/pages/auth/login.tsx‎

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
import { useForm } from '@inertiajs/react'
2+
import { FormEvent } from 'react'
3+
import { router } from '@inertiajs/react'
4+
5+
export default function Login() {
6+
const { data, setData, processing, errors } = useForm({
7+
email: '',
8+
password: '',
9+
remember: false,
10+
})
11+
12+
function handleSubmit(e: FormEvent) {
13+
e.preventDefault()
14+
router.post('/login', data)
15+
}
16+
17+
return (
18+
<div className="min-h-screen flex items-center justify-center bg-gray-50">
19+
<div className="max-w-md w-full space-y-8">
20+
<div>
21+
<h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900">
22+
Sign in to your account
23+
</h2>
24+
</div>
25+
<form className="mt-8 space-y-6" onSubmit={handleSubmit}>
26+
<div className="rounded-md shadow-sm -space-y-px">
27+
<div>
28+
<label htmlFor="email" className="sr-only">
29+
Email address
30+
</label>
31+
<input
32+
id="email"
33+
name="email"
34+
type="email"
35+
required
36+
className="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-t-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm"
37+
placeholder="Email address"
38+
value={data.email}
39+
onChange={(e) => setData('email', e.target.value)}
40+
/>
41+
{errors.email && <p className="text-red-500 text-xs mt-1">{errors.email}</p>}
42+
</div>
43+
<div>
44+
<label htmlFor="password" className="sr-only">
45+
Password
46+
</label>
47+
<input
48+
id="password"
49+
name="password"
50+
type="password"
51+
required
52+
className="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-b-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm"
53+
placeholder="Password"
54+
value={data.password}
55+
onChange={(e) => setData('password', e.target.value)}
56+
/>
57+
{errors.password && <p className="text-red-500 text-xs mt-1">{errors.password}</p>}
58+
</div>
59+
</div>
60+
61+
<div className="flex items-center justify-between">
62+
<div className="flex items-center">
63+
<input
64+
id="remember"
65+
name="remember"
66+
type="checkbox"
67+
className="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"
68+
checked={data.remember}
69+
onChange={(e) => setData('remember', e.target.checked)}
70+
/>
71+
<label htmlFor="remember" className="ml-2 block text-sm text-gray-900">
72+
Remember me
73+
</label>
74+
</div>
75+
</div>
76+
77+
<div>
78+
<button
79+
type="submit"
80+
disabled={processing}
81+
className="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
82+
>
83+
Sign in
84+
</button>
85+
</div>
86+
</form>
87+
</div>
88+
</div>
89+
)
90+
}

‎start/routes.ts‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,5 +8,17 @@
88
*/
99

1010
import router from '@adonisjs/core/services/router'
11-
router.on('/').renderInertia('home')
11+
import { middleware } from '#start/kernel'
12+
const LoginController = () => import('#controllers/auth/login_controller')
1213

14+
router
15+
.group(() => {
16+
router.get('login', [LoginController, 'show']).as('login')
17+
router.post('login', [LoginController, 'login']).as('login.store')
18+
router.post('logout', [LoginController, 'logout']).as('logout')
19+
})
20+
.middleware(middleware.guest())
21+
22+
router.get('/', async ({ inertia }) => {
23+
return inertia.render('home')
24+
})

0 commit comments

Comments
 (0)