Skip to content

Instantly share code, notes, and snippets.

@raress96
Created April 4, 2022 09:26
Show Gist options
  • Save raress96/4135c92049667e9df0d88d4b3b65bb7c to your computer and use it in GitHub Desktop.
Save raress96/4135c92049667e9df0d88d4b3b65bb7c to your computer and use it in GitHub Desktop.
Elrond generate jwt
import { BadRequestException, Body, Controller, Post, UseGuards } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { CachingService } from '../../common/caching/caching.service';
import { randomBytes } from 'crypto';
import { Constants } from '../../utils/constants';
import { JwtService } from '@nestjs/jwt';
import { LoginDto } from './dto/login.dto';
import { Address, SignableMessage, UserPublicKey } from '@elrondnetwork/erdjs/out';
import { ThrottlerBehindProxyGuard } from '../../common/throttle/throttle.guard';
@Controller('/auth')
@ApiTags('auth')
export class AuthController {
constructor(private readonly cachingService: CachingService, private readonly jwtService: JwtService) {}
@UseGuards(ThrottlerBehindProxyGuard)
@Post('/token')
async token(): Promise<string> {
const token: string = await new Promise((resolve, reject) => {
randomBytes(16, (err, buffer) => {
if (err) {
reject(err);
return;
}
resolve(buffer.toString('hex'));
});
});
await this.cachingService.setCache(`token:${token}`, true, Constants.oneMinute() * 10);
return token;
}
@Post('/login')
async login(@Body() loginDto: LoginDto): Promise<string> {
if (!(await this.cachingService.getCache(`token:${loginDto.token}`))) {
throw new BadRequestException('Token has expired!');
}
const address = new Address(loginDto.address);
const publicKey = new UserPublicKey(address.pubkey());
const verify = publicKey.verify(
new SignableMessage({
message: Buffer.from(`${loginDto.address}${loginDto.token}\{\}`),
address,
}).serializeForSigning(),
Buffer.from(loginDto.signature, 'hex')
);
if (!verify) {
throw new BadRequestException('Signature could not be verified');
}
const payload = { sub: loginDto.address };
return this.jwtService.sign(payload);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment