1
0
Fork 0
mirror of https://github.com/classchartsapi/classcharts-api-js.git synced 2026-05-14 11:58:13 +00:00
classcharts-api-js/src/core/studentClient.ts

70 lines
2 KiB
TypeScript
Raw Normal View History

2023-04-16 21:06:10 +01:00
import { API_BASE_STUDENT, BASE_URL } from "../utils/consts.js";
2023-04-16 20:47:40 +01:00
import { BaseClient } from "./baseClient.js";
2023-04-16 21:06:10 +01:00
import { parseCookies } from "../utils/utils.js";
import ky from "ky-universal";
2023-04-16 20:47:40 +01:00
2022-03-12 11:30:03 +00:00
/**
2023-04-07 13:47:08 +01:00
* Student Client
2022-03-12 11:30:03 +00:00
*/
2023-04-16 20:47:40 +01:00
export class StudentClient extends BaseClient {
/**
* @property studentCode Classcharts student code
* @internal
*/
private studentCode = "";
/**
* @property dateOfBirth Student's date of birth
* @internal
*/
private dateOfBirth = "";
2022-03-12 11:30:03 +00:00
/**
*
* @param studentCode Classcharts student code
* @param dateOfBirth Student's date of birth
*/
constructor(studentCode: string, dateOfBirth?: string) {
super(API_BASE_STUDENT);
2022-03-12 11:30:03 +00:00
this.studentCode = String(studentCode);
this.dateOfBirth = String(dateOfBirth);
}
/**
2023-04-16 20:47:40 +01:00
* Authenticates with classcharts
2022-03-12 11:30:03 +00:00
*/
async login(): Promise<void> {
if (!this.studentCode) throw new Error("Student Code not inputted");
const formData = new URLSearchParams();
formData.append("_method", "POST");
formData.append("code", this.studentCode.toUpperCase());
formData.append("dob", this.dateOfBirth);
formData.append("remember_me", "1");
formData.append("recaptcha-token", "no-token-avaliable");
const request = await ky(BASE_URL + "/student/login", {
2022-03-12 11:30:03 +00:00
method: "POST",
body: formData,
redirect: "manual",
throwHttpErrors: false,
credentials: undefined,
2022-03-12 11:30:03 +00:00
});
if (request.status != 302 || !request.headers.get("set-cookie")) {
throw new Error(
"Unauthenticated: Classcharts returned an error: " +
request.status +
" " +
request.statusText
);
}
const cookies = String(request.headers.get("set-cookie"));
this.authCookies = cookies.split(",");
2022-08-03 16:53:46 +01:00
const sessionCookies = parseCookies(cookies);
const sessionID = JSON.parse(
String(sessionCookies["student_session_credentials"])
2022-03-12 11:30:03 +00:00
);
this.sessionId = sessionID.session_id;
2023-04-07 12:43:46 +01:00
await this.getNewSessionId();
2022-03-12 11:30:03 +00:00
const user = await this.getStudentInfo();
2023-04-07 13:47:08 +01:00
this.studentId = user.data.user.id;
2022-03-12 11:30:03 +00:00
}
}