Skip to content

Commit

Permalink
Merge pull request #1 from hypersign-protocol/hypersignAuth
Browse files Browse the repository at this point in the history
added user module
  • Loading branch information
varsha766 authored Nov 13, 2023
2 parents aa8ded4 + 4769135 commit e5dbfd3
Show file tree
Hide file tree
Showing 9 changed files with 87 additions and 17 deletions.
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,16 @@
"fs": "^0.0.1-security",
"hid-hd-wallet": "git+https://github.com/hypersign-protocol/hid-hd-wallet.git#main",
"hs-ssi-sdk": "7.0.1",
"hypersign-auth-node-sdk": "^6.3.2",
"hypersign-auth-node-sdk": "^6.3.4",
"hypersign-edv-client": "github:hypersign-protocol/hypersign-edv-client#develop",
"mongoose": "^6.8.3",
"passport": "^0.6.0",
"passport-jwt": "^4.0.1",
"passport-local": "^1.0.0",
"reflect-metadata": "^0.1.13",
"rxjs": "^7.2.0",
"swagger-ui-express": "^4.6.0"
"swagger-ui-express": "^4.6.0",
"uuid": "^9.0.1"
},
"devDependencies": {
"@nestjs/cli": "^9.0.0",
Expand Down
2 changes: 1 addition & 1 deletion src/app-auth/app-auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { JwtStrategy } from './strategy/jwt.strategy';
import { AppAuthApiKeyService } from './services/app-auth-apikey.service';
import { TrimMiddleware } from 'src/utils/middleware/trim.middleware';
import { HypersignAuthorizeMiddleware } from 'src/utils/middleware/hypersign-authorize.middleware';
import { HypersignAuthDataTransformerMiddleware } from 'src/utils/middleware/tranform-hypersign-user-data';
import { HypersignAuthDataTransformerMiddleware } from '../user/middleware/tranform-hypersign-user-data';
@Module({
imports: [
MongooseModule.forFeature([{ name: App.name, schema: AppSchema }]),
Expand Down
4 changes: 1 addition & 3 deletions src/app-auth/controllers/app-auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ import { AuthenticatedGuard } from 'src/org-user/guard/authenticated.guard';
@UseFilters(AllExceptionsFilter)
@ApiTags('Application')
@Controller('/api/v1/app')
// @UseGuards(AuthenticatedGuard)
export class AppAuthController {
constructor(private readonly appAuthService: AppAuthService) {}
@UseInterceptors(
Expand Down Expand Up @@ -132,12 +131,11 @@ export class AppAuthController {
type: AppError,
})
@UsePipes(new ValidationPipe({ transform: true }))
register(
async register(
@Req() req: any,
@Body() createAppDto: CreateAppDto,
): Promise<createAppResponse> {
Logger.log('register() method: starts', 'AppAuthController');

const userId = req.user.userId;

return this.appAuthService.createAnApp(createAppDto, userId);
Expand Down
17 changes: 14 additions & 3 deletions src/user/controllers/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,22 +33,33 @@ import { AllExceptionsFilter } from '../../utils/utils';
import { PaginationDto } from 'src/utils/pagination.dto';
import { AuthenticatedGuard } from 'src/org-user/guard/authenticated.guard';
import { UserService } from '../services/user.service';
import { UserRepository } from '../repository/user.repository';

@UseFilters(AllExceptionsFilter)
@ApiTags('Authentication')
@Controller()
export class UserController {
constructor(private readonly userService: UserService) {}
constructor(
private readonly userService: UserService,
private readonly userRepository: UserRepository,
) {}

@Post('/hs/api/v2/auth')
@UsePipes(new ValidationPipe({ transform: true }))
authenticate(@Res() res: any, @Req() req: any, @Body() body: any) {
async authenticate(@Res() res: any, @Req() req: any, @Body() body: any) {
Logger.log('authenticate() method: starts', 'userController');

const { hypersign } = body;
Logger.log(hypersign);
const { user } = hypersign.data;
Logger.log(user);
let userInfo = await this.userRepository.findOne({ email: user.email });
if (!userInfo) {
userInfo = await this.userRepository.create({
email: user.email,
did: user.id,
userId: user.appUserID,
});
}
res.status(200).json({
status: 200,
message: user,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,10 @@ import { NextFunction } from 'express';

export class HypersignAuthDataTransformerMiddleware implements NestMiddleware {
async use(req: Request, res: Response, next: NextFunction) {
const {} = req.body;
const { data } = req.body['hypersign'];
const userId = data.email;

req['user'] = {
userId: data['email'],
userId: data.appUserID,
email: data.email,
did: data['id'],
name: data['name'],
};
Expand Down
39 changes: 39 additions & 0 deletions src/user/repository/user.repository.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { Logger } from '@nestjs/common';
import { User, UserDocument } from '../schema/user.schema';
import { InjectModel } from '@nestjs/mongoose';
import { FilterQuery, Model } from 'mongoose';

export class UserRepository {
constructor(
@InjectModel(User.name) private readonly userModel: Model<UserDocument>,
) {}
async findOne(userFilterQuery: FilterQuery<User>): Promise<User> {
Logger.log(
'findOne() method: starts, finding particular user from db',
'UserRepository',
);
return this.userModel.findOne(userFilterQuery);
}

async create(user: User): Promise<UserDocument> {
Logger.log(
'create() method: starts, adding user to userDb',
'UserRepository',
);
const newUser = new this.userModel(user);
return newUser.save();
}

async findOneUpdate(
userFilterQuery: FilterQuery<UserDocument>,
user: Partial<UserDocument>,
) {
Logger.log(
'findOneUpdate() method: start, updating user db',
'UserRepository',
);
return this.userModel.findOneAndUpdate(userFilterQuery, user, {
new: true,
});
}
}
15 changes: 15 additions & 0 deletions src/user/schema/user.schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';

export type UserDocument = User & Document;
@Schema({ timestamps: true })
export class User {
@Prop({ required: true })
userId: string;
@Prop({ required: true, unique: true })
email: string;
@Prop({ required: true, unique: true })
did: string;
}

export const UserSchema = SchemaFactory.createForClass(User);
UserSchema.index({ email: 1 }, { unique: true });
11 changes: 9 additions & 2 deletions src/user/user.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,17 @@ import { HypersignAuthenticateMiddleware } from 'src/utils/middleware/hypersign-
import { WhitelistAppCorsMiddleware } from 'src/app-auth/middlewares/cors.middleware';
import { AppAuthModule } from 'src/app-auth/app-auth.module';
import { HypersignAuthorizeMiddleware } from 'src/utils/middleware/hypersign-authorize.middleware';
import { UserRepository } from './repository/user.repository';
import { MongooseModule } from '@nestjs/mongoose';
import { UserSchema, User } from './schema/user.schema';
@Module({
imports: [AppAuthModule],
imports: [
MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]),
AppAuthModule,
],
controllers: [UserController],
providers: [UserService],
providers: [UserService, UserRepository],
exports: [UserRepository, UserModule],
})
export class UserModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
Expand Down
5 changes: 3 additions & 2 deletions src/utils/middleware/hypersign-authenticate.middleware.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Injectable, Logger, NestMiddleware } from '@nestjs/common';

import { v4 as uuidv4 } from 'uuid';
import { NextFunction, Request, Response } from 'express';
@Injectable()
export class HypersignAuthenticateMiddleware implements NestMiddleware {
Expand All @@ -8,6 +8,7 @@ export class HypersignAuthenticateMiddleware implements NestMiddleware {
'Inside HypersignAuthenticateMiddleware; before calling hs auth authenticate()',
'HypersignAuthenticateMiddleware',
);
return globalThis.hypersignAuth.authenticate(req, res, next);
const userId = uuidv4(); // can't generate userId here fetch userId based on email and use that userID
return globalThis.hypersignAuth.authenticate(req, res, next, userId);
}
}

0 comments on commit e5dbfd3

Please sign in to comment.