import { Injectable } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { PassportStrategy } from '@nestjs/passport'; import { Strategy } from 'passport-github2'; import { AuthService } from '../services/auth.service'; @Injectable() export class GithubStrategy extends PassportStrategy(Strategy, 'github') { constructor( private readonly configService: ConfigService, private readonly authService: AuthService, ) { const clientID = configService.get('GITHUB_CLIENT_ID') || 'dummy-client-id'; const clientSecret = configService.get('GITHUB_CLIENT_SECRET') || 'dummy-client-secret'; const callbackURL = configService.get('GITHUB_CALLBACK_URL') || 'http://localhost:3001/api/auth/github/callback'; super({ clientID, clientSecret, callbackURL, scope: ['user:email'], }); } /** * Validate the GitHub profile and return the user */ async validate(accessToken: string, refreshToken: string, profile: any) { // Extract user information from GitHub profile const { id, displayName, emails, photos } = profile; // Get primary email or first email const email = emails && emails.length > 0 ? (emails.find(e => e.primary)?.value || emails[0].value) : null; // Get avatar URL const avatarUrl = photos && photos.length > 0 ? photos[0].value : null; // Validate or create user const user = await this.authService.validateGithubUser( id, email, displayName || 'GitHub User', avatarUrl, ); return user; } }