Skip to content

Commit

Permalink
feat: added password check route that returns a token on success
Browse files Browse the repository at this point in the history
  • Loading branch information
tycrek committed Dec 26, 2022
1 parent 758237f commit 3edb2e0
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
18 changes: 18 additions & 0 deletions src/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,24 @@ export const setUserPassword = (unid: string, password: string): Promise<User> =
.catch(reject);
});

/**
* Check a username & password, and return the token if it's correct
* @since v0.14.2
*/
export const checkUser = (username: string, password: string): Promise<string> => new Promise(async (resolve, reject) => {

// Find the user
const user = users.find((user) => user.username === username);
if (!user) return reject(new Error('User not found'));

// Check the password
const match = await bcrypt.compare(password, user.passhash);
if (!match) return reject(new Error('Incorrect password'));

// Return the token
resolve(user.token);
});

/**
* Deletes a user account
* @since v0.14.1
Expand Down
12 changes: 11 additions & 1 deletion src/routers/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import { MagicNumbers } from 'ass-json';
import fs from 'fs-extra';
import { Router, Request, Response, NextFunction } from 'express';
import { findFromToken, setUserPassword, users, createNewUser, deleteUser, setUserMeta, deleteUserMeta, setUsername, resetToken, verifyCliKey } from '../auth';
import { findFromToken, setUserPassword, users, createNewUser, deleteUser, setUserMeta, deleteUserMeta, setUsername, resetToken, checkUser, verifyCliKey } from '../auth';
import { log, path } from '../utils';
import { data } from '../data';
import { User } from '../types/auth';
Expand Down Expand Up @@ -84,6 +84,16 @@ function buildUserRouter() {
.catch((err) => errorHandler(res, err));
});

// Check password (plaintext password in form data; HOST SHOULD BE USING HTTPS)
userRouter.post('/password/check', (req: Request, res: Response) => {
const username = req.body.username;
const password = req.body.password;

checkUser(username, password)
.then((result) => res.send(result))
.catch((err) => errorHandler(res, err));
});

// Create a new user
// Admin only
userRouter.post('/', adminAuthMiddleware, (req: Request, res: Response) => {
Expand Down

0 comments on commit 3edb2e0

Please sign in to comment.