Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions app/graphql/mutations/users/email_verification.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# frozen_string_literal: true

module Mutations
module Users
class EmailVerification < BaseMutation
description 'Verify your email when changing it or signing up'

field :user, Types::UserType, null: true, description: 'The user whose email was verified'

argument :token, String, required: true, description: 'The email verification token'

def resolve(token:)
::Users::EmailVerificationService.new(
current_authentication,
token
).execute.to_mutation_response(success_key: :user)
end
end
end
end
1 change: 1 addition & 0 deletions app/graphql/types/mutation_type.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ class MutationType < Types::BaseObject
mount_mutation Mutations::Users::Mfa::BackupCodes::Rotate
mount_mutation Mutations::Users::Mfa::Totp::GenerateSecret
mount_mutation Mutations::Users::Mfa::Totp::ValidateSecret
mount_mutation Mutations::Users::EmailVerification
mount_mutation Mutations::Users::Login
mount_mutation Mutations::Users::Logout
mount_mutation Mutations::Users::Register
Expand Down
10 changes: 10 additions & 0 deletions app/mailers/user_mailer.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# frozen_string_literal: true

class UserMailer < ApplicationMailer
def email_verification
@user = params[:user]
@verification_code = params[:verification_code]

mail(to: @user.email, subject: 'Email verification')
end
end
2 changes: 2 additions & 0 deletions app/models/audit_event.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ class AuditEvent < ApplicationRecord
flow_created: 31,
flow_updated: 32,
flow_deleted: 33,
email_verification_sent: 34,
email_verified: 35,
}.with_indifferent_access

# rubocop:disable Lint/StructNewOverride
Expand Down
4 changes: 4 additions & 0 deletions app/models/user.rb
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,8 @@ def validate_mfa!(mfa)
end
[mfa_passed, mfa_type]
end

generates_token_for :email_verification, expires_in: 15.minutes do
email
end
end
2 changes: 2 additions & 0 deletions app/policies/namespace_policy.rb
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ class NamespacePolicy < BasePolicy
customizable_permission :delete_runtime
customizable_permission :rotate_runtime_token
customizable_permission :assign_role_projects
customizable_permission :verify_email
customizable_permission :send_verification_email
end

NamespacePolicy.prepend_extensions
2 changes: 2 additions & 0 deletions app/policies/user_policy.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,7 @@ class UserPolicy < BasePolicy
enable :manage_mfa
enable :update_user
enable :update_attachment_avatar
enable :verify_email
enable :send_verification_email
end
end
45 changes: 45 additions & 0 deletions app/services/users/email_verification_send_service.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# frozen_string_literal: true

module Users
class EmailVerificationSendService
include Sagittarius::Database::Transactional

attr_reader :current_authentication, :user

def initialize(current_authentication, user)
@current_authentication = current_authentication
@user = user
end

def execute
unless Ability.allowed?(current_authentication, :send_verification_email, user)
return ServiceResponse.error(message: 'Missing permission', payload: :missing_permission)
end

transactional do |t|
user.email_verified_at = nil
unless user.save
t.rollback_and_return! ServiceResponse.error(message: 'Failed to set email to unverified',
payload: user.errors)
end

UserMailer.with(
user: user,
verification_code: user.generate_token_for(:email_verification)
).email_verification.deliver_later

AuditService.audit(
:email_verification_sent,
author_id: current_authentication.user.id,
entity: user,
target: user,
details: {
email: user.email,
}
)

ServiceResponse.success(message: 'Successfully sent email verification', payload: user)
end
end
end
end
41 changes: 41 additions & 0 deletions app/services/users/email_verification_service.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# frozen_string_literal: true

module Users
class EmailVerificationService
include Sagittarius::Database::Transactional

attr_reader :current_authentication, :verification_code

def initialize(current_authentication, verification_code)
@current_authentication = current_authentication
@verification_code = verification_code
end

def execute
user = User.find_by_token_for(:email_verification, verification_code)

unless Ability.allowed?(current_authentication, :verify_email, user)
return ServiceResponse.error(message: 'Missing permission', payload: :missing_permission)
end

transactional do |t|
user.email_verified_at = Time.zone.now
unless user.save
t.rollback_and_return! ServiceResponse.error(message: 'Failed to set email to verified', payload: user.errors)
end

AuditService.audit(
:email_verified,
author_id: current_authentication.user.id,
entity: user,
target: user,
details: {
email: user.email,
}
)

ServiceResponse.success(message: 'Successfully verified email', payload: user)
end
end
end
end
8 changes: 8 additions & 0 deletions app/services/users/register_service.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,14 @@ def execute
payload: user_session.errors)
end

response = EmailVerificationSendService.new(Sagittarius::Authentication.new(:session, user_session),
user).execute

unless response.success?
t.rollback_and_return! ServiceResponse.error(message: 'Failed to send verification email',
payload: response.payload)
end

AuditService.audit(
:user_registered,
author_id: user.id,
Expand Down
9 changes: 9 additions & 0 deletions app/services/users/update_service.rb
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,15 @@ def execute
)
end

if params.key?(:email)
response = EmailVerificationSendService.new(current_authentication, user).execute

unless response.success?
t.rollback_and_return! ServiceResponse.error(message: 'Failed to send verification email',
payload: response.payload)
end
end

AuditService.audit(
:user_updated,
author_id: current_authentication.user.id,
Expand Down
1 change: 1 addition & 0 deletions app/views/user_mailer/email_verification.html.erb
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<p><a href="https://code0.tech/verify?code=<%= @verification_code %>">Click here</a> to verify your email</p>
1 change: 1 addition & 0 deletions app/views/user_mailer/email_verification.text.erb
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Click here to verify your email: https://code0.tech/verify?code=<%= @verification_code %>
7 changes: 7 additions & 0 deletions db/migrate/20250919201730_add_email_verified_at_to_user.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# frozen_string_literal: true

class AddEmailVerifiedAtToUser < Code0::ZeroTrack::Database::Migration[1.0]
def change
add_column :users, :email_verified_at, :datetime_with_timezone
end
end
1 change: 1 addition & 0 deletions db/schema_migrations/20250919201730
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
f1a90f8b00e992db78b5b4d7dd3bbe0235ef9758e5c96b848a0c025df40e3da1
1 change: 1 addition & 0 deletions db/structure.sql
Original file line number Diff line number Diff line change
Expand Up @@ -847,6 +847,7 @@ CREATE TABLE users (
updated_at timestamp with time zone NOT NULL,
admin boolean DEFAULT false NOT NULL,
totp_secret text,
email_verified_at timestamp with time zone,
CONSTRAINT check_3bedaaa612 CHECK ((char_length(email) <= 255)),
CONSTRAINT check_56606ce552 CHECK ((char_length(username) <= 50)),
CONSTRAINT check_60346c5299 CHECK ((char_length(lastname) <= 50)),
Expand Down
20 changes: 20 additions & 0 deletions docs/graphql/mutation/usersemailverification.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
---
title: usersEmailVerification
---

Verify your email when changing it or signing up

## Arguments

| Name | Type | Description |
|------|------|-------------|
| `clientMutationId` | [`String`](../scalar/string.md) | A unique identifier for the client performing the mutation. |
| `token` | [`String!`](../scalar/string.md) | The email verification token |

## Fields

| Name | Type | Description |
|------|------|-------------|
| `clientMutationId` | [`String`](../scalar/string.md) | A unique identifier for the client performing the mutation. |
| `errors` | [`[Error!]!`](../union/error.md) | Errors encountered during execution of the mutation. |
| `user` | [`User`](../object/user.md) | The user whose email was verified |
7 changes: 7 additions & 0 deletions spec/graphql/mutations/users/email_verification_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# frozen_string_literal: true

require 'rails_helper'

RSpec.describe Mutations::Users::EmailVerification do
it { expect(described_class.graphql_name).to eq('UsersEmailVerification') }
end
9 changes: 9 additions & 0 deletions spec/mailers/previews/application_mailer_preview.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# frozen_string_literal: true

# Preview all emails at http://localhost:3000/rails/mailers/user_mailer
class ApplicationMailerPreview < ActionMailer::Preview
def test_mail
user = User.first || FactoryBot.create(:user)
ApplicationMailer.with(user: user).test_mail
end
end
9 changes: 9 additions & 0 deletions spec/mailers/previews/user_mailer_preview.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# frozen_string_literal: true

# Preview all emails at http://localhost:3000/rails/mailers/user_mailer
class UserMailerPreview < ActionMailer::Preview
def email_verification
user = User.first || FactoryBot.create(:user)
UserMailer.with(user: user, verification_code: user.generate_token_for(:email_verification)).email_verification
end
end
54 changes: 54 additions & 0 deletions spec/requests/graphql/mutation/users/verify_email_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# frozen_string_literal: true

require 'rails_helper'

RSpec.describe 'usersEmailVerification Mutation' do
include GraphqlHelpers

subject(:mutate!) { post_graphql mutation, variables: variables, current_user: user }

let(:mutation) do
<<~QUERY
mutation($input: UsersEmailVerificationInput!) {
usersEmailVerification(input: $input) {
#{error_query}
user {
id
}
}
}
QUERY
end

let(:user) { create(:user) }

let(:input) do
{
token: user.generate_token_for(:email_verification),
}
end

let(:variables) { { input: input } }

context 'when token is valid' do
it 'creates runtime' do
expect(user.email_verified_at).to be_nil
mutate!

expect(graphql_data_at(:users_email_verification, :user, :id)).to be_present
expect(user.reload.email_verified_at).not_to be_nil

is_expected.to create_audit_event(
:email_verified,
author_id: user.id,
entity_id: user.id,
entity_type: 'User',
details: {
email: user.email,
},
target_id: user.id,
target_type: 'User'
)
end
end
end
8 changes: 4 additions & 4 deletions spec/services/organizations/update_service_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
RSpec.describe Organizations::UpdateService do
subject(:service_response) { described_class.new(create_authentication(current_user), organization, params).execute }

shared_examples 'does not update' do
shared_examples 'user doesnt verify' do
it { is_expected.to be_error }

it 'does not update organization' do
Expand All @@ -22,7 +22,7 @@
{ name: generate(:organization_name) }
end

it_behaves_like 'does not update'
it_behaves_like 'user doesnt verify'
end

context 'when params are invalid' do
Expand All @@ -36,13 +36,13 @@
context 'when name is to long' do
let(:params) { { name: generate(:organization_name) + ('*' * 50) } }

it_behaves_like 'does not update'
it_behaves_like 'user doesnt verify'
end

context 'when name is to short' do
let(:params) { { name: 'a' } }

it_behaves_like 'does not update'
it_behaves_like 'user doesnt verify'
end
end

Expand Down
8 changes: 4 additions & 4 deletions spec/services/runtimes/update_service_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
RSpec.describe Runtimes::UpdateService do
subject(:service_response) { described_class.new(create_authentication(current_user), runtime, params).execute }

shared_examples 'does not update' do
shared_examples 'user doesnt verify' do
it { is_expected.to be_error }

it 'does not update organization' do
Expand All @@ -22,7 +22,7 @@
{ name: generate(:runtime_name) }
end

it_behaves_like 'does not update'
it_behaves_like 'user doesnt verify'
end

context 'when params are invalid' do
Expand All @@ -32,13 +32,13 @@
context 'when name is to long' do
let(:params) { { name: generate(:runtime_name) + ('*' * 50) } }

it_behaves_like 'does not update'
it_behaves_like 'user doesnt verify'
end

context 'when name is to short' do
let(:params) { { name: 'a' } }

it_behaves_like 'does not update'
it_behaves_like 'user doesnt verify'
end
end

Expand Down
Loading