From 07b360e1fdcb0528565aac7b062d5f291711062c Mon Sep 17 00:00:00 2001 From: dyoshikawa Date: Wed, 19 Jan 2022 02:40:25 +0900 Subject: [PATCH] refactor --- README.md | 6 +- api.http | 7 +- packages/niseliff-sdk/src/index.ts | 9 +- packages/niseliff-sdk/src/method/init.ts | 89 +++++-------------- packages/niseliff-sdk/src/type.ts | 9 ++ .../handler/authorize-fastify-handler.ts | 7 +- ...nd-user-by-access-token-fastify-handler.ts | 29 ------ .../find-user-by-id-fastify-handler.ts | 22 +++++ .../adapter/handler/login-fastify-handler.ts | 1 - packages/server/src/di/bootstrap.ts | 10 +-- packages/server/src/di/type.ts | 6 +- packages/server/src/main.ts | 10 +-- packages/server/template/authorize.ejs | 6 -- 13 files changed, 73 insertions(+), 138 deletions(-) create mode 100644 packages/niseliff-sdk/src/type.ts delete mode 100644 packages/server/src/component/user/adapter/handler/find-user-by-access-token-fastify-handler.ts create mode 100644 packages/server/src/component/user/adapter/handler/find-user-by-id-fastify-handler.ts diff --git a/README.md b/README.md index 5ca8e88..6717a8e 100644 --- a/README.md +++ b/README.md @@ -112,7 +112,7 @@ niseliff ```bash docker run -d -p 3000:3000 dyoshikawa/niseline:latest -curl http://localhost:3000/niseline/ping +curl http://localhost:3000/niseline/api/ping # => {"ping":"pong"} ``` @@ -130,7 +130,7 @@ services: ```bash docker compose up -d -curl http://localhost:3000/niseline/ping +curl http://localhost:3000/niseline/api/ping # => {"ping":"pong"} ``` @@ -138,7 +138,7 @@ curl http://localhost:3000/niseline/ping ```bash curl --request POST \ - --url http://localhost:3000/niseline/users \ + --url http://localhost:3000/niseline/api/users \ --header 'content-type: application/json' \ --data '{"id": "FOO_ID","name": "Foo","picture": "http://example.com/foo.jpg","email": "foo@example.com"}' # => null diff --git a/api.http b/api.http index 742336f..9a15e85 100644 --- a/api.http +++ b/api.http @@ -2,11 +2,11 @@ ### -GET {{ BASE_URL }}/niseline/ping +GET {{ BASE_URL }}/niseline/api/ping ### -POST {{ BASE_URL }}/niseline/users +POST {{ BASE_URL }}/niseline/api/users Content-Type: application/json { @@ -18,9 +18,8 @@ Content-Type: application/json ### -GET {{ BASE_URL }}/niseline/users/me/_accessToken +GET {{ BASE_URL }}/niseline/api/users/DEFAULT_USER Content-Type: application/json -Authorization: Bearer DEFAULT_USER_ACCESS_TOKEN ### diff --git a/packages/niseliff-sdk/src/index.ts b/packages/niseliff-sdk/src/index.ts index eb535b5..b9d7c06 100644 --- a/packages/niseliff-sdk/src/index.ts +++ b/packages/niseliff-sdk/src/index.ts @@ -34,8 +34,7 @@ import { buildShareTargetPicker } from './method/share-target-picker' import { ConsoleLogger, Logger } from './util/logger' export const buildNiseLiff = (params?: { - clientEndpoint?: string - authEndpoint?: string + niseliffServerEndpoint?: string liffId?: string os?: 'ios' | 'android' | 'web' | undefined language?: string @@ -57,8 +56,8 @@ export const buildNiseLiff = (params?: { | '_postMessage' > => { const logger: Logger = new ConsoleLogger() - const clientEndpoint = params?.clientEndpoint ?? window.location.origin - const authEndpoint = params?.authEndpoint ?? 'http://localhost:3000' + const niseliffServerEndpoint = + params?.niseliffServerEndpoint ?? 'http://localhost:3000' const liffId = params?.liffId ?? 'DEFAULT_LIFF_ID' const os = params?.os ?? 'web' const language = params?.language ?? 'ja' @@ -69,7 +68,7 @@ export const buildNiseLiff = (params?: { return { id: buildId(liffId), ready: buildReady(), - init: buildInit({ logger, clientEndpoint, authEndpoint }), + init: buildInit({ logger, niseliffServerEndpoint }), getOS: buildGetOs(os), getLanguage: buildGetLanguage(language), getVersion: buildGetVersion(version), diff --git a/packages/niseliff-sdk/src/method/init.ts b/packages/niseliff-sdk/src/method/init.ts index db337ac..cfb14f0 100644 --- a/packages/niseliff-sdk/src/method/init.ts +++ b/packages/niseliff-sdk/src/method/init.ts @@ -1,87 +1,49 @@ import liff from '@line/liff' -import { v4 as uuidV4 } from 'uuid' +import { User } from '../type' import { Logger } from '../util/logger' export const buildInit = ({ logger, - clientEndpoint, - authEndpoint, + niseliffServerEndpoint, }: { logger: Logger - clientEndpoint: string - authEndpoint: string + niseliffServerEndpoint: string }): typeof liff.init => - async (config): ReturnType => { + async (): ReturnType => { logger.info('Init start') /** - * Check exists tokens + * Check user info */ - const accessToken = localStorage.getItem('ACCESS_TOKEN') - const idToken = localStorage.getItem('ID_TOKEN') - if (accessToken != null && idToken != null) { - logger.info('Exists tokens') - - const fetchMeResult = await fetch( - new URL('/niseline/users/me/_accessToken', authEndpoint).toString(), - { - headers: { - Authorization: `Bearer ${accessToken}`, - }, - } - ) - if (!fetchMeResult.ok) { - logger.error( - 'Invalid response from GET /niseline/users/me/_accessToken' - ) - return - } - - const fetchMeResponseBody = await fetchMeResult.json() - localStorage.setItem('MY_USER', JSON.stringify(fetchMeResponseBody)) - logger.info('Get and set my user info successfully') + const userStr = localStorage.getItem('MY_USER') + if (userStr != null) { + logger.info(`Get my user info successfully`) return } - logger.info('Not exists tokens') + logger.info('Not exists my user info') /** - * Check state and authorization code + * Check userId */ const urlSearchParams = new URLSearchParams(window.location.search) - const authorizationCode = urlSearchParams.get('code') - const state = urlSearchParams.get('state') - if (authorizationCode != null && state != null) { - if (state !== localStorage.getItem('STATE')) { - logger.error('Invalid state value') - return - } - - logger.info('Valid state value') + const userId = urlSearchParams.get('userId') + if (userId != null) { const result = await fetch( - new URL('/niseline/token', authEndpoint).toString(), - { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - grantType: 'authorization_code', - redirectUri: clientEndpoint, - code: authorizationCode, - }), - } + new URL( + `/niseline/api/users/${userId}`, + niseliffServerEndpoint + ).toString() ) if (!result.ok) { - logger.error('Invalid response from POST /niseline/token') + logger.error(`Invalid response from GET /niseline/api/users/${userId}`) return } - const json: { accessToken: string; idToken: string } = await result.json() - localStorage.setItem('ACCESS_TOKEN', json.accessToken) - localStorage.setItem('ID_TOKEN', json.idToken) - logger.info('Get and set tokens successfully') + const json: User = await result.json() + localStorage.setItem('MY_USER', JSON.stringify(json)) + logger.info('Get and set my user info successfully') window.location.reload() return } @@ -89,15 +51,6 @@ export const buildInit = /** * Start authorization flow */ - const newState = uuidV4() - localStorage.setItem('STATE', newState) - const url = new URL('/niseline/authorize', authEndpoint) - url.search = new URLSearchParams({ - response_type: 'code', - client_id: config.liffId, - scope: 'default', - redirect_uri: clientEndpoint, - state: newState, - }).toString() + const url = new URL('/niseline/authorize', niseliffServerEndpoint) window.location.href = url.toString() } diff --git a/packages/niseliff-sdk/src/type.ts b/packages/niseliff-sdk/src/type.ts new file mode 100644 index 0000000..d28848c --- /dev/null +++ b/packages/niseliff-sdk/src/type.ts @@ -0,0 +1,9 @@ +export interface User { + id: string + name: string + picture: string + email: string + channelId: string + idToken: string + accessToken: string +} diff --git a/packages/server/src/component/user/adapter/handler/authorize-fastify-handler.ts b/packages/server/src/component/user/adapter/handler/authorize-fastify-handler.ts index a926cdb..1efce26 100644 --- a/packages/server/src/component/user/adapter/handler/authorize-fastify-handler.ts +++ b/packages/server/src/component/user/adapter/handler/authorize-fastify-handler.ts @@ -1,9 +1,6 @@ import { RouteHandlerMethod } from 'fastify' export const buildAuthorizeFastifyHandler = - (): RouteHandlerMethod => async (request, reply) => { - const query = request.query as { - state: string - } - reply.view('/template/authorize.ejs', { state: query.state }) + (): RouteHandlerMethod => async (_, reply) => { + reply.view('/template/authorize.ejs') } diff --git a/packages/server/src/component/user/adapter/handler/find-user-by-access-token-fastify-handler.ts b/packages/server/src/component/user/adapter/handler/find-user-by-access-token-fastify-handler.ts deleted file mode 100644 index 44f4193..0000000 --- a/packages/server/src/component/user/adapter/handler/find-user-by-access-token-fastify-handler.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { RouteHandlerMethod } from 'fastify' -import { User } from '../../domain/entity' -import { - FindUserByAccessTokenUseCase, - UserNotFoundError, -} from '../../use-case/find-user-by-access-token-use-case' - -export const buildFindUserByAccessTokenFastifyHandler = - ({ - findUserByAccessTokenUseCase, - }: { - findUserByAccessTokenUseCase: FindUserByAccessTokenUseCase - }): RouteHandlerMethod => - async (request, reply) => { - const [, accessToken] = request.headers.authorization!.split(' ') - const user = await findUserByAccessTokenUseCase(accessToken) - if (user instanceof UserNotFoundError) { - reply.type('application/json').code(401).send() - return - } - - const responseBody: Pick = { - id: user.id, - name: user.name, - picture: user.picture, - email: user.email, - } - reply.type('application/json').code(200).send(responseBody) - } diff --git a/packages/server/src/component/user/adapter/handler/find-user-by-id-fastify-handler.ts b/packages/server/src/component/user/adapter/handler/find-user-by-id-fastify-handler.ts new file mode 100644 index 0000000..081b3ba --- /dev/null +++ b/packages/server/src/component/user/adapter/handler/find-user-by-id-fastify-handler.ts @@ -0,0 +1,22 @@ +import { RouteHandlerMethod } from 'fastify' +import { + FindUserUseCase, + UserNotFoundError, +} from '../../use-case/find-user-use-case' + +export const buildFindUserByIdFastifyHandler = + ({ + findUserUseCase, + }: { + findUserUseCase: FindUserUseCase + }): RouteHandlerMethod => + async (request, reply) => { + const { id } = request.params as { id: string } + const user = await findUserUseCase(id) + if (user instanceof UserNotFoundError) { + reply.type('application/json').code(401).send() + return + } + + reply.type('application/json').code(200).send(user) + } diff --git a/packages/server/src/component/user/adapter/handler/login-fastify-handler.ts b/packages/server/src/component/user/adapter/handler/login-fastify-handler.ts index 4158f6d..857002e 100644 --- a/packages/server/src/component/user/adapter/handler/login-fastify-handler.ts +++ b/packages/server/src/component/user/adapter/handler/login-fastify-handler.ts @@ -12,7 +12,6 @@ export const buildLoginFastifyHandler = async (request, reply) => { const body = request.body as { userId: string - state: string } const user = await loginUseCase(body.userId) if (user instanceof UserNotFoundError) { diff --git a/packages/server/src/di/bootstrap.ts b/packages/server/src/di/bootstrap.ts index 49cfc9f..bb94638 100644 --- a/packages/server/src/di/bootstrap.ts +++ b/packages/server/src/di/bootstrap.ts @@ -12,7 +12,7 @@ import { buildSendReplyMessageUseCase } from '../component/message/use-case/send import { buildAuthorizeFastifyHandler } from '../component/user/adapter/handler/authorize-fastify-handler' import { buildDebugPingFastifyHandler } from '../component/user/adapter/handler/debug-ping-fastify-handler' import { buildDebugRegisterUserFastifyHandler } from '../component/user/adapter/handler/debug-register-user-fastify-handler' -import { buildFindUserByAccessTokenFastifyHandler } from '../component/user/adapter/handler/find-user-by-access-token-fastify-handler' +import { buildFindUserByIdFastifyHandler } from '../component/user/adapter/handler/find-user-by-id-fastify-handler' import { buildShowUserComponentHandler } from '../component/user/adapter/handler/find-user-component-handler' import { buildFriendshipStatusFastifyHandler } from '../component/user/adapter/handler/get-friendship-status-fastify-handler' import { buildGetUserProfileFastifyHandler } from '../component/user/adapter/handler/get-user-profile-fastify-handler' @@ -173,12 +173,10 @@ export const bootstrap = (): Container => { }) ) container - .bind(DI_TYPE.FIND_USER_BY_ACCESS_TOKEN_FASTIFY_HANDLER) + .bind(DI_TYPE.FIND_USER_BY_ID_FASTIFY_HANDLER) .toDynamicValue(({ container: c }) => - buildFindUserByAccessTokenFastifyHandler({ - findUserByAccessTokenUseCase: c.get( - DI_TYPE.FIND_USER_BY_ACCESS_TOKEN_USE_CASE - ), + buildFindUserByIdFastifyHandler({ + findUserUseCase: c.get(DI_TYPE.FIND_USER_USE_CASE), }) ) diff --git a/packages/server/src/di/type.ts b/packages/server/src/di/type.ts index b41fd0d..3a2877e 100644 --- a/packages/server/src/di/type.ts +++ b/packages/server/src/di/type.ts @@ -18,8 +18,6 @@ export const DI_TYPE = { REGISTER_USER_USE_CASE: 'REGISTER_USER_USER_CASE', LOGIN_USE_CASE: 'LOGIN_USE_CASE', FIND_USER_USE_CASE: 'FIND_USER_USE_CASE', - FIND_USER_BY_AUTHORIZATION_CODE_USE_CASE: - 'FIND_USER_BY_AUTHORIZATION_CODE_USE_CASE', FIND_USER_BY_ACCESS_TOKEN_USE_CASE: 'FIND_USER_BY_ACCESS_TOKEN_USE_CASE', FIND_USER_BY_ID_TOKEN_USE_CASE: 'FIND_USER_BY_ID_TOKEN_USE_CASE', DEBUG_PING_HANDLER: 'DEBUG_PING_HANDLER', @@ -32,9 +30,7 @@ export const DI_TYPE = { FIND_USER_COMPONENT_HANDLER: 'FIND_USER_COMPONENT_HANDLER', AUTHORIZE_FASTIFY_HANDLER: 'AUTHORIZE_FASTIFY_HANDLER', LOGIN_FASTIFY_HANDLER: 'LOGIN_FASTIFY_HANDLER', - TOKEN_FASTIFY_HANDLER: 'TOKEN_FASTIFY_HANDLER', - FIND_USER_BY_ACCESS_TOKEN_FASTIFY_HANDLER: - 'FIND_USER_BY_ACCESS_TOKEN_FASTIFY_HANDLER', + FIND_USER_BY_ID_FASTIFY_HANDLER: 'FIND_USER_BY_ID_FASTIFY_HANDLER', // Message Component MESSAGE_COMPONENT_USER_REPOSITORY: 'MESSAGE_COMPONENT_USER_REPOSITORY', diff --git a/packages/server/src/main.ts b/packages/server/src/main.ts index dc99b21..9c36229 100644 --- a/packages/server/src/main.ts +++ b/packages/server/src/main.ts @@ -25,18 +25,16 @@ const container = bootstrap() * NiseLine original */ fastify.get( - '/niseline/ping', + '/niseline/api/ping', container.get(DI_TYPE.DEBUG_PING_HANDLER) ) fastify.post( - '/niseline/users', + '/niseline/api/users', container.get(DI_TYPE.DEBUG_REGISTER_USER_HANDLER) ) fastify.get( - '/niseline/users/me/_accessToken', - container.get( - DI_TYPE.FIND_USER_BY_ACCESS_TOKEN_FASTIFY_HANDLER - ) + '/niseline/api/users/:id', + container.get(DI_TYPE.FIND_USER_BY_ID_FASTIFY_HANDLER) ) fastify.get( '/niseline/authorize', diff --git a/packages/server/template/authorize.ejs b/packages/server/template/authorize.ejs index b4f3317..989def6 100644 --- a/packages/server/template/authorize.ejs +++ b/packages/server/template/authorize.ejs @@ -34,12 +34,6 @@ name="userId" /> -