Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue #77 password reset/recovery codes functionality #93

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
5 changes: 4 additions & 1 deletion backend/.env
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,7 @@ JWT_SECRET=
PORT=6969
CORS_ORIGINS=http://localhost
BASE_API_URL=/api
RUNNING_LOCALY=1
RUNNING_LOCALY=1
RECOVERY_CODE_COUNT=5
RECOVERY_CODE_SALT="salty:)"
RECOVERY_CODE_LENGTH=6
8 changes: 8 additions & 0 deletions backend/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@ import {
} from "./controllers/ChatControllers";
import { getNotifications } from "./controllers/NotificationControllers";

import {
checkRecoveryCode,
getUpdateRecoveryCodes
} from "./controllers/RecoveryControllers";

dotenv.config();
dotenv.config({ path: `.env.local`, override: true });
const API_URL = process.env.BASE_API_URL || "";
Expand Down Expand Up @@ -173,6 +178,9 @@ app.get(API_URL + "/getContacts", authenticateToken, getContacts);

app.get(API_URL + "/notifications", authenticateToken, getNotifications);

app.get(API_URL + "/updateRecoveryCodes", authenticateToken, getUpdateRecoveryCodes);
app.post(API_URL + "/checkRecoveryCode", checkRecoveryCode);

io.on;

if ((process.env.RUNNING_LOCALLY = "1")) {
Expand Down
56 changes: 56 additions & 0 deletions backend/controllers/RecoveryControllers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { Request, Response } from "express";
import User, { IUser } from "../models/User"
import { sha256 } from "js-sha256";
import bcrypt from "bcryptjs";

const RECOVERY_CODE_COUNT = Number.parseInt(process.env.RECOVERY_CODE_COUNT);
const RECOVERY_CODE_SALT = process.env.RECOVERY_CODE_SALT;
const RECOVERY_CODE_LENGTH = Number.parseInt(process.env.RECOVERY_CODE_LENGTH);

const bcryptSalt = bcrypt.genSaltSync(10);

const generateRecoveryCode = (user: IUser) => {
let codes = []

const salt_hash = sha256(RECOVERY_CODE_SALT);

const initial_value = user._id.toString() + user.lastCodeUpdate.getTime().toString();

for (let i = 0; i < RECOVERY_CODE_COUNT; i++) {
codes.push(sha256(initial_value + salt_hash[i]).split("").slice(0, RECOVERY_CODE_LENGTH).join("").toUpperCase()); // with upper they look pretier :D // ! DON'T FORGET TO ALLOW ON FRONTEND ONLY UPPERCASE CHARACTERS
}
return codes
}

export const getUpdateRecoveryCodes = async (req: Request, res: Response) => {
const user = await User.findById(req.user.id);
user.lastCodeUpdate = new Date();
user.usedCodesIndexes = [];
let codes = generateRecoveryCode(user);
await user.save();

res.json(codes);
}

export const checkRecoveryCode = async (req: Request, res: Response) => {
const { username, code, newPassword } = req.body;
const user = await User.findOne({ username: username });
if (!user) {
return res.status(404).json({ message: "User not found" });
}
if (!code || !newPassword) {
return res.status(400).json({ message: "Bad request" });
}
const codes = generateRecoveryCode(user);

if (codes.includes(code) && !user.usedCodesIndexes.includes(codes.indexOf(code))) {
user.usedCodesIndexes.push(codes.indexOf(code));

user.password = bcrypt.hashSync(newPassword, bcryptSalt);

await user.save();
res.json({message: "ok", check: true});
} else {
res.json({message: "code was used or don't exist", check: false});
}
}
4 changes: 4 additions & 0 deletions backend/models/User.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ export interface IUser {
pronouns: string,
profileHashColor: string,
contacts: Array<string>,
lastCodeUpdate?: Date
usedCodesIndexes: Array<number>
}

const UserSchema = new Schema<IUser>(
Expand All @@ -26,6 +28,8 @@ const UserSchema = new Schema<IUser>(
max: 7,
},
contacts: [{ type: Schema.Types.ObjectId, ref: "User" }],
lastCodeUpdate: { type: Date, default: new Date(-8640000000000000) }, // yep. thanks javascript :S
usedCodesIndexes: [{ type: Number, default: [] }],
},
{
timestamps: true,
Expand Down
7 changes: 7 additions & 0 deletions backend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"date-fns": "^3.6.0",
"dotenv": "^16.4.5",
"express": "^4.21.0",
"js-sha256": "^0.11.0",
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.6.3",
"multer": "^1.4.5-lts.1",
Expand Down
22 changes: 22 additions & 0 deletions frontend/src/pages/Settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,25 @@ export default function Settings() {
});
}, [token]);

const downloadRecoveryCodes = async () => {
const response = await fetch(`${api}/updateRecoveryCodes`, {
method: "GET",
headers: {
Authorization: `Bearer ${token}`,
},
credentials: "include",
});
const data: string[] = await response.json();

// thanks js for this junk
const element = document.createElement("a");
const file = new Blob(["Those codes are used to reset your passwords:\n" + data.join("\n")], {type: 'text/plain'});
element.href = URL.createObjectURL(file);
element.download = "rgsn.live-recovery-codes.txt";
document.body.appendChild(element); // Required for this to work in FireFox
element.click();
}

return (
<div className={Styles.wrapper}>
<Header color={"#a6e3a1"} />
Expand Down Expand Up @@ -92,6 +111,9 @@ export default function Settings() {

<button>Save</button>
</form>
<div className={Styles.recoveryCodes}>
<button onClick={downloadRecoveryCodes}>Download recovery codes</button> {/* //TODO it sucks and should be ONLY in dev. For prod add password request */}
</div>
</div>

<div className={Styles.colorPicker}>
Expand Down