All files / src/controllers/public/scan grafana-token.controller.ts

55.56% Statements 10/18
0% Branches 0/4
0% Functions 0/2
50% Lines 8/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 671x 1x 1x 1x 1x 1x   1x                                               1x                                                                      
import { inject } from '@loopback/core';
import { get, RestBindings, Response, HttpErrors } from '@loopback/rest';
import * as fs from 'fs';
import * as path from 'path';
const jwt = require('jsonwebtoken');
const jwkToPem = require('jwk-to-pem');
 
export class GrafanaTokenController {
  constructor(
    @inject(RestBindings.Http.RESPONSE)
    private response: Response,
  ) {}
 
  @get('/grafana/token', {
    responses: {
      '200': {
        description: 'Returns a short-lived Grafana JWT',
        content: {
          'application/json': {
            schema: {
              type: 'object',
              properties: {
                token: { type: 'string' },
                expires_in: { type: 'number' },
              },
            },
          },
        },
      },
    },
  })
  async getGrafanaToken(): Promise<object> {
    const keyPath = path.resolve(
      process.env.GRAFANA_JWT_KEY_PATH ??
      "",
    );
 
    let pemKey: string;
    try {
      pemKey = fs.readFileSync(keyPath, 'utf-8');
    } catch (err) {
      throw new HttpErrors.InternalServerError(
        `Cannot read Grafana JWT private key at: ${keyPath}`,
      );
    }
 
    const EXPIRES_IN_SECONDS = 3600;
 
    const token = jwt.sign(
      {
        sub: 'embed-viewer',
        email: 'embed@grafana.local',
        iss: 'grafana-embed',
      },
      pemKey,
      {
        algorithm: 'RS256',
        expiresIn: EXPIRES_IN_SECONDS,
      },
    );
 
    return {
      token,
      expires_in: EXPIRES_IN_SECONDS,
    };
  }
}