Browse Source

Setup API key strategy

pull/4093/head
Thomas Kaul 9 months ago
parent
commit
82ff95245f
  1. 5
      apps/api/src/app/user/user.service.ts
  2. 4
      apps/api/src/helper/string.helper.ts
  3. 12
      apps/api/src/services/api-key/api-key.service.ts

5
apps/api/src/app/user/user.service.ts

@ -38,11 +38,10 @@ import { UserWithSettings } from '@ghostfolio/common/types';
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { EventEmitter2 } from '@nestjs/event-emitter'; import { EventEmitter2 } from '@nestjs/event-emitter';
import { Prisma, Role, User } from '@prisma/client'; import { Prisma, Role, User } from '@prisma/client';
import { createHmac } from 'crypto';
import { differenceInDays, subDays } from 'date-fns'; import { differenceInDays, subDays } from 'date-fns';
import { sortBy, without } from 'lodash'; import { sortBy, without } from 'lodash';
const crypto = require('crypto');
@Injectable() @Injectable()
export class UserService { export class UserService {
private i18nService = new I18nService(); private i18nService = new I18nService();
@ -62,7 +61,7 @@ export class UserService {
} }
public createAccessToken(password: string, salt: string): string { public createAccessToken(password: string, salt: string): string {
const hash = crypto.createHmac('sha512', salt); const hash = createHmac('sha512', salt);
hash.update(password); hash.update(password);
return hash.digest('hex'); return hash.digest('hex');

4
apps/api/src/helper/string.helper.ts

@ -1,7 +1,7 @@
const crypto = require('crypto'); import { randomBytes } from 'crypto';
export function getRandomString(length: number) { export function getRandomString(length: number) {
const bytes = crypto.randomBytes(length); const bytes = randomBytes(length);
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
const result = []; const result = [];

12
apps/api/src/services/api-key/api-key.service.ts

@ -3,7 +3,7 @@ import { PrismaService } from '@ghostfolio/api/services/prisma/prisma.service';
import { ApiKeyResponse } from '@ghostfolio/common/interfaces'; import { ApiKeyResponse } from '@ghostfolio/common/interfaces';
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import * as crypto from 'crypto'; import { pbkdf2Sync } from 'crypto';
@Injectable() @Injectable()
export class ApiKeyService { export class ApiKeyService {
@ -41,9 +41,13 @@ export class ApiKeyService {
} }
public hashApiKey(apiKey: string): string { public hashApiKey(apiKey: string): string {
return crypto return pbkdf2Sync(
.pbkdf2Sync(apiKey, '', this.iterations, this.keyLength, this.algorithm) apiKey,
.toString('hex'); '',
this.iterations,
this.keyLength,
this.algorithm
).toString('hex');
} }
private generateApiKey(): string { private generateApiKey(): string {

Loading…
Cancel
Save