TIL(210821): GitHub Slack Integration, Jwt payload 추출하기

최수민·2021년 8월 20일
0

TIL

목록 보기
3/8
post-thumbnail

1. GitHub Slack Integration 설정하기

새로운 레포지토리를 subscribe하면 기본적으로 issues, pulls, commits, releases, deployments를 listen한다. 아래와 같이 알림이 온다.

내가 추가로 커스터마이징한 부분들은 다음과 같다.
1. 배포와 관련된 알림은 껐다. Vercel, AWS가 제공하는 자체 Integration을 통해 다른 채널에서 관리중이었기 때문이다. (/github unsubscribe DEV-MUGLES/pickk-server deployments)
2. 이슈/PR의 댓글,리뷰 알림을 추가했다. (/github subscribe DEV-MUGLES/pickk-server reviews)

명령어들 정리

# 새로운 저장소 등록하기
# e.g. /github subscribe greatSumini/react-facebook-login
/github subscribe owner/repo

# 등록한 저장소 취소하기
/github unsubscribe owner/repo

# 새로운 기능 추가와 취소
/github subscribe owner/repo feature
/github unsubscribe owner/repo feature

원래는 subscribe만 해뒀는데 기능들이 추가됐길래 정리해봤다 ㅎ

공식 문서 링크

2. JWT 토큰에서 payload 얻어오기

찾아볼 생각도 안 해봤었는데 막상 보니 생각보다 엄청 간단해서 놀랐습니다.
외부 인증 없이 jwt 검증 정도만 수행할 생각이라면 굳이 passport를 쓰지 않아도 될 것 같네요!
아래는 사용한 코드입니다.

  • JwtPayload: payload를 표현하는 데이터 클래스.
  • _atob: global atob의 polyfill
  • extractPayload: jwt token을 입력 받아 추출한 JwtPayload를 반환한다.
// 실제 적용할땐 JwtPayload는 별도 파일에 작성했음.
class JwtPayload implements IJwtPayload {
  constructor(attributes?: Partial<JwtPayload>) {
    if (!attributes) {
      return;
    }
    // 생략 ...
    this.sub = attributes.sub;
    this.iat = attributes.iat;
    this.exp = attributes.exp;
  }
  
  // 팩토리 패턴 적용 - 필요에 따라 검증 로직을 추가해봐도 좋겠습니다.
  static of(attributes: JwtPayload): JwtPayload {
    return new JwtPayload(attributes);
  }

  // 생략 ...
  sub: number;
  iat: number;
  exp: number;

  get isExpired() {
    // Fast fail principle 적용함!
    if (!this.exp) {
      return false;
    }

    return Date.now() > this.exp * 1000;
  }
}


const _atob = (input: string): string =>
  Buffer.from(input, 'base64').toString();

export const extractPayload = (token: string): JwtPayload => {
  // Fast fail principle 적용함!2
  if (!token) {
    throw new UnauthorizedException('Token Not Given');
  }

  try {
    const payload = JSON.parse(_atob(token.split('.')[1]));
    return JwtPayload.of(payload);
  } catch {
    throw new UnauthorizedException('Invalid Token provided');
  }
};

특징
1. JwtPayload를 class로 정의하고, isExpired getter를 추가했습니다. (리팩토링 2판에서 읽은 내용 적용해봤음 ㅎㅎ)
2. _atob는 polyfill로 추가해봤습니다.
3. 사용된 UnauthorizedException은 Nestjs에서 제공하는 에러 객체입니다.

(번외) 재밌는 블로그 발견함

글 내용이랑 댓글이 재밌닿 링크
항해99를 하고 계신 것 같다. 열심히 공부하시는 모습이 멋있다. 리스펙합니다..! 😄 🤙 🤙

profile
velog에는 TIL, 잡담만 올립니다! 아티클들은 블로그로 (https://sumini.dev)

0개의 댓글