@chevre/domain
Version:
Chevre Domain Library for Node.js
492 lines (491 loc) • 22.4 kB
JavaScript
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PersonRepo = void 0;
// import { fromEnv } from '@aws-sdk/credential-providers';
const google_libphonenumber_1 = require("google-libphonenumber");
const factory = require("../factory");
/**
* 会員リポジトリ
*/
class PersonRepo {
constructor(options) {
const { cognitoIdentityServiceProvider, userPoolId } = options;
this.userPoolId = userPoolId;
this.cognitoIdentityServiceProvider = cognitoIdentityServiceProvider;
// this.cognitoIdentityServiceProvider = new CognitoIdentityProvider({
// apiVersion: 'latest',
// region: 'ap-northeast-1',
// credentials: awsCredentials
// });
}
static ATTRIBUTE2PROFILE(params) {
let additionalProperty = [];
if (Array.isArray(params.attributes)) {
additionalProperty = params.attributes.map((a) => {
return { name: String(a.Name), value: String(a.Value) };
});
}
const profile = {
givenName: '',
familyName: '',
email: '',
image: '',
telephone: '',
additionalProperty: additionalProperty
};
if (Array.isArray(params.attributes)) {
params.attributes.forEach((userAttribute) => {
switch (userAttribute.Name) {
case 'given_name':
// tslint:disable-next-line:max-line-length no-single-line-block-comment
profile.givenName = (userAttribute.Value !== undefined) ? userAttribute.Value : /* istanbul ignore next: please write tests */ '';
break;
case 'family_name':
// tslint:disable-next-line:max-line-length no-single-line-block-comment
profile.familyName = (userAttribute.Value !== undefined) ? userAttribute.Value : /* istanbul ignore next: please write tests */ '';
break;
case 'email':
// tslint:disable-next-line:max-line-length no-single-line-block-comment
profile.email = (userAttribute.Value !== undefined) ? userAttribute.Value : /* istanbul ignore next: please write tests */ '';
break;
case 'picture':
// tslint:disable-next-line:max-line-length no-single-line-block-comment
profile.image = (userAttribute.Value !== undefined) ? userAttribute.Value : /* istanbul ignore next: please write tests */ '';
break;
case 'phone_number':
// tslint:disable-next-line:max-line-length no-single-line-block-comment
profile.telephone = (userAttribute.Value !== undefined) ? userAttribute.Value : /* istanbul ignore next: please write tests */ '';
break;
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore next */
default:
}
});
}
return profile;
}
static ATTRIBUTE2PERSON(params) {
const profile = PersonRepo.ATTRIBUTE2PROFILE(params);
const identifier = [];
if (typeof params.userPoolId === 'string') {
// identifier.push(
// { name: 'iss', value: `${credentials.aws.tokenIssuerEndpoint}/${params.userPoolId}` }
// );
}
const person = Object.assign(Object.assign({}, profile), { typeOf: factory.personType.Person, id: '', identifier: identifier, memberOf: {
membershipNumber: params.username,
typeOf: factory.programMembership.ProgramMembershipType.ProgramMembership
} });
if (Array.isArray(params.attributes)) {
params.attributes.forEach((a) => {
switch (a.Name) {
case 'sub':
// tslint:no-single-line-block-comment
person.id = (a.Value !== undefined) ? a.Value : /* istanbul ignore next: please write tests */ '';
break;
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore next */
default:
}
});
}
return person;
}
static PROFILE2ATTRIBUTE(params) {
let formatedPhoneNumber;
if (typeof params.telephone === 'string' && params.telephone.length > 0) {
try {
const phoneUtil = google_libphonenumber_1.PhoneNumberUtil.getInstance();
const phoneNumber = phoneUtil.parse(params.telephone);
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore if */
if (!phoneUtil.isValidNumber(phoneNumber)) {
throw new factory.errors.Argument('telephone', 'Invalid phone number');
}
formatedPhoneNumber = phoneUtil.format(phoneNumber, google_libphonenumber_1.PhoneNumberFormat.E164);
}
catch (error) {
throw new factory.errors.Argument('telephone', 'Invalid phone number');
}
}
const userAttributes = [];
if (typeof params.givenName === 'string') {
userAttributes.push({
Name: 'given_name',
Value: params.givenName
});
}
if (typeof params.familyName === 'string') {
userAttributes.push({
Name: 'family_name',
Value: params.familyName
});
}
if (typeof params.email === 'string') {
userAttributes.push({
Name: 'email',
Value: params.email
});
}
if (typeof formatedPhoneNumber === 'string') {
userAttributes.push({
Name: 'phone_number',
Value: formatedPhoneNumber
});
}
if (Array.isArray(params.additionalProperty)) {
userAttributes.push(...params.additionalProperty.map((a) => {
let userAttributesValue = a.value;
// custom:telephoneに関してもtelephoneと同様のバリデーションを追加
if (a.name === 'custom:telephone') {
try {
const phoneUtil = google_libphonenumber_1.PhoneNumberUtil.getInstance();
const phoneNumber = phoneUtil.parse(String(a.value));
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore if */
if (!phoneUtil.isValidNumber(phoneNumber)) {
throw new factory.errors.Argument('custom:telephone', 'Invalid phone number');
}
userAttributesValue = phoneUtil.format(phoneNumber, google_libphonenumber_1.PhoneNumberFormat.E164);
}
catch (error) {
throw new factory.errors.Argument('custome:telephone', 'Invalid phone number');
}
}
return {
Name: a.name,
Value: userAttributesValue
};
}));
}
return userAttributes;
}
/**
* 管理者権限でユーザー属性を取得する
*/
getUserAttributes(params) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
this.cognitoIdentityServiceProvider.adminGetUser({
UserPoolId: this.userPoolId,
Username: params.username
}, (err, data) => {
if (err instanceof Error) {
reject(err);
}
else {
resolve(PersonRepo.ATTRIBUTE2PROFILE({ attributes: data === null || data === void 0 ? void 0 : data.UserAttributes }));
}
});
});
});
}
/**
* 管理者権限でプロフィール更新
*/
updateProfile(params) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
const userAttributes = PersonRepo.PROFILE2ATTRIBUTE(params.profile);
this.cognitoIdentityServiceProvider.adminUpdateUserAttributes({
UserPoolId: this.userPoolId,
Username: params.username,
UserAttributes: userAttributes
}, (err) => {
if (err instanceof Error) {
reject(new factory.errors.Argument('profile', err.message));
}
else {
resolve();
}
});
});
});
}
/**
* 管理者権限でsubでユーザーを検索する
*/
findById(params) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
this.cognitoIdentityServiceProvider.listUsers({
UserPoolId: this.userPoolId,
Filter: `sub="${params.userId}"`
}, (err, data) => {
if (err instanceof Error) {
reject(err);
}
else {
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore if: please write tests */
if ((data === null || data === void 0 ? void 0 : data.Users) === undefined) {
reject(new factory.errors.NotFound('User'));
}
else {
const user = data.Users.shift();
if (user === undefined) {
reject(new factory.errors.NotFound('User'));
}
else {
const person = PersonRepo.ATTRIBUTE2PERSON({
username: user.Username,
userPoolId: this.userPoolId,
attributes: user.Attributes
});
resolve(Object.assign(Object.assign({}, user), person));
}
}
}
});
});
});
}
/**
* アクセストークンでユーザー属性を取得する
*/
getUserAttributesByAccessToken(accessToken) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
this.cognitoIdentityServiceProvider.getUser({
AccessToken: accessToken
}, (err, data) => {
if (err instanceof Error) {
reject(err);
}
else {
resolve(PersonRepo.ATTRIBUTE2PROFILE({ attributes: data === null || data === void 0 ? void 0 : data.UserAttributes }));
}
});
});
});
}
/**
* 会員プロフィール更新
*/
updateProfileByAccessToken(params) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
const userAttributes = PersonRepo.PROFILE2ATTRIBUTE(params.profile);
this.cognitoIdentityServiceProvider.updateUserAttributes({
AccessToken: params.accessToken,
UserAttributes: userAttributes
}, (err) => {
if (err instanceof Error) {
reject(new factory.errors.Argument('profile', err.message));
}
else {
resolve();
}
});
});
});
}
/**
* 削除
*/
deleteById(params) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
this.cognitoIdentityServiceProvider.listUsers({
UserPoolId: this.userPoolId,
Filter: `sub="${params.userId}"`
}, (listUsersErr, data) => {
if (listUsersErr instanceof Error) {
reject(listUsersErr);
}
else {
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore if: please write tests */
if ((data === null || data === void 0 ? void 0 : data.Users) === undefined) {
reject(new factory.errors.NotFound('User'));
}
else {
const user = data.Users.shift();
if (user === undefined || user.Username === undefined) {
reject(new factory.errors.NotFound('User'));
}
else {
this.cognitoIdentityServiceProvider.adminDeleteUser({
UserPoolId: this.userPoolId,
Username: user.Username
}, (err) => {
if (err instanceof Error) {
reject(err);
}
else {
resolve();
}
});
}
}
}
});
});
});
}
/**
* 無効化する
*/
disable(params) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
this.cognitoIdentityServiceProvider.listUsers({
UserPoolId: this.userPoolId,
Filter: `sub="${params.userId}"`
}, (listUsersErr, data) => {
if (listUsersErr instanceof Error) {
reject(listUsersErr);
}
else {
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore if: please write tests */
if ((data === null || data === void 0 ? void 0 : data.Users) === undefined) {
reject(new factory.errors.NotFound('User'));
}
else {
const user = data.Users.shift();
if (user === undefined || user.Username === undefined) {
reject(new factory.errors.NotFound('User'));
}
else {
this.cognitoIdentityServiceProvider.adminDisableUser({
UserPoolId: this.userPoolId,
Username: user.Username
}, (err) => {
if (err instanceof Error) {
reject(err);
}
else {
resolve();
}
});
}
}
}
});
});
});
}
/**
* グローバルサインアウトかつ無効化
*/
globalSignOutAndDisable(params) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
this.cognitoIdentityServiceProvider.listUsers({
UserPoolId: this.userPoolId,
Filter: `sub="${params.userId}"`
}, (listUsersErr, data) => {
var _a, _b;
if (listUsersErr instanceof Error) {
reject(listUsersErr);
}
else {
const username = (_b = (_a = data === null || data === void 0 ? void 0 : data.Users) === null || _a === void 0 ? void 0 : _a.shift()) === null || _b === void 0 ? void 0 : _b.Username;
if (typeof username !== 'string') {
reject(new factory.errors.NotFound('User'));
}
else {
this.cognitoIdentityServiceProvider.adminUserGlobalSignOut({
UserPoolId: this.userPoolId,
Username: username
}, (adminUserGlobalSignOutErr) => {
if (adminUserGlobalSignOutErr instanceof Error) {
reject(adminUserGlobalSignOutErr);
}
else {
this.cognitoIdentityServiceProvider.adminDisableUser({
UserPoolId: this.userPoolId,
Username: username
}, (adminDisableUserErr) => {
if (adminDisableUserErr instanceof Error) {
reject(adminDisableUserErr);
}
else {
resolve();
}
});
}
});
}
}
});
});
});
}
/**
* 検索
*/
search(params) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
const request = {
// Limit: 60,
UserPoolId: this.userPoolId
};
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore else */
if (params.id !== undefined) {
request.Filter = `sub^="${params.id}"`;
}
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore else */
if (params.username !== undefined) {
request.Filter = `username^="${params.username}"`;
}
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore else */
if (params.email !== undefined) {
request.Filter = `email^="${params.email}"`;
}
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore else */
if (params.telephone !== undefined) {
request.Filter = `phone_number^="${params.telephone}"`;
}
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore else */
if (params.givenName !== undefined) {
request.Filter = `given_name^="${params.givenName}"`;
}
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore else */
if (params.familyName !== undefined) {
request.Filter = `family_name^="${params.familyName}"`;
}
this.cognitoIdentityServiceProvider.listUsers(request, (err, data) => {
if (err instanceof Error) {
reject(err);
}
else {
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore if: please write tests */
if ((data === null || data === void 0 ? void 0 : data.Users) === undefined) {
reject(new factory.errors.NotFound('User'));
}
else {
resolve(data.Users.map((u) => {
const person = PersonRepo.ATTRIBUTE2PERSON({
username: u.Username,
userPoolId: this.userPoolId,
attributes: u.Attributes
});
return Object.assign(Object.assign({}, u), person);
}));
}
}
});
});
});
}
}
exports.PersonRepo = PersonRepo;
;