Skip to content

Commit 45a851c

Browse files
committed
Sign in with GitHub, Google and Apple
- One social controller and provider modules (no new dependency): state in an encrypted cookie, PKCE + nonce for Google, nonce and a fresh ES256 client-secret JWT for Apple, ID token claims checked (iss, aud, exp, nonce) - Apple's form_post callback is the only CSRF exception; its state cookie is SameSite=None so it survives Apple's cross-site POST - Accounts link only to verified e-mails, never relink to another provider account, banned members are refused; OAuth query strings no longer leak into the next redirect - Buttons follow each brand's rules and appear only for configured providers; settings list the linked providers - isBanned treated freshly created users as banned (bannedAt undefined)
1 parent 93266b9 commit 45a851c

29 files changed

Lines changed: 1753 additions & 258 deletions

‎.adonisjs/client/registry/index.ts‎

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -54,17 +54,23 @@ const routes = {
5454
tokens: [{"old":"/register","type":0,"val":"register","end":""}],
5555
types: placeholder as Registry['register.store']['types'],
5656
},
57-
'auth.github': {
57+
'auth.social': {
5858
methods: ["GET","HEAD"],
59-
pattern: '/auth/github',
60-
tokens: [{"old":"/auth/github","type":0,"val":"auth","end":""},{"old":"/auth/github","type":0,"val":"github","end":""}],
61-
types: placeholder as Registry['auth.github']['types'],
59+
pattern: '/auth/:provider',
60+
tokens: [{"old":"/auth/:provider","type":0,"val":"auth","end":""},{"old":"/auth/:provider","type":1,"val":"provider","end":""}],
61+
types: placeholder as Registry['auth.social']['types'],
6262
},
63-
'auth.github.callback': {
63+
'auth.social.callback': {
6464
methods: ["GET","HEAD"],
65-
pattern: '/auth/github/callback',
66-
tokens: [{"old":"/auth/github/callback","type":0,"val":"auth","end":""},{"old":"/auth/github/callback","type":0,"val":"github","end":""},{"old":"/auth/github/callback","type":0,"val":"callback","end":""}],
67-
types: placeholder as Registry['auth.github.callback']['types'],
65+
pattern: '/auth/:provider/callback',
66+
tokens: [{"old":"/auth/:provider/callback","type":0,"val":"auth","end":""},{"old":"/auth/:provider/callback","type":1,"val":"provider","end":""},{"old":"/auth/:provider/callback","type":0,"val":"callback","end":""}],
67+
types: placeholder as Registry['auth.social.callback']['types'],
68+
},
69+
'auth.apple.callback': {
70+
methods: ["POST"],
71+
pattern: '/auth/apple/callback',
72+
tokens: [{"old":"/auth/apple/callback","type":0,"val":"auth","end":""},{"old":"/auth/apple/callback","type":0,"val":"apple","end":""},{"old":"/auth/apple/callback","type":0,"val":"callback","end":""}],
73+
types: placeholder as Registry['auth.apple.callback']['types'],
6874
},
6975
'logout': {
7076
methods: ["POST"],

‎.adonisjs/client/registry/schema.d.ts‎

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -103,28 +103,40 @@ export interface Registry {
103103
errorResponse: ExtractErrorResponse<Awaited<ReturnType<import('#controllers/auth/register_controller').default['store']>>> | { status: 422; response: { errors: SimpleError[] } }
104104
}
105105
}
106-
'auth.github': {
106+
'auth.social': {
107107
methods: ["GET","HEAD"]
108-
pattern: '/auth/github'
108+
pattern: '/auth/:provider'
109109
types: {
110110
body: {}
111-
paramsTuple: []
112-
params: {}
111+
paramsTuple: [ParamValue]
112+
params: { provider: ParamValue }
113113
query: {}
114-
response: ExtractResponse<Awaited<ReturnType<import('#controllers/auth/github_controller').default['redirect']>>>
115-
errorResponse: ExtractErrorResponse<Awaited<ReturnType<import('#controllers/auth/github_controller').default['redirect']>>>
114+
response: ExtractResponse<Awaited<ReturnType<import('#controllers/auth/social_controller').default['redirect']>>>
115+
errorResponse: ExtractErrorResponse<Awaited<ReturnType<import('#controllers/auth/social_controller').default['redirect']>>>
116116
}
117117
}
118-
'auth.github.callback': {
118+
'auth.social.callback': {
119119
methods: ["GET","HEAD"]
120-
pattern: '/auth/github/callback'
120+
pattern: '/auth/:provider/callback'
121+
types: {
122+
body: {}
123+
paramsTuple: [ParamValue]
124+
params: { provider: ParamValue }
125+
query: {}
126+
response: ExtractResponse<Awaited<ReturnType<import('#controllers/auth/social_controller').default['callback']>>>
127+
errorResponse: ExtractErrorResponse<Awaited<ReturnType<import('#controllers/auth/social_controller').default['callback']>>>
128+
}
129+
}
130+
'auth.apple.callback': {
131+
methods: ["POST"]
132+
pattern: '/auth/apple/callback'
121133
types: {
122134
body: {}
123135
paramsTuple: []
124136
params: {}
125137
query: {}
126-
response: ExtractResponse<Awaited<ReturnType<import('#controllers/auth/github_controller').default['callback']>>>
127-
errorResponse: ExtractErrorResponse<Awaited<ReturnType<import('#controllers/auth/github_controller').default['callback']>>>
138+
response: ExtractResponse<Awaited<ReturnType<import('#controllers/auth/social_controller').default['appleCallback']>>>
139+
errorResponse: ExtractErrorResponse<Awaited<ReturnType<import('#controllers/auth/social_controller').default['appleCallback']>>>
128140
}
129141
}
130142
'logout': {

‎.adonisjs/client/registry/tree.d.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,11 @@ export interface ApiDefinition {
1515
store: typeof routes['register.store']
1616
}
1717
auth: {
18-
github: typeof routes['auth.github'] & {
19-
callback: typeof routes['auth.github.callback']
18+
social: typeof routes['auth.social'] & {
19+
callback: typeof routes['auth.social.callback']
20+
}
21+
apple: {
22+
callback: typeof routes['auth.apple.callback']
2023
}
2124
}
2225
logout: typeof routes['logout']

‎.adonisjs/server/controllers.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ export const controllers = {
1818
Github: () => import('#controllers/auth/github_controller'),
1919
Login: () => import('#controllers/auth/login_controller'),
2020
Register: () => import('#controllers/auth/register_controller'),
21+
Social: () => import('#controllers/auth/social_controller'),
2122
},
2223
Dashboard: () => import('#controllers/dashboard_controller'),
2324
DiscussionActions: () => import('#controllers/discussion_actions_controller'),

‎.adonisjs/server/routes.d.ts‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,9 @@ export type ScannedRoutes = {
1212
'login.store': { paramsTuple?: []; params?: {} }
1313
'register': { paramsTuple?: []; params?: {} }
1414
'register.store': { paramsTuple?: []; params?: {} }
15-
'auth.github': { paramsTuple?: []; params?: {} }
16-
'auth.github.callback': { paramsTuple?: []; params?: {} }
15+
'auth.social': { paramsTuple: [ParamValue]; params: {'provider': ParamValue} }
16+
'auth.social.callback': { paramsTuple: [ParamValue]; params: {'provider': ParamValue} }
17+
'auth.apple.callback': { paramsTuple?: []; params?: {} }
1718
'logout': { paramsTuple?: []; params?: {} }
1819
'markdown.preview': { paramsTuple?: []; params?: {} }
1920
'replies.update': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
@@ -96,8 +97,8 @@ export type ScannedRoutes = {
9697
'pages.code_of_conduct': { paramsTuple?: []; params?: {} }
9798
'login': { paramsTuple?: []; params?: {} }
9899
'register': { paramsTuple?: []; params?: {} }
99-
'auth.github': { paramsTuple?: []; params?: {} }
100-
'auth.github.callback': { paramsTuple?: []; params?: {} }
100+
'auth.social': { paramsTuple: [ParamValue]; params: {'provider': ParamValue} }
101+
'auth.social.callback': { paramsTuple: [ParamValue]; params: {'provider': ParamValue} }
101102
'seo.robots': { paramsTuple?: []; params?: {} }
102103
'seo.sitemap': { paramsTuple?: []; params?: {} }
103104
'seo.feed': { paramsTuple?: []; params?: {} }
@@ -135,8 +136,8 @@ export type ScannedRoutes = {
135136
'pages.code_of_conduct': { paramsTuple?: []; params?: {} }
136137
'login': { paramsTuple?: []; params?: {} }
137138
'register': { paramsTuple?: []; params?: {} }
138-
'auth.github': { paramsTuple?: []; params?: {} }
139-
'auth.github.callback': { paramsTuple?: []; params?: {} }
139+
'auth.social': { paramsTuple: [ParamValue]; params: {'provider': ParamValue} }
140+
'auth.social.callback': { paramsTuple: [ParamValue]; params: {'provider': ParamValue} }
140141
'seo.robots': { paramsTuple?: []; params?: {} }
141142
'seo.sitemap': { paramsTuple?: []; params?: {} }
142143
'seo.feed': { paramsTuple?: []; params?: {} }
@@ -170,6 +171,7 @@ export type ScannedRoutes = {
170171
POST: {
171172
'login.store': { paramsTuple?: []; params?: {} }
172173
'register.store': { paramsTuple?: []; params?: {} }
174+
'auth.apple.callback': { paramsTuple?: []; params?: {} }
173175
'logout': { paramsTuple?: []; params?: {} }
174176
'markdown.preview': { paramsTuple?: []; params?: {} }
175177
'replies.like': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }

‎.env.example‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,29 @@ DB_DATABASE=jscm
2222
# Rate limiting
2323
LIMITER_STORE=database
2424

25-
# GitHub OAuth — https://github.com/settings/developers
26-
# Callback URL: ${APP_URL}/auth/github/callback
25+
# Social sign-in (all optional). A provider is enabled only when ALL its
26+
# variables are set; otherwise its button is hidden and its routes return 404.
27+
28+
# GitHub OAuth — https://github.com/settings/developers ("OAuth Apps")
29+
# Authorization callback URL: ${APP_URL}/auth/github/callback
2730
GITHUB_CLIENT_ID=
2831
GITHUB_CLIENT_SECRET=
32+
33+
# Google — https://console.cloud.google.com/apis/credentials
34+
# OAuth client of type "Web application" (scopes: openid, email, profile)
35+
# Authorized redirect URI: ${APP_URL}/auth/google/callback
36+
GOOGLE_CLIENT_ID=
37+
GOOGLE_CLIENT_SECRET=
38+
39+
# Sign in with Apple — https://developer.apple.com/account/resources
40+
# APPLE_CLIENT_ID: the Services ID (e.g. cm.javascript.web), with "Sign in with
41+
# Apple" enabled, the site domain registered and the Return URL:
42+
# ${APP_URL}/auth/apple/callback (HTTPS and a real domain are required)
43+
# APPLE_TEAM_ID: 10-character Team ID; APPLE_KEY_ID: ID of the key below.
44+
# APPLE_PRIVATE_KEY: contents of the AuthKey_XXXXXXXXXX.p8 file (PEM). Either
45+
# quoted on several lines, or on one line with escaped newlines:
46+
# APPLE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nMIGT...\n-----END PRIVATE KEY-----"
47+
APPLE_CLIENT_ID=
48+
APPLE_TEAM_ID=
49+
APPLE_KEY_ID=
50+
APPLE_PRIVATE_KEY=
Lines changed: 10 additions & 95 deletions
Original file line numberDiff line numberDiff line change
@@ -1,104 +1,19 @@
1-
import { SESSION_VERSION_KEY } from '#middleware/silent_auth_middleware'
2-
import { DateTime } from 'luxon'
3-
import string from '@adonisjs/core/helpers/string'
41
import type { HttpContext } from '@adonisjs/core/http'
5-
import User from '#models/user'
6-
import GithubOAuth from '#services/github_oauth'
7-
import { githubEnabled } from '#config/ally'
8-
import { RESERVED_USERNAMES } from '#validators/register_validator'
2+
import SocialController from '#controllers/auth/social_controller'
93

4+
/**
5+
* @deprecated Kept for backward compatibility only: the routes point to
6+
* SocialController ("/auth/:provider", "/auth/:provider/callback"), which
7+
* handles GitHub, Google and Apple with the same account rules.
8+
*/
109
export default class GithubController {
1110
async redirect(ctx: HttpContext) {
12-
if (!githubEnabled()) {
13-
ctx.session.flash('error', 'La connexion avec GitHub n’est pas encore activée.')
14-
return ctx.response.redirect().toRoute('login')
15-
}
16-
return ctx.response.redirect(new GithubOAuth(ctx).redirectUrl())
11+
ctx.params.provider = 'github'
12+
return new SocialController().redirect(ctx)
1713
}
1814

1915
async callback(ctx: HttpContext) {
20-
const { auth, response, session } = ctx
21-
if (!githubEnabled()) return response.redirect().toRoute('login')
22-
23-
const profile = await new GithubOAuth(ctx).user().catch(() => null)
24-
if (!profile) {
25-
session.flash('error', 'Connexion GitHub annulée ou expirée. Réessayez.')
26-
return response.redirect().toRoute('login')
27-
}
28-
29-
let user = await User.findBy('githubId', profile.id)
30-
31-
if (!user && profile.email) {
32-
// Link the GitHub account to an existing account with the same e-mail.
33-
const existing = await User.findBy('email', profile.email.toLowerCase())
34-
if (existing && !existing.emailVerifiedAt) {
35-
// Local e-mails are not verified: auto-linking would let anyone who
36-
// registered with someone else's address capture their GitHub login.
37-
session.flash(
38-
'error',
39-
'Un compte existe déjà avec cette adresse e-mail. Connectez-vous avec votre mot de passe.'
40-
)
41-
return response.redirect().toRoute('login')
42-
}
43-
if (existing) {
44-
existing.githubId = profile.id
45-
existing.githubUsername = profile.login
46-
existing.avatarUrl = existing.avatarUrl ?? profile.avatarUrl
47-
await existing.save()
48-
user = existing
49-
}
50-
}
51-
52-
if (!user) {
53-
if (!profile.email) {
54-
session.flash(
55-
'error',
56-
'Votre compte GitHub n’expose aucune adresse e-mail vérifiée. Créez un compte avec votre e-mail.'
57-
)
58-
return response.redirect().toRoute('register')
59-
}
60-
user = await User.create({
61-
githubId: profile.id,
62-
githubUsername: profile.login,
63-
username: await this.availableUsername(profile.login),
64-
name: profile.name,
65-
email: profile.email.toLowerCase(),
66-
avatarUrl: profile.avatarUrl,
67-
bio: profile.bio?.slice(0, 280) ?? null,
68-
location: profile.location?.slice(0, 100) ?? null,
69-
websiteUrl:
70-
profile.blog && /^https?:\/\//.test(profile.blog) ? profile.blog.slice(0, 255) : null,
71-
twitterUsername: profile.twitterUsername,
72-
password: null,
73-
role: 'member',
74-
// GitHub only returns verified addresses.
75-
emailVerifiedAt: DateTime.now(),
76-
})
77-
session.flash('success', `Bienvenue dans la communauté, ${user.displayName} !`)
78-
} else {
79-
session.flash('success', `Bon retour, ${user.displayName} !`)
80-
}
81-
82-
if (user.isBanned) {
83-
session.flash('error', 'Ce compte a été suspendu.')
84-
return response.redirect().toRoute('login')
85-
}
86-
87-
await auth.use('web').login(user, true)
88-
session.put(SESSION_VERSION_KEY, user.sessionVersion)
89-
return response.redirect().toPath('/dashboard')
90-
}
91-
92-
private async availableUsername(login: string) {
93-
const base =
94-
login
95-
.toLowerCase()
96-
.replace(/[^a-z0-9_-]/g, '')
97-
.slice(0, 24) || 'membre'
98-
let candidate = RESERVED_USERNAMES.includes(base) ? `${base}-dev` : base
99-
while (await User.findBy('username', candidate)) {
100-
candidate = `${base}-${string.random(4).toLowerCase()}`
101-
}
102-
return candidate
16+
ctx.params.provider = 'github'
17+
return new SocialController().callback(ctx)
10318
}
10419
}

0 commit comments

Comments
 (0)