All files / src/user put.js

100% Statements 16/16
75% Branches 3/4
100% Functions 1/1
100% Lines 16/16
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 67 68 69 70 71 72 73 74 75 76              3x   3x 3x 3x 3x   3x 3x           3x           3x 3x 3x                   2x 1x             1x                     2x               1x                  
import url from 'url';
import GitHub from 'github';
 
export default async ({ body }, context, callback) => {
  const {
    name,
    password,
  } = JSON.parse(body);
 
  const scopes = ['user:email'];
  const nameParts = name.split('.');
  const username = nameParts[0];
  const otp = nameParts.length > 1 ? nameParts[nameParts.length - 1] : '';
 
  const parsedUrl = url.parse(process.env.githubUrl);
  const github = new GitHub({
    host: parsedUrl.host,
    protocol: 'https',
    pathPrefix: parsedUrl.path,
  });
 
  github.authenticate({
    type: 'basic',
    username,
    password,
  });
 
  let auth = {};
  try {
    auth = await github.authorization.getOrCreateAuthorizationForApp({
      scopes,
      client_id: process.env.githubClientId,
      client_secret: process.env.githubSecret,
      note: 'yith private npm registry',
      headers: {
        'X-GitHub-OTP': otp,
      },
    });
 
    if (!auth.token.length) {
      await github.authorization.delete({
        id: auth.id,
        headers: {
          'X-GitHub-OTP': otp,
        },
      });
 
      auth = await github.authorization.create({
        scopes,
        client_id: process.env.githubClientId,
        client_secret: process.env.githubSecret,
        note: 'yith private npm registry',
        headers: {
          'X-GitHub-OTP': otp,
        },
      });
    }
 
    return callback(null, {
      statusCode: 201,
      body: JSON.stringify({
        ok: true,
        token: auth.token,
      }),
    });
  } catch (error) {
    return callback(null, {
      statusCode: 500,
      body: JSON.stringify({
        ok: false,
        error: error.message,
      }),
    });
  }
};