Skip to content

Commit

Permalink
Mini fix
Browse files Browse the repository at this point in the history
  • Loading branch information
Zamelane committed Sep 6, 2024
1 parent 7eb9d14 commit cc54cc8
Show file tree
Hide file tree
Showing 14 changed files with 83 additions and 88 deletions.
1 change: 1 addition & 0 deletions apps/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"elysia": "1.1.6",
"elysia-compression": "^0.0.7",
"elysia-helmet": "^2.0.0",
"ky": "^1.7.2",
"node-rsa": "^1.1.1",
"pg": "^8.12.0",
"pg-hstore": "^2.3.4",
Expand Down
9 changes: 6 additions & 3 deletions apps/api/src/routes/ads/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { SERVER_URL } from '@config'
import { getCookieFromToken } from '@helpers'
import { HeadersWithCookie } from '@utils'

import ky from 'ky'
import { adsGetFromDB, saveAds } from 'src/models/Ads/actions'
import type { WithToken } from '../../types'

Expand All @@ -18,15 +19,17 @@ export const getAds = async ({
const authData = await getCookieFromToken(token)
const path = `${SERVER_URL}/services/people/organization/news/last/10`
console.log(path)
const response = await fetch(path, {
headers: HeadersWithCookie(authData.cookie)

const response = await ky.get(path, {
headers: HeadersWithCookie(authData.cookie),
timeout: 10000 // 10 seconds
})

if (!response.ok) {
return adsGetFromDB(spoId)
}

const result = await response.json()
const result = await response.json<NotificationsResponse[]>()

// Попутно сохраняем
saveAds(result, authData)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,17 @@ import type { AttestationResponse } from '@diary-spo/shared'
import { SERVER_URL } from '@config'
import type { ICacheData } from '@helpers'
import { HeadersWithCookie } from '@utils'
import ky from 'ky'

export const getAttestationFromDiary = async (
authData: ICacheData
): Promise<AttestationResponse> => {
const path = `${SERVER_URL}/services/reports/curator/group-attestation-for-student/${authData.idFromDiary}`

return fetch(path, {
headers: HeadersWithCookie(authData.cookie)
})
return ky
.get(path, {
headers: HeadersWithCookie(authData.cookie),
timeout: 10000 // 10 seconds
})
.json()
}
27 changes: 19 additions & 8 deletions apps/api/src/routes/auth/login/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { API_ERRORS, NotFoundError, UnknownError } from '@api'
import { SERVER_URL } from '@config'
import { b64 } from '@diary-spo/crypto'
import type { ResponseLogin, UserData } from '@diary-spo/shared'
import { fetcher } from '@utils'
import ky from 'ky'
import { offlineAuth } from './service'
import { handleResponse } from './service/helpers'
import { saveUserData } from './service/save'
Expand All @@ -23,11 +23,15 @@ const postAuth = async ({
password = await b64(password)
}

const res = await fetcher<UserData>({
url: `${SERVER_URL}/services/security/login`,
method: 'POST',
body: JSON.stringify({ login, password, isRemember: true })
const rawResponse = await ky.post(`${SERVER_URL}/services/security/login`, {
json: { login, password, isRemember: true },
timeout: 10000 // 10 seconds
})

const res = rawResponse.ok
? await rawResponse.json<UserData>()
: rawResponse.status

const parsedRes = handleResponse(res)

switch (parsedRes) {
Expand All @@ -51,11 +55,18 @@ const postAuth = async ({
* Поэтому проверяем хотя бы наличие одного обязательного поля
**/

if (!parsedRes.data.tenants) {
throw new UnknownError('Unreachable auth error')
const setCookieHeader = rawResponse.headers.get('Set-Cookie')

if (!parsedRes.tenants || !setCookieHeader) {
throw new UnknownError(`Unreachable auth error${parsedRes}`)
}

const userData = await saveUserData(parsedRes, login, password)
const userData = await saveUserData(
parsedRes,
login,
password,
setCookieHeader
)

if (!userData) {
throw new UnknownError('Unreachable auth error')
Expand Down
29 changes: 19 additions & 10 deletions apps/api/src/routes/auth/login/service/save/saveUserData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import { API_CODES, ApiError } from '@api'
import { SERVER_URL } from '@config'
import type { PersonResponse, UserData } from '@diary-spo/shared'
import { generateToken } from '@helpers'
import { type ApiResponse, cookieExtractor, error, fetcher } from '@utils'
import { cookieExtractor, error } from '@utils'
import ky from 'ky'
import {
getFormattedDiaryUserData,
saveOrGetDiaryUser,
Expand All @@ -11,21 +12,29 @@ import {
import { saveOrGetSPO } from '../../../../../models/SPO'

export const saveUserData = async (
parsedRes: ApiResponse<UserData>,
parsedRes: UserData,
login: string,
password: string
password: string,
setCookieHeader: string
) => {
const tenant = parsedRes.data.tenants[parsedRes.data.tenantName]
const tenant = parsedRes.tenants[parsedRes.tenantName]
const student = tenant.studentRole.students[0]
const SPO = tenant.settings.organization

const setCookieHeader = parsedRes.headers.get('Set-Cookie')
const cookie = cookieExtractor(setCookieHeader ?? '')
try {
const detailedInfo = await fetcher<PersonResponse>({
url: `${SERVER_URL}/services/security/account-settings`,
cookie
})
const rawResponse = await ky.get(
`${SERVER_URL}/services/security/account-settings`,
{
headers: {
Cookie: cookie
},
timeout: 10000 // 10 seconds
}
)
const detailedInfo = rawResponse.ok
? await rawResponse.json<PersonResponse>()
: rawResponse.status

if (typeof detailedInfo === 'number') {
throw new ApiError(
Expand All @@ -34,7 +43,7 @@ export const saveUserData = async (
)
}

const person = detailedInfo.data.person
const person = detailedInfo.persons[0]

const spoAddress =
SPO.actualAddress.length > 5
Expand Down
6 changes: 4 additions & 2 deletions apps/api/src/routes/finalMarks/service/get/getFinalMarks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@ import { SERVER_URL } from '@config'
import type { AcademicRecord } from '@diary-spo/shared'
import type { ICacheData } from '@helpers'
import { HeadersWithCookie } from '@utils'
import ky from 'ky'

export const getFinalMarksFromDiary = async (authData: ICacheData) => {
const path = `${SERVER_URL}/services/students/${authData.idFromDiary}/attestation`

const response = fetch(path, {
headers: HeadersWithCookie(authData.cookie)
const response = ky.get(path, {
headers: HeadersWithCookie(authData.cookie),
timeout: 10000 // 10 seconds
})

return response
Expand Down
6 changes: 4 additions & 2 deletions apps/api/src/routes/lessons/service/get/getLessons.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { SERVER_URL } from '@config'
import type { Day } from '@diary-spo/shared'
import type { ICacheData } from '@helpers'
import { HeadersWithCookie } from '@utils'
import ky from 'ky'
import { detectTerm } from 'src/models/Term/actions/other/detectTerm'
import { ScheduleGetFromDB, daySave } from '../../../../models/Schedule'
import { getFormattedResponse } from '../helpers'
Expand All @@ -15,8 +16,9 @@ export const getLessonsService = async (
): Promise<Day[]> => {
const path = `${SERVER_URL}/services/students/${authData.idFromDiary}/lessons/${startDate}/${endDate}`

const response = await fetch(path, {
headers: HeadersWithCookie(authData.cookie)
const response = await ky.get(path, {
headers: HeadersWithCookie(authData.cookie),
timeout: 10000 // 10 seconds
})

if (response.status === API_CODES.FORBIDDEN) {
Expand Down
10 changes: 7 additions & 3 deletions apps/api/src/routes/organization/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { Optional } from 'sequelize'
import { API_CODES, API_ERRORS, ApiError } from '@api'
import { SERVER_URL } from '@config'
import { HeadersWithCookie } from '@utils'
import ky from 'ky'
import { DiaryUserModel } from '../../models/DiaryUser'
import { GroupModel } from '../../models/Group'
import { SPOModel, type SPOModelType } from '../../models/SPO'
Expand All @@ -18,9 +19,12 @@ const getOrganization = async ({
}: Data): Promise<Optional<SPOModelType, 'id'>> => {
const path = `${SERVER_URL}/services/people/organization`

const response = await fetch(path, {
headers: HeadersWithCookie(cookie)
}).then((res) => res.json())
const rawResponse = await ky.get(path, {
headers: HeadersWithCookie(cookie),
timeout: 10000 // 10 seconds
})

const response = await rawResponse.json<any>()

if (response) {
/* Хотелось бы красиво по убыванию...
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { SERVER_URL } from '@config'
import type { ICacheData } from '@helpers'
import { HeadersWithCookie } from '@utils'
import ky from 'ky'

export const getPerformanceCurrent = async (authData: ICacheData) => {
const path = `${SERVER_URL}/services/reports/current/performance/${authData.idFromDiary}`
console.log(path)

return fetch(path, {
headers: HeadersWithCookie(authData.cookie)
return ky.get(path, {
headers: HeadersWithCookie(authData.cookie),
timeout: 10000 // 10 seconds
})
}
46 changes: 0 additions & 46 deletions apps/api/src/utils/fetcher.ts

This file was deleted.

1 change: 0 additions & 1 deletion apps/api/src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,4 @@ export * from './headers'
export * from './formatted'
export * from './error'
export * from './cookieExtractor'
export * from './fetcher'
export * from './errorLogger'
16 changes: 10 additions & 6 deletions apps/api/src/worker/cookieUpdater/submodules/updateUserCookie.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { SERVER_URL } from '@config'
import type { UserData } from '@diary-spo/shared'
import { cookieExtractor, fetcher, formatDate } from '@utils'
import { cookieExtractor, formatDate } from '@utils'
import ky from 'ky'
import type { IDiaryUserModel } from '../../../models/DiaryUser'
import { logger } from '../../utils/logger'

Expand All @@ -13,24 +14,27 @@ export const updateUserCookie = async (
console.log('Обновляю cookie пользователя', userInfo)

// 1. Авторизируемся
const res = await fetcher<UserData>({
url: `${SERVER_URL}/services/security/login`,
method: 'POST',
const rawResponse = await ky.post(`${SERVER_URL}/services/security/login`, {
body: JSON.stringify({
login: user.login,
password: user.password,
isRemember: true
})
}),
timeout: 10000 // 10 seconds
})

const res = rawResponse.ok
? await rawResponse.json<UserData>()
: rawResponse.status

// Если дневник вернул что-то другое...
if (typeof res === 'number') {
log('WORKER: Что-то не так... Дневник ответил чем-то другим ?')
return
}

// 2. Подготавливаем куку
const setCookieHeader = res.headers.get('Set-Cookie')
const setCookieHeader = rawResponse.headers.get('Set-Cookie')
const cookie = cookieExtractor(setCookieHeader ?? '')

// 3. Обновляем куку и дату обновления
Expand Down
4 changes: 2 additions & 2 deletions apps/shared/src/api/self/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import type { Person } from '../../base.ts'

export interface PersonResponse {
person: Person & {
persons: (Person & {
login: string
phone: string
birthday: string
isTrusted: boolean
isEsiaBound: boolean
}
})[]
}

/**
Expand Down
Binary file modified bun.lockb
Binary file not shown.

0 comments on commit cc54cc8

Please sign in to comment.