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

implemented basic backend for notification #28

Merged
merged 1 commit into from
Nov 15, 2024
Merged
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
3 changes: 2 additions & 1 deletion backend/dist/app.module.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,12 @@ const common_1 = require("@nestjs/common");
const auth_module_1 = require("./auth/auth.module");
const user_module_1 = require("./user/user.module");
const grant_module_1 = require("./grant/grant.module");
const notification_module_1 = require("./notifications/notification.module");
let AppModule = class AppModule {
};
AppModule = __decorate([
(0, common_1.Module)({
imports: [auth_module_1.AuthModule, user_module_1.UserModule, grant_module_1.GrantModule],
imports: [auth_module_1.AuthModule, user_module_1.UserModule, grant_module_1.GrantModule, notification_module_1.NotificationsModule],
})
], AppModule);
exports.AppModule = AppModule;
12 changes: 12 additions & 0 deletions backend/dist/auth/auth.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ let AuthController = class AuthController {
async setNewPassword(newPassword, session, username, email) {
return await this.authService.setNewPassword(newPassword, session, username, email);
}
async updateProfile(username, displayName) {
await this.authService.updateProfile(username, displayName);
return { message: 'Profile has been updated' };
}
};
__decorate([
(0, common_1.Post)('register'),
Expand Down Expand Up @@ -58,6 +62,14 @@ __decorate([
__metadata("design:paramtypes", [String, String, String, String]),
__metadata("design:returntype", Promise)
], AuthController.prototype, "setNewPassword", null);
__decorate([
(0, common_1.Post)('update-profile'),
__param(0, (0, common_1.Body)('username')),
__param(1, (0, common_1.Body)('displayName')),
__metadata("design:type", Function),
__metadata("design:paramtypes", [String, String]),
__metadata("design:returntype", Promise)
], AuthController.prototype, "updateProfile", null);
AuthController = __decorate([
(0, common_1.Controller)('auth'),
__metadata("design:paramtypes", [auth_service_1.AuthService])
Expand Down
47 changes: 40 additions & 7 deletions backend/dist/auth/auth.service.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,6 @@ exports.AuthService = void 0;
const common_1 = require("@nestjs/common");
const aws_sdk_1 = __importDefault(require("aws-sdk"));
const crypto = __importStar(require("crypto"));
aws_sdk_1.default.config.update({
region: process.env.AWS_REGION,
});
let AuthService = AuthService_1 = class AuthService {
constructor() {
this.logger = new common_1.Logger(AuthService_1.name);
Expand Down Expand Up @@ -187,14 +184,28 @@ let AuthService = AuthService_1 = class AuthService {
.promise();
user = newUser;
}
return { access_token: idToken, user };
return { access_token: idToken, user, message: "Login Successful!" };
}
catch (error) {
if (error instanceof Error) {
/* Login Failures */
const cognitoError = error;
if (cognitoError.code) {
switch (cognitoError.code) {
case 'NotAuthorizedException':
this.logger.warn(`Login failed: ${cognitoError.message}`);
throw new common_1.UnauthorizedException('Incorrect username or password.');
default:
this.logger.error(`Login failed: ${cognitoError.message}`, cognitoError.stack);
throw new common_1.InternalServerErrorException('An error occurred during login.');
}
}
else if (error instanceof Error) {
// Handle non-AWS errors
this.logger.error('Login failed', error.stack);
throw new Error(error.message || 'Login failed');
throw new common_1.InternalServerErrorException(error.message || 'Login failed.');
}
throw new Error('An unknown error occurred during login');
// Handle unknown errors
throw new common_1.InternalServerErrorException('An unknown error occurred during login.');
}
}
async setNewPassword(newPassword, session, username, email) {
Expand Down Expand Up @@ -238,6 +249,28 @@ let AuthService = AuthService_1 = class AuthService {
throw new Error('An unknown error occurred');
}
}
async updateProfile(username, displayName) {
try {
const tableName = process.env.DYNAMODB_USER_TABLE_NAME || 'TABLE_FAILURE';
const params = {
TableName: tableName,
Key: { userId: username },
UpdateExpression: 'set displayName = :displayName',
ExpressionAttributeValues: {
':displayName': displayName
},
};
await this.dynamoDb.update(params).promise();
this.logger.log(`User ${username} updated user profile.`);
}
catch (error) {
if (error instanceof Error) {
this.logger.error('Updating the profile failed', error.stack);
throw new Error(error.message || 'Updating the profile failed');
}
throw new Error('An unknown error occurred');
}
}
};
AuthService = AuthService_1 = __decorate([
(0, common_1.Injectable)()
Expand Down
4 changes: 3 additions & 1 deletion backend/dist/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@ const aws_sdk_1 = __importDefault(require("aws-sdk"));
/* ! */
async function bootstrap() {
aws_sdk_1.default.config.update({
region: process.env.AWS_REGION
region: process.env.AWS_REGION,
accessKeyId: process.env.OPEN_HATCH,
secretAccessKey: process.env.CLOSED_HATCH
});
const app = await core_1.NestFactory.create(app_module_1.AppModule);
app.enableCors();
Expand Down
2 changes: 1 addition & 1 deletion backend/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Module } from '@nestjs/common';
import { AuthModule } from './auth/auth.module';
import { UserModule } from './user/user.module';
import { GrantModule } from './grant/grant.module';
import { NotificationsModule } from './notifications/notifications.module';
import { NotificationsModule } from './notifications/notification.module';

@Module({
imports: [AuthModule, UserModule, GrantModule, NotificationsModule],
Expand Down
62 changes: 62 additions & 0 deletions backend/src/notifications/notifcation.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// src/notifications/notifications.service.ts
import { Injectable } from '@nestjs/common';
import * as AWS from 'aws-sdk';
import { Notification } from './notification.model'; // Adjust the path as needed




AWS.config.update({ region: 'us-east-1' });
const dynamodb = new AWS.DynamoDB.DocumentClient();


@Injectable()
export class NotificationService {


// Function to create a notification
async createNotification(notification: Notification): Promise<Notification> {

const alertTime = new Date(notification.alertTime); // Ensures a Date can be created from the given alertTime


const params = {
TableName: process.env.DYNAMODB_NOTIFICATION_TABLE_NAME || 'TABLE_FAILURE',
Item: {
...notification,
alertTime: alertTime.toISOString(),
},
};
await dynamodb.put(params).promise();
return notification;
}


// function to find notifications by notification id
async getNotificationByUserId(userId: string): Promise<Notification> {


const params = {
TableName: process.env.DYNAMODB_NOTIFICATION_TABLE_NAME || 'TABLE_FAILURE',
Key: {
userId : userId
},
};


try {
const data = await dynamodb.get(params).promise();


if (!data.Item) {
throw new Error('No notification with user id ' + userId + ' found.');
}


return data.Item as Notification;
} catch (error) {
console.log(error)
throw new Error('Failed to retrieve notification.');
}
}
}
14 changes: 0 additions & 14 deletions backend/src/notifications/notifcations.service.ts

This file was deleted.

27 changes: 27 additions & 0 deletions backend/src/notifications/notification.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// src/notifications/notifications.controller.ts
import { Controller, Post, Body, Get, Query } from '@nestjs/common';
import { NotificationService } from './notifcation.service';
import { Notification } from './notification.model';


@Controller('notifications')
export class NotificationController {


constructor(private readonly notificationService: NotificationService) { }


@Post()
async create(@Body() notification: Partial<Notification>): Promise<Notification> {
// Call the service's createNotification method and return the result
return await this.notificationService.createNotification(notification as Notification);
}


@Get(':userId')
async findByUser(@Query('userId') userId: string) {
return await this.notificationService.getNotificationByUserId(userId);
}


}
6 changes: 6 additions & 0 deletions backend/src/notifications/notification.model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export interface Notification {
notificationId: string; // Partition
userId: string;
message: string;
alertTime: Date; // Sort
}
12 changes: 12 additions & 0 deletions backend/src/notifications/notification.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// src/notifications/notifications.module.ts
import { Module } from '@nestjs/common';
import { NotificationController } from './notification.controller';
import { NotificationService } from './notifcation.service';


@Module({
providers: [NotificationService],
controllers: [NotificationController],
exports: [NotificationService],
})
export class NotificationsModule {}
17 changes: 0 additions & 17 deletions backend/src/notifications/notifications.controller.ts

This file was deleted.

11 changes: 0 additions & 11 deletions backend/src/notifications/notifications.module.ts

This file was deleted.

Loading