-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathauth.service.ts
159 lines (141 loc) · 5.23 KB
/
auth.service.ts
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
import { forwardRef, Inject, Injectable } from '@nestjs/common';
import got from 'got';
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
import { MembersService } from 'src/members/members.service';
import {
GetJwtInput,
GetJwtOutput,
GetKakaoTokenOutput,
UnlinkTokenOutput,
} from './dtos/get-token.dto';
import * as camelcaseKeys from 'camelcase-keys';
import { GetKakoLoginUrlOutput } from './dtos/get-kakak-login-url.dto';
@Injectable()
export class AuthService {
constructor(
@Inject(forwardRef(() => MembersService))
private readonly memberService: MembersService,
private readonly jwtServce: JwtService,
private readonly configService: ConfigService,
) {}
getKakaoLoginUrl(): GetKakoLoginUrlOutput {
try {
const hostName = this.configService.get('KAKAO_LOGIN_HOST');
const clientId = this.configService.get('KAKAO_CLIENT_ID');
const baseDomain = 'http://localhost:3000';
const redirectUrl = `${baseDomain}/auth/kakaoLoginRedirect`;
const url = `https://${hostName}/oauth/authorize?client_id=${clientId}&redirect_uri=${redirectUrl}&response_type=code`;
return { ok: true, url };
} catch (error) {
console.log(error.stack, error.message);
return {
ok: false,
error: '카카오 로그인 URL을 받아오지 못했습니다.',
};
}
}
async getJwt(getJwtInput: GetJwtInput): Promise<GetJwtOutput> {
try {
const { code, redirectUrl } = getJwtInput;
const kakaoTokens = await this.getKakaoToken(code, redirectUrl);
const mbrKakaoSeq = await this.getMbrKakaoSeq(
kakaoTokens.accessToken,
);
const { member } = await this.memberService.getMemberByKakaoSeq(
mbrKakaoSeq,
);
const jwtToken = this.createJwt(
member?.mbrSeq,
kakaoTokens.accessToken,
this.UnixEpochTimestamp() + kakaoTokens.expiresIn,
);
return { ok: true, token: jwtToken };
} catch (error) {
console.log(error.stack, error.message);
return {
ok: false,
error: '회원 인증에 실패했습니다',
};
}
}
async unlinkToken(accessToken: string): Promise<UnlinkTokenOutput> {
try {
const hostName = this.configService.get('KAKAO_LOGOUT_HOST');
const url = `https://${hostName}/v1/user/unlink`;
await got.post(url, {
headers: {
'Content-type':
'application/x-www-form-urlencoded;charset=utf-8',
Authorization: `Bearer ${accessToken}`,
},
});
return { ok: true };
} catch (error) {
console.log(error.message);
return { ok: false, error: '로그아웃에 실패했습니다' };
}
}
private async getKakaoToken(
code: string,
redirectUrl: string,
): Promise<GetKakaoTokenOutput> {
try {
const hostName = this.configService.get('KAKAO_LOGIN_HOST');
const baseDomain = redirectUrl;
const url = `https://${hostName}/oauth/token`;
const clientId = this.configService.get('KAKAO_CLIENT_ID');
const grantType = this.configService.get('KAKAO_GRANT_TYPE');
const redirectUri = `${baseDomain}/auth/kakaoLoginRedirect`;
const response: any = await got
.post(url, {
headers: {
'Content-type':
'application/x-www-form-urlencoded;charset=utf-8',
},
form: {
client_id: clientId,
grant_type: grantType,
redirect_uri: redirectUri,
code,
},
})
.json();
const kakaoTokens: GetKakaoTokenOutput = camelcaseKeys(response);
return kakaoTokens;
} catch (error) {
error.message += `\n
error args at getKakaoToken \n
code: ${code} \n
response body: ${error.response.body}
`;
throw error;
}
}
async getMbrKakaoSeq(accessToken: string): Promise<string> {
try {
const response: any = await got
.get('https://kapi.kakao.com/v2/user/me', {
headers: { Authorization: `Bearer ${accessToken}` },
})
.json();
return response.id;
} catch (error) {
error.message += `\n
error args at getMbrKakaoSeq \n
accessToken: ${accessToken}
`;
throw error;
}
}
private UnixEpochTimestamp(): number {
return Math.floor(new Date().valueOf() / 1000);
}
createJwt(mbrSeq: string, accessToken: string, exp: number): string {
return this.jwtServce.sign({
mbrSeq,
exp,
accessToken,
});
}
}