Skip to content

Commit

Permalink
test fix routes
Browse files Browse the repository at this point in the history
  • Loading branch information
viictoo committed Mar 11, 2024
1 parent aa551a6 commit 9cc3829
Show file tree
Hide file tree
Showing 3 changed files with 159 additions and 11 deletions.
26 changes: 15 additions & 11 deletions controllers/AuthController.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,28 @@ import dbClient from '../utils/db';
import redisClient from '../utils/redis';

class AuthController {
static async getConnect(req, res) {
const auth = req.header('Authorization').split(' ')[1];
const [email, password] = Buffer.from(auth, 'base64').toString('ascii').split(':');
if (!email || !password) {
res.status(401).json({ error: 'Unauthorized' });
static async getConnect(request, response) {
const user64 = request.header('Authorization').split(' ')[1];
const credentials = Buffer.from(user64, 'base64').toString('ascii');
const [email, rawPassword] = credentials.split(':');
if (!email || !rawPassword) {
response.status(401).json({ error: 'Unauthorized' });
return;
}
const hashPassword = sha1(password);
const users = dbClient.db.collection('users');
const user = await users.findOne({ email, password: hashPassword });
const password = sha1(rawPassword);

const dbUsers = dbClient.db.collection('users');
const user = await dbUsers.findOne({ email, password });
if (!user) {
res.status(401).json({ error: 'Unauthorized' });
response.status(401).json({ error: 'Unauthorized' });
return;
}

const token = uuidv4();
const key = `auth_${token}`;
// set a key for 24hrs
await redisClient.set(key, user._id.toString(), 86400);
res.status(200).json({ token });
response.status(200).json({ token });
}

static async getDisconnect(req, res) {
Expand All @@ -33,7 +37,7 @@ class AuthController {
return;
}
await redisClient.del(key);
res.status(204).json({});
res.status(204).send();
}
}

Expand Down
141 changes: 141 additions & 0 deletions controllers/FilesController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
import { ObjectID } from 'mongodb';
import { v4 as uuidv4 } from 'uuid';
import { promises as fs } from 'fs';
import dbClient from '../utils/db';
import redisClient from '../utils/redis';

class FilesController {
static async getUser(request) {
const token = request.header('X-Token');
const key = `auth_${token}`;
const sessionID = await redisClient.get(key);
if (sessionID) {
const users = dbClient.db.collection('users');
const mongoID = new ObjectID(sessionID);
const user = users.findOne({ _id: mongoID });
if (user) return user;
return null;
}
return null;
}

static async postUpload(req, res) {
const user = await FilesController.getUser(req, res);
if (!user) {
res.status(401).json({ error: 'Unauthorized' });
}
// eslint demands new line object-curly-newline: ["error", "never"]
const {
name, parentId, type, data,
} = req.body;
const { isPublic } = req.body.isPublic || false;

if (!name) {
res.status(400).json({ error: 'Missing name' });
}
if (!type) {
res.status(400).json({ error: 'Missing type' });
}
if (!data && type !== 'folder') {
res.status(400).json({ error: 'Missing data' });
}

const dbfiles = dbClient.db.collection('files');
if (parentId) {
const mongoObj = new ObjectID(parentId);
const parent = await dbfiles.findOne({ _id: mongoObj });
if (!parent) {
res.status(400).json({ error: 'Parent not found' });
}
if (parent.type !== 'folder') {
res.status(400).json({ error: 'Parent is not a folder' });
}
}

if (type === 'folder') {
dbfiles.insertOne({
userId: user._id,
name,
type,
parentId: parentId || 0,
isPublic,
}).then((file) => {
res.status(201).json({
id: file.insertedId,
userId: user._id,
name,
type,
isPublic,
parentId: parentId || 0,
});
}).catch((error) => console.log(error));
} else {
const filePath = process.env.FOLDER_PATH || '/tmp/files_manager';
const fileName = `${filePath}/${uuidv4()}`;
const buff = Buffer.from(data, 'base64');

try {
try {
await fs.mkdir(filePath, { recursive: true });
} catch (error) {
console.error(`file exists ${error}`);
}
await fs.writeFile(fileName, buff, 'utf-8');
} catch (error) {
console.log(error);
}

dbfiles.insertOne({
userId: user._id,
name,
type,
parentId: parentId || 0,
isPublic,
localPath: fileName,
}).then((result) => {
res.status(201).json({
id: result.insertedId,
userId: user._id,
name,
type,
isPublic,
parentId: parentId || 0,
});
}).catch((error) => console.log(error));
}
return null;
}

static async getIndex(req, res) {
const token = req.header('X-Token');
const key = `auth_${token}`;
const userId = await redisClient.get(key);
if (!userId) {
res.status(401).json({ error: 'Unauthorized' });
return;
}
const { parentId = 0, page = 0 } = req.query;
const files = dbClient.db.collection('files');
const result = await files.aggregate([
{ $match: { userId, parentId: new ObjectID(parentId) } },
{ $skip: page * 20 },
{ $limit: 20 },
]).toArray();
res.status(200).json(result);
}

static async getShow(request, response) {
const user = await FilesController.getUser(request);
if (!user) {
return response.status(401).json({ error: 'Unauthorized' });
}
const { id } = request.params;
const files = dbClient.db.collection('files');
const mongoID = new ObjectID(id);
const file = await files.findOne({ _id: mongoID, userId: user._id });
if (!file) return response.status(404).json({ error: 'Not found' });
return response.status(200).json(file);
}
}

export default FilesController;
3 changes: 3 additions & 0 deletions routes/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Router } from 'express';
import AppController from '../controllers/AppController';
import UsersController from '../controllers/UsersController';
import AuthController from '../controllers/AuthController';
import FilesController from '../controllers/FilesController';

const router = Router();

Expand All @@ -14,4 +15,6 @@ router.get('/users/me', UsersController.getMe);
router.get('/connect', AuthController.getConnect);
router.get('/disconnect', AuthController.getDisconnect);

router.post('/files', FilesController.postUpload);

export default router;

0 comments on commit 9cc3829

Please sign in to comment.