@ts-core/oauth 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,43 @@
1
+ import { PromiseHandler, LoggerWrapper, ILogger, TransportHttp } from "@ts-core/common";
2
+ export declare abstract class OAuthBase<T = any> extends LoggerWrapper {
3
+ protected window: Window;
4
+ protected applicationId: string;
5
+ protected scope?: string;
6
+ protected http: TransportHttp;
7
+ protected timer: any;
8
+ protected popUp: Window;
9
+ protected promise: PromiseHandler<IOAuthDto>;
10
+ protected popUpWidth: number;
11
+ protected popUpHeight: number;
12
+ protected responseType: string;
13
+ constructor(logger: ILogger, window: Window, applicationId: string, scope?: string);
14
+ protected open(): Promise<IOAuthDto>;
15
+ protected openPopup(url: string, target: string): Window;
16
+ protected checkPopUp: () => void;
17
+ protected messageHandler: (event: MessageEvent<IOAuthPopUpDto>) => void;
18
+ protected abstract getAuthUrl(): string;
19
+ protected get redirectUri(): string;
20
+ protected get originUrl(): string;
21
+ abstract getProfile(token: string, ...params: any[]): Promise<T>;
22
+ abstract getTokenByCode(dto: IOAuthDto, secret: string): Promise<IOAuthToken>;
23
+ getCode(): Promise<IOAuthDto>;
24
+ getToken(): Promise<IOAuthDto>;
25
+ close(): void;
26
+ destroy(): void;
27
+ }
28
+ export interface IOAuthDto {
29
+ codeOrToken: string;
30
+ redirectUri: string;
31
+ }
32
+ export interface IOAuthPopUpDto {
33
+ oAuthCodeOrToken: string;
34
+ oAuthError: string;
35
+ }
36
+ export interface IOAuthToken {
37
+ type?: string;
38
+ state?: string;
39
+ scope?: string;
40
+ userId: number;
41
+ expiresIn: number;
42
+ accessToken: string;
43
+ }
@@ -0,0 +1,108 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.OAuthBase = void 0;
13
+ const common_1 = require("@ts-core/common");
14
+ const _ = require("lodash");
15
+ class OAuthBase extends common_1.LoggerWrapper {
16
+ constructor(logger, window, applicationId, scope) {
17
+ super(logger);
18
+ this.window = window;
19
+ this.applicationId = applicationId;
20
+ this.scope = scope;
21
+ this.popUpWidth = 640;
22
+ this.popUpHeight = 480;
23
+ this.checkPopUp = () => {
24
+ if (_.isNil(this.popUp) || this.popUp.closed) {
25
+ this.close();
26
+ }
27
+ };
28
+ this.messageHandler = (event) => {
29
+ let data = event.data;
30
+ if (event.origin !== this.originUrl || !_.isObject(data)) {
31
+ return;
32
+ }
33
+ if (!_.isEmpty(data.oAuthCodeOrToken)) {
34
+ this.promise.resolve({ redirectUri: this.redirectUri, codeOrToken: data.oAuthCodeOrToken });
35
+ }
36
+ if (!_.isEmpty(data.oAuthError)) {
37
+ this.promise.reject(data.oAuthError);
38
+ }
39
+ if (!this.promise.isPending) {
40
+ this.close();
41
+ }
42
+ };
43
+ this.http = new common_1.TransportHttp(logger, { method: 'get' });
44
+ }
45
+ open() {
46
+ return __awaiter(this, void 0, void 0, function* () {
47
+ if (!_.isNil(this.promise)) {
48
+ return this.promise.promise;
49
+ }
50
+ this.promise = common_1.PromiseHandler.create();
51
+ this.popUp = this.openPopup(this.getAuthUrl(), '_blank');
52
+ this.window.addEventListener('message', this.messageHandler, false);
53
+ this.timer = setInterval(this.checkPopUp, common_1.DateUtil.MILLISECONDS_NANOSECOND / 2);
54
+ return this.promise.promise;
55
+ });
56
+ }
57
+ openPopup(url, target) {
58
+ let window = this.window;
59
+ let top = (window.screen.height - this.popUpHeight) / 2;
60
+ let left = (window.screen.width - this.popUpWidth) / 2;
61
+ let item = window.open(url, target, `scrollbars=yes,width=${this.popUpWidth},height=${this.popUpHeight},top=${top},left=${left}`);
62
+ item.focus();
63
+ return item;
64
+ }
65
+ get redirectUri() {
66
+ return `${this.originUrl}/oauth`;
67
+ }
68
+ get originUrl() {
69
+ return this.window.location.origin;
70
+ }
71
+ getCode() {
72
+ return __awaiter(this, void 0, void 0, function* () {
73
+ this.responseType = 'code';
74
+ return this.open();
75
+ });
76
+ }
77
+ getToken() {
78
+ return __awaiter(this, void 0, void 0, function* () {
79
+ this.responseType = 'token';
80
+ return this.open();
81
+ });
82
+ }
83
+ close() {
84
+ this.window.removeEventListener('message', this.messageHandler, false);
85
+ clearInterval(this.timer);
86
+ this.timer = null;
87
+ if (!_.isNil(this.popUp)) {
88
+ this.popUp.close();
89
+ this.popUp = null;
90
+ }
91
+ if (!_.isNil(this.promise)) {
92
+ this.promise.reject();
93
+ this.promise = null;
94
+ }
95
+ }
96
+ destroy() {
97
+ if (this.isDestroyed) {
98
+ return;
99
+ }
100
+ super.destroy();
101
+ this.close();
102
+ if (!_.isNil(this.http)) {
103
+ this.http.destroy();
104
+ this.http = null;
105
+ }
106
+ }
107
+ }
108
+ exports.OAuthBase = OAuthBase;
@@ -0,0 +1,23 @@
1
+ export declare abstract class OAuthUser {
2
+ id: string | number;
3
+ name: string;
4
+ city?: string;
5
+ phone?: string;
6
+ email?: string;
7
+ status?: string;
8
+ isMale?: boolean;
9
+ locale?: string;
10
+ country?: string;
11
+ picture?: string;
12
+ latitude?: number;
13
+ longitude?: number;
14
+ description?: string;
15
+ vk?: string;
16
+ facebook?: string;
17
+ telegram?: string;
18
+ instagram?: string;
19
+ birthday?: Date;
20
+ constructor(item?: any);
21
+ protected abstract parse(item: any): void;
22
+ get location(): string;
23
+ }
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.OAuthUser = void 0;
13
+ const _ = require("lodash");
14
+ const class_transformer_1 = require("class-transformer");
15
+ class OAuthUser {
16
+ constructor(item) {
17
+ if (!_.isNil(item)) {
18
+ this.parse(item);
19
+ }
20
+ }
21
+ get location() {
22
+ let items = new Array();
23
+ if (!_.isEmpty(this.country)) {
24
+ items.push(this.country);
25
+ }
26
+ if (!_.isEmpty(this.city)) {
27
+ items.push(this.city);
28
+ }
29
+ return !_.isEmpty(items) ? items.join(', ') : null;
30
+ }
31
+ }
32
+ __decorate([
33
+ (0, class_transformer_1.Type)(() => Date),
34
+ __metadata("design:type", Date)
35
+ ], OAuthUser.prototype, "birthday", void 0);
36
+ exports.OAuthUser = OAuthUser;
@@ -0,0 +1,7 @@
1
+ import { GoUser } from './GoUser';
2
+ import { IOAuthDto, IOAuthToken, OAuthBase } from '../OAuthBase';
3
+ export declare class GoOAuth<T extends GoUser = GoUser> extends OAuthBase<T> {
4
+ protected getAuthUrl(): string;
5
+ getProfile(token: string): Promise<T>;
6
+ getTokenByCode(dto: IOAuthDto, secret: string): Promise<IOAuthToken>;
7
+ }
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.GoOAuth = void 0;
13
+ const _ = require("lodash");
14
+ const GoUser_1 = require("./GoUser");
15
+ const OAuthBase_1 = require("../OAuthBase");
16
+ class GoOAuth extends OAuthBase_1.OAuthBase {
17
+ getAuthUrl() {
18
+ let params = new URLSearchParams();
19
+ params.append('display', 'popup');
20
+ params.append('client_id', this.applicationId);
21
+ params.append('redirect_uri', this.redirectUri);
22
+ params.append('response_type', this.responseType);
23
+ if (!_.isEmpty(this.scope)) {
24
+ params.append('scope', this.scope);
25
+ }
26
+ return `https://accounts.google.com/o/oauth2/v2/auth?${params.toString()}`;
27
+ }
28
+ getProfile(token) {
29
+ return __awaiter(this, void 0, void 0, function* () {
30
+ let item = yield this.http.call('https://www.googleapis.com/oauth2/v3/userinfo', { headers: { 'Authorization': `Bearer ${token}` } });
31
+ return new GoUser_1.GoUser(item);
32
+ });
33
+ }
34
+ getTokenByCode(dto, secret) {
35
+ return __awaiter(this, void 0, void 0, function* () {
36
+ let item = yield this.http.call('https://oauth2.googleapis.com/token', {
37
+ method: 'post',
38
+ data: {
39
+ code: dto.codeOrToken,
40
+ client_id: this.applicationId,
41
+ client_secret: secret,
42
+ redirect_uri: dto.redirectUri,
43
+ grant_type: 'authorization_code'
44
+ }
45
+ });
46
+ return { userId: item.user_id, expiresIn: item.expires_in, accessToken: item.access_token };
47
+ });
48
+ }
49
+ }
50
+ exports.GoOAuth = GoOAuth;
@@ -0,0 +1,4 @@
1
+ import { OAuthUser } from "../OAuthUser";
2
+ export declare class GoUser extends OAuthUser {
3
+ protected parse(item: any): void;
4
+ }
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GoUser = void 0;
4
+ const OAuthUser_1 = require("../OAuthUser");
5
+ class GoUser extends OAuthUser_1.OAuthUser {
6
+ parse(item) {
7
+ this.id = item.sub;
8
+ this.name = item.name;
9
+ this.email = item.email;
10
+ this.locale = item.locale;
11
+ this.picture = item.picture;
12
+ }
13
+ }
14
+ exports.GoUser = GoUser;
@@ -0,0 +1,8 @@
1
+ export * from './OAuthBase';
2
+ export * from './OAuthUser';
3
+ export * from './go/GoUser';
4
+ export * from './go/GoOAuth';
5
+ export * from './vk/VkUser';
6
+ export * from './vk/VkOAuth';
7
+ export * from './ya/YaUser';
8
+ export * from './ya/YaOAuth';
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./OAuthBase"), exports);
18
+ __exportStar(require("./OAuthUser"), exports);
19
+ __exportStar(require("./go/GoUser"), exports);
20
+ __exportStar(require("./go/GoOAuth"), exports);
21
+ __exportStar(require("./vk/VkUser"), exports);
22
+ __exportStar(require("./vk/VkOAuth"), exports);
23
+ __exportStar(require("./ya/YaUser"), exports);
24
+ __exportStar(require("./ya/YaOAuth"), exports);
@@ -0,0 +1,7 @@
1
+ import { IOAuthDto, IOAuthToken, OAuthBase } from "../OAuthBase";
2
+ import { VkUser } from "./VkUser";
3
+ export declare class VkOAuth<T extends VkUser = VkUser> extends OAuthBase<T> {
4
+ protected getAuthUrl(): string;
5
+ getProfile(token: string, fields: string): Promise<T>;
6
+ getTokenByCode(dto: IOAuthDto, secret: string): Promise<IOAuthToken>;
7
+ }
@@ -0,0 +1,48 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.VkOAuth = void 0;
13
+ const _ = require("lodash");
14
+ const OAuthBase_1 = require("../OAuthBase");
15
+ const VkUser_1 = require("./VkUser");
16
+ class VkOAuth extends OAuthBase_1.OAuthBase {
17
+ getAuthUrl() {
18
+ let params = new URLSearchParams();
19
+ params.append('display', 'popup');
20
+ params.append('client_id', this.applicationId);
21
+ params.append('redirect_uri', this.redirectUri);
22
+ params.append('response_type', this.responseType);
23
+ if (!_.isEmpty(this.scope)) {
24
+ params.append('scope', this.scope);
25
+ }
26
+ return `https://oauth.vk.com/authorize?${params.toString()}`;
27
+ }
28
+ getProfile(token, fields) {
29
+ return __awaiter(this, void 0, void 0, function* () {
30
+ let { response } = yield this.http.call('https://api.vk.com/method/users.get', { data: { access_token: token, v: '5.131', fields } });
31
+ return new VkUser_1.VkUser(response[0]);
32
+ });
33
+ }
34
+ getTokenByCode(dto, secret) {
35
+ return __awaiter(this, void 0, void 0, function* () {
36
+ let item = yield this.http.call('https://oauth.vk.com/access_token', {
37
+ data: {
38
+ code: dto.codeOrToken,
39
+ client_id: this.applicationId,
40
+ redirect_uri: dto.redirectUri,
41
+ client_secret: secret,
42
+ }
43
+ });
44
+ return { userId: item.user_id, expiresIn: item.expires_in, accessToken: item.access_token };
45
+ });
46
+ }
47
+ }
48
+ exports.VkOAuth = VkOAuth;
@@ -0,0 +1,5 @@
1
+ import { OAuthUser } from "../OAuthUser";
2
+ export declare class VkUser extends OAuthUser {
3
+ params: string;
4
+ protected parse(item: any): void;
5
+ }
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.VkUser = void 0;
4
+ const OAuthUser_1 = require("../OAuthUser");
5
+ const _ = require("lodash");
6
+ class VkUser extends OAuthUser_1.OAuthUser {
7
+ parse(item) {
8
+ this.id = item.id;
9
+ this.vk = `https://vk.com/id${item.id}`;
10
+ this.name = `${item.first_name} ${item.last_name}`;
11
+ this.picture = item.photo_200;
12
+ this.city = _.get(item, 'city.title');
13
+ this.country = _.get(item, 'country.title');
14
+ if (!_.isNil(item.sex) && item.sex !== 0) {
15
+ this.isMale = item.sex === 2;
16
+ }
17
+ if (!_.isNil(item.about)) {
18
+ this.description = item.about;
19
+ }
20
+ else if (!_.isNil(item.status)) {
21
+ this.description = item.status;
22
+ }
23
+ if (!_.isNil(item.bdate)) {
24
+ let array = String(item.bdate).split('.');
25
+ if (array.length === 3) {
26
+ this.birthday = new Date(Number(array[2]), Number(array[1]) - 1, Number(array[0]));
27
+ }
28
+ else if (array.length === 2) {
29
+ this.birthday = new Date(1900, Number(array[1]) - 1, Number(array[0]));
30
+ }
31
+ }
32
+ }
33
+ }
34
+ exports.VkUser = VkUser;
@@ -0,0 +1,9 @@
1
+ import { ILogger } from "@ts-core/common";
2
+ import { IOAuthDto, IOAuthToken, OAuthBase } from "../OAuthBase";
3
+ import { YaUser } from "./YaUser";
4
+ export declare class YaOAuth<T extends YaUser = YaUser> extends OAuthBase<T> {
5
+ constructor(logger: ILogger, window: Window, applicationId: string, scope?: string);
6
+ protected getAuthUrl(): string;
7
+ getProfile(token: string): Promise<T>;
8
+ getTokenByCode(dto: IOAuthDto, secret: string): Promise<IOAuthToken>;
9
+ }
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.YaOAuth = void 0;
13
+ const OAuthBase_1 = require("../OAuthBase");
14
+ const YaUser_1 = require("./YaUser");
15
+ const _ = require("lodash");
16
+ const axios_1 = require("axios");
17
+ class YaOAuth extends OAuthBase_1.OAuthBase {
18
+ constructor(logger, window, applicationId, scope) {
19
+ super(logger, window, applicationId, scope);
20
+ this.popUpWidth = 480;
21
+ this.popUpHeight = 520;
22
+ }
23
+ getAuthUrl() {
24
+ let params = new URLSearchParams();
25
+ params.append('display', 'popup');
26
+ params.append('client_id', this.applicationId);
27
+ params.append('redirect_uri', this.redirectUri);
28
+ params.append('response_type', this.responseType);
29
+ if (!_.isEmpty(this.scope)) {
30
+ params.append('scope', this.scope);
31
+ }
32
+ return `https://oauth.yandex.ru/authorize?${params.toString()}`;
33
+ }
34
+ getProfile(token) {
35
+ return __awaiter(this, void 0, void 0, function* () {
36
+ let item = yield this.http.call('https://login.yandex.ru/info', { data: { oauth_token: token } });
37
+ return new YaUser_1.YaUser(item);
38
+ });
39
+ }
40
+ getTokenByCode(dto, secret) {
41
+ return __awaiter(this, void 0, void 0, function* () {
42
+ let { data } = yield axios_1.default.postForm('https://oauth.yandex.ru/token', {
43
+ code: dto.codeOrToken,
44
+ client_id: this.applicationId,
45
+ client_secret: secret,
46
+ grant_type: 'authorization_code'
47
+ });
48
+ return { userId: data.user_id, expiresIn: data.expires_in, accessToken: data.access_token, type: data.token_type, scope: data.scope };
49
+ });
50
+ }
51
+ }
52
+ exports.YaOAuth = YaOAuth;
@@ -0,0 +1,4 @@
1
+ import { OAuthUser } from "../OAuthUser";
2
+ export declare class YaUser extends OAuthUser {
3
+ protected parse(item: any): void;
4
+ }
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.YaUser = void 0;
4
+ const OAuthUser_1 = require("../OAuthUser");
5
+ const _ = require("lodash");
6
+ class YaUser extends OAuthUser_1.OAuthUser {
7
+ parse(item) {
8
+ this.id = item.id;
9
+ this.name = item.display_name;
10
+ this.email = item.default_email;
11
+ this.phone = _.get(item, 'default_phone.number');
12
+ if (!_.isNil(item.sex)) {
13
+ this.isMale = item.sex === 'male';
14
+ }
15
+ if (!item.is_avatar_empty) {
16
+ this.picture = `https://avatars.yandex.net/get-yapic/${item.default_avatar_id}/islands-200`;
17
+ }
18
+ if (!_.isNil(item.birthday)) {
19
+ let array = String(item.birthday).split('-');
20
+ if (array.length === 3) {
21
+ this.birthday = new Date(Number(array[0]), Number(array[1]) - 1, Number(array[2]));
22
+ }
23
+ }
24
+ }
25
+ }
26
+ exports.YaUser = YaUser;
@@ -0,0 +1,43 @@
1
+ import { PromiseHandler, LoggerWrapper, ILogger, TransportHttp } from "@ts-core/common";
2
+ export declare abstract class OAuthBase<T = any> extends LoggerWrapper {
3
+ protected window: Window;
4
+ protected applicationId: string;
5
+ protected scope?: string;
6
+ protected http: TransportHttp;
7
+ protected timer: any;
8
+ protected popUp: Window;
9
+ protected promise: PromiseHandler<IOAuthDto>;
10
+ protected popUpWidth: number;
11
+ protected popUpHeight: number;
12
+ protected responseType: string;
13
+ constructor(logger: ILogger, window: Window, applicationId: string, scope?: string);
14
+ protected open(): Promise<IOAuthDto>;
15
+ protected openPopup(url: string, target: string): Window;
16
+ protected checkPopUp: () => void;
17
+ protected messageHandler: (event: MessageEvent<IOAuthPopUpDto>) => void;
18
+ protected abstract getAuthUrl(): string;
19
+ protected get redirectUri(): string;
20
+ protected get originUrl(): string;
21
+ abstract getProfile(token: string, ...params: any[]): Promise<T>;
22
+ abstract getTokenByCode(dto: IOAuthDto, secret: string): Promise<IOAuthToken>;
23
+ getCode(): Promise<IOAuthDto>;
24
+ getToken(): Promise<IOAuthDto>;
25
+ close(): void;
26
+ destroy(): void;
27
+ }
28
+ export interface IOAuthDto {
29
+ codeOrToken: string;
30
+ redirectUri: string;
31
+ }
32
+ export interface IOAuthPopUpDto {
33
+ oAuthCodeOrToken: string;
34
+ oAuthError: string;
35
+ }
36
+ export interface IOAuthToken {
37
+ type?: string;
38
+ state?: string;
39
+ scope?: string;
40
+ userId: number;
41
+ expiresIn: number;
42
+ accessToken: string;
43
+ }
@@ -0,0 +1,104 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { PromiseHandler, DateUtil, LoggerWrapper, TransportHttp } from "@ts-core/common";
11
+ import * as _ from 'lodash';
12
+ export class OAuthBase extends LoggerWrapper {
13
+ constructor(logger, window, applicationId, scope) {
14
+ super(logger);
15
+ this.window = window;
16
+ this.applicationId = applicationId;
17
+ this.scope = scope;
18
+ this.popUpWidth = 640;
19
+ this.popUpHeight = 480;
20
+ this.checkPopUp = () => {
21
+ if (_.isNil(this.popUp) || this.popUp.closed) {
22
+ this.close();
23
+ }
24
+ };
25
+ this.messageHandler = (event) => {
26
+ let data = event.data;
27
+ if (event.origin !== this.originUrl || !_.isObject(data)) {
28
+ return;
29
+ }
30
+ if (!_.isEmpty(data.oAuthCodeOrToken)) {
31
+ this.promise.resolve({ redirectUri: this.redirectUri, codeOrToken: data.oAuthCodeOrToken });
32
+ }
33
+ if (!_.isEmpty(data.oAuthError)) {
34
+ this.promise.reject(data.oAuthError);
35
+ }
36
+ if (!this.promise.isPending) {
37
+ this.close();
38
+ }
39
+ };
40
+ this.http = new TransportHttp(logger, { method: 'get' });
41
+ }
42
+ open() {
43
+ return __awaiter(this, void 0, void 0, function* () {
44
+ if (!_.isNil(this.promise)) {
45
+ return this.promise.promise;
46
+ }
47
+ this.promise = PromiseHandler.create();
48
+ this.popUp = this.openPopup(this.getAuthUrl(), '_blank');
49
+ this.window.addEventListener('message', this.messageHandler, false);
50
+ this.timer = setInterval(this.checkPopUp, DateUtil.MILLISECONDS_NANOSECOND / 2);
51
+ return this.promise.promise;
52
+ });
53
+ }
54
+ openPopup(url, target) {
55
+ let window = this.window;
56
+ let top = (window.screen.height - this.popUpHeight) / 2;
57
+ let left = (window.screen.width - this.popUpWidth) / 2;
58
+ let item = window.open(url, target, `scrollbars=yes,width=${this.popUpWidth},height=${this.popUpHeight},top=${top},left=${left}`);
59
+ item.focus();
60
+ return item;
61
+ }
62
+ get redirectUri() {
63
+ return `${this.originUrl}/oauth`;
64
+ }
65
+ get originUrl() {
66
+ return this.window.location.origin;
67
+ }
68
+ getCode() {
69
+ return __awaiter(this, void 0, void 0, function* () {
70
+ this.responseType = 'code';
71
+ return this.open();
72
+ });
73
+ }
74
+ getToken() {
75
+ return __awaiter(this, void 0, void 0, function* () {
76
+ this.responseType = 'token';
77
+ return this.open();
78
+ });
79
+ }
80
+ close() {
81
+ this.window.removeEventListener('message', this.messageHandler, false);
82
+ clearInterval(this.timer);
83
+ this.timer = null;
84
+ if (!_.isNil(this.popUp)) {
85
+ this.popUp.close();
86
+ this.popUp = null;
87
+ }
88
+ if (!_.isNil(this.promise)) {
89
+ this.promise.reject();
90
+ this.promise = null;
91
+ }
92
+ }
93
+ destroy() {
94
+ if (this.isDestroyed) {
95
+ return;
96
+ }
97
+ super.destroy();
98
+ this.close();
99
+ if (!_.isNil(this.http)) {
100
+ this.http.destroy();
101
+ this.http = null;
102
+ }
103
+ }
104
+ }
@@ -0,0 +1,23 @@
1
+ export declare abstract class OAuthUser {
2
+ id: string | number;
3
+ name: string;
4
+ city?: string;
5
+ phone?: string;
6
+ email?: string;
7
+ status?: string;
8
+ isMale?: boolean;
9
+ locale?: string;
10
+ country?: string;
11
+ picture?: string;
12
+ latitude?: number;
13
+ longitude?: number;
14
+ description?: string;
15
+ vk?: string;
16
+ facebook?: string;
17
+ telegram?: string;
18
+ instagram?: string;
19
+ birthday?: Date;
20
+ constructor(item?: any);
21
+ protected abstract parse(item: any): void;
22
+ get location(): string;
23
+ }
@@ -0,0 +1,32 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ import * as _ from 'lodash';
11
+ import { Type } from 'class-transformer';
12
+ export class OAuthUser {
13
+ constructor(item) {
14
+ if (!_.isNil(item)) {
15
+ this.parse(item);
16
+ }
17
+ }
18
+ get location() {
19
+ let items = new Array();
20
+ if (!_.isEmpty(this.country)) {
21
+ items.push(this.country);
22
+ }
23
+ if (!_.isEmpty(this.city)) {
24
+ items.push(this.city);
25
+ }
26
+ return !_.isEmpty(items) ? items.join(', ') : null;
27
+ }
28
+ }
29
+ __decorate([
30
+ Type(() => Date),
31
+ __metadata("design:type", Date)
32
+ ], OAuthUser.prototype, "birthday", void 0);
@@ -0,0 +1,7 @@
1
+ import { GoUser } from './GoUser';
2
+ import { IOAuthDto, IOAuthToken, OAuthBase } from '../OAuthBase';
3
+ export declare class GoOAuth<T extends GoUser = GoUser> extends OAuthBase<T> {
4
+ protected getAuthUrl(): string;
5
+ getProfile(token: string): Promise<T>;
6
+ getTokenByCode(dto: IOAuthDto, secret: string): Promise<IOAuthToken>;
7
+ }
@@ -0,0 +1,46 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import * as _ from 'lodash';
11
+ import { GoUser } from './GoUser';
12
+ import { OAuthBase } from '../OAuthBase';
13
+ export class GoOAuth extends OAuthBase {
14
+ getAuthUrl() {
15
+ let params = new URLSearchParams();
16
+ params.append('display', 'popup');
17
+ params.append('client_id', this.applicationId);
18
+ params.append('redirect_uri', this.redirectUri);
19
+ params.append('response_type', this.responseType);
20
+ if (!_.isEmpty(this.scope)) {
21
+ params.append('scope', this.scope);
22
+ }
23
+ return `https://accounts.google.com/o/oauth2/v2/auth?${params.toString()}`;
24
+ }
25
+ getProfile(token) {
26
+ return __awaiter(this, void 0, void 0, function* () {
27
+ let item = yield this.http.call('https://www.googleapis.com/oauth2/v3/userinfo', { headers: { 'Authorization': `Bearer ${token}` } });
28
+ return new GoUser(item);
29
+ });
30
+ }
31
+ getTokenByCode(dto, secret) {
32
+ return __awaiter(this, void 0, void 0, function* () {
33
+ let item = yield this.http.call('https://oauth2.googleapis.com/token', {
34
+ method: 'post',
35
+ data: {
36
+ code: dto.codeOrToken,
37
+ client_id: this.applicationId,
38
+ client_secret: secret,
39
+ redirect_uri: dto.redirectUri,
40
+ grant_type: 'authorization_code'
41
+ }
42
+ });
43
+ return { userId: item.user_id, expiresIn: item.expires_in, accessToken: item.access_token };
44
+ });
45
+ }
46
+ }
@@ -0,0 +1,4 @@
1
+ import { OAuthUser } from "../OAuthUser";
2
+ export declare class GoUser extends OAuthUser {
3
+ protected parse(item: any): void;
4
+ }
@@ -0,0 +1,10 @@
1
+ import { OAuthUser } from "../OAuthUser";
2
+ export class GoUser extends OAuthUser {
3
+ parse(item) {
4
+ this.id = item.sub;
5
+ this.name = item.name;
6
+ this.email = item.email;
7
+ this.locale = item.locale;
8
+ this.picture = item.picture;
9
+ }
10
+ }
@@ -0,0 +1,8 @@
1
+ export * from './OAuthBase';
2
+ export * from './OAuthUser';
3
+ export * from './go/GoUser';
4
+ export * from './go/GoOAuth';
5
+ export * from './vk/VkUser';
6
+ export * from './vk/VkOAuth';
7
+ export * from './ya/YaUser';
8
+ export * from './ya/YaOAuth';
@@ -0,0 +1,8 @@
1
+ export * from './OAuthBase';
2
+ export * from './OAuthUser';
3
+ export * from './go/GoUser';
4
+ export * from './go/GoOAuth';
5
+ export * from './vk/VkUser';
6
+ export * from './vk/VkOAuth';
7
+ export * from './ya/YaUser';
8
+ export * from './ya/YaOAuth';
@@ -0,0 +1,7 @@
1
+ import { IOAuthDto, IOAuthToken, OAuthBase } from "../OAuthBase";
2
+ import { VkUser } from "./VkUser";
3
+ export declare class VkOAuth<T extends VkUser = VkUser> extends OAuthBase<T> {
4
+ protected getAuthUrl(): string;
5
+ getProfile(token: string, fields: string): Promise<T>;
6
+ getTokenByCode(dto: IOAuthDto, secret: string): Promise<IOAuthToken>;
7
+ }
@@ -0,0 +1,44 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import * as _ from 'lodash';
11
+ import { OAuthBase } from "../OAuthBase";
12
+ import { VkUser } from "./VkUser";
13
+ export class VkOAuth extends OAuthBase {
14
+ getAuthUrl() {
15
+ let params = new URLSearchParams();
16
+ params.append('display', 'popup');
17
+ params.append('client_id', this.applicationId);
18
+ params.append('redirect_uri', this.redirectUri);
19
+ params.append('response_type', this.responseType);
20
+ if (!_.isEmpty(this.scope)) {
21
+ params.append('scope', this.scope);
22
+ }
23
+ return `https://oauth.vk.com/authorize?${params.toString()}`;
24
+ }
25
+ getProfile(token, fields) {
26
+ return __awaiter(this, void 0, void 0, function* () {
27
+ let { response } = yield this.http.call('https://api.vk.com/method/users.get', { data: { access_token: token, v: '5.131', fields } });
28
+ return new VkUser(response[0]);
29
+ });
30
+ }
31
+ getTokenByCode(dto, secret) {
32
+ return __awaiter(this, void 0, void 0, function* () {
33
+ let item = yield this.http.call('https://oauth.vk.com/access_token', {
34
+ data: {
35
+ code: dto.codeOrToken,
36
+ client_id: this.applicationId,
37
+ redirect_uri: dto.redirectUri,
38
+ client_secret: secret,
39
+ }
40
+ });
41
+ return { userId: item.user_id, expiresIn: item.expires_in, accessToken: item.access_token };
42
+ });
43
+ }
44
+ }
@@ -0,0 +1,5 @@
1
+ import { OAuthUser } from "../OAuthUser";
2
+ export declare class VkUser extends OAuthUser {
3
+ params: string;
4
+ protected parse(item: any): void;
5
+ }
@@ -0,0 +1,30 @@
1
+ import { OAuthUser } from "../OAuthUser";
2
+ import * as _ from 'lodash';
3
+ export class VkUser extends OAuthUser {
4
+ parse(item) {
5
+ this.id = item.id;
6
+ this.vk = `https://vk.com/id${item.id}`;
7
+ this.name = `${item.first_name} ${item.last_name}`;
8
+ this.picture = item.photo_200;
9
+ this.city = _.get(item, 'city.title');
10
+ this.country = _.get(item, 'country.title');
11
+ if (!_.isNil(item.sex) && item.sex !== 0) {
12
+ this.isMale = item.sex === 2;
13
+ }
14
+ if (!_.isNil(item.about)) {
15
+ this.description = item.about;
16
+ }
17
+ else if (!_.isNil(item.status)) {
18
+ this.description = item.status;
19
+ }
20
+ if (!_.isNil(item.bdate)) {
21
+ let array = String(item.bdate).split('.');
22
+ if (array.length === 3) {
23
+ this.birthday = new Date(Number(array[2]), Number(array[1]) - 1, Number(array[0]));
24
+ }
25
+ else if (array.length === 2) {
26
+ this.birthday = new Date(1900, Number(array[1]) - 1, Number(array[0]));
27
+ }
28
+ }
29
+ }
30
+ }
@@ -0,0 +1,9 @@
1
+ import { ILogger } from "@ts-core/common";
2
+ import { IOAuthDto, IOAuthToken, OAuthBase } from "../OAuthBase";
3
+ import { YaUser } from "./YaUser";
4
+ export declare class YaOAuth<T extends YaUser = YaUser> extends OAuthBase<T> {
5
+ constructor(logger: ILogger, window: Window, applicationId: string, scope?: string);
6
+ protected getAuthUrl(): string;
7
+ getProfile(token: string): Promise<T>;
8
+ getTokenByCode(dto: IOAuthDto, secret: string): Promise<IOAuthToken>;
9
+ }
@@ -0,0 +1,48 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { OAuthBase } from "../OAuthBase";
11
+ import { YaUser } from "./YaUser";
12
+ import * as _ from 'lodash';
13
+ import axios from 'axios';
14
+ export class YaOAuth extends OAuthBase {
15
+ constructor(logger, window, applicationId, scope) {
16
+ super(logger, window, applicationId, scope);
17
+ this.popUpWidth = 480;
18
+ this.popUpHeight = 520;
19
+ }
20
+ getAuthUrl() {
21
+ let params = new URLSearchParams();
22
+ params.append('display', 'popup');
23
+ params.append('client_id', this.applicationId);
24
+ params.append('redirect_uri', this.redirectUri);
25
+ params.append('response_type', this.responseType);
26
+ if (!_.isEmpty(this.scope)) {
27
+ params.append('scope', this.scope);
28
+ }
29
+ return `https://oauth.yandex.ru/authorize?${params.toString()}`;
30
+ }
31
+ getProfile(token) {
32
+ return __awaiter(this, void 0, void 0, function* () {
33
+ let item = yield this.http.call('https://login.yandex.ru/info', { data: { oauth_token: token } });
34
+ return new YaUser(item);
35
+ });
36
+ }
37
+ getTokenByCode(dto, secret) {
38
+ return __awaiter(this, void 0, void 0, function* () {
39
+ let { data } = yield axios.postForm('https://oauth.yandex.ru/token', {
40
+ code: dto.codeOrToken,
41
+ client_id: this.applicationId,
42
+ client_secret: secret,
43
+ grant_type: 'authorization_code'
44
+ });
45
+ return { userId: data.user_id, expiresIn: data.expires_in, accessToken: data.access_token, type: data.token_type, scope: data.scope };
46
+ });
47
+ }
48
+ }
@@ -0,0 +1,4 @@
1
+ import { OAuthUser } from "../OAuthUser";
2
+ export declare class YaUser extends OAuthUser {
3
+ protected parse(item: any): void;
4
+ }
@@ -0,0 +1,22 @@
1
+ import { OAuthUser } from "../OAuthUser";
2
+ import * as _ from 'lodash';
3
+ export class YaUser extends OAuthUser {
4
+ parse(item) {
5
+ this.id = item.id;
6
+ this.name = item.display_name;
7
+ this.email = item.default_email;
8
+ this.phone = _.get(item, 'default_phone.number');
9
+ if (!_.isNil(item.sex)) {
10
+ this.isMale = item.sex === 'male';
11
+ }
12
+ if (!item.is_avatar_empty) {
13
+ this.picture = `https://avatars.yandex.net/get-yapic/${item.default_avatar_id}/islands-200`;
14
+ }
15
+ if (!_.isNil(item.birthday)) {
16
+ let array = String(item.birthday).split('-');
17
+ if (array.length === 3) {
18
+ this.birthday = new Date(Number(array[0]), Number(array[1]) - 1, Number(array[2]));
19
+ }
20
+ }
21
+ }
22
+ }
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@ts-core/oauth",
3
+ "version": "3.0.1",
4
+ "description": "Classes and utils for oauth",
5
+ "main": "./cjs/public-api.js",
6
+ "module": "./esm/public-api.js",
7
+ "exports": {
8
+ ".": {
9
+ "import": "./esm/public-api.js",
10
+ "require": "./cjs/public-api.js"
11
+ }
12
+ },
13
+ "scripts": {},
14
+ "author": {
15
+ "name": "Renat Gubaev",
16
+ "email": "renat.gubaev@gmail.com"
17
+ },
18
+ "license": "ISC",
19
+ "dependencies": {
20
+ "@ts-core/common": "^3.0.7"
21
+ },
22
+ "devDependencies": {
23
+ "@types/node": "^14.14.31",
24
+ "gulp-npm-module-publisher": "^3.0.0"
25
+ },
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "git+https://github.com/ManhattanDoctor/ts-core-oauth.git"
29
+ },
30
+ "keywords": [
31
+ "typescript"
32
+ ],
33
+ "bugs": {
34
+ "url": "https://github.com/ManhattanDoctor/ts-core-oauth/issues"
35
+ },
36
+ "homepage": "https://github.com/ManhattanDoctor/ts-core-oauth#readme"
37
+ }