✨ Integrate GitHub authentication · javascriptcm/javascript.cm@60b5c12 · GitHub
Skip to content

Commit 60b5c12

Browse files
committed
✨ Integrate GitHub authentication
1 parent b9119ca commit 60b5c12

9 files changed

Lines changed: 346 additions & 6 deletions

File tree

‎.env.example‎

Lines changed: 4 additions & 1 deletion

‎adonisrc.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ export default defineConfig({
3838
() => import('@adonisjs/lucid/database_provider'),
3939
() => import('@adonisjs/auth/auth_provider'),
4040
() => import('@adonisjs/inertia/inertia_provider'),
41+
() => import('@adonisjs/ally/ally_provider'),
4142
],
4243

4344
/*
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
import { HttpContext } from '@adonisjs/core/http'
2+
import User from '#models/user'
3+
import type { GithubDriver } from '@adonisjs/ally/drivers/github'
4+
5+
export default class GithubController {
6+
async redirect({ ally }: HttpContext) {
7+
return (ally.use('github') as GithubDriver).redirect()
8+
}
9+
10+
async callback({ ally, auth, response }: HttpContext) {
11+
const github = ally.use('github') as GithubDriver
12+
13+
/**
14+
* User has explicitly cancelled the login flow
15+
*/
16+
if (github.accessDenied()) {
17+
return response.redirect().toRoute('login')
18+
}
19+
20+
/**
21+
* OAuth state verification failed. This happens when the
22+
* CSRF cookie gets expired or request is forged
23+
*/
24+
if (github.stateMisMatch()) {
25+
return response.redirect().toRoute('login')
26+
}
27+
28+
/**
29+
* GitHub responded with some error
30+
*/
31+
if (github.hasError()) {
32+
return response.redirect().toRoute('login')
33+
}
34+
35+
/**
36+
* Get user details from GitHub
37+
*/
38+
const githubUser = await github.user()
39+
40+
/**
41+
* Find or create user by GitHub ID
42+
*/
43+
const user = await User.firstOrCreate(
44+
{
45+
githubId: githubUser.id,
46+
},
47+
{
48+
username: githubUser.nickName,
49+
name: githubUser.name,
50+
email: githubUser.email!,
51+
avatar: githubUser.avatarUrl,
52+
githubId: githubUser.id,
53+
}
54+
)
55+
56+
/**
57+
* Login user using the web guard
58+
*/
59+
await auth.use('web').login(user)
60+
return response.redirect().toRoute('dashboard')
61+
}
62+
}

‎config/ally.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import env from '#start/env'
2+
import { defineConfig, services } from '@adonisjs/ally'
3+
4+
const allyConfig = defineConfig({
5+
github: services.github({
6+
clientId: env.get('GITHUB_CLIENT_ID'),
7+
clientSecret: env.get('GITHUB_CLIENT_SECRET'),
8+
callbackUrl: env.get('GITHUB_CALLBACK_URL'),
9+
}),
10+
})
11+
12+
export default allyConfig

‎inertia/pages/auth/login.tsx‎

Lines changed: 26 additions & 1 deletion

0 commit comments

Comments
 (0)