83 lines
2.8 KiB
Swift
Executable File
83 lines
2.8 KiB
Swift
Executable File
//
|
|
// PostsController.swift
|
|
//
|
|
//
|
|
// Created by Mario on 04/10/22.
|
|
//
|
|
|
|
import Fluent
|
|
import Vapor
|
|
|
|
struct PostsController: RouteCollection {
|
|
func boot(routes: RoutesBuilder) throws {
|
|
routes.group("exploit") { e in
|
|
e.get(use: read)
|
|
e.post(use: create)
|
|
e.delete(use: delete)
|
|
}
|
|
routes.get("lists", use: getLists)
|
|
}
|
|
|
|
func getLists(req: Request) async throws -> [PostSummary] {
|
|
let query: String? = try? req.query.get(at: "q")
|
|
let offset: Int = try req.query.get(at: "o") ?? 0
|
|
let postRecords = try await Post.query(on: req.db)
|
|
.filter((query != nil) ? (\.$content ~~ query!) : (\.$created_at > 0))
|
|
.sort(\.$created_at)
|
|
.offset(offset)
|
|
.limit(20)
|
|
.all()
|
|
return postRecords.map { p in
|
|
PostSummary(id: p.id!, title: p.title, pub: p.pub, created_at: p.created_at, whitelist: p.whitelist)
|
|
}
|
|
}
|
|
|
|
func read(req: Request) async throws -> Post {
|
|
guard let postId: UUID = try req.query.get(at: "id") else {throw Abort(.badRequest)}
|
|
guard let postRecord = try await Post.find(postId, on: req.db) else {throw Abort(.notFound)}
|
|
|
|
if !postRecord.pub {
|
|
let whitelist = postRecord.whitelist
|
|
if try whitelist.contains(req.session.data["user"] ?? {throw Abort(.unauthorized)}()) || postRecord.created_by == req.session.data["user"] {
|
|
return postRecord
|
|
} else {
|
|
throw Abort(.unauthorized)
|
|
}
|
|
}
|
|
return postRecord
|
|
}
|
|
|
|
func create(req: Request) async throws -> Post {
|
|
guard let thisUser = req.session.data["user"] else {throw Abort(.unauthorized)}
|
|
let _ = try await User.query(on: req.db)
|
|
.filter(\.$username == thisUser)
|
|
.first() ?? {throw Abort(.unauthorized)}()
|
|
|
|
let content = try req.content.decode(PostRequest.self)
|
|
|
|
let post = Post(created_by: thisUser,
|
|
content: content.content,
|
|
title: content.title,
|
|
pub: content.pub ?? false)
|
|
|
|
try await post.save(on: req.db)
|
|
|
|
return post
|
|
}
|
|
|
|
func delete(req: Request) async throws -> HTTPResponseStatus {
|
|
guard let thisUser = req.session.data["user"] else {return .unauthorized}
|
|
guard let postId: UUID = try req.query.get(at: "id") else {return .badRequest}
|
|
guard let postRecord = try await Post.find(postId, on: req.db) else {return .notFound}
|
|
|
|
let author = postRecord.created_by
|
|
|
|
if (author == thisUser) {
|
|
try await postRecord.delete(on: req.db)
|
|
return .ok
|
|
}
|
|
|
|
return .unauthorized
|
|
}
|
|
}
|