introduce an authentication service and prepare user management
This commit is contained in:
72
src/auth/auth.service.ts
Normal file
72
src/auth/auth.service.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
import { HttpService } from '@nestjs/axios';
|
||||
import { HttpException, Injectable } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { InjectModel } from '@nestjs/mongoose';
|
||||
import { Model } from 'mongoose';
|
||||
import { catchError, lastValueFrom, map } from 'rxjs';
|
||||
|
||||
import { UserDocument } from './models/user.model';
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
constructor(
|
||||
@InjectModel('user')
|
||||
private readonly userModel: Model<UserDocument>,
|
||||
private config: ConfigService,
|
||||
private httpService: HttpService,
|
||||
private jwtService: JwtService,
|
||||
) {}
|
||||
|
||||
async login(code: string): Promise<string> {
|
||||
const token = await lastValueFrom(
|
||||
this.httpService
|
||||
.post(
|
||||
`${this.config.get<string>(
|
||||
'vatsim-auth.base-url',
|
||||
)}/${this.config.get<string>('vatsim-auth.token-endpoint')}`,
|
||||
{
|
||||
grant_type: 'authorization_code',
|
||||
client_id: this.config.get<string>('vatsim-auth.client-id'),
|
||||
client_secret: this.config.get<string>('vatsim-auth.client-secret'),
|
||||
redirect_uri: 'http://localhost:3000/auth/vatsim',
|
||||
code,
|
||||
},
|
||||
)
|
||||
.pipe(
|
||||
map((response) => response.data.access_token),
|
||||
catchError((err) => {
|
||||
throw new HttpException(err.response.data, err.response.status);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const userdata = await lastValueFrom(
|
||||
this.httpService
|
||||
.get(
|
||||
`${this.config.get<string>(
|
||||
'vatsim-auth.base-url',
|
||||
)}/${this.config.get<string>('vatsim-auth.user-endpoint')}`,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
Accept: 'application/json',
|
||||
},
|
||||
},
|
||||
)
|
||||
.pipe(
|
||||
map((response) => response.data.data),
|
||||
catchError((err) => {
|
||||
throw new HttpException(err.response.data, err.response.status);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
if (userdata.oauth.token_valid) {
|
||||
const payload = { username: userdata.cid, sub: token };
|
||||
return this.jwtService.sign(payload);
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user