-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathauth_controller.ts
More file actions
176 lines (160 loc) · 4.83 KB
/
auth_controller.ts
File metadata and controls
176 lines (160 loc) · 4.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
import { DateTime } from "luxon";
import assert from "node:assert";
import { HttpContext } from "@adonisjs/core/http";
import mail from "@adonisjs/mail/services/main";
import User from "#models/user";
import { createClient } from "../usos/usos_client.js";
export default class AuthController {
//login with usos
async store({ request, response, auth }: HttpContext) {
/**
* Step 1: Get credentials from the request body
*/
const { accessToken, accessSecret } = request.only([
"accessToken",
"accessSecret",
]) as { accessToken: string; accessSecret: string };
try {
const usosClient = createClient({
token: accessToken,
secret: accessSecret,
});
const profile = await usosClient.get<{
id: string;
student_number: string;
first_name: string;
last_name: string;
photo_urls: Record<string, string>;
}>("users/user?fields=id|student_number|first_name|last_name|photo_urls");
let user = await User.findBy("student_number", profile.student_number);
if (user === null) {
user = await User.create({
usos_id: profile.id,
studentNumber: profile.student_number,
firstName: profile.first_name,
lastName: profile.last_name,
avatar: profile.photo_urls["50x50"],
verified: true,
});
} else if (
user.avatar !== profile.photo_urls["50x50"] ||
user.firstName !== profile.first_name ||
user.lastName !== profile.last_name ||
user.usosId !== profile.id
) {
user.avatar = profile.photo_urls["50x50"];
user.firstName = profile.first_name;
user.lastName = profile.last_name;
user.usosId = profile.id;
await user.save();
}
await auth.use("jwt").generate(user);
return response.ok({
...user.serialize(),
});
} catch (error) {
assert(error instanceof Error);
return response.unauthorized({
message: "Login failed.",
error: error.message,
});
}
}
//get otp for login
async show({ request, response }: HttpContext) {
/**
* Step 1: Get credentials from the request body
*/
const { email } = request.only(["email"]) as { email: string };
try {
const studentNumber = email.split("@")[0];
let user = await User.findBy("studentNumber", studentNumber);
if (user === null) {
user = await User.create({
usos_id: "",
studentNumber,
firstName: "",
lastName: "",
avatar: "",
verified: false,
});
}
const otp = Math.floor(100000 + Math.random() * 900000);
user.otpCode = otp.toString();
user.otpExpire = DateTime.now().plus({ minutes: 15 });
await user.save();
//send email
await mail.send((message) => {
message
.from("Solvro Planer <planer@solvro.pl>")
.to(email)
.subject("Zweryfikuj adres email")
.text(`Twój kod weryfikacyjny to: ${otp}`)
.html(`<h1>Twój kod weryfikacyjny to: ${otp}</h1>`);
});
return response.ok({
success: true,
message: "Wysłano kod weryfikacyjny",
});
} catch (error) {
assert(error instanceof Error);
return response.unauthorized({
message: "Login failed.",
error: error.message,
success: false,
});
}
}
//login with otp
async update({ request, response, auth }: HttpContext) {
/**
* Step 1: Get credentials from the request body
*/
// const { otp } = request.only(["otp"]) as { otp: string };
const { otp, email } = request.only(["otp", "email"]) as {
otp: string;
email: string;
};
try {
const user = await User.query()
.where("studentNumber", email.split("@")[0])
.where("otp_code", otp)
.where("otp_expire", ">", new Date())
.first();
if (user === null) {
return response.unauthorized({
message: "Login failed.",
error: "Invalid OTP",
});
}
await auth.use("jwt").generate(user);
user.verified = true;
user.otpCode = null;
user.otpExpire = null;
await user.save();
return response.ok({
success: true,
user: user.serialize(),
});
} catch (error) {
assert(error instanceof Error);
return response.unauthorized({
message: "Login failed.",
error: error.message,
});
}
}
// logout
async destroy({ response }: HttpContext) {
try {
response.clearCookie("token");
return response.ok({ message: "Successfully logged out" });
} catch (error) {
assert(error instanceof Error);
return response.internalServerError({
message: "Logout failed",
error: error.message,
});
}
}
}