-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathverifyAuth.ts
202 lines (176 loc) · 6.53 KB
/
verifyAuth.ts
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
import { connection } from "../db/connection";
import { sha256 } from "../crypto/createHash";
import { getUser, getUserByUsername, User, UserType, _getUserByUsername } from "../db/user";
import { RowDataPacket } from "mysql2";
import { generateUuid } from "../crypto/uuid";
import { getUnixTime } from "../lib/getUnixTime";
import { RecordType } from "../db/record";
import { getChore } from "../db/chore";
import { getCompletedChore } from "../db/completedChore";
import { createHousehold, getHouseholdById } from "../db/household";
import { getPurchaseById } from "../db/purchase";
export interface LoginKey extends RowDataPacket {
id: number,
login_key: string,
time_created: number,
length: number,
user: number,
}
export interface LoginAttemptResult {
loginKey: string,
success: boolean,
user?: User,
message: string,
}
export interface SignupAttemptResult {
success: boolean,
error?: string,
user?: User,
}
const LOGIN_KEY_LENGTH = 2592000;
export const addLoginKey = async (userId: number): Promise<string> => {
return new Promise((resolve, reject) => {
try {
const key = generateUuid();
connection.query(`INSERT INTO login_keys (login_key, time_created, length, user) VALUES (?, ?, ?, ?);`, [key, getUnixTime(), LOGIN_KEY_LENGTH, userId], (err: any, result: LoginKey[]) => {
resolve(key);
})
} catch {
reject("Error adding login key.");
}
});
}
export const verifyLogin = async (username: string, password: string): Promise<LoginAttemptResult> => {
const hashedPassword = sha256(password);
const user = await _getUserByUsername(username);
if (user && user.password == hashedPassword) {
const loginKey = await addLoginKey(user.id);
const result: LoginAttemptResult = {
user,
loginKey,
success: true,
message: "Successfully logged in"
};
return result;
} else {
console.log()
const result: LoginAttemptResult = {
user,
loginKey: '',
success: false,
message: "Incorrect password"
};
return result;
}
}
export const getLoginKey = async (loginKey: string): Promise<LoginKey> => {
return new Promise((resolve, reject) => {
try {
connection.query(`SELECT * FROM login_keys WHERE login_key=?;`, [loginKey], (err: any, result: LoginKey[]) => {
resolve(result[0]);
})
} catch {
reject("Error adding login key.");
}
});
}
export const tokenIsValid = async (loginKey: string): Promise<LoginAttemptResult> => {
try {
const key = await getLoginKey(loginKey);
const user = await getUser(key.user);
const result: LoginAttemptResult = {
loginKey,
user,
success: true,
message: "Token valid!"
};
return result;
} catch {
const result: LoginAttemptResult = {
loginKey: loginKey,
success: false,
message: "Token invalid."
};
return result;
}
}
export const userExists = async (username: string): Promise<boolean> => {
try {
const result = await getUserByUsername(username);
result.id;
return true;
} catch {
return false;
}
}
export const signUp = async (username: string, password: string, time_created: number, balance: number, role: UserType, allowance: number, nickname: string, household: string): Promise<SignupAttemptResult> => {
return new Promise(async (resolve, reject) => {
try {
if ((await userExists(username)))
{
const result: SignupAttemptResult = {
success: false,
error: "Username is already in use!",
};
resolve(result);
}
if (role == UserType.Parent)
{
const house = await createHousehold(household, getUnixTime());
household = house.code;
}
connection.query(`INSERT INTO users (username, password, time_created, balance, role, allowance, household, nickname) VALUES (?, ?, ?, ?, ?, ?, ?, ?);`, [username, sha256(password), time_created, balance, role, allowance, household, nickname], async (err: any) => {
const user = await getUserByUsername(username);
const result: SignupAttemptResult = {
success: true,
user: user,
};
resolve(result);
});
} catch {
const result: SignupAttemptResult = {
success: false,
error: "Server error processing sign-up.",
};
resolve(result);
}
})
}
export const userCanAccessRecord = async (userId: number, recordId: number, recordType: RecordType): Promise<boolean> => {
const user = await getUser(userId);
try {
switch (recordType) {
case RecordType.Bonus:
return false;
case RecordType.Chore:
const chore = await getChore(recordId);
return user.household == chore.household;
case RecordType.ChoreCompleted:
const choreCompleted = await getCompletedChore(recordId);
return (
(user.role == UserType.Parent && user.household == choreCompleted.household) ||
(user.role == UserType.Child && user.id == choreCompleted.user)
);
case RecordType.Household:
const household = await getHouseholdById(recordId);
return household.code == user.household;
case RecordType.Purchase:
const purchase = await getPurchaseById(recordId);
return (
(user.role == UserType.Parent && user.household == purchase.household) ||
(user.role == UserType.Child && user.id == purchase.user)
);
case RecordType.User:
const recordUser = await getUser(recordId);
return (
(user.role == UserType.Parent && user.household == recordUser.household) ||
(user.role == UserType.Parent && user.id == recordUser.id) ||
(user.role == UserType.Child && user.id == recordUser.id)
);
default:
return false;
}
} catch {
return false;
}
}