Skip to content
This repository has been archived by the owner on Jan 20, 2022. It is now read-only.

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
dyoshikawa committed Jan 18, 2022
1 parent fa7f823 commit 07b360e
Show file tree
Hide file tree
Showing 13 changed files with 73 additions and 138 deletions.
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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"}
```

Expand All @@ -130,15 +130,15 @@ services:
```bash
docker compose up -d
curl http://localhost:3000/niseline/ping
curl http://localhost:3000/niseline/api/ping
# => {"ping":"pong"}
```

### Usage

```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": "[email protected]"}'
# => null
Expand Down
7 changes: 3 additions & 4 deletions api.http
Original file line number Diff line number Diff line change
Expand Up @@ -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

{
Expand All @@ -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

###

Expand Down
9 changes: 4 additions & 5 deletions packages/niseliff-sdk/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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'
Expand All @@ -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),
Expand Down
89 changes: 21 additions & 68 deletions packages/niseliff-sdk/src/method/init.ts
Original file line number Diff line number Diff line change
@@ -1,103 +1,56 @@
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<typeof liff.init> => {
async (): ReturnType<typeof liff.init> => {
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
}

/**
* 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()
}
9 changes: 9 additions & 0 deletions packages/niseliff-sdk/src/type.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export interface User {
id: string
name: string
picture: string
email: string
channelId: string
idToken: string
accessToken: string
}
Original file line number Diff line number Diff line change
@@ -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')
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -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)
}
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
10 changes: 4 additions & 6 deletions packages/server/src/di/bootstrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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),
})
)

Expand Down
6 changes: 1 addition & 5 deletions packages/server/src/di/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand All @@ -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',
Expand Down
10 changes: 4 additions & 6 deletions packages/server/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,16 @@ const container = bootstrap()
* NiseLine original
*/
fastify.get(
'/niseline/ping',
'/niseline/api/ping',
container.get<RouteHandlerMethod>(DI_TYPE.DEBUG_PING_HANDLER)
)
fastify.post(
'/niseline/users',
'/niseline/api/users',
container.get<RouteHandlerMethod>(DI_TYPE.DEBUG_REGISTER_USER_HANDLER)
)
fastify.get(
'/niseline/users/me/_accessToken',
container.get<RouteHandlerMethod>(
DI_TYPE.FIND_USER_BY_ACCESS_TOKEN_FASTIFY_HANDLER
)
'/niseline/api/users/:id',
container.get<RouteHandlerMethod>(DI_TYPE.FIND_USER_BY_ID_FASTIFY_HANDLER)
)
fastify.get(
'/niseline/authorize',
Expand Down
6 changes: 0 additions & 6 deletions packages/server/template/authorize.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,6 @@
name="userId"
/>
</div>
<input
data-test="stateInput"
type="hidden"
name="state"
value="<%= state %>"
/>
<div class="flex items-center justify-between">
<button
class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"
Expand Down

0 comments on commit 07b360e

Please sign in to comment.