|
| 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 | +} |
0 commit comments