Files
air-bookings/src/user_service.v
2025-03-15 20:16:58 +05:30

100 lines
2.4 KiB
V

module main
import veb.auth
// service_add_user is a function that adds a new user to the database.
fn (app &App) service_add_user(first_name string, last_name string, email string, password string, gender string) ! {
salt := auth.generate_salt()
user_model := User{
first_name: first_name
last_name: last_name
email: email
password: auth.hash_password_with_salt(password, salt)
gender: gender
salt: salt
}
mut insert_error := ''
sql app.db {
insert user_model into User
} or { insert_error = err.msg() }
if insert_error != '' {
return error(insert_error)
}
}
// service_find_user_by_email is a function that finds a user by their email address.
fn (app &App) service_find_user_by_email(email string, password string) !User {
mut user := sql app.db {
select from User where email == email
}!
if user[0].id == 0 {
return error('User not found')
}
if !auth.compare_password_with_hash(password, user[0].salt, user[0].password) {
return error('Invalid password')
}
return user[0]
}
// service_update_user is a function that updates a user's information.
fn (app &App) service_update_user(id ?string, first_name string, last_name string, password string) ! {
if id == none {
return error('User ID is required')
}
// Unwrap the id value
user_id := id or { return error('Invalid ID') }
// Get current user data
current_user := sql app.db {
select from User where id == user_id limit 1
}!
if current_user.len == 0 {
return error('User not found')
}
// Check which fields have changed
if first_name != current_user[0].first_name {
sql app.db {
update User set first_name = first_name where id == user_id
}!
}
if last_name != current_user[0].last_name {
sql app.db {
update User set last_name = last_name where id == user_id
}!
}
if !auth.compare_password_with_hash(password, current_user[0].salt, current_user[0].password) {
salt := auth.generate_salt()
hashed_password := auth.hash_password_with_salt(password, salt)
sql app.db {
update User set password = hashed_password, salt = salt where id == user_id
}!
}
return
}
// service_get_user is a function that retrieves a user's information.
fn (app &App) service_get_user(id int) !User {
if id == 0 {
return error('User ID is required')
}
user_id := id
// Get user data
user := sql app.db {
select from User where id == user_id limit 1
}!
if user.len == 0 {
return error('User not found')
}
return user[0]
}