Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions apps/backend/src/api/routes/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ export class AuthController {

@Get('/oauth/:provider')
async oauthLink(@Param('provider') provider: string, @Query() query: any) {
return this._authService.oauthLink(provider, query);
return await this._authService.oauthLink(provider, query);
}

@Post('/activate')
Expand Down Expand Up @@ -235,10 +235,11 @@ export class AuthController {
@Post('/oauth/:provider/exists')
async oauthExists(
@Body('code') code: string,
@Body('state') state: string,
@Param('provider') provider: string,
@Res({ passthrough: false }) response: Response
) {
const { jwt, token } = await this._authService.checkExists(provider, code);
const { jwt, token } = await this._authService.checkExists(provider, code, state);

if (token) {
return response.json({ token });
Expand Down
8 changes: 4 additions & 4 deletions apps/backend/src/services/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,18 +218,18 @@ export class AuthService {
return false;
}

oauthLink(provider: string, query?: any) {
async oauthLink(provider: string, query?: any) {
const providerInstance = ProvidersFactory.loadProvider(
provider as Provider
);
return providerInstance.generateLink(query);
return await providerInstance.generateLink(query);
}

async checkExists(provider: string, code: string) {
async checkExists(provider: string, code: string, state?: string) {
const providerInstance = ProvidersFactory.loadProvider(
provider as Provider
);
const token = await providerInstance.getToken(code);
const token = await providerInstance.getToken(code, state);
const user = await providerInstance.getUser(token);
if (!user) {
throw new Error('Invalid user');
Expand Down
2 changes: 1 addition & 1 deletion apps/backend/src/services/auth/providers.interface.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export interface ProvidersInterface {
generateLink(query?: any): Promise<string> | string;
getToken(code: string): Promise<string>;
getToken(code: string, state?: string): Promise<string>;
getUser(
providerToken: string
): Promise<{ email: string; id: string }> | false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export class FarcasterProvider implements ProvidersInterface {
return '';
}

async getToken(code: string) {
async getToken(code: string, state?: string) {
const data = JSON.parse(Buffer.from(code, 'base64').toString());
const status = await client.lookupSigner({ signerUuid: data.signer_uuid });
if (status.status === 'approved') {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export class GithubProvider implements ProvidersInterface {
)}`;
}

async getToken(code: string): Promise<string> {
async getToken(code: string, state?: string): Promise<string> {
const { access_token } = await (
await fetch('https://github.com/login/oauth/access_token', {
method: 'POST',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export class GoogleProvider implements ProvidersInterface {
});
}

async getToken(code: string) {
async getToken(code: string, state?: string) {
const { client, oauth2 } = clientAndYoutube();
const { tokens } = await client.getToken(code);
return tokens.access_token;
Expand Down
30 changes: 28 additions & 2 deletions apps/backend/src/services/auth/providers/oauth.provider.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { ProvidersInterface } from '@gitroom/backend/services/auth/providers.interface';
import { randomBytes } from 'crypto';
import { ioRedis } from '@gitroom/nestjs-libraries/redis/redis.service';

export class OauthProvider implements ProvidersInterface {
private readonly authUrl: string;
Expand Down Expand Up @@ -48,18 +50,42 @@ export class OauthProvider implements ProvidersInterface {
this.userInfoUrl = POSTIZ_OAUTH_USERINFO_URL;
}

generateLink(): string {
async generateLink(): Promise<string> {
const state = randomBytes(32).toString('hex');

await ioRedis.set(`oauth_state:${state}`, '1', 'EX', 600);

const params = new URLSearchParams({
client_id: this.clientId,
scope: 'openid profile email',
response_type: 'code',
redirect_uri: `${this.frontendUrl}/settings`,
state,
});

return `${this.authUrl}/?${params.toString()}`;
}

async getToken(code: string): Promise<string> {
private async validateState(state: string): Promise<boolean> {
if (!state) {
return false;
}

const key = `oauth_state:${state}`;
const exists = await ioRedis.get(key);

if (!exists) {
return false;
}

await ioRedis.del(key);
return true;
}

async getToken(code: string, state?: string): Promise<string> {
if (state && !(await this.validateState(state))) {
throw new Error('Invalid or expired state parameter');
}
const response = await fetch(`${this.tokenUrl}`, {
method: 'POST',
headers: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export class WalletProvider implements ProvidersInterface {
return challenge;
}

async getToken(code: string) {
async getToken(code: string, state?: string) {
const { publicKey, challenge, signature } = JSON.parse(
Buffer.from(code, 'base64').toString()
);
Expand Down
6 changes: 4 additions & 2 deletions apps/frontend/src/components/auth/register.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,26 +41,28 @@ export function Register() {
const fetch = useFetch();
const [provider] = useState(getQuery?.get('provider')?.toUpperCase());
const [code, setCode] = useState(getQuery?.get('code') || '');
const [state] = useState(getQuery?.get('state') || '');
const [show, setShow] = useState(false);
useEffect(() => {
if (provider && code) {
load();
}
}, []);
}, [provider, code, state]);
const load = useCallback(async () => {
const { token } = await (
await fetch(`/auth/oauth/${provider?.toUpperCase() || 'LOCAL'}/exists`, {
method: 'POST',
body: JSON.stringify({
code,
state,
}),
})
).json();
if (token) {
setCode(token);
setShow(true);
}
}, [provider, code]);
}, [provider, code, state]);
if (!code && !provider) {
return <RegisterAfter token="" provider="LOCAL" />;
}
Expand Down