|
| 1 | +import type { HttpContext } from '@adonisjs/core/http' |
| 2 | +import User from '#models/user' |
| 3 | +import Provider from '#models/provider' |
| 4 | +import { DateTime } from 'luxon' |
| 5 | + |
| 6 | +export default class AuthController { |
| 7 | + async redirect({ ally, params }: HttpContext) { |
| 8 | + const providerParams = params.provider |
| 9 | + const socialProvider = ally.use(providerParams) |
| 10 | + return await socialProvider.redirect() |
| 11 | + } |
| 12 | + |
| 13 | + async callback({ ally, auth, response, params, session }: HttpContext) { |
| 14 | + const providerParams = params.provider |
| 15 | + const socialProvider = ally.use(providerParams) |
| 16 | + |
| 17 | + if ( |
| 18 | + socialProvider.accessDenied() || |
| 19 | + socialProvider.stateMisMatch() || |
| 20 | + socialProvider.hasError() |
| 21 | + ) { |
| 22 | + return response.redirect('/login') |
| 23 | + } |
| 24 | + |
| 25 | + const socialUser = await socialProvider.user() |
| 26 | + |
| 27 | + if (socialUser) { |
| 28 | + const provider = await Provider.findByOrFail('name', providerParams) |
| 29 | + await User.firstOrCreate( |
| 30 | + { email: socialUser.email }, |
| 31 | + { |
| 32 | + email: socialUser.email, |
| 33 | + username: socialUser.nickName, |
| 34 | + avatarUrl: socialUser.avatarUrl, |
| 35 | + providerId: provider.id, |
| 36 | + } |
| 37 | + ) |
| 38 | + |
| 39 | + const user = await User.findByOrFail('email', socialUser.email) |
| 40 | + await auth.use('web').login(user) |
| 41 | + |
| 42 | + user.lastSessionId = session.sessionId |
| 43 | + user.lastSessionAt = DateTime.now() |
| 44 | + await user.save() |
| 45 | + |
| 46 | + return response.redirect('/') |
| 47 | + } |
| 48 | + return response.redirect('/') |
| 49 | + } |
| 50 | +} |
0 commit comments