Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/models/User.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,10 @@ const UserSchema = new Schema(
providers: {
type: [UserProvider],
},
isAdmin: {
type: Boolean,
default: false,
},
},
{
timestamps: true,
Expand Down
21 changes: 20 additions & 1 deletion src/services/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
*/

import { accessibleRecordsPlugin } from "@casl/mongoose";
import User from "models/User";
import mongoose, { Mongoose } from "mongoose";

interface AppOptions {
Expand Down Expand Up @@ -48,10 +49,28 @@ class App implements AppOptions {

private async connect() {
try {
// connect to the database.
this.database = await mongoose.connect(this.databaseUri);
this.database.plugin(accessibleRecordsPlugin);

// try to create an admin user.
try {
const email = process.env.ADMIN_EMAIL;
if (email) {
const user = await User.findOne({ email });
if (!user) {
User.create({ email, isAdmin: true });
}
} else {
console.log("An admin email could not be found.")
}
} catch (e) {
console.error("Could not create an admin user.");
console.error(e);
}
} catch (e) {
//
console.error("Cannot connect to MongoDB server.");
console.error(e);
}
}
}
Expand Down
9 changes: 6 additions & 3 deletions src/services/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ class Authentication {
});

try {
const user = await User.findOne({ email });
const user = await User.findOne({ email: email.email });
if (!user) {
// is user cannot be found, then they are not allowed in.
throw new Error({
Expand All @@ -54,7 +54,7 @@ class Authentication {
// init access token
const accessToken = uuidv4();
await User.findOneAndUpdate(
{ email },
{ email: email.email },
{
accessToken: {
value: accessToken,
Expand Down Expand Up @@ -87,7 +87,10 @@ class Authentication {
new Date(user.accessToken?.createdAt).getTime() + 5 * 60 * 1000
) {
const token = generateToken(user.toJSON());
await User.findOneAndUpdate({ email }, { "accessToken.used": true });
await User.findOneAndUpdate(
{ email: email.email },
{ "accessToken.used": true },
);
return new Response<{ token: string }>({
message: `Welcome, ${user.name}`,
details: { token },
Expand Down