You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

49 lines
1.6 KiB

import { Injectable } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { PassportStrategy } from '@nestjs/passport'
2 years ago
import { Strategy, type Profile, type VerifyCallback } from 'passport-42'
import { get } from 'https'
import { createWriteStream } from 'fs'
import { UsersService } from 'src/users/users.service'
import { User } from 'src/users/entity/user.entity'
@Injectable()
export class FtStrategy extends PassportStrategy(Strategy, '42') {
constructor (
private readonly configService: ConfigService,
private readonly usersService: UsersService
) {
super({
clientID: configService.get<string>('FT_OAUTH_CLIENT_ID'),
clientSecret: configService.get<string>('FT_OAUTH_CLIENT_SECRET'),
callbackURL: configService.get<string>('FT_OAUTH_CALLBACK_URL'),
passReqToCallback: true
})
}
async validate (
request: { session: { accessToken: string } },
accessToken: string,
refreshToken: string,
profile: Profile,
cb: VerifyCallback
): Promise<VerifyCallback> {
request.session.accessToken = accessToken
2 years ago
const ftId = profile.id as number
console.log('Validated ', profile.username)
2 years ago
if ((await this.usersService.findUser(ftId)) === null) {
const newUser = new User()
2 years ago
newUser.ftId = profile.id as number
newUser.username = profile.username
newUser.avatar = `${ftId}.jpg`
void this.usersService.create(newUser)
const file = createWriteStream(`avatars/${ftId}.jpg`)
2 years ago
get(profile._json.image.versions.small, function (response) {
response.pipe(file)
})
}
return cb(null, profile)
}
}