Skip to content
Draft
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
9 changes: 8 additions & 1 deletion apps/client/src/app/app.component.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { SocialAuthService } from '@abacritt/angularx-social-login';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
Expand All @@ -8,7 +9,13 @@ describe('AppComponent', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [AppComponent, RouterTestingModule, HttpClientTestingModule],
providers: [provideMockStore()],
providers: [
provideMockStore(),
{
provide: SocialAuthService,
useValue: {},
},
],
}).compileComponents();
});

Expand Down
27 changes: 24 additions & 3 deletions apps/client/src/app/app.component.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,34 @@
import { SocialAuthService } from '@abacritt/angularx-social-login';
import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';
import { RouterModule } from '@angular/router';
import { Component, OnInit, inject } from '@angular/core';
import { Router, RouterModule } from '@angular/router';
import { AuthService } from '@fst/client/data-access';

// eslint-disable-next-line @nx/enforce-module-boundaries
import { HeaderComponent } from '@fst/client/ui-components/header';
import { filter, switchMap } from 'rxjs';
@Component({
standalone: true,
imports: [CommonModule, RouterModule, HeaderComponent],
selector: 'fse-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent {}
export class AppComponent implements OnInit {
private socialAuthService = inject(SocialAuthService);
private authService = inject(AuthService);
private router = inject(Router);

ngOnInit(): void {
this.socialAuthService.authState
.pipe(
filter((user) => !!user),
switchMap(({ idToken }) => this.authService.loginGoogleUser(idToken))
)
.subscribe(({ access_token }) => {
// console.log(`[AppComponent] Got JWT for Google user`, access_token);
// console.log(`[AppComponent] Got google access token`, token);
this.router.navigate(['/']);
});
}
}
31 changes: 30 additions & 1 deletion apps/client/src/app/app.config.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
import {
GoogleLoginProvider,
SocialAuthServiceConfig,
SocialLoginModule,
} from '@abacritt/angularx-social-login';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { APP_INITIALIZER, ApplicationConfig, isDevMode } from '@angular/core';
import {
APP_INITIALIZER,
ApplicationConfig,
importProvidersFrom,
isDevMode,
} from '@angular/core';
import {
provideRouter,
withEnabledBlockingInitialNavigation,
Expand All @@ -19,6 +29,7 @@ import {
import { provideEffects } from '@ngrx/effects';
import { provideState, provideStore } from '@ngrx/store';
import { provideStoreDevtools } from '@ngrx/store-devtools';

import { appRoutes } from './app.routes';

export const appConfig: ApplicationConfig = {
Expand Down Expand Up @@ -49,5 +60,23 @@ export const appConfig: ApplicationConfig = {
// useClass: TodoElfFacade,
// useClass: TodoRxjsFacade,
},
importProvidersFrom(SocialLoginModule),
{
provide: 'SocialAuthServiceConfig',
useValue: {
autoLogin: true,
providers: [
{
id: GoogleLoginProvider.PROVIDER_ID,
provider: new GoogleLoginProvider(
'1082517220825-693bq09as195vkni3uvhkaun3qdn79tr.apps.googleusercontent.com',
{
oneTapEnabled: false,
}
),
},
],
} as SocialAuthServiceConfig,
},
],
};
22 changes: 17 additions & 5 deletions apps/server-e2e/src/server/todo-controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
ITokenResponse,
IUser,
} from '@fst/shared/domain';
import { createMockTodo } from '@fst/shared/util-testing';
import { createMockTodo, createMockUser } from '@fst/shared/util-testing';
import {
HttpStatus,
INestApplication,
Expand All @@ -21,7 +21,7 @@ import {
import { ConfigModule, ConfigService } from '@nestjs/config';
import { APP_FILTER, APP_GUARD } from '@nestjs/core';
import { Test } from '@nestjs/testing';
import { getRepositoryToken, TypeOrmModule } from '@nestjs/typeorm';
import { TypeOrmModule, getRepositoryToken } from '@nestjs/typeorm';
import { randEmail, randPassword, randUuid } from '@ngneat/falso';
import Joi from 'joi';
import * as request from 'supertest';
Expand All @@ -32,10 +32,11 @@ describe('ServerFeatureTodoController E2E', () => {
const baseUrl = `/api/v1`;
const todoUrl = `/todos`;
const userUrl = `/users`;
const authUrl = `/auth`;
const authUrl = `/auth/email`;

const USER_EMAIL = randEmail();
const USER_UNHASHED_PASSWORD = `Password1!`;
const MOCK_USER = createMockUser({ email: USER_EMAIL });

let app: INestApplication;
let todoRepo: Repository<ITodo>;
Expand Down Expand Up @@ -127,7 +128,15 @@ describe('ServerFeatureTodoController E2E', () => {
.default(app.getHttpServer())
.post(`${baseUrl}${userUrl}`)
.set('Content-type', 'application/json')
.send({ email: USER_EMAIL, password: USER_UNHASHED_PASSWORD })
.send({
email: USER_EMAIL,
password: USER_UNHASHED_PASSWORD,
socialProvider: MOCK_USER.socialProvider,
socialId: MOCK_USER.socialId,
givenName: MOCK_USER.givenName,
familyName: MOCK_USER.familyName,
profilePicture: MOCK_USER.profilePicture,
})
.expect(201)
.expect('Content-Type', /json/)
.then((res) => {
Expand All @@ -141,7 +150,10 @@ describe('ServerFeatureTodoController E2E', () => {
access_token = await request
.default(app.getHttpServer())
.post(`${baseUrl}${authUrl}/login`)
.send({ email: USER_EMAIL, password: USER_UNHASHED_PASSWORD })
.send({
email: USER_EMAIL,
password: USER_UNHASHED_PASSWORD,
})
.expect(200)
.expect('Content-Type', /json/)
.then((resp) => (resp.body as ITokenResponse).access_token);
Expand Down
34 changes: 26 additions & 8 deletions apps/server-e2e/src/server/user-controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
ITokenResponse,
IUser,
} from '@fst/shared/domain';
import { createMockUser } from '@fst/shared/util-testing';
import {
HttpStatus,
INestApplication,
Expand All @@ -20,8 +21,8 @@ import {
import { ConfigModule, ConfigService } from '@nestjs/config';
import { APP_FILTER, APP_GUARD } from '@nestjs/core';
import { Test } from '@nestjs/testing';
import { getRepositoryToken, TypeOrmModule } from '@nestjs/typeorm';
import { randEmail, randPassword, randUser } from '@ngneat/falso';
import { TypeOrmModule, getRepositoryToken } from '@nestjs/typeorm';
import { randEmail, randPassword } from '@ngneat/falso';
import Joi from 'joi';
import * as request from 'supertest';
import { Repository } from 'typeorm';
Expand All @@ -30,10 +31,11 @@ describe('ServerFeatureUserController E2E', () => {
const baseUrl = `/api/v1`;
const todoUrl = `/todos`;
const userUrl = `/users`;
const authUrl = `/auth`;
const authUrl = `/auth/email`;

const USER_EMAIL = randEmail();
const USER_UNHASHED_PASSWORD = `Password1!`;
const MOCK_USER = createMockUser({ email: USER_EMAIL });

let app: INestApplication;
let todoRepo: Repository<ITodo>;
Expand Down Expand Up @@ -125,7 +127,15 @@ describe('ServerFeatureUserController E2E', () => {
.default(app.getHttpServer())
.post(`${baseUrl}${userUrl}`)
.set('Content-type', 'application/json')
.send({ email: USER_EMAIL, password: USER_UNHASHED_PASSWORD })
.send({
email: USER_EMAIL,
password: USER_UNHASHED_PASSWORD,
socialProvider: MOCK_USER.socialProvider,
socialId: MOCK_USER.socialId,
givenName: MOCK_USER.givenName,
familyName: MOCK_USER.familyName,
profilePicture: MOCK_USER.profilePicture,
})
.expect(201)
.expect('Content-Type', /json/)
.then((res) => {
Expand Down Expand Up @@ -240,14 +250,17 @@ describe('ServerFeatureUserController E2E', () => {

describe('POST /users', () => {
it('should create a new user', () => {
const { email: randEmail } = randUser();
const { id, todos, ...user } = createMockUser({
password: 'FullStackT0d0!',
});
return request
.default(app.getHttpServer())
.post(`${baseUrl}${userUrl}`)
.send({ email: randEmail, password: 'FullStackT0d0!' })
.send({ ...user })
.expect(({ body }) => {
console.log(`body`, body);
const { email, id } = body as IPublicUserData;
expect(email).toEqual(randEmail);
expect(email).toEqual(user.email);
expect(typeof id).toBe('string');
expect(Object.keys(body).includes('password')).toEqual(false);
})
Expand Down Expand Up @@ -287,6 +300,10 @@ describe('ServerFeatureUserController E2E', () => {

it('should prevent duplicate emails', async () => {
const existingUser = (await userRepo.find({ take: 1 })).pop();
const { id, todos, ...newUser } = createMockUser({
email: existingUser.email,
password: 'FullStackT0d0!',
});
const users = await userRepo.find();
Logger.debug(
`All users:\n${JSON.stringify(users, null, 2)}`,
Expand All @@ -295,8 +312,9 @@ describe('ServerFeatureUserController E2E', () => {
return request
.default(app.getHttpServer())
.post(`${baseUrl}${userUrl}`)
.send({ email: existingUser.email, password: 'FullStackT0d0!' })
.send({ ...newUser })
.expect((resp) => {
console.log(`resp`, resp.body);
const { message } = resp.body;
// this error does not come back in the form of an array of
// errors since it's a database error, not a payload
Expand Down
12 changes: 8 additions & 4 deletions apps/server/src/app/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,30 @@
import { ServerFeatureTodoModule } from '@fst/server/feature-todo';
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';

import { TypeOrmModule } from '@nestjs/typeorm';

import { ServerFeatureAuthModule } from '@fst/server/feature-auth';
import { ServerFeatureAuthGoogleModule } from '@fst/server/feature-auth-google';
import { ServerFeatureHealthModule } from '@fst/server/feature-health';
import { ServerFeatureTodoModule } from '@fst/server/feature-todo';
import { ServerFeatureUserModule } from '@fst/server/feature-user';
import {
DatabaseExceptionFilter,
JwtAuthGuard,
TypeormConfigService,
appConfig,
dbConfig,
googleConfig,
validationSchema,
} from '@fst/server/util';
import { APP_FILTER, APP_GUARD } from '@nestjs/core';
import { TypeOrmModule } from '@nestjs/typeorm';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
envFilePath: ['.env'],
ignoreEnvVars: true,
validationSchema,
load: [appConfig, dbConfig],
load: [appConfig, dbConfig, googleConfig],
}),
TypeOrmModule.forRootAsync({
useClass: TypeormConfigService,
Expand All @@ -31,6 +33,8 @@ import { APP_FILTER, APP_GUARD } from '@nestjs/core';
ServerFeatureTodoModule,
ServerFeatureHealthModule,
ServerFeatureAuthModule,
ServerFeatureUserModule,
ServerFeatureAuthGoogleModule,
],
controllers: [],
providers: [
Expand Down
5 changes: 4 additions & 1 deletion apps/server/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@
import { Logger, ValidationPipe, VersioningType } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { NestFactory } from '@nestjs/core';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';

import { CONFIG_PORT } from '@fst/server/util';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { AppModule } from './app/app.module';

async function bootstrap() {
Expand All @@ -25,6 +25,7 @@ async function bootstrap() {
);
const configService = app.get(ConfigService);
const port = configService.get(CONFIG_PORT);
Logger.log(`Listening on port ${port}`);

// set up versioning
app.enableVersioning({
Expand All @@ -36,6 +37,7 @@ async function bootstrap() {
app.enableCors({
origin: '*',
});
Logger.log(`Enabled all origins for CORS`);

// handle swagger
const config = new DocumentBuilder()
Expand All @@ -47,6 +49,7 @@ async function bootstrap() {
SwaggerModule.setup('api/v1', app, document, {
jsonDocumentUrl: 'api/v1/swagger.json',
});
Logger.log(`Swagger initialized`);

await app.listen(port);
Logger.log(
Expand Down
17 changes: 12 additions & 5 deletions libs/client/data-access/src/lib/auth.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { SocialAuthService } from '@abacritt/angularx-social-login';
import { HttpClient } from '@angular/common/http';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { TOKEN_STORAGE_KEY } from '@fst/client/util';
import { ITokenResponse } from '@fst/shared/domain';
import { ITokenResponse, SocialProviderEnum } from '@fst/shared/domain';
import { randEmail } from '@ngneat/falso';
import { of } from 'rxjs';

Expand All @@ -18,6 +19,12 @@ describe('AuthService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [
{
provide: SocialAuthService,
useValue: {},
},
],
});
service = TestBed.inject(AuthService);
http = TestBed.inject(HttpClient);
Expand All @@ -28,7 +35,7 @@ describe('AuthService', () => {
});

it('should update localStorage when setting a token', (done) => {
service.setToken('foo');
service.setToken(SocialProviderEnum.email, 'foo');
service.accessToken$.subscribe({
next: (token) => {
expect(token).toEqual('foo');
Expand Down Expand Up @@ -68,7 +75,7 @@ describe('AuthService', () => {
access_token: '',
};
const spy = jest.spyOn(http, 'post').mockReturnValue(of(resp));
service.loginUser({ email: randEmail(), password: '' }).subscribe({
service.loginUserByEmail({ email: randEmail(), password: '' }).subscribe({
next: ({ access_token }) => {
expect(access_token).toStrictEqual('');
done();
Expand All @@ -80,7 +87,7 @@ describe('AuthService', () => {
it('should clear storage on log out', (done) => {
const token =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6IndhbGxhY2VAdGhlZnVsbHN0YWNrLmVuZ2luZWVyIiwic3ViIjoiYmQ0ZTNmOTEtMDUxZC00NGU4LTgyMDQtZmY4YjFjYzk1OTU3IiwiaWF0IjoxNjgwMDE0MDQwLCJleHAiOjE2ODAwMTQ2NDB9.LdH-sN9IXD78P9z78a8k__70zS6FFqOenpiNrJ6eifg';
service.setToken(token);
service.setToken(SocialProviderEnum.email, token);
expect(localStorage.getItem(TOKEN_STORAGE_KEY)).toStrictEqual(token);

service.logoutUser();
Expand All @@ -91,7 +98,7 @@ describe('AuthService', () => {
it('should detect an expired token', (done) => {
const token =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6IndhbGxhY2VAdGhlZnVsbHN0YWNrLmVuZ2luZWVyIiwic3ViIjoiYmQ0ZTNmOTEtMDUxZC00NGU4LTgyMDQtZmY4YjFjYzk1OTU3IiwiaWF0IjoxNjgwMDE0MDQwLCJleHAiOjE2ODAwMTQ2NDB9.LdH-sN9IXD78P9z78a8k__70zS6FFqOenpiNrJ6eifg';
service.setToken(token);
service.setToken(SocialProviderEnum.email, token);
expect(localStorage.getItem(TOKEN_STORAGE_KEY)).toStrictEqual(token);
service.loadToken();

Expand Down
Loading