codecheck

Форк
0
/
login.post.ts 
90 строк · 2.4 Кб
1
import { prisma, lucia } from "../../utils/auth";
2
// import { generateId } from "lucia";
3

4
// import type { DatabaseUser } from "../utils/db";
5

6
export default eventHandler(async (event) => {
7
  const data = await readBody(event);
8

9
  const username = data.username;
10
  // console.log(username);
11
  if (
12
    typeof username !== "string" ||
13
    username.length < 3 ||
14
    username.length > 31 ||
15
    !/^[a-z0-9_-]+$/.test(username)
16
  ) {
17
    throw createError({
18
      message: "Некорректное имя пользователя",
19
      statusCode: 400,
20
    });
21
  }
22
  const password = data.password;
23
  if (
24
    typeof password !== "string" ||
25
    password.length < 6 ||
26
    password.length > 255
27
  ) {
28
    throw createError({
29
      message: "Неправильный пароль",
30
      statusCode: 400,
31
    });
32
  }
33
  const formData = new FormData();
34
  formData.append("username", username);
35
  formData.append("password", password);
36
  formData.append("service", "moodle_mobile_app");
37
  const tokens: any = await $fetch(
38
    "https://xn--d1a.xn--j1al4b.xn--p1ai/login/token.php",
39
    {
40
      method: "POST",
41
      body: formData,
42
    }
43
  );
44
  // console.log(tokens);
45
  if (tokens.errorcode) {
46
    throw createError({
47
      message: "Неправильное имя пользователя или пароль",
48
      statusCode: 400,
49
    });
50
  }
51

52
  let existingUser = await prisma.user.findFirst({
53
    where: {
54
      username: username,
55
    },
56
  });
57
  const userInfo: any = await $fetch(
58
    `https://xn--d1a.xn--j1al4b.xn--p1ai/webservice/rest/server.php?wstoken=${tokens.token}&wsfunction=core_user_get_users_by_field&field=username&values[0]=${username}&moodlewsrestformat=json`
59
  );
60
  // console.log(userInfo);
61
  if (!existingUser) {
62
    existingUser = await prisma.user.create({
63
      data: {
64
        // id: generateId(15),
65
        email: userInfo[0].email,
66
        fio: userInfo[0].fullname,
67
        username: userInfo[0].username,
68
        group: userInfo[0].city || "",
69
      },
70
    });
71
  } else {
72
    existingUser = await prisma.user.update({
73
      where: {
74
        username: existingUser.username,
75
      },
76
      data: {
77
        email: userInfo[0].email,
78
        fio: userInfo[0].fullname,
79
        group: userInfo[0].city || "",
80
      },
81
    });
82
  }
83

84
  const session = await lucia.createSession(existingUser!.id, {});
85
  appendHeader(
86
    event,
87
    "Set-Cookie",
88
    lucia.createSessionCookie(session.id).serialize()
89
  );
90
});
91

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.