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

Commit

Permalink
Merge pull request #41 from cm-dyoshikawa/refactor
Browse files Browse the repository at this point in the history
Refactor
  • Loading branch information
dyoshikawa authored Jan 18, 2022
2 parents 980714c + 73686f5 commit 069bb45
Show file tree
Hide file tree
Showing 22 changed files with 122 additions and 266 deletions.
62 changes: 42 additions & 20 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,23 @@ npm i @niseline/niseliff
Use NiseLiff sdk in your client app!

```tsx
import { buildNiseLiff } from '@niseline/niseliff'
import { buildNiseliff } from '@niseline/niseliff'
import React from 'react'
import ReactDOM from 'react-dom'

const niseliff = buildNiseLiff()
declare global {
interface Window {
liff: Liff
}
}

niseliff
window.liff = buildNiseliff({
liffId: 'DUMMY_LIFF_ID',
})

window.liff
.init({
liffId: 'DEFAULT_LIFF_ID', // You can use any value
liffId: 'DUMMY_LIFF_ID',
})
.then(() => {
ReactDOM.render(
Expand All @@ -49,23 +57,37 @@ npm i @niseline/niseliff

### Usage

```ts
// /path/to/config.ts

export const env: 'local' | 'development' | 'staging' | 'production' = 'local'
```

```ts
// /path/to/liff.ts

import * as config from '/path/to/config'
import realLiff from '@line/liff'
import { buildNiseliff } from '@niseline/niseliff'

const liff =
config.env === 'local' ? buildNiseliff({ liffId: 'DUMMY_LIFF_ID' }) : realLiff
export default liff
```

```tsx
import { buildNiseLiff } from '@niseline/niseliff'
// /path/to/index.tsx

import liff from '/path/to/liff'
import React from 'react'
import ReactDOM from 'react-dom'

const niseliff = buildNiseLiff()

niseliff
.init({
liffId: 'DEFAULT_LIFF_ID', // You can use any value
})
.then(() => {
ReactDOM.render(
<React.StrictMode>Your client app</React.StrictMode>,
document.getElementById('root')
)
})
liff.init({ liffId: 'DUMMY_LIFF_ID' }).then(() => {
ReactDOM.render(
<React.StrictMode>Your client app</React.StrictMode>,
document.getElementById('root')
)
})
```

### Features
Expand Down Expand Up @@ -112,7 +134,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 +152,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
11 changes: 5 additions & 6 deletions packages/niseliff-sdk/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,8 @@ import { buildSendMessages } from './method/send-messages'
import { buildShareTargetPicker } from './method/share-target-picker'
import { ConsoleLogger, Logger } from './util/logger'

export const buildNiseLiff = (params?: {
clientEndpoint?: string
authEndpoint?: string
export const buildNiseliff = (params?: {
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
}
4 changes: 2 additions & 2 deletions packages/sample-client-app/src/main.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Liff } from '@line/liff'
import { buildNiseLiff } from '@niseline/niseliff'
import { buildNiseliff } from '@niseline/niseliff'
import React from 'react'
import ReactDOM from 'react-dom'
import { App } from './app'
Expand All @@ -11,7 +11,7 @@ declare global {
}
}

window.liff = buildNiseLiff() as Liff
window.liff = buildNiseliff() as Liff

window.liff
.init({
Expand Down
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')
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ export const buildDebugRegisterUserFastifyHandler =
channelId: body.channelId,
accessToken: body.accessToken,
idToken: body.idToken,
authorizationCode: '',
})

reply.type('application/json').code(200)
Expand Down

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)
}
Loading

0 comments on commit 069bb45

Please sign in to comment.