67 lines
1.7 KiB
Swift
67 lines
1.7 KiB
Swift
//
|
|
// UserAuthRepository.swift
|
|
// ExodaiAcademy
|
|
//
|
|
// Created by Exodai on 25/01/2026.
|
|
//
|
|
|
|
import Foundation
|
|
|
|
protocol UserAuthRepository {
|
|
func findByEmail(_ email: String) async throws -> UserModel?
|
|
func findByUsername(_ username: String) async throws -> UserModel?
|
|
func create(
|
|
username: String,
|
|
email: String,
|
|
passwordHash: String,
|
|
role: Role
|
|
) async throws -> UserModel
|
|
func updatePassword(userID: UUID, passwordHash: String) async throws
|
|
func delete(userID: UUID) async throws
|
|
}
|
|
|
|
import Fluent
|
|
import Vapor
|
|
|
|
struct FluentUserAuthRepository: UserAuthRepository {
|
|
let db: any FluentKit.Database
|
|
|
|
func findByEmail(_ email: String) async throws -> UserModel? {
|
|
try await UserModel.query(on: db)
|
|
.filter(\.$email == email)
|
|
.first()
|
|
}
|
|
|
|
func findByUsername(_ username: String) async throws -> UserModel? {
|
|
try await UserModel.query(on: db)
|
|
.filter(\.$username == username)
|
|
.first()
|
|
}
|
|
|
|
func create(username: String, email: String, passwordHash: String, role: Role) async throws -> UserModel {
|
|
let user = UserModel(
|
|
username: username,
|
|
email: email,
|
|
password: passwordHash,
|
|
role: role
|
|
)
|
|
|
|
try await user.create(on: db)
|
|
return user
|
|
}
|
|
|
|
func updatePassword(userID: UUID, passwordHash: String) async throws {
|
|
guard let user = try await UserModel.find(userID, on: db) else {
|
|
throw Abort(.notFound)
|
|
}
|
|
|
|
user.password = passwordHash
|
|
try await user.save(on: db)
|
|
}
|
|
|
|
func delete(userID: UUID) async throws {
|
|
try await UserModel.find(userID, on: db)?
|
|
.delete(on: db)
|
|
}
|
|
}
|