Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: basic attempt to authorize users #5

Open
wants to merge 15 commits into
base: develop
Choose a base branch
from
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: 5 additions & 0 deletions .firebaserc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"projects": {
"default": "auth-20a66"
}
}
7 changes: 7 additions & 0 deletions database.rules.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
/* Visit https://firebase.google.com/docs/database/security to learn more about security rules. */
"rules": {
".read": false,
".write": false
}
}
5 changes: 5 additions & 0 deletions firebase.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"database": {
"rules": "database.rules.json"
}
}
763 changes: 744 additions & 19 deletions package-lock.json

Large diffs are not rendered by default.

4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,11 @@
"class-validator": "^0.14.1",
"dotenv": "^16.4.5",
"mongoose": "^8.5.1",
"nest-winston": "^1.9.7",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1",
"uuid": "^10.0.0"
"uuid": "^10.0.0",
"winston": "^3.14.2"
},
"devDependencies": {
"@eslint/js": "^9.7.0",
Expand Down
18 changes: 18 additions & 0 deletions src/app.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';

describe('AppController', () => {
let controller: AppController;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [AppController],
}).compile();

controller = module.get<AppController>(AppController);
});

it('should be defined', () => {
expect(controller).toBeDefined();
});
});
11 changes: 11 additions & 0 deletions src/app.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Controller, Get, UseGuards, Request } from '@nestjs/common';
import { AuthGuard } from './auth/auth.guard';

@Controller()
export class AppController {
@Get('protected')
@UseGuards(AuthGuard)
getProtected(@Request() req): string {
return `Hello ${req.user.name}`;
}
}
13 changes: 10 additions & 3 deletions src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
import { Module } from '@nestjs/common';
import { Logger, Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { MongooseModule } from '@nestjs/mongoose';
import { getMongoConnectionString } from './libs';
import { MongooseModule } from '@nestjs/mongoose';
import { AppController } from './app.controller';
import { AuthModule } from './auth/auth.module';
import { AppService } from './app.service';

@Module({
imports: [
MongooseModule.forRoot('mongodb://localhost/nest'),
AuthModule,

ConfigModule.forRoot({
envFilePath: ['.env.local', '.env'],
isGlobal: true,
Expand All @@ -17,7 +24,7 @@ import { getMongoConnectionString } from './libs';
}),
}),
],
controllers: [],
providers: [],
controllers: [AppController],
providers: [LoggerAppService]
})
export class AppModule {}
8 changes: 8 additions & 0 deletions src/app.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { Injectable } from '@nestjs/common';

@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}
18 changes: 18 additions & 0 deletions src/auth/auth.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AuthController } from './auth.controller';

describe('AuthController', () => {
let controller: AuthController;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [AuthController],
}).compile();

controller = module.get<AuthController>(AuthController);
});

it('should be defined', () => {
expect(controller).toBeDefined();
});
});
4 changes: 4 additions & 0 deletions src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { Controller } from '@nestjs/common';

@Controller('auth')
export class AuthController {}
26 changes: 26 additions & 0 deletions src/auth/auth.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from '@nestjs/common';
import { AuthService } from './auth.service';

@Injectable()
export class AuthGuard implements CanActivate {
constructor(private readonly authService: AuthService) {}

async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const token = request.headers.authorization?.split(' ')[1];

if (!token) {
console.error('No token provided');
throw new UnauthorizedException('No token');
}

try {
const decodedToken = await this.authService.verifyToken(token);
request.user = decodedToken;
return true;
} catch (error) {
console.error('Token verification failed:', error);
throw new UnauthorizedException('Invalid token');
}
}
}
15 changes: 15 additions & 0 deletions src/auth/auth.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { User, UserSchema } from '../schemas/user.schema';
import { AuthGuard } from './auth.guard';


@Module({
imports: [MongooseModule.forFeature([{ name: User.name, schema: UserSchema }])],
providers: [AuthService, AuthGuard],
controllers: [AuthController],
exports: [AuthService],
})
export class AuthModule {}
18 changes: 18 additions & 0 deletions src/auth/auth.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AuthService } from './auth.service';

describe('AuthService', () => {
let service: AuthService;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [AuthService],
}).compile();

service = module.get<AuthService>(AuthService);
});

it('should be defined', () => {
expect(service).toBeDefined();
});
});
35 changes: 35 additions & 0 deletions src/auth/auth.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import * as admin from 'firebase-admin';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { User } from '../schemas/user.schema';

@Injectable()
export class AuthService {
constructor(@InjectModel(User.name) private userModel: Model<User>) {}

async verifyToken(token: string): Promise<any> {
try {
const decodedToken = await admin.auth().verifyIdToken(token);
await this.storeToken(decodedToken.uid, token);
return decodedToken;
} catch (error) {
throw new UnauthorizedException('Invalid token');
}
}

private async storeToken(uid: string, token: string): Promise<void> {
const user = await this.userModel.findOne({ uid });

if (user) {
user.tokens.push(token);
await user.save();
} else {
const newUser = new this.userModel({
uid,
tokens: [token],
});
await newUser.save();
}
}
}
30 changes: 30 additions & 0 deletions src/components/loginButton.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import React from 'react';
import firebase from '../config/firebaseConfig';

const LoginButton = () => {
const handleLogin = async () => {
try {
const provider = new firebase.auth.GoogleAuthProvider();
const result = await firebase.auth().signInWithPopup(provider);
const token = await result.user.getIdToken();

console.log('Token:', token);

const response = await fetch('http://localhost:3000/protected', {
method: 'GET',
headers: {
Authorization: `Bearer ${token}`,
},
});

const data = await response.text();
console.log('Protected data:', data);
} catch (error) {
console.error('Error logging in:', error.message);
}
};

return <button onClick={handleLogin}>Zaloguj się przez Google</button>;
};

export default LoginButton;
15 changes: 15 additions & 0 deletions src/config/firebaseConfig.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";

const firebaseConfig = {
apiKey: "AIzaSyBcaalyPESHwdg_Gq7ezuXJKC-p9KndztU",
authDomain: "auth-20a66.firebaseapp.com",
projectId: "auth-20a66",
storageBucket: "auth-20a66.appspot.com",
messagingSenderId: "323908200672",
appId: "1:323908200672:web:ceb3ebe36816038fc00885",
measurementId: "G-C6FZWMPVCW"
};

const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
41 changes: 41 additions & 0 deletions src/libs/internal/winston.logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { createLogger, format, transports } from 'winston';

const customFormat = format.printf(({ timestamp, level, stack, message }) => {
return `${timestamp} - [${level.toUpperCase().padEnd(1)}] - ${stack || message}`;
});

const options = {
file: {
filename: './logs/error.log',
level: 'error',
},
console: {
level: 'silly',
colorize: true,
},
ExceptionHandlers: {
filename: './logs/exceptions.log',
},
};

const devLogger = {
format: format.combine(
format.timestamp(),
format.errors({ stack: true }),
customFormat,
),
transports: [
new transports.File(options.file),
new transports.File({
filename: './logs/combine.log',
level: 'info',
}),
new transports.Console(options.console),
],
};

export const WinstonLogger = createLogger(devLogger);

WinstonLogger.exceptions.handle(
new transports.File({ filename: './logs/exceptions.log' }),
);
24 changes: 20 additions & 4 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,34 @@
import { ValidationPipe } from '@nestjs/common';
import { Logger } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as admin from 'firebase-admin';
import * as dotenv from 'dotenv';
import { HttpExceptionFilter } from './libs';
import { WinstonModule } from 'nest-winston';
import { WinstonLogger } from 'src/libs/internal/winston.logger';

async function bootstrap(): Promise<void> {
const app = await NestFactory.create(AppModule);
dotenv.config();

admin.initializeApp({
credential: admin.credential.cert({
projectId: process.env.PROJECT_ID,
clientEmail: process.env.CLIENT_EMAIL,
privateKey: process.env.PRIVATE_KEY.replace(/\\n/g, '\n'),
}),
});

const app = await NestFactory.create(AppModule, {
logger: WinstonModule.createLogger({
instance: WinstonLogger,
}),
});
app.useGlobalPipes(new ValidationPipe());
app.setGlobalPrefix('api/v1');
app.useGlobalFilters(new HttpExceptionFilter());
await app.listen(`${process.env.HOST_PORT}`);

const logger = new Logger('Bootstrap');
logger.log(
WinstonLogger.info(
`Server running on: http://${process.env.HOST_NAME}:${process.env.HOST_PORT}`,
);
}
Expand Down
19 changes: 19 additions & 0 deletions src/schemas/user.schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';

@Schema()
export class User extends Document {
@Prop({ required: true })
uid: string;

@Prop()
name: string;

@Prop()
email: string;

@Prop()
tokens: string[];
}

export const UserSchema = SchemaFactory.createForClass(User);
5 changes: 4 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@
"noImplicitAny": false,
"strictBindCallApply": false,
"forceConsistentCasingInFileNames": false,
"noFallthroughCasesInSwitch": false
"noFallthroughCasesInSwitch": false,
"resolveJsonModule": true,
"esModuleInterop": true

}
}
Loading