first commit
This commit is contained in:
81
libs/api/identity/presenters/src/lib/http/auth.controller.ts
Normal file
81
libs/api/identity/presenters/src/lib/http/auth.controller.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
HttpCode,
|
||||
Post,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import {
|
||||
IdentityService,
|
||||
InvalidCredentialsError,
|
||||
} from '@task-stream/api/identity/application';
|
||||
import {
|
||||
AuthorizationConfig,
|
||||
TokenGrant,
|
||||
TokenSet,
|
||||
} from '@task-stream/api/identity/domain';
|
||||
import { Public } from '../auth/auth.decorators';
|
||||
import { IssueTokenDto } from './dto/issue-token.dto';
|
||||
|
||||
/**
|
||||
* Sign-in for browsers. Pireon's /oauth/token has no CORS and the client
|
||||
* secret must stay server-side, so the web app goes through here.
|
||||
*/
|
||||
@Controller('auth')
|
||||
export class AuthController {
|
||||
constructor(private readonly identity: IdentityService) {}
|
||||
|
||||
/** What the web app needs to start Authorization Code + PKCE (null = not configured). */
|
||||
@Public()
|
||||
@Get('config')
|
||||
config(): Promise<AuthorizationConfig | null> {
|
||||
return this.identity.authorizationConfig();
|
||||
}
|
||||
|
||||
@Public()
|
||||
@Post('token')
|
||||
@HttpCode(200)
|
||||
async token(@Body() dto: IssueTokenDto) {
|
||||
try {
|
||||
return toResponse(await this.identity.issueToken(toGrant(dto)));
|
||||
} catch (error) {
|
||||
if (error instanceof InvalidCredentialsError)
|
||||
throw new UnauthorizedException(error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function toGrant(dto: IssueTokenDto): TokenGrant {
|
||||
switch (dto.grant_type) {
|
||||
case 'authorization_code':
|
||||
return {
|
||||
type: 'authorization_code',
|
||||
code: dto.code as string,
|
||||
codeVerifier: dto.code_verifier as string,
|
||||
redirectUri: dto.redirect_uri as string,
|
||||
};
|
||||
case 'password':
|
||||
return {
|
||||
type: 'password',
|
||||
username: dto.username as string,
|
||||
password: dto.password as string,
|
||||
};
|
||||
case 'refresh_token':
|
||||
return {
|
||||
type: 'refresh_token',
|
||||
refreshToken: dto.refresh_token as string,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/** Standard OAuth2 token response. */
|
||||
function toResponse(token: TokenSet) {
|
||||
return {
|
||||
access_token: token.accessToken,
|
||||
refresh_token: token.refreshToken,
|
||||
expires_in: token.expiresIn,
|
||||
token_type: token.tokenType,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user