Dedicated messages to change the user email address.

This commit is contained in:
Philippe Pittoli 2024-11-18 07:45:37 +01:00
parent 6cbd421370
commit 1f929cdab6
3 changed files with 91 additions and 1 deletions

77
src/requests/mail.cr Normal file
View File

@ -0,0 +1,77 @@
class AuthD::Request
# NewEmailAddress: any connected user can ask to change its email address.
IPC::JSON.message NewEmailAddress, 16 do
property email : String
def initialize(@email)
end
def handle(authd : AuthD::Service, fd : Int32)
logged_user = authd.get_logged_user_full? fd
return Response::ErrorMustBeAuthenticated.new if logged_user.nil?
cloned_user = logged_user.clone
# In case of a new email address:
# 1. the new address is stored as "pending_email"
# 2. the new address has to be validated before being used as primary email address
# Verify the email address isn't already in the database.
if authd.users_per_email.get? Base64.encode(@email).chomp
return Response::ErrorEmailAddressAlreadyUsed.new
end
cloned_user.contact.pending_email = @email
cloned_user.contact.new_activation_key
begin
u_login = cloned_user.login
u_email = cloned_user.contact.pending_email.not_nil!
u_activation_token = cloned_user.contact.activation_key.not_nil!
# Once the user is created and stored, we try to contact him.
send_activation_token authd, u_login, u_email, u_activation_token
rescue e
Baguette::Log.error "mailer: #{e}"
return Response::ErrorCannotContactUser.new
end
authd.users_per_uid.update cloned_user
Response::NewEmailTokenSent.new
end
end
AuthD.requests << NewEmailAddress
# NewEmailAddressToken: validate a pending email address.
IPC::JSON.message NewEmailAddressToken, 17 do
property token : String
def initialize(@token)
end
def handle(authd : AuthD::Service, fd : Int32)
logged_user = authd.get_logged_user_full? fd
return Response::ErrorMustBeAuthenticated.new if logged_user.nil?
if logged_user.contact.activation_key.nil?
return Response::ErrorUserAlreadyValidated.new
end
# Remove the user contact activation key: the email is validated.
if logged_user.contact.activation_key != @token
return Response::ErrorInvalidActivationKey.new
end
cloned_user = logged_user.clone
cloned_user.contact.activation_key = nil
cloned_user.contact.email = cloned_user.contact.pending_email
cloned_user.contact.pending_email = nil
authd.users_per_uid.update cloned_user
Response::NewEmailAddressValidated.new
end
end
AuthD.requests << NewEmailAddressToken
end

View File

@ -1,5 +1,5 @@
class AuthD::Response
IPC::JSON.message Contacts, 12 do
IPC::JSON.message Contacts, 13 do
property user : UInt32
property email : String? = nil
def initialize(@user, @email)

13
src/responses/email.cr Normal file
View File

@ -0,0 +1,13 @@
class AuthD::Response
IPC::JSON.message NewEmailTokenSent, 14 do
def initialize()
end
end
AuthD.responses << NewEmailTokenSent
IPC::JSON.message NewEmailAddressValidated, 15 do
def initialize()
end
end
AuthD.responses << NewEmailAddressValidated
end