Skip to content

Commit

Permalink
Merge pull request #50 from usd-cs/Jacob-Backend
Browse files Browse the repository at this point in the history
Jacob backend
  • Loading branch information
JacobTFernandez authored Nov 14, 2024
2 parents 3a83713 + d759637 commit 68d010f
Show file tree
Hide file tree
Showing 8 changed files with 253 additions and 146 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
objects = {

/* Begin PBXBuildFile section */
1698157A2CE5AE52002BDDB7 /* Testing.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 91A8C4462CDD8D9C00764A81 /* Testing.framework */; };
9162EEB72CE15CD7005394AD /* Testing.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 91A8C4462CDD8D9C00764A81 /* Testing.framework */; platformFilter = ios; };
9162EEB82CE15CD7005394AD /* Testing.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 91A8C4462CDD8D9C00764A81 /* Testing.framework */; platformFilter = ios; };
/* End PBXBuildFile section */
Expand Down Expand Up @@ -91,6 +92,7 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
1698157A2CE5AE52002BDDB7 /* Testing.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,13 @@ enum DataError: Error {
case couldNotLoginUser
}

struct DataUtils
{

/**
im really not sure on whether or not @Envirorment and @Query should go here or if i'd be better off passing them as parameters to the functions
im really not sure on whether or not @Envirorment and @Query should go here or if i'd be better off passing them as parameters to the functions
*/
// @Environment(\.modelContext) static var context: ModelContext
// @Environment(\.modelContext) static var context: ModelContext
//@Query() static var logged_users: [User]


Expand All @@ -27,7 +30,7 @@ enum DataError: Error {
/// - Parameter logged_users: the array containing all of the users currently in the database
///
///- Returns: true if the user is found in the array --> (in DB), false otherwhise
func checkIfLoggedIn(for user :User, in logged_users: [User])->Bool{
static func checkIfLoggedIn(for user :User, in logged_users: [User])->Bool{
//im still not to sure on how to do this, but
/**
if user is logged in --> return true
Expand Down Expand Up @@ -56,48 +59,48 @@ enum DataError: Error {
/// - Throws: the function will throw an error if post_content is empty or if the Post failed to be saved to DB from context
///
/// - Returns: Post the post added to the database if operation was succesfull or nil otherwise
func addPost(for commenting_user: User, post_content: String, logged_users: [User], context: ModelContext) throws -> Post?{
static func addPost(for commenting_user: User, post_content: String, logged_users: [User], context: ModelContext) throws -> Post?{

//we probably don't want to add any empty posts
guard !post_content.isEmpty else { throw DataError.invalidContent }
print(commenting_user.name, logged_users)


// if(checkIfLoggedIn(for: commenting_user, in: logged_users)){

let new_post = Post(user: commenting_user , contents: post_content)

commenting_user.posts.append(new_post) //we may not even need this line

context.insert(new_post) //we insert the post into the context

/**
lastly based on what i understand the new post is currently stored in the context but is not saved permanently yet, so we have to do a try save

**/

do{
try context.save()
print("Printing inside of data utils: ")
printAllUsers(context: context)
printAllPosts(context: context)
printAllComments(context: context)
return new_post //if post is succesfully created we return the post to indicate this
}
catch{
print("error post could not be saved to database")
throw DataError.couldNotSave
}
// if(checkIfLoggedIn(for: commenting_user, in: logged_users)){

let new_post = Post(user: commenting_user , contents: post_content)

commenting_user.posts.append(new_post) //we may not even need this line

context.insert(new_post) //we insert the post into the context

/**
lastly based on what i understand the new post is currently stored in the context but is not saved permanently yet, so we have to do a try save

**/

do{
try context.save()
print("Printing inside of data utils: ")
// printAllUsers(context: context)
// printAllPosts(context: context)
// printAllComments(context: context)
return new_post //if post is succesfully created we return the post to indicate this
}
catch{
print("error post could not be saved to database")
throw DataError.couldNotSave
}






// }
// else{
// // if user not found we return null so we prompt to login later in the program
// return nil
// }



// }
// else{
// // if user not found we return null so we prompt to login later in the program
// return nil
// }


}
Expand All @@ -110,61 +113,91 @@ func addPost(for commenting_user: User, post_content: String, logged_users: [Use
///- Throws function throws an error if saving new user in database fails or if the user in question has no emial (unique identifier)
///
///- Returns void
func userLogin(for user_to_login: User, context: ModelContext) throws -> Bool?{

//fist we check if the user object being passed has an email
guard !user_to_login.email.isEmpty else{throw DataError.invalidContent}

// func userLogin(for user_to_login: User, context: ModelContext) throws -> Bool?{
//
// //fist we check if the user object being passed has an email
// guard !user_to_login.email.isEmpty else{throw DataError.invalidContent}
//
//
// context.insert(user_to_login) //insert the user into the context layer
//
// do{
// try context.save()
// return true
// }
// catch{
// print("error saving user")
// throw DataError.couldNotLoginUser
// }
//
//
// }

static func userLogin(username: String, password: String, context: ModelContext) throws -> User?
{
let fetchDescriptor = FetchDescriptor<User>()

guard let user = try context.fetch(fetchDescriptor).first(where: {$0.name == username }) else {
print("Why are we here")
// If the user is not found, return nil (or false if you prefer to return a boolean)
return nil
}

context.insert(user_to_login) //insert the user into the context layer
// Step 2: Use the stored salt and hashed password to verify the input password
let storedHash = user.password // The stored hashed password
let salt = user.salt // The stored salt
let createdHash = hashSaltPassword(password: password, salt: salt)

do{
// Step 3: Verify the password using the `verifyPassword` function
print("stored Hash: \(storedHash), created Hash: \(createdHash)")
let isPasswordValid = verifyPassword(input: password, storedHash: storedHash, salt: salt)
if isPasswordValid == true{

// Return the result
context.insert(user)
try context.save()
return true
}
catch{
print("error saving user")
throw DataError.couldNotLoginUser
return user
}


return user
}
func printAllUsers(context: ModelContext) {
let fetchRequest = FetchDescriptor<User>() // Create a fetch descriptor for User

static func printAllUsers(context: ModelContext) {
let fetchRequest = FetchDescriptor<User>() // Create a fetch descriptor for User
//print(fetchRequest)
do {
let users: [User] = try context.fetch(fetchRequest) // Fetch all users
print("Users in Database:")
for user in users {
print("Name: \(user.name), Email: \(user.email), Admin: \(user.admin)")
}
} catch {
print("Failed to fetch users: \(error.localizedDescription)")
do {
let users: [User] = try context.fetch(fetchRequest) // Fetch all users
print("Users in Database:")
for user in users {
print("Name: \(user.name), Email: \(user.email), Admin: \(user.admin), Password: \(user.password), Salt \(user.salt)")
}
} catch {
print("Failed to fetch users: \(error.localizedDescription)")
}

func printAllPosts(context: ModelContext) {
let fetchRequest = FetchDescriptor<Post>() // Create a fetch descriptor for Post
do {
let posts: [Post] = try context.fetch(fetchRequest) // Fetch all posts
print("Posts in Database:")
for post in posts {
print("Contents: \(post.contents), Created At: \(post.createdAt), Posted By: \(post.user.name)")
}
} catch {
print("Failed to fetch posts: \(error.localizedDescription)")
}

static func printAllPosts(context: ModelContext) {
let fetchRequest = FetchDescriptor<Post>() // Create a fetch descriptor for Post
do {
let posts: [Post] = try context.fetch(fetchRequest) // Fetch all posts
print("Posts in Database:")
for post in posts {
print("Contents: \(post.contents), Created At: \(post.createdAt), Posted By: \(post.user.name)")
}
} catch {
print("Failed to fetch posts: \(error.localizedDescription)")
}

func printAllComments(context: ModelContext) {
let fetchRequest = FetchDescriptor<Comment>() // Create a fetch descriptor for Comment
do {
let comments: [Comment] = try context.fetch(fetchRequest) // Fetch all comments
print("Comments in Database:")
for comment in comments {
print("Contents: \(comment.contents), Created At: \(comment.createdAt), Commented By: \(comment.user.name), On Post: \(comment.post.contents)")
}
} catch {
print("Failed to fetch comments: \(error.localizedDescription)")
}

static func printAllComments(context: ModelContext) {
let fetchRequest = FetchDescriptor<Comment>() // Create a fetch descriptor for Comment
do {
let comments: [Comment] = try context.fetch(fetchRequest) // Fetch all comments
print("Comments in Database:")
for comment in comments {
print("Contents: \(comment.contents), Created At: \(comment.createdAt), Commented By: \(comment.user.name), On Post: \(comment.post.contents)")
}
} catch {
print("Failed to fetch comments: \(error.localizedDescription)")
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,21 @@ final class User { //may need to make this Identifiable
var name: String
var email: String
var admin: Bool
var password: String
var salt: String

// Revised One-to-many relationship to posts
@Relationship(inverse: \Post.user) var posts: [Post] = []

// Revised One-to-many relationship to comments
@Relationship(inverse: \Comment.user) var comments: [Comment] = []

init(name: String, email: String, admin: Bool) {
init(name: String, email: String, admin: Bool, password: String, salt: String) {
self.name = name
self.email = email
self.admin = admin
self.password = password
self.salt = salt
}
}

Expand Down
Loading

0 comments on commit 68d010f

Please sign in to comment.