34 Commits

Author SHA1 Message Date
Râu Cao
387a2fa2e6 0.6.0
All checks were successful
continuous-integration/drone/push Build is passing
2023-05-31 14:12:26 +02:00
68eba80fd7 Merge pull request 'Integrate Discourse Connect (SSO)' (#131) from feature/126_discourse_sso into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #131
2023-05-31 10:02:43 +00:00
Râu Cao
7e05530ab7 Add specs for Discourse Connect
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
Release Drafter / Update release notes draft (pull_request) Successful in 3s
2023-05-31 12:00:33 +02:00
Râu Cao
745a319b3d Minor refactoring 2023-05-31 12:00:31 +02:00
Râu Cao
f829bb3379 Use devise method for requiring login 2023-05-31 12:00:02 +02:00
Râu Cao
19bafe081f Integrate Discourse Connect (SSO) 2023-05-31 12:00:02 +02:00
d130f2f68b Merge pull request 'Allow users to set/update their display name in LDAP' (#128) from feature/123-display_names into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #128
Reviewed-by: greg <greg@noreply.kosmos.org>
2023-05-31 09:13:50 +00:00
Râu Cao
e284996c1c Remove obsolete route
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
Release Drafter / Update release notes draft (pull_request) Successful in 4s
2023-05-28 15:28:51 +02:00
Râu Cao
51489a83ab Use feature block for email update specs
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2023-05-28 15:25:53 +02:00
Râu Cao
05426e4ced Add specs for display name update 2023-05-28 15:25:42 +02:00
Râu Cao
445cdfa024 Only validate display name when updated
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
Otherwise we needlessly fetch the validated one from LDAP every time a
model is saved.
2023-05-27 20:11:01 +02:00
Râu Cao
f74227fedb Allow users to set/update their display name in LDAP
Some checks failed
continuous-integration/drone/push Build is failing
continuous-integration/drone/pr Build is failing
2023-05-27 19:59:49 +02:00
Râu Cao
32d1992632 Set user instance var for settings routes where needed 2023-05-27 19:58:59 +02:00
48be35f1b1 Merge pull request 'Allow updating one's email address on the account settings page' (#127) from feature/103-update_email into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #127
Reviewed-by: greg <greg@noreply.kosmos.org>
2023-05-26 18:07:07 +00:00
87720ef285 Merge pull request 'Add feature flags' (#125) from feature/124-feature_flags into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #125
Reviewed-by: greg <greg@noreply.kosmos.org>
2023-05-26 17:56:50 +00:00
Râu Cao
193a4c2edd Remove obsolete function argument
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
Release Drafter / Update release notes draft (pull_request) Successful in 4s
2023-05-25 19:31:16 +02:00
Râu Cao
134c81460a Allow email address updates on account settings page
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2023-05-25 16:58:53 +02:00
Râu Cao
b1a693e7cf Send different Devise mail for re-confirmations 2023-05-25 16:58:45 +02:00
Râu Cao
75bd879f84 Rename settings menu item for Lightning 2023-05-25 16:57:14 +02:00
Râu Cao
33a9e1eaa9 Use username instead of email in Devise mails 2023-05-25 16:56:40 +02:00
Râu Cao
7b321577db Update LDAP mail attribute when re-confirming email 2023-05-25 16:55:27 +02:00
Râu Cao
61f12c2741 Improve form fields with errors for model updates 2023-05-25 16:53:16 +02:00
Râu Cao
c58358c66e Add feature flags, RS dashboard dummy
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
Release Drafter / Update release notes draft (pull_request) Successful in 4s
closes #124
refs #94
2023-05-23 19:18:11 +02:00
Râu Cao
287adbd365 Add flipper gem and database migration/tables 2023-05-23 14:09:35 +02:00
Râu Cao
9048052318 Fix URL in email template
All checks were successful
continuous-integration/drone/push Build is passing
2023-05-16 13:22:44 +02:00
cddc1e86f6 Merge pull request 'Show fees of Lightning transactions' (#122) from feature/lightning_fees into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #122
Reviewed-by: hueso <hueso@noreply.kosmos.org>
Reviewed-by: bumi <bumi@noreply.kosmos.org>
2023-05-10 12:27:24 +00:00
Râu Cao
ce7387a409 Remove obsolete routes
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
Release Drafter / Update release notes draft (pull_request) Successful in 6s
2023-05-03 21:54:33 +02:00
Râu Cao
f1ae5667de Shape tx details UI a bit
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2023-05-03 12:51:22 +02:00
Râu Cao
67a9fc02d7 Rename Wallet to Lightning Network, move to Services
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2023-05-01 16:13:41 +02:00
Râu Cao
34849b28b0 WIP show fees of Lightning transactions 2023-05-01 15:15:23 +02:00
8ce5f9708f Merge pull request 'Add configurable default chatroom bookmarks for new users' (#116) from feature/default_chatrooms into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #116
Reviewed-by: galfert <garret.alfert@gmail.com>
2023-04-19 13:07:00 +00:00
Râu Cao
cb2197893c Merge branch 'master' into feature/default_chatrooms
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
Release Drafter / Update release notes draft (pull_request) Successful in 4s
2023-04-18 17:00:48 +02:00
Râu Cao
ad90fcd539 Add specs for xmpp default bookmarks, refactor xmpp job usage
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2023-04-08 16:37:21 +02:00
Râu Cao
705bd63b42 Add configurable default room bookmarks for new users
All checks were successful
continuous-integration/drone/push Build is passing
2023-04-07 23:03:43 +02:00
71 changed files with 843 additions and 471 deletions

View File

@@ -19,6 +19,8 @@ LDAP_SUFFIX='dc=kosmos,dc=org'
WEBHOOKS_ALLOWED_IPS='10.1.1.163' WEBHOOKS_ALLOWED_IPS='10.1.1.163'
DISCOURSE_PUBLIC_URL='https://community.kosmos.org' DISCOURSE_PUBLIC_URL='https://community.kosmos.org'
DISCOURSE_CONNECT_SECRET='discourse_connect_ftw'
GITEA_PUBLIC_URL='https://gitea.kosmos.org' GITEA_PUBLIC_URL='https://gitea.kosmos.org'
MASTODON_PUBLIC_URL='https://kosmos.social' MASTODON_PUBLIC_URL='https://kosmos.social'
MEDIAWIKI_PUBLIC_URL='https://wiki.kosmos.org' MEDIAWIKI_PUBLIC_URL='https://wiki.kosmos.org'

View File

@@ -1,3 +1,6 @@
DISCOURSE_PUBLIC_URL='http://discourse.example.com'
DISCOURSE_CONNECT_SECRET='discourse_connect_ftw'
EJABBERD_API_URL='http://xmpp.example.com/api' EJABBERD_API_URL='http://xmpp.example.com/api'
BTCPAY_API_URL='http://btcpay.example.com/api/v1' BTCPAY_API_URL='http://btcpay.example.com/api/v1'

View File

@@ -40,6 +40,9 @@ gem 'net-ldap'
gem "rqrcode", "~> 2.0" gem "rqrcode", "~> 2.0"
gem 'rails-settings-cached', '~> 2.8.3' gem 'rails-settings-cached', '~> 2.8.3'
gem 'pagy', '~> 6.0', '>= 6.0.2' gem 'pagy', '~> 6.0', '>= 6.0.2'
gem 'flipper'
gem 'flipper-active_record'
gem 'flipper-ui'
# HTTP requests # HTTP requests
gem 'faraday' gem 'faraday'
@@ -48,6 +51,9 @@ gem 'faraday'
gem 'sidekiq', '< 7' gem 'sidekiq', '< 7'
gem 'sidekiq-scheduler' gem 'sidekiq-scheduler'
# Service integrations
gem 'discourse_api'
# Monitoring # Monitoring
gem "sentry-ruby" gem "sentry-ruby"
gem "sentry-rails" gem "sentry-rails"

View File

@@ -108,6 +108,11 @@ GEM
devise (>= 3.4.1) devise (>= 3.4.1)
net-ldap (>= 0.16.0) net-ldap (>= 0.16.0)
diff-lcs (1.5.0) diff-lcs (1.5.0)
discourse_api (2.0.0)
faraday (~> 2.7)
faraday-follow_redirects
faraday-multipart
rack (>= 1.6)
dotenv (2.8.1) dotenv (2.8.1)
dotenv-rails (2.8.1) dotenv-rails (2.8.1)
dotenv (= 2.8.1) dotenv (= 2.8.1)
@@ -126,8 +131,23 @@ GEM
faraday (2.7.1) faraday (2.7.1)
faraday-net_http (>= 2.0, < 3.1) faraday-net_http (>= 2.0, < 3.1)
ruby2_keywords (>= 0.0.4) ruby2_keywords (>= 0.0.4)
faraday-follow_redirects (0.3.0)
faraday (>= 1, < 3)
faraday-multipart (1.0.4)
multipart-post (~> 2)
faraday-net_http (3.0.2) faraday-net_http (3.0.2)
ffi (1.15.5) ffi (1.15.5)
flipper (0.28.0)
concurrent-ruby (< 2)
flipper-active_record (0.28.0)
activerecord (>= 4.2, < 8)
flipper (~> 0.28.0)
flipper-ui (0.28.0)
erubi (>= 1.0.0, < 2.0.0)
flipper (~> 0.28.0)
rack (>= 1.4, < 3)
rack-protection (>= 1.5.3, <= 4.0.0)
sanitize (< 7)
fugit (1.7.2) fugit (1.7.2)
et-orbi (~> 1, >= 1.2.7) et-orbi (~> 1, >= 1.2.7)
raabro (~> 1.4) raabro (~> 1.4)
@@ -172,6 +192,7 @@ GEM
mini_mime (1.1.2) mini_mime (1.1.2)
mini_portile2 (2.8.0) mini_portile2 (2.8.0)
minitest (5.16.3) minitest (5.16.3)
multipart-post (2.3.0)
net-imap (0.3.1) net-imap (0.3.1)
net-protocol net-protocol
net-ldap (0.17.1) net-ldap (0.17.1)
@@ -199,6 +220,8 @@ GEM
raabro (1.4.0) raabro (1.4.0)
racc (1.6.0) racc (1.6.0)
rack (2.2.4) rack (2.2.4)
rack-protection (3.0.6)
rack
rack-test (2.0.2) rack-test (2.0.2)
rack (>= 1.3) rack (>= 1.3)
rails (7.0.4) rails (7.0.4)
@@ -283,6 +306,9 @@ GEM
ruby2_keywords (0.0.5) ruby2_keywords (0.0.5)
rufus-scheduler (3.8.2) rufus-scheduler (3.8.2)
fugit (~> 1.1, >= 1.1.6) fugit (~> 1.1, >= 1.1.6)
sanitize (6.0.1)
crass (~> 1.0.2)
nokogiri (>= 1.12.0)
sentry-rails (5.8.0) sentry-rails (5.8.0)
railties (>= 5.0) railties (>= 5.0)
sentry-ruby (~> 5.8.0) sentry-ruby (~> 5.8.0)
@@ -370,10 +396,14 @@ DEPENDENCIES
database_cleaner database_cleaner
devise (~> 4.9.0) devise (~> 4.9.0)
devise_ldap_authenticatable devise_ldap_authenticatable
discourse_api
dotenv-rails dotenv-rails
factory_bot_rails factory_bot_rails
faker faker
faraday faraday
flipper
flipper-active_record
flipper-ui
importmap-rails importmap-rails
jbuilder (~> 2.7) jbuilder (~> 2.7)
letter_opener letter_opener

View File

@@ -114,6 +114,10 @@ command:
* [Sidekiq](https://github.com/mperham/sidekiq/wiki/) * [Sidekiq](https://github.com/mperham/sidekiq/wiki/)
* [ActiveJob](https://github.com/mperham/sidekiq/wiki/Active-Job) * [ActiveJob](https://github.com/mperham/sidekiq/wiki/Active-Job)
### Feature Flags
* [Flipper](https://www.flippercloud.io/docs/get-started/self-hosted)
## License ## License
[GNU Affero General Public License v3.0](https://choosealicense.com/licenses/agpl-3.0/) [GNU Affero General Public License v3.0](https://choosealicense.com/licenses/agpl-3.0/)

View File

@@ -32,8 +32,4 @@
@apply bg-red-600 hover:bg-red-700 text-white @apply bg-red-600 hover:bg-red-700 text-white
focus:ring-red-500 focus:ring-opacity-75; focus:ring-red-500 focus:ring-opacity-75;
} }
input[type=text]:disabled {
@apply text-gray-700;
}
} }

View File

@@ -6,12 +6,13 @@
focus:ring-blue-600 focus:ring-opacity-75; focus:ring-blue-600 focus:ring-opacity-75;
} }
.field_with_errors { input[type=text]:disabled,
@apply inline-block; input[type=email]:disabled {
@apply text-gray-700;
} }
.field_with_errors input { input.field_with_errors {
@apply w-full bg-red-100; @apply border-b-red-600;
} }
.error-msg { .error-msg {

View File

@@ -1,5 +1,5 @@
class AccountController < ApplicationController class AccountController < ApplicationController
before_action :require_user_signed_in before_action :authenticate_user!
def index def index
@current_section = :account @current_section = :account

View File

@@ -1,5 +1,5 @@
class Contributions::DonationsController < ApplicationController class Contributions::DonationsController < ApplicationController
before_action :require_user_signed_in before_action :authenticate_user!
# GET /donations # GET /donations
# GET /donations.json # GET /donations.json

View File

@@ -1,5 +1,5 @@
class Contributions::ProjectsController < ApplicationController class Contributions::ProjectsController < ApplicationController
before_action :require_user_signed_in before_action :authenticate_user!
# GET /contributions # GET /contributions
def index def index

View File

@@ -1,7 +1,7 @@
class DashboardController < ApplicationController class DashboardController < ApplicationController
before_action :require_user_signed_in before_action :authenticate_user!
def index def index
@current_section = :dashboard @current_section = :services
end end
end end

View File

@@ -0,0 +1,17 @@
class Discourse::SsoController < ApplicationController
before_action :authenticate_user!
def connect
secret = Setting.discourse_connect_secret
sso = DiscourseApi::SingleSignOn.parse(request.query_string, secret)
sso.external_id = current_user.id
sso.email = current_user.email
sso.username = current_user.cn
sso.name = current_user.display_name
sso.admin = current_user.is_admin?
sso.sso_secret = secret
redirect_to sso.to_url("#{Setting.discourse_public_url}/session/sso_login"),
allow_other_host: true
end
end

View File

@@ -1,5 +1,5 @@
class InvitationsController < ApplicationController class InvitationsController < ApplicationController
before_action :require_user_signed_in, except: ["show"] before_action :authenticate_user!, except: ["show"]
before_action :require_user_signed_out, only: ["show"] before_action :require_user_signed_out, only: ["show"]
# GET /invitations # GET /invitations

View File

@@ -1,130 +0,0 @@
class Rs::OauthController < ApplicationController
before_action :require_user_signed_in
def new
username, org = params[:useraddress].split("@")
@user = User.where(cn: username.downcase, ou: org).first
@scopes = parse_scopes params[:scope]
@redirect_uri = params[:redirect_uri]
@client_id = params[:client_id]
@state = params[:state]
@root_access_requested = (@scopes & [":r",":rw"]).any?
@denial_url = url_with_state("#{@redirect_uri}#error=access_denied", @state)
@expire_at_dates = [["Never", nil],
["In 1 month", 1.month.from_now],
["In 1 day", 1.day.from_now]]
http_status :bad_request and return unless @redirect_uri.present?
unless current_user == @user
sign_out :user
redirect_to new_rs_oauth_url(@user.address,
scope: params[:scope],
redirect_uri: params[:redirect_uri],
client_id: params[:client_id],
state: params[:state])
return
end
unless @client_id.present?
redirect_to url_with_state("#{@redirect_uri}#error=invalid_request", @state) and return
end
if @scopes.empty?
redirect_to url_with_state("#{@redirect_uri}#error=invalid_scope", @state) and return
end
unless hostname_of(@client_id) == hostname_of(@redirect_uri)
redirect_to url_with_state("#{@redirect_uri}#error=invalid_client", @state) and return
end
@client_id.gsub!(/http(s)?:\/\//, "")
# TODO
# if auth = current_user.remote_storage_authorizations.valid.where(permissions: @scopes, client_id: @client_id).first
# redirect_to url_with_state("#{@redirect_uri}#access_token=#{auth.token}", @state), allow_other_host: true
# end
end
def create
unless current_user.id.to_s == params[:user_id]
Rails.logger.info("NO MATCH: #{params[:user_id]}, #{current_user.id}")
http_status :forbidden and return
end
permissions = parse_scopes params[:scope]
redirect_uri = params[:redirect_uri].presence
client_id = params[:client_id].presence
state = params[:state].presence
expire_at = params[:expire_at].presence
http_status :bad_request and return unless redirect_uri.present?
if permissions.empty?
redirect_to url_with_state("#{redirect_uri}#error=invalid_scope", state), allow_other_host: true and return
end
unless client_id.present?
redirect_to url_with_state("#{redirect_uri}#error=invalid_request", state), allow_other_host: true and return
end
unless hostname_of(client_id) == hostname_of(redirect_uri)
redirect_to url_with_state("#{redirect_uri}#error=invalid_client", state), allow_other_host: true and return
end
client_id.gsub!(/http(s)?:\/\//, "")
auth = current_user.remote_storage_authorizations.create!(
permissions: permissions,
client_id: client_id,
redirect_uri: redirect_uri,
app_name: client_id, #TODO use user-defined name
expire_at: expire_at
)
redirect_to url_with_state("#{redirect_uri}#access_token=#{auth.token}", state), allow_other_host: true
end
# GET /rs/oauth/token/:id/launch_app
def launch_app
auth = current_user.remote_storage_authorizations.find(params[:id])
redirect_to app_auth_url(auth)
end
private
def app_auth_url(auth)
url = "#{auth.url}#remotestorage=#{current_user.address}"
url += "&access_token=#{auth.token}"
url
end
def hostname_of(uri)
uri.gsub(/http(s)?:\/\//, "").split(":")[0].split("/")[0]
end
def parse_scopes(scope_string)
return [] if scope_string.blank?
scopes = scope_string.
gsub(/\[|\]/, "").
gsub(/\,/, " ").
gsub(/\/:/, ":").
split(/\s/).map(&:strip).
reject(&:empty?)
scopes = [":r"] if scopes.include?("*:r")
scopes = [":rw"] if scopes.include?("*:rw")
scopes
end
def url_with_state(url, state)
state ? "#{url}&state=#{CGI.escape(state)}" : url
end
end

View File

@@ -1,7 +1,7 @@
require "rqrcode" require "rqrcode"
class WalletController < ApplicationController class Services::LightningController < ApplicationController
before_action :require_user_signed_in before_action :authenticate_user!
before_action :authenticate_with_lndhub before_action :authenticate_with_lndhub
before_action :set_current_section before_action :set_current_section
before_action :fetch_balance before_action :fetch_balance
@@ -42,7 +42,7 @@ class WalletController < ApplicationController
end end
def set_current_section def set_current_section
@current_section = :wallet @current_section = :services
end end
def fetch_balance def fetch_balance
@@ -78,6 +78,7 @@ class WalletController < ApplicationController
tx["received"] = true tx["received"] = true
else else
tx["amount_sats"] = tx["value"] || tx["amt"] tx["amount_sats"] = tx["value"] || tx["amt"]
tx["fee"] = tx["type"] == "paid_invoice" ? tx["fee"] : nil
tx["datetime"] = Time.at(tx["timestamp"].to_i) tx["datetime"] = Time.at(tx["timestamp"].to_i)
tx["title"] = tx["type"] == "paid_invoice" ? "Sent" : "Received" tx["title"] = tx["type"] == "paid_invoice" ? "Sent" : "Received"
tx["description"] = tx["memo"] || tx["description"] tx["description"] = tx["memo"] || tx["description"]

View File

@@ -0,0 +1,30 @@
class Services::RemotestorageController < ApplicationController
before_action :require_user_signed_in
before_action :require_service_enabled
before_action :require_feature_enabled
before_action :set_current_section
def dashboard
# unless current_user.services_enabled.include?(:remotestorage)
# redirect_to service_remotestorage_info_path
# end
end
private
def require_feature_enabled
unless Flipper.enabled?(:remotestorage, current_user)
http_status :forbidden
end
end
def require_service_enabled
unless Setting.remotestorage_enabled?
http_status :not_found
end
end
def set_current_section
@current_section = :services
end
end

View File

@@ -1,24 +1,49 @@
class SettingsController < ApplicationController class SettingsController < ApplicationController
before_action :authenticate_user! before_action :authenticate_user!
before_action :set_main_nav_section before_action :set_main_nav_section
before_action :set_settings_section, only: ['show', 'update'] before_action :set_settings_section, only: [:show, :update, :update_email]
before_action :set_user, only: [:show, :update, :update_email]
def index def index
redirect_to setting_path(:profile) redirect_to setting_path(:profile)
end end
def show def show
@user = current_user
end end
def update def update
@user = current_user @user.preferences.merge!(user_params[:preferences] || {})
@user.preferences.merge! user_params[:preferences] @user.display_name = user_params[:display_name]
@user.save!
redirect_to setting_path(@settings_section), flash: { if @user.save
success: 'Settings saved.' if @user.display_name && (@user.display_name != @user.ldap_entry[:display_name])
} LdapManager::UpdateDisplayName.call(@user.dn, user_params[:display_name])
end
redirect_to setting_path(@settings_section), flash: {
success: 'Settings saved.'
}
else
@validation_errors = @user.errors
render :show, status: :unprocessable_entity
end
end
def update_email
if @user.valid_ldap_authentication?(email_params[:current_password])
if @user.update email: email_params[:email]
redirect_to setting_path(:account), flash: {
notice: 'Please confirm your new address using the confirmation link we just sent you.'
}
else
@validation_errors = @user.errors
render :show, status: :unprocessable_entity
end
else
redirect_to setting_path(:account), flash: {
error: 'Password did not match your current password. Try again.'
}
end
end end
def reset_password def reset_password
@@ -30,23 +55,31 @@ class SettingsController < ApplicationController
private private
def set_main_nav_section def set_main_nav_section
@current_section = :settings @current_section = :settings
end
def set_settings_section
@settings_section = params[:section]
allowed_sections = [:profile, :account, :lightning, :xmpp]
unless allowed_sections.include?(@settings_section.to_sym)
redirect_to setting_path(:profile)
end end
end
def user_params def set_settings_section
params.require(:user).permit(preferences: [ @settings_section = params[:section]
:lightning_notify_sats_received, allowed_sections = [:profile, :account, :lightning, :xmpp]
:xmpp_exchange_contacts_with_invitees
]) unless allowed_sections.include?(@settings_section.to_sym)
end redirect_to setting_path(:profile)
end
end
def set_user
@user = current_user
end
def user_params
params.require(:user).permit(:display_name, preferences: [
:lightning_notify_sats_received,
:xmpp_exchange_contacts_with_invitees
])
end
def email_params
params.require(:user).permit(:email, :current_password)
end
end end

View File

@@ -1,11 +0,0 @@
module OauthHelper
def scope_name(scope)
scope.gsub(/(\:.+)/, '')
end
def scope_permissions(scope)
scope.match(/\:r$/) ? "r" : "rw"
end
end

View File

@@ -0,0 +1,27 @@
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static targets = [ "emailField", "editEmailButton" ]
static values = { validationFailed: Boolean }
connect () {
if (this.validationFailedValue) return;
this.emailFieldTarget.disabled = true;
this.element.querySelectorAll(".initial-hidden").forEach(el => {
el.classList.add("hidden");
})
this.element.querySelectorAll(".initial-visible").forEach(el => {
el.classList.remove("hidden");
})
}
editEmail () {
this.emailFieldTarget.disabled = false;
this.emailFieldTarget.select();
this.editEmailButtonTarget.classList.add("hidden");
this.element.querySelectorAll(".initial-hidden").forEach(el => {
el.classList.remove("hidden");
})
}
}

View File

@@ -1,18 +1,22 @@
class XmppExchangeContactsJob < ApplicationJob class XmppExchangeContactsJob < ApplicationJob
queue_as :default queue_as :default
def perform(inviter, username, domain) def perform(inviter, invitee)
return unless inviter.services_enabled.include?("xmpp") &&
invitee.services_enabled.include?("xmpp") &&
inviter.preferences[:xmpp_exchange_contacts_with_invitees]
ejabberd = EjabberdApiClient.new ejabberd = EjabberdApiClient.new
ejabberd.add_rosteritem({ ejabberd.add_rosteritem({
"localuser": username, "localhost": domain, "localuser": invitee.cn, "localhost": invitee.ou,
"user": inviter.cn, "host": inviter.ou, "user": inviter.cn, "host": inviter.ou,
"nick": inviter.cn, "group": Setting.ejabberd_buddy_roster, "subs": "both" "nick": inviter.cn, "group": Setting.ejabberd_buddy_roster, "subs": "both"
}) })
ejabberd.add_rosteritem({ ejabberd.add_rosteritem({
"localuser": inviter.cn, "localhost": inviter.ou, "localuser": inviter.cn, "localhost": inviter.ou,
"user": username, "host": domain, "user": invitee.cn, "host": invitee.ou,
"nick": username, "group": Setting.ejabberd_buddy_roster, "subs": "both" "nick": invitee.cn, "group": Setting.ejabberd_buddy_roster, "subs": "both"
}) })
end end
end end

View File

@@ -0,0 +1,26 @@
class XmppSetDefaultBookmarksJob < ApplicationJob
queue_as :default
def perform(user)
return unless Setting.xmpp_default_rooms.any?
@user = user
ejabberd = EjabberdApiClient.new
ejabberd.private_set user, storage_content
end
def storage_content
bookmarks = ""
Setting.xmpp_default_rooms.each do |r|
bookmarks << conference_element(
jid: r[/<(.+)>/, 1], name: r[/^(.+)\s/, 1], nick: @user.cn,
autojoin: Setting.xmpp_autojoin_default_rooms
)
end
"<storage xmlns='storage:bookmarks'>#{bookmarks}</storage>"
end
def conference_element(jid:, name:, autojoin: false, nick:)
"<conference jid='#{jid}' name='#{name}' autojoin='#{autojoin.to_s}'><nick>#{nick}</nick></conference>"
end
end

View File

@@ -0,0 +1,34 @@
# frozen_string_literal: true
if defined?(ActionMailer)
class Devise::Mailer < Devise.parent_mailer.constantize
include Devise::Mailers::Helpers
def confirmation_instructions(record, token, opts = {})
@token = token
if record.pending_reconfirmation?
devise_mail(record, :reconfirmation_instructions, opts)
else
devise_mail(record, :confirmation_instructions, opts)
end
end
def reset_password_instructions(record, token, opts = {})
@token = token
devise_mail(record, :reset_password_instructions, opts)
end
def unlock_instructions(record, token, opts = {})
@token = token
devise_mail(record, :unlock_instructions, opts)
end
def email_changed(record, opts = {})
devise_mail(record, :email_changed, opts)
end
def password_change(record, opts = {})
devise_mail(record, :password_change, opts)
end
end
end

View File

@@ -1,32 +0,0 @@
class RemoteStorageAuthorization < ApplicationRecord
belongs_to :user
serialize :permissions
validates_presence_of :permissions
validates_presence_of :client_id
scope :valid, -> { where(expire_at: nil).or(where(expire_at: (DateTime.now)..)) }
scope :expired, -> { where(expire_at: ..(DateTime.now)) }
after_initialize do |a|
a.permisisons = [] if a.permissions == nil
end
before_create :generate_token
def url
if self.redirect_uri
uri = URI.parse self.redirect_uri
"#{uri.scheme}://#{client_id}"
else
"http://#{client_id}"
end
end
private
def generate_token(length=16)
self.token = SecureRandom.hex(length) if self.token.blank?
end
end

View File

@@ -2,6 +2,9 @@
class Setting < RailsSettings::Base class Setting < RailsSettings::Base
cache_prefix { "v1" } cache_prefix { "v1" }
field :accounts_domain, type: :string,
default: ENV["AKKOUNTS_DOMAIN"].presence
# #
# Internal services # Internal services
# #
@@ -17,6 +20,13 @@ class Setting < RailsSettings::Base
account accounts donations mail webmaster support account accounts donations mail webmaster support
] ]
#
# XMPP
#
field :xmpp_default_rooms, type: :array, default: []
field :xmpp_autojoin_default_rooms, type: :boolean, default: false
# #
# Sentry # Sentry
# #
@@ -34,6 +44,9 @@ class Setting < RailsSettings::Base
field :discourse_enabled, type: :boolean, field :discourse_enabled, type: :boolean,
default: (ENV["DISCOURSE_PUBLIC_URL"].present?.to_s || false) default: (ENV["DISCOURSE_PUBLIC_URL"].present?.to_s || false)
field :discourse_connect_secret, type: :string, readonly: true,
default: ENV["DISCOURSE_CONNECT_SECRET"].presence
# #
# ejabberd # ejabberd
# #

View File

@@ -1,6 +1,8 @@
class User < ApplicationRecord class User < ApplicationRecord
include EmailValidatable include EmailValidatable
attr_accessor :display_name
serialize :preferences, UserPreferences serialize :preferences, UserPreferences
# Relations # Relations
@@ -16,10 +18,8 @@ class User < ApplicationRecord
has_many :accounts, through: :lndhub_user has_many :accounts, through: :lndhub_user
has_many :remote_storage_authorizations
validates_uniqueness_of :cn validates_uniqueness_of :cn
validates_length_of :cn, :minimum => 3 validates_length_of :cn, minimum: 3
validates_format_of :cn, with: /\A([a-z0-9\-])*\z/, validates_format_of :cn, with: /\A([a-z0-9\-])*\z/,
if: Proc.new{ |u| u.cn.present? }, if: Proc.new{ |u| u.cn.present? },
message: "is invalid. Please use only letters, numbers and -" message: "is invalid. Please use only letters, numbers and -"
@@ -33,6 +33,9 @@ class User < ApplicationRecord
validates_uniqueness_of :email validates_uniqueness_of :email
validates :email, email: true validates :email, email: true
validates_length_of :display_name, minimum: 3, maximum: 35, allow_blank: true,
if: -> { defined?(@display_name) }
scope :confirmed, -> { where.not(confirmed_at: nil) } scope :confirmed, -> { where.not(confirmed_at: nil) }
scope :pending, -> { where(confirmed_at: nil) } scope :pending, -> { where(confirmed_at: nil) }
@@ -60,16 +63,18 @@ class User < ApplicationRecord
end end
def devise_after_confirmation def devise_after_confirmation
enable_service %w[ discourse gitea mediawiki xmpp ] if ldap_entry[:mail] != self.email
# E-Mail update confirmed
LdapManager::UpdateEmail.call(self.dn, self.email)
else
# E-Mail from signup confirmed (i.e. account activation)
enable_service %w[ discourse gitea mediawiki xmpp ]
#TODO enable in development when we have easy setup of ejabberd etc. #TODO enable in development when we have easy setup of ejabberd etc.
return if Rails.env.development? return if Rails.env.development? || !Setting.ejabberd_enabled?
if inviter.present? XmppExchangeContactsJob.perform_later(inviter, self) if inviter.present?
if Setting.ejabberd_enabled? && XmppSetDefaultBookmarksJob.perform_later(self)
inviter.preferences[:xmpp_exchange_contacts_with_invitees]
exchange_xmpp_contact_with_inviter
end
end end
end end
@@ -115,8 +120,13 @@ class User < ApplicationRecord
@dn = Devise::LDAP::Adapter.get_dn(self.cn) @dn = Devise::LDAP::Adapter.get_dn(self.cn)
end end
def ldap_entry def ldap_entry(reload: false)
ldap.fetch_users(uid: self.cn, ou: self.ou).first return @ldap_entry if defined?(@ldap_entry) && !reload
@ldap_entry = ldap.fetch_users(uid: self.cn, ou: self.ou).first
end
def display_name
@display_name ||= ldap_entry[:display_name]
end end
def services_enabled def services_enabled
@@ -141,12 +151,6 @@ class User < ApplicationRecord
ldap.delete_attribute(dn,:service) ldap.delete_attribute(dn,:service)
end end
def exchange_xmpp_contact_with_inviter
return unless inviter.services_enabled.include?("xmpp") &&
services_enabled.include?("xmpp")
XmppExchangeContactsJob.perform_later(inviter, self.cn, self.ou)
end
private private
def ldap def ldap

View File

@@ -10,7 +10,7 @@ class EjabberdApiClient
if res.status != 200 if res.status != 200
Rails.logger.error "[ejabberd] API request failed:" Rails.logger.error "[ejabberd] API request failed:"
Rails.logger.error res.body Rails.logger.error res.body
#TODO add some kind of exception tracking/notifications #TODO Send custom event to Sentry
end end
end end
@@ -21,4 +21,9 @@ class EjabberdApiClient
def send_message(payload) def send_message(payload)
post "send_message", payload post "send_message", payload
end end
def private_set(user, content)
payload = { user: user.cn, host: user.ou, element: content }
post "private_set", payload
end
end end

View File

@@ -0,0 +1,12 @@
module LdapManager
class UpdateDisplayName < LdapManagerService
def initialize(dn, display_name)
@dn = dn
@display_name = display_name
end
def call
replace_attribute @dn, :displayName, @display_name
end
end
end

View File

@@ -0,0 +1,12 @@
module LdapManager
class UpdateEmail < LdapManagerService
def initialize(dn, address)
@dn = dn
@address = address
end
def call
replace_attribute @dn, :mail, @address
end
end
end

View File

@@ -0,0 +1,2 @@
class LdapManagerService < LdapService
end

View File

@@ -50,7 +50,7 @@ class LdapService < ApplicationService
treebase = ldap_config["base"] treebase = ldap_config["base"]
end end
attributes = %w{dn cn uid mail admin service} attributes = %w{dn cn uid mail displayName admin service}
filter = Net::LDAP::Filter.eq("uid", args[:uid] || "*") filter = Net::LDAP::Filter.eq("uid", args[:uid] || "*")
entries = ldap_client.search(base: treebase, filter: filter, attributes: attributes) entries = ldap_client.search(base: treebase, filter: filter, attributes: attributes)
@@ -59,6 +59,7 @@ class LdapService < ApplicationService
{ {
uid: e.uid.first, uid: e.uid.first,
mail: e.try(:mail) ? e.mail.first : nil, mail: e.try(:mail) ? e.mail.first : nil,
display_name: e.try(:displayName) ? e.displayName.first : nil,
admin: e.try(:admin) ? 'admin' : nil, admin: e.try(:admin) ? 'admin' : nil,
service: e.try(:service) service: e.try(:service)
} }

View File

@@ -7,11 +7,46 @@
title: "Enable Discourse integration", title: "Enable Discourse integration",
description: "Discourse configuration present and features enabled" description: "Discourse configuration present and features enabled"
) %> ) %>
<% if Setting.discourse_enabled? %> <% if Setting.discourse_enabled? %>
<%= render FormElements::FieldsetComponent.new(title: "Public URL") do %> <%= render FormElements::FieldsetComponent.new(title: "Public URL") do %>
<%= f.text_field :discourse_public_url, <%= f.text_field :discourse_public_url,
value: Setting.discourse_public_url, value: Setting.discourse_public_url,
class: "w-full", disabled: true %> class: "w-full", disabled: true %>
<% end %>
<% end %> <% end %>
<%= render FormElements::FieldsetComponent.new(title: "Connect secret") do %>
<%= f.password_field :discourse_connect_secret,
value: Setting.discourse_connect_secret,
class: "w-full", disabled: true %>
<% end %>
<% end %>
</ul> </ul>
<% if Setting.discourse_enabled? %>
<% content_for :documentation do %>
<h3 class="mt-8">How to configure Discourse</h3>
<ol class="list-decimal list-inside">
<li class="mb-6">
Set the <strong>Discourse Connect URL</strong> to the following URL:
</li>
<li data-controller="clipboard" class="mb-6 flex gap-1">
<input type="text" class="grow" disabled="disabled"
value="https://<%= Setting.accounts_domain %>/discourse/connect"
data-clipboard-target="source" />
<button class="btn-md btn-icon btn-blue shrink-0"
data-clipboard-target="trigger" data-action="clipboard#copy"
title="Copy to clipboard">
<span class="content-initial">
<%= render partial: "icons/copy", locals: { custom_class: "text-white h-4 w-4 inline" } %>
</span>
<span class="content-active hidden">
<%= render partial: "icons/check", locals: { custom_class: "text-white h-4 w-4 inline" } %>
</span>
</button>
</li>
<li class="mb-6">
Set the <strong>Discourse Connect Secret</strong> to the value above.
</li>
<li>
Enable Discourse Connect.
</li>
<% end %>
<% end %>

View File

@@ -7,24 +7,43 @@
title: "Enable ejabberd integration", title: "Enable ejabberd integration",
description: "ejabberd configuration present and features enabled" description: "ejabberd configuration present and features enabled"
) %> ) %>
<% if Setting.ejabberd_enabled? %> <% if Setting.ejabberd_enabled? %>
<%= render FormElements::FieldsetComponent.new(title: "API URL") do %> <%= render FormElements::FieldsetComponent.new(title: "API URL") do %>
<%= f.text_field :ejabberd_api_url, <%= f.text_field :ejabberd_api_url,
value: Setting.ejabberd_api_url, value: Setting.ejabberd_api_url,
class: "w-full", disabled: true %> class: "w-full", disabled: true %>
<% end %> <% end %>
<%= render FormElements::FieldsetComponent.new(title: "Admin URL") do %> <%= render FormElements::FieldsetComponent.new(title: "Admin URL") do %>
<%= f.text_field :ejabberd_admin_url, <%= f.text_field :ejabberd_admin_url,
value: Setting.ejabberd_admin_url, value: Setting.ejabberd_admin_url,
class: "w-full", disabled: true %> class: "w-full", disabled: true %>
<% end %>
<%= render FormElements::FieldsetComponent.new(
title: "Contact roster name",
description: "Used when exchanging contacts after signup from invitation"
) do %>
<%= f.text_field :ejabberd_buddy_roster,
value: Setting.ejabberd_buddy_roster,
class: "w-full" %>
<% end %>
<% end %> <% end %>
</ul> </ul>
<h3 class="mt-10">User default settings</h3>
<ul role="list">
<%= render FormElements::FieldsetComponent.new(
title: "Default rooms",
description: "Add these default rooms to new users' bookmarks"
) do %>
<%= f.text_area :xmpp_default_rooms,
value: Setting.xmpp_default_rooms.join("\n"),
placeholder: "Welcome <welcome@kosmos.chat>\nKosmos <kosmos@kosmos.chat>",
class: "h-24 w-full" %>
<% end %>
<%= render FormElements::FieldsetToggleComponent.new(
form: f,
attribute: :xmpp_autojoin_default_rooms,
enabled: Setting.xmpp_autojoin_default_rooms?,
title: "Auto-join default rooms",
description: "Automatically join above default rooms in chat clients"
) %>
<%= render FormElements::FieldsetComponent.new(
title: "Contact roster name",
description: "Used when exchanging contacts after signup from invitation"
) do %>
<%= f.text_field :ejabberd_buddy_roster,
value: Setting.ejabberd_buddy_roster,
class: "w-full" %>
<% end %>
<% end %>
</ul>

View File

@@ -20,4 +20,10 @@
</p> </p>
</section> </section>
<% end %> <% end %>
<% if content_for?(:documentation) %>
<section>
<%= yield :documentation %>
</section>
<% end %>
<% end %> <% end %>

View File

@@ -6,6 +6,10 @@
<h3>Account</h3> <h3>Account</h3>
<table class="divided"> <table class="divided">
<tbody> <tbody>
<tr>
<th>ID</th>
<td><%= @user.id %></td>
</tr>
<tr> <tr>
<th>Created at</th> <th>Created at</th>
<td><%= @user.created_at.strftime("%Y-%m-%d (%H:%M UTC)") %></td> <td><%= @user.created_at.strftime("%Y-%m-%d (%H:%M UTC)") %></td>

View File

@@ -43,9 +43,9 @@
<div class="border border-gray-300 rounded-md hover:border-gray-400 <div class="border border-gray-300 rounded-md hover:border-gray-400
bg-cover bg-center sm:bg-[center_top_-140px] bg-no-repeat bg-cover bg-center sm:bg-[center_top_-140px] bg-no-repeat
bg-[url(/img/logos/icon_lightning.svg)]"> bg-[url(/img/logos/icon_lightning.svg)]">
<%= link_to wallet_path, <%= link_to services_lightning_index_path,
class: "block h-full px-6 py-6 rounded-md" do %> class: "block h-full px-6 py-6 rounded-md" do %>
<h3 class="mb-3.5">Wallet</h3> <h3 class="mb-3.5">Lightning Network</h3>
<p class="text-gray-600"> <p class="text-gray-600">
Send and receive sats over the Bitcoin Lightning Network Send and receive sats over the Bitcoin Lightning Network
</p> </p>
@@ -73,6 +73,17 @@
</p> </p>
<% end %> <% end %>
</div> </div>
<% if Setting.remotestorage_enabled? && Flipper.enabled?(:remotestorage, current_user) %>
<div class="border border-gray-300 rounded-md hover:border-gray-400">
<%= link_to services_storage_path,
class: "block h-full px-6 py-6 rounded-md" do %>
<h3 class="mb-3.5">Storage</h3>
<p class="text-gray-600">
Sync your data between apps and devices
</p>
<% end %>
</div>
<% end %>
<!-- <div class="border border&#45;gray&#45;300 rounded&#45;md hover:border&#45;gray&#45;400 --> <!-- <div class="border border&#45;gray&#45;300 rounded&#45;md hover:border&#45;gray&#45;400 -->
<!-- bg&#45;[length:80%] bg&#45;[right_top_&#45;30px] bg&#45;no&#45;repeat --> <!-- bg&#45;[length:80%] bg&#45;[right_top_&#45;30px] bg&#45;no&#45;repeat -->
<!-- bg&#45;[url(/img/logos/icon_mastodon.svg)]"> --> <!-- bg&#45;[url(/img/logos/icon_mastodon.svg)]"> -->

View File

@@ -1,5 +1,5 @@
<p>Welcome <%= @email %>!</p> <p>Welcome <%= @resource.cn %>!</p>
<p>You can confirm your account email through the link below:</p> <p>Please confirm your email address through the link below:</p>
<p><%= link_to 'Confirm my account', confirmation_url(@resource, confirmation_token: @token) %></p> <p><%= link_to 'Confirm my account', confirmation_url(@resource, confirmation_token: @token) %></p>

View File

@@ -1,4 +1,4 @@
<p>Hello <%= @email %>!</p> <p>Hello <%= @resource.cn %>!</p>
<% if @resource.try(:unconfirmed_email?) %> <% if @resource.try(:unconfirmed_email?) %>
<p>We're contacting you to notify you that your email is being changed to <%= @resource.unconfirmed_email %>.</p> <p>We're contacting you to notify you that your email is being changed to <%= @resource.unconfirmed_email %>.</p>

View File

@@ -1,3 +1,3 @@
<p>Hello <%= @resource.email %>!</p> <p>Hello <%= @resource.cn %>!</p>
<p>We're contacting you to notify you that your password has been changed.</p> <p>We're contacting you to notify you that your password has been changed.</p>

View File

@@ -0,0 +1,5 @@
<p>Hello <%= @resource.cn %>,</p>
<p>Please confirm your new email address through the link below:</p>
<p><%= link_to 'Confirm my address', confirmation_url(@resource, confirmation_token: @token) %></p>

View File

@@ -1,4 +1,4 @@
<p>Hello <%= @resource.email %>!</p> <p>Hello <%= @resource.cn %>!</p>
<p>Someone has requested a link to change your password. You can do this through the link below.</p> <p>Someone has requested a link to change your password. You can do this through the link below.</p>

View File

@@ -1,4 +1,4 @@
<p>Hello <%= @resource.email %>!</p> <p>Hello <%= @resource.cn %>!</p>
<p>Your account has been locked due to an excessive number of unsuccessful sign in attempts.</p> <p>Your account has been locked due to an excessive number of unsuccessful sign in attempts.</p>

View File

@@ -1,7 +1,13 @@
<%
# TODO remove when https://github.com/hotwired/turbo/issues/203 is fixed
enable_turbo = !session[:user_return_to].match?('/discourse/connect')
%>
<%= render HeaderCompactComponent.new(title: "Log in") %> <%= render HeaderCompactComponent.new(title: "Log in") %>
<%= render MainCompactComponent.new do %> <%= render MainCompactComponent.new do %>
<%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %> <%= form_for(resource, as: resource_name, url: session_path(resource_name),
data: { turbo: enable_turbo.to_s }) do |f| %>
<%= render "devise/shared/error_messages", resource: resource %> <%= render "devise/shared/error_messages", resource: resource %>
<div class="mb-6"> <div class="mb-6">
<%= f.label :cn, 'User', class: 'block mb-2 font-bold' %> <%= f.label :cn, 'User', class: 'block mb-2 font-bold' %>

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 512 512" fill="currentColor" stroke="currentColor" stroke-width="2" class="<%= custom_class %>"><path d="M475.31 364.144L288 256l187.31-108.144c5.74-3.314 7.706-10.653 4.392-16.392l-4-6.928c-3.314-5.74-10.653-7.706-16.392-4.392L272 228.287V12c0-6.627-5.373-12-12-12h-8c-6.627 0-12 5.373-12 12v216.287L52.69 120.144c-5.74-3.314-13.079-1.347-16.392 4.392l-4 6.928c-3.314 5.74-1.347 13.079 4.392 16.392L224 256 36.69 364.144c-5.74 3.314-7.706 10.653-4.392 16.392l4 6.928c3.314 5.74 10.653 7.706 16.392 4.392L240 283.713V500c0 6.627 5.373 12 12 12h8c6.627 0 12-5.373 12-12V283.713l187.31 108.143c5.74 3.314 13.079 1.347 16.392-4.392l4-6.928c3.314-5.74 1.347-13.079-4.392-16.392z"/></svg>

Before

Width:  |  Height:  |  Size: 760 B

View File

@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-edit-2"><path d="M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"></path></svg> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-edit-2 <%= custom_class %>"><path d="M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"></path></svg>

Before

Width:  |  Height:  |  Size: 291 B

After

Width:  |  Height:  |  Size: 312 B

View File

@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-edit-3"><path d="M12 20h9"></path><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"></path></svg> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-edit-3 <%= custom_class %>"><path d="M12 20h9"></path><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"></path></svg>

Before

Width:  |  Height:  |  Size: 317 B

After

Width:  |  Height:  |  Size: 338 B

View File

@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-edit"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path></svg> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-edit <%= custom_class %>"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path></svg>

Before

Width:  |  Height:  |  Size: 365 B

After

Width:  |  Height:  |  Size: 386 B

View File

@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-folder <%= custom_class %>"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"></path></svg> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-folder"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"></path></svg>

Before

Width:  |  Height:  |  Size: 331 B

After

Width:  |  Height:  |  Size: 311 B

View File

@@ -1,3 +1,3 @@
You just received <%= number_with_delimiter @amount_sats %> sats in your Lightning account (<%= @user.address %>). Check your wallet app, or open the account page for details: You just received <%= number_with_delimiter @amount_sats %> sats in your Lightning account (<%= @user.address %>). Check your wallet app, or open the account page for details:
<%= wallet_transactions_url %> <%= transactions_services_lightning_index_url %>

View File

@@ -1,60 +0,0 @@
<%= render HeaderComponent.new(title: "App Authorization") %>
<%= render MainSimpleComponent.new do %>
<section class="px-16 pb-8 mt-8">
<p class="text-lg mb-8">
The app
<%= link_to @client_id, "https://#{@client_id}", class: "ks-text-link" %>
is asking for access to these folders:
</p>
<p class="text-xl mb-8">
<% if @root_access_requested %>
<span class="text-red-700">
<span class="text-red-700">
<%= render partial: "icons/asterisk", locals: { custom_class: "inline-block align-middle mb-1" } %>
All files and directories
</span>
<% if (@scopes & [":r"]).any? %>
<span class="text-sm text-gray-500">(read only)</span>
<% end %>
</span>
<% else %>
<% @scopes.each do |scope| %>
<span class="text-gray-500">
<span>
<%= render partial: "icons/folder", locals: { custom_class: "inline-block align-middle mb-2" } %>
<%= scope_name(scope) %>
</span>
<% if scope_permissions(scope) == "r" %>
<span class="text-sm text-gray-500">(read only)</span>
<% end %>
</span>
<% end %>
<% end %>
</p>
<%= form_with(url: rs_oauth_path, method: :post, data: { turbo: false }) do |f| %>
<%= f.hidden_field :redirect_uri, value: @redirect_uri %>
<%= f.hidden_field :scope, value: @scopes.join(" ") %>
<%= f.hidden_field :user_id, value: @user.id %>
<%= f.hidden_field :client_id, value: @client_id %>
<%= f.hidden_field :state, value: @state %>
<p>
<%= f.label :expire_at, "Expire:" %>
<%= f.select :expire_at, options_for_select(@expire_at_dates) %>
</p>
<p class="text-sm text-gray-500 my-10">
You can revoke access for this app at any time on your storage dashboard.
</p>
<div>
<%= f.submit class: "btn-md btn-blue w-full sm:w-auto", data: { disable_with: "Saving..." } do %>
Allow
<% end %>
<%= link_to @denial_url, class: "btn-md btn-red w-full sm:w-auto" do %>
Deny
<% end %>
</div>
<% end %>
</section>
<% end %>

View File

@@ -1,9 +1,9 @@
<%= render HeaderComponent.new(title: "Wallet") %> <%= render HeaderComponent.new(title: "Lightning Network") %>
<%= render MainSimpleComponent.new do %> <%= render MainSimpleComponent.new do %>
<%= render WalletSummaryComponent.new(balance: @balance) %> <%= render WalletSummaryComponent.new(balance: @balance) %>
<%= render partial: "shared/tabnav_wallet" %> <%= render partial: "shared/tabnav_lightning" %>
<section> <section>
<h3>Lightning Address</h3> <h3>Lightning Address</h3>

View File

@@ -1,9 +1,9 @@
<%= render HeaderComponent.new(title: "Wallet") %> <%= render HeaderComponent.new(title: "Lightning Network") %>
<%= render MainSimpleComponent.new do %> <%= render MainSimpleComponent.new do %>
<%= render WalletSummaryComponent.new(balance: @balance) %> <%= render WalletSummaryComponent.new(balance: @balance) %>
<%= render partial: "shared/tabnav_wallet" %> <%= render partial: "shared/tabnav_lightning" %>
<section> <section>
<h3 class="hidden">Transactions</h3> <h3 class="hidden">Transactions</h3>
@@ -27,7 +27,7 @@
<p class="col-span-2 md:col-span-1 mb-0 text-right"> <p class="col-span-2 md:col-span-1 mb-0 text-right">
<span class="text-xl font-mono <%= tx["received"] ? "text-emerald-600" : "" %>"> <span class="text-xl font-mono <%= tx["received"] ? "text-emerald-600" : "" %>">
<%= tx["received"] ? "+" : "" %><%= number_with_delimiter tx["amount_sats"] %> <%= tx["received"] ? "+" : "" %><%= number_with_delimiter tx["amount_sats"] %>
<span class="hidden md:inline">sats</span> <span class="text-base md:text-lg">sats</span>
</span> </span>
</p> </p>
<p class="col-span-4 md:col-span-3 mb-0 text-gray-500"> <p class="col-span-4 md:col-span-3 mb-0 text-gray-500">
@@ -35,7 +35,10 @@
</p> </p>
<p class="col-span-4 md:col-span-1 md:text-right mb-0"> <p class="col-span-4 md:col-span-1 md:text-right mb-0">
<span class="col-span-2 md:col-span-1 text-sm text-gray-500"> <span class="col-span-2 md:col-span-1 text-sm text-gray-500">
<%= tx["datetime"].strftime("%B %e, %H:%M") %> <%= tx["datetime"].strftime("%B %e, %H:%M") -%>
<% if tx["fee"] && (tx["fee"] > 0) %>
~ Fee: <%= pluralize tx["fee"], "sat" %>
<% end %>
</span> </span>
</p> </p>
</li> </li>

View File

@@ -0,0 +1,7 @@
<%= render HeaderComponent.new(title: "Storage") %>
<%= render MainSimpleComponent.new do %>
<section>
<h3>Feature enabled</h3>
</section>
<% end %>

View File

@@ -1,13 +1,44 @@
<section> <%= tag.section data: {
controller: "settings--account--email",
"settings--account--email-validation-failed-value": @validation_errors.present?
} do %>
<h3>E-Mail</h3> <h3>E-Mail</h3>
<p class="mb-2"> <%= form_for(@user, url: update_email_settings_path, method: "post") do |f| %>
<%= label :email, 'Address', class: 'font-bold' %> <%= hidden_field_tag :section, "account" %>
</p> <p class="mb-2">
<p class="flex gap-1 mb-2 sm:w-3/5"> <%= f.label :email, 'Address', class: 'font-bold' %>
<input type="text" id="email" class="grow" </p>
value=<%= current_user.email %> disabled="disabled" /> <p class="mb-2 flex gap-1 sm:w-3/5">
</p> <%= f.email_field :email, class: "grow", data: {
</section> 'settings--account--email-target': 'emailField'
}, required: true %>
<button type="button" id="edit-email"
class="btn-md btn-icon btn-blue shrink-0 hidden initial-visible"
data-settings--account--email-target="editEmailButton"
data-action="settings--account--email#editEmail"
title="Edit email address">
<span class="">
<%= render partial: "icons/edit-3", locals: {
custom_class: "text-white h-4 w-4 inline" } %>
</span>
</button>
</p>
<% if @validation_errors.present? && @validation_errors[:email].present? %>
<p class="error-msg"><%= @validation_errors[:email].first %></p>
<% end %>
<div class="initial-hidden">
<p class="mt-4 mb-2">
<%= f.label :current_password, 'Current password', class: 'font-bold' %>
</p>
<p class="sm:w-3/5">
<%= f.password_field :current_password, class: "w-full", required: true %>
</p>
<p class="mt-6">
<%= f.submit "Update", class: "btn-md btn-blue w-full md:w-auto" %>
</p>
</div>
<% end %>
<% end %>
<section> <section>
<h3>Password</h3> <h3>Password</h3>
<p class="mb-8">Use the following button to request an email with a password reset link:</p> <p class="mb-8">Use the following button to request an email with a password reset link:</p>

View File

@@ -21,10 +21,15 @@
<p class="text-sm text-gray-500"> <p class="text-sm text-gray-500">
Your user address for Chat and Lightning Network. Your user address for Chat and Lightning Network.
</p> </p>
<%= form_for(@user, url: setting_path(:profile), html: { :method => :put }) do |f| %>
<%# <%= form_for(@user, as: "profile", url: settings_profile_path) do |f| %> <%= render FormElements::FieldsetComponent.new(tag: "div", title: "Display name") do %>
<%# <p class="mt-8"> <%= f.text_field :display_name, class: "w-full sm:w-3/5 mb-2" %>
<%# <%= f.submit "Save changes", class: 'btn-md btn-blue w-full sm:w-auto' %> <% if @validation_errors.present? && @validation_errors[:display_name].present? %>
<%# </p> <p class="error-msg"><%= @validation_errors[:display_name].first %></p>
<%# <% end %> <% end %>
<% end %>
<p class="mt-8 pt-6 border-t border-gray-200 text-right">
<%= f.submit 'Save', class: "btn-md btn-blue w-full md:w-auto" %>
</p>
<% end %>
</section> </section>

View File

@@ -1,10 +1,8 @@
<%= link_to "Services", root_path, <%= link_to "Services", root_path,
class: main_nav_class(@current_section, :dashboard) %> class: main_nav_class(@current_section, :services) %>
<%= link_to "Contributions", contributions_donations_path,
class: main_nav_class(@current_section, :contributions) %>
<%= link_to "Invitations", invitations_path, <%= link_to "Invitations", invitations_path,
class: main_nav_class(@current_section, :invitations) %> class: main_nav_class(@current_section, :invitations) %>
<%= link_to "Wallet", wallet_path, <%= link_to "Contributions", contributions_donations_path,
class: main_nav_class(@current_section, :wallet) %> class: main_nav_class(@current_section, :contributions) %>
<%= link_to "Settings", settings_path, <%= link_to "Settings", settings_path,
class: main_nav_class(@current_section, :settings) %> class: main_nav_class(@current_section, :settings) %>

View File

@@ -1,20 +1,20 @@
<%= render SidenavLinkComponent.new( <%= render SidenavLinkComponent.new(
name: "Profile", path: setting_path(:profile), icon: "user", name: "Profile", path: setting_path(:profile), icon: "user",
active: current_page?(setting_path(:profile)) active: @settings_section.to_s == "profile"
) %> ) %>
<%= render SidenavLinkComponent.new( <%= render SidenavLinkComponent.new(
name: "Account", path: setting_path(:account), icon: "key", name: "Account", path: setting_path(:account), icon: "key",
active: current_page?(setting_path(:account)) active: @settings_section.to_s == "account"
) %> ) %>
<% if Setting.ejabberd_enabled %> <% if Setting.ejabberd_enabled %>
<%= render SidenavLinkComponent.new( <%= render SidenavLinkComponent.new(
name: "Chat", path: setting_path(:xmpp), icon: "message-circle", name: "Chat", path: setting_path(:xmpp), icon: "message-circle",
active: current_page?(setting_path(:xmpp)) active: @settings_section.to_s == "xmpp"
) %> ) %>
<% end %> <% end %>
<% if Setting.lndhub_enabled %> <% if Setting.lndhub_enabled %>
<%= render SidenavLinkComponent.new( <%= render SidenavLinkComponent.new(
name: "Wallet", path: setting_path(:lightning), icon: "zap", name: "Lightning", path: setting_path(:lightning), icon: "zap",
active: current_page?(setting_path(:lightning)) active: @settings_section.to_s == "lightning"
) %> ) %>
<% end %> <% end %>

View File

@@ -0,0 +1,14 @@
<section>
<div class="border-b border-gray-200">
<nav class="-mb-px flex" aria-label="Tabs">
<%= render TabnavLinkComponent.new(
name: "Info", path: services_lightning_index_path,
active: current_page?(services_lightning_index_path)
) %>
<%= render TabnavLinkComponent.new(
name: "Transactions", path: transactions_services_lightning_index_path,
active: current_page?(transactions_services_lightning_index_path)
) %>
</nav>
</div>
</section>

View File

@@ -1,14 +0,0 @@
<section>
<div class="border-b border-gray-200">
<nav class="-mb-px flex" aria-label="Tabs">
<%= render TabnavLinkComponent.new(
name: "Info", path: wallet_path,
active: current_page?(wallet_path)
) %>
<%= render TabnavLinkComponent.new(
name: "Transactions", path: wallet_transactions_path,
active: current_page?(wallet_transactions_path)
) %>
</nav>
</div>
</section>

View File

@@ -0,0 +1,9 @@
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
if html_tag.match('class')
html_tag.gsub(/class="(.*?)"/, 'class="\1 field_with_errors"').html_safe
else
parts = html_tag.split('>', 2)
parts[0] += ' class="field_with_errors">'
(parts[0] + parts[1]).html_safe
end
end

View File

@@ -3,7 +3,7 @@
en: en:
devise: devise:
confirmations: confirmations:
confirmed: "Thanks for confirming your email address! Your account has been activated." confirmed: "Thanks for confirming your email address."
send_instructions: "You will receive an email with instructions for how to confirm your email address in a moment." send_instructions: "You will receive an email with instructions for how to confirm your email address in a moment."
send_paranoid_instructions: "If your email address exists in our database, you will receive an email with instructions for how to confirm your email address in a few minutes." send_paranoid_instructions: "If your email address exists in our database, you will receive an email with instructions for how to confirm your email address in a few minutes."
failure: failure:

View File

@@ -1,7 +1,7 @@
require 'sidekiq/web' require 'sidekiq/web'
Rails.application.routes.draw do Rails.application.routes.draw do
devise_for :users, controllers: { confirmations: "users/confirmations" } devise_for :users, controllers: { confirmations: 'users/confirmations' }
get 'welcome', to: 'welcome#index' get 'welcome', to: 'welcome#index'
get 'check_your_email', to: 'welcome#check_your_email' get 'check_your_email', to: 'welcome#check_your_email'
@@ -18,11 +18,19 @@ Rails.application.routes.draw do
resources :invitations, only: ['index', 'show', 'create', 'destroy'] resources :invitations, only: ['index', 'show', 'create', 'destroy']
get 'wallet', to: 'wallet#index' namespace :services do
get 'wallet/transactions', to: 'wallet#transactions' get 'storage', to: 'remotestorage#dashboard'
resources :lightning, only: [:index] do
collection do
get 'transactions'
end
end
end
resources :settings, param: 'section', only: ['index', 'show', 'update'] do resources :settings, param: 'section', only: ['index', 'show', 'update'] do
collection do collection do
post 'update_email'
post 'reset_password' post 'reset_password'
end end
end end
@@ -53,22 +61,20 @@ Rails.application.routes.draw do
end end
end end
namespace :rs do get ".well-known/webfinger", to: 'webfinger#show'
resource :oauth, only: [:new, :create], path_names: { new: ':useraddress' },
controller: 'oauth', constraints: { useraddress: /[^\/]+/} namespace :discourse do
get 'oauth/token/:id/launch_app' => 'oauth#launch_app', as: :launch_app get "connect", to: 'sso#connect'
end end
get ".well-known/webfinger" => "webfinger#show"
authenticate :user, ->(user) { user.is_admin? } do authenticate :user, ->(user) { user.is_admin? } do
mount Sidekiq::Web => '/sidekiq' mount Sidekiq::Web, at: '/sidekiq'
mount Flipper::UI.app(Flipper), at: '/flipper'
end end
# Letter Opener (open "sent" emails in dev and staging) # Letter Opener (open "sent" emails in dev and staging)
if Rails.env.match(/staging|development/) if Rails.env.match(/staging|development/)
mount LetterOpenerWeb::Engine, at: "letter_opener" mount LetterOpenerWeb::Engine, at: '/letter_opener'
end end
root to: 'dashboard#index' root to: 'dashboard#index'

View File

@@ -1,17 +0,0 @@
class CreateRemoteStorageAuthorizations < ActiveRecord::Migration[7.0]
def change
create_table :remote_storage_authorizations do |t|
t.references :user, null: false, foreign_key: true
t.string :token
t.text :permissions, array: true, default: [].to_yaml
t.string :client_id
t.string :redirect_uri
t.string :app_name
t.datetime :expire_at
t.timestamps
end
add_index :remote_storage_authorizations, :permissions, using: 'gin'
end
end

View File

@@ -0,0 +1,22 @@
class CreateFlipperTables < ActiveRecord::Migration[7.0]
def self.up
create_table :flipper_features do |t|
t.string :key, null: false
t.timestamps null: false
end
add_index :flipper_features, :key, unique: true
create_table :flipper_gates do |t|
t.string :feature_key, null: false
t.string :key, null: false
t.string :value
t.timestamps null: false
end
add_index :flipper_gates, [:feature_key, :key, :value], unique: true
end
def self.down
drop_table :flipper_gates
drop_table :flipper_features
end
end

View File

@@ -10,7 +10,7 @@
# #
# It's strongly recommended that you check this file into your version control system. # It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema[7.0].define(version: 2023_04_03_150200) do ActiveRecord::Schema[7.0].define(version: 2023_05_23_120753) do
create_table "donations", force: :cascade do |t| create_table "donations", force: :cascade do |t|
t.integer "user_id" t.integer "user_id"
t.integer "amount_sats" t.integer "amount_sats"
@@ -23,6 +23,22 @@ ActiveRecord::Schema[7.0].define(version: 2023_04_03_150200) do
t.index ["user_id"], name: "index_donations_on_user_id" t.index ["user_id"], name: "index_donations_on_user_id"
end end
create_table "flipper_features", force: :cascade do |t|
t.string "key", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["key"], name: "index_flipper_features_on_key", unique: true
end
create_table "flipper_gates", force: :cascade do |t|
t.string "feature_key", null: false
t.string "key", null: false
t.string "value"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["feature_key", "key", "value"], name: "index_flipper_gates_on_feature_key_and_key_and_value", unique: true
end
create_table "invitations", force: :cascade do |t| create_table "invitations", force: :cascade do |t|
t.string "token" t.string "token"
t.integer "user_id" t.integer "user_id"
@@ -34,20 +50,6 @@ ActiveRecord::Schema[7.0].define(version: 2023_04_03_150200) do
t.index ["user_id"], name: "index_invitations_on_user_id" t.index ["user_id"], name: "index_invitations_on_user_id"
end end
create_table "remote_storage_authorizations", force: :cascade do |t|
t.integer "user_id", null: false
t.string "token"
t.text "permissions", default: "--- []\n"
t.string "client_id"
t.string "redirect_uri"
t.string "app_name"
t.datetime "expire_at"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["permissions"], name: "index_remote_storage_authorizations_on_permissions"
t.index ["user_id"], name: "index_remote_storage_authorizations_on_user_id"
end
create_table "settings", force: :cascade do |t| create_table "settings", force: :cascade do |t|
t.string "var", null: false t.string "var", null: false
t.text "value" t.text "value"
@@ -79,5 +81,4 @@ ActiveRecord::Schema[7.0].define(version: 2023_04_03_150200) do
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end end
add_foreign_key "remote_storage_authorizations", "users"
end end

View File

@@ -11,7 +11,7 @@
"postcss-preset-env": "^7.8.3", "postcss-preset-env": "^7.8.3",
"tailwindcss": "^3.2.4" "tailwindcss": "^3.2.4"
}, },
"version": "0.5.0", "version": "0.6.0",
"scripts": { "scripts": {
"build:css:tailwind": "tailwindcss --postcss -i ./app/assets/stylesheets/application.tailwind.css -o ./app/assets/builds/application.css", "build:css:tailwind": "tailwindcss --postcss -i ./app/assets/stylesheets/application.tailwind.css -o ./app/assets/builds/application.css",
"build:css": "yarn run build:css:tailwind" "build:css": "yarn run build:css:tailwind"

View File

@@ -0,0 +1,58 @@
require 'rails_helper'
RSpec.describe 'Account settings', type: :feature do
let(:user) { create :user }
feature "Update email address" do
let(:geraint) { create :user, id: 2, cn: 'geraint', email: "lamagliarosa@example.com" }
before do
login_as user, :scope => :user
geraint.save!
allow_any_instance_of(User).to receive(:valid_ldap_authentication?)
.with("invalid password").and_return(false)
allow_any_instance_of(User).to receive(:valid_ldap_authentication?)
.with("valid password").and_return(true)
end
scenario 'fails with invalid password' do
visit setting_path(:account)
fill_in 'Address', with: "lamagliarosa@example.com"
fill_in 'Current password', with: "invalid password"
click_button "Update"
expect(current_url).to eq(setting_url(:account))
expect(user.reload.unconfirmed_email).to be_nil
within ".flash-msg" do
expect(page).to have_content("did not match your current password")
end
end
scenario 'fails when new address already taken' do
visit setting_path(:account)
fill_in 'Address', with: "lamagliarosa@example.com"
fill_in 'Current password', with: "valid password"
click_button "Update"
expect(current_url).to eq(setting_url(:update_email))
expect(user.reload.unconfirmed_email).to be_nil
within ".error-msg" do
expect(page).to have_content("has already been taken")
end
end
scenario 'works with valid password and address' do
visit setting_path(:account)
fill_in 'Address', with: "lamagliabianca@example.com"
fill_in 'Current password', with: "valid password"
click_button "Update"
expect(current_url).to eq(setting_url(:account))
expect(user.reload.unconfirmed_email).to eq("lamagliabianca@example.com")
within ".flash-msg" do
expect(page).to have_content("Please confirm your new address")
end
end
end
end

View File

@@ -0,0 +1,45 @@
require 'rails_helper'
RSpec.describe 'Profile settings', type: :feature do
let(:user) { create :user, cn: "mwahlberg" }
before do
login_as user, :scope => :user
end
feature "Update display name" do
before do
allow(user).to receive(:display_name).and_return("Mark")
allow_any_instance_of(User).to receive(:dn).and_return("cn=mwahlberg,ou=kosmos.org,cn=users,dc=kosmos,dc=org")
allow_any_instance_of(User).to receive(:ldap_entry).and_return({
uid: user.cn, ou: user.ou, display_name: "Mark"
})
end
scenario 'fails with validation error' do
visit setting_path(:profile)
fill_in 'Display name', with: "M"
click_button "Save"
expect(current_url).to eq(setting_url(:profile))
expect(page).to have_field('Display name', with: 'M')
within ".error-msg" do
expect(page).to have_content("is too short")
end
end
scenario 'works with valid input' do
expect(LdapManager::UpdateDisplayName).to receive(:call)
.with(user.dn, "Marky Mark").and_return(true)
visit setting_path(:profile)
fill_in 'Display name', with: "Marky Mark"
click_button "Save"
expect(current_url).to eq(setting_url(:profile))
within ".flash-msg" do
expect(page).to have_content("Settings saved")
end
end
end
end

View File

@@ -2,15 +2,18 @@ require 'rails_helper'
require 'webmock/rspec' require 'webmock/rspec'
RSpec.describe XmppExchangeContactsJob, type: :job do RSpec.describe XmppExchangeContactsJob, type: :job do
let(:user) { create :user, cn: "willherschel", ou: "kosmos.org" } let(:user) { create :user, cn: "willherschel", ou: "kosmos.org" }
let(:guest) { create :user, cn: "isaacnewton", ou: "kosmos.org",
id: 2, email: "hotapple42@eol.com" }
subject(:job) { subject(:job) {
described_class.perform_later(user, 'isaacnewton', 'kosmos.org') described_class.perform_later(user, guest)
} }
before do before do
stub_request(:post, "http://xmpp.example.com/api/add_rosteritem") stub_request(:post, "http://xmpp.example.com/api/add_rosteritem")
.to_return(status: 200, body: "", headers: {}) .to_return(status: 200, body: "", headers: {})
allow_any_instance_of(User).to receive(:services_enabled).and_return(["xmpp"])
end end
it "posts add_rosteritem commands to the ejabberd API" do it "posts add_rosteritem commands to the ejabberd API" do

View File

@@ -0,0 +1,34 @@
require 'rails_helper'
require 'webmock/rspec'
RSpec.describe XmppSetDefaultBookmarksJob, type: :job do
let(:user) { create :user, cn: "willherschel", ou: "kosmos.org" }
before do
Setting.xmpp_default_rooms = [
"Welcome <welcome@kosmos.chat>",
"Kosmos Dev <kosmos-dev@kosmos.chat>"
]
end
subject(:job) {
described_class.perform_later(user)
}
before do
stub_request(:post, "http://xmpp.example.com/api/private_set")
.to_return(status: 200, body: "", headers: {})
end
it "posts a private_set command to the ejabberd API" do
perform_enqueued_jobs { job }
expect(WebMock).to have_requested(:post, "http://xmpp.example.com/api/private_set")
.with { |req| req.body == '{"user":"willherschel","host":"kosmos.org","element":"\u003cstorage xmlns=\'storage:bookmarks\'\u003e\u003cconference jid=\'welcome@kosmos.chat\' name=\'Welcome\' autojoin=\'false\'\u003e\u003cnick\u003ewillherschel\u003c/nick\u003e\u003c/conference\u003e\u003cconference jid=\'kosmos-dev@kosmos.chat\' name=\'Kosmos Dev\' autojoin=\'false\'\u003e\u003cnick\u003ewillherschel\u003c/nick\u003e\u003c/conference\u003e\u003c/storage\u003e"}' }
end
after do
clear_enqueued_jobs
clear_performed_jobs
end
end

View File

@@ -101,64 +101,75 @@ RSpec.describe User, type: :model do
end end
end end
describe "#exchange_xmpp_contact_with_inviter" do describe "#devise_after_confirmation" do
include ActiveJob::TestHelper include ActiveJob::TestHelper
let(:user) { create :user, cn: "willherschel", ou: "kosmos.org" } let(:user) { create :user, cn: "willherschel", ou: "kosmos.org", email: "will@hrsch.el" }
let(:guest) { create :user, id: 2, cn: "isaacnewton", ou: "kosmos.org", email: "newt@example.com" }
before do before do
Invitation.create! user: user, invited_user_id: guest.id, used_at: DateTime.now allow(user).to receive(:ldap_entry).and_return({
allow_any_instance_of(User).to receive(:services_enabled).and_return(%w[ xmpp ]) uid: "willherschel", ou: "kosmos.org", mail: "will@hrsch.el"
})
end end
it "enqueues a job to exchange XMPP contacts between inviter and invitee" do after { clear_enqueued_jobs }
guest.send(:exchange_xmpp_contact_with_inviter)
expect(enqueued_jobs.size).to eq(1)
args = enqueued_jobs.first['arguments']
expect(args[0]['_aj_globalid']).to match('gid://akkounts/User')
expect(args[1]).to eq('isaacnewton')
expect(args[2]).to eq('kosmos.org')
end
after do
clear_enqueued_jobs
end
end
describe "#devise_after_confirmation" do
let(:user) { create :user, cn: "willherschel", ou: "kosmos.org" }
it "enables default services" do it "enables default services" do
expect(user).to receive(:enable_service).with(%w[ discourse gitea mediawiki xmpp ]) expect(user).to receive(:enable_service).with(%w[ discourse gitea mediawiki xmpp ])
user.send(:devise_after_confirmation) user.send :devise_after_confirmation
end
it "enqueues a job to set default chatroom bookmarks for XMPP" do
allow(user).to receive(:enable_service).and_return(true)
user.send :devise_after_confirmation
job = enqueued_jobs.select{|j| j['job_class'] == "XmppSetDefaultBookmarksJob"}.first
expect(job['arguments'][0]['_aj_globalid']).to eq('gid://akkounts/User/1')
end end
context "for invited user with xmpp enabled" do context "for invited user with xmpp enabled" do
let(:guest) { create :user, id: 2, cn: "isaacnewton", ou: "kosmos.org", email: "newt@example.com" } let(:guest) { create :user, id: 2, cn: "isaacnewton", ou: "kosmos.org", email: "newt@example.com" }
before do before do
# TODO remove when defaults are implemented
user.update! preferences: { xmpp_exchange_contacts_with_invitees: true }
Invitation.create! user: user, invited_user_id: guest.id, used_at: DateTime.now Invitation.create! user: user, invited_user_id: guest.id, used_at: DateTime.now
allow_any_instance_of(User).to receive(:enable_service).and_return(true) allow_any_instance_of(User).to receive(:enable_service)
allow(guest).to receive(:ldap_entry).and_return({
uid: "isaacnewton", ou: "kosmos.org", mail: "newt@example.com"
})
end end
it "exchanges XMPP contacts with the inviter" do it "enqueues jobs to exchange XMPP contacts between inviter and invitee" do
expect(guest).to receive(:exchange_xmpp_contact_with_inviter) guest.send :devise_after_confirmation
guest.send(:devise_after_confirmation)
job = enqueued_jobs.select{|j| j['job_class'] == "XmppExchangeContactsJob"}.first
expect(job["arguments"][0]['_aj_globalid']).to eq('gid://akkounts/User/1')
expect(job["arguments"][1]['_aj_globalid']).to eq('gid://akkounts/User/2')
end
end
context "for email address update of existing account" do
before do
allow(user).to receive(:ldap_entry)
.and_return({ uid: "willherschel", ou: "kosmos.org", mail: "willyboy@aol.com" })
allow(user).to receive(:dn)
.and_return("cn=willherschel,ou=kosmos.org,cn=users,dc=kosmos,dc=org")
allow(LdapManager::UpdateEmail).to receive(:call)
end end
context "automatic contact exchange disabled" do it "updates the LDAP 'mail' attribute" do
before do expect(LdapManager::UpdateEmail).to receive(:call)
user.update! preferences: { xmpp_exchange_contacts_with_invitees: false } .with("cn=willherschel,ou=kosmos.org,cn=users,dc=kosmos,dc=org", "will@hrsch.el")
end user.send :devise_after_confirmation
end
it "does not exchange XMPP contacts with the inviter" do it "does not re-enable default services" do
expect(guest).to_not receive(:exchange_xmpp_contact_with_inviter) expect(user).not_to receive(:enable_service)
guest.send(:devise_after_confirmation) user.send :devise_after_confirmation
end end
it "does not enqueue any delayed jobs" do
user.send :devise_after_confirmation
expect(enqueued_jobs).to be_empty
end end
end end
end end

View File

@@ -0,0 +1,41 @@
require 'rails_helper'
require 'webmock/rspec'
RSpec.describe "Discourse SSO", type: :request do
describe "GET /discourse/connect" do
let(:user) { create :user, cn: 'jimmy', ou: 'kosmos.org' }
before do
Warden.test_mode!
login_as user, scope: :user
allow(user).to receive(:display_name).and_return('Jimbo')
allow(user).to receive(:is_admin?).and_return(false)
end
after do
Warden.test_reset!
end
context "with invalid SSO credentials" do
it "results in a failed signature check" do
expect {
get discourse_connect_path(
sso: "bm9uY2U9ODk2N2NiMmFlZTdlMjdjNzZiZTNkZWQ5ODIwYzMzN2QmcmV0dXJuX3Nzb191cmw9aHR0cCUzQSUyRiUyRmxvY2FsaG9zdCUzQTMwMDAlMkZzZXNzaW9uJTJGc3NvX2xvZ2lu",
sig: "01fc008ff7b51855217e879b6f14aaddefbbd4df2d128951f7bb70cfde834c2a"
)
}.to raise_error(DiscourseApi::SingleSignOn::ParseError)
end
end
context "valid SSO credentials" do
it "redirects to the Discourse SSO endpoint" do
get discourse_connect_path(
sso: "bm9uY2U9YjQwYWZmYzg0YWQ2NWE1ZTk5MjdlZWU1NWEzMjdhMTQmcmV0dXJuX3Nzb191cmw9aHR0cCUzQSUyRiUyRmxvY2FsaG9zdCUzQTMwMDAlMkZzZXNzaW9uJTJGc3NvX2xvZ2lu",
sig: "b7905c5db612391293249ad5272dac493681efcd255133f6c2aff91ba654a319"
)
expect(response).to redirect_to('http://discourse.example.com/session/sso_login?sso=YWRtaW49ZmFsc2UmZW1haWw9amltbXklNDBleGFtcGxlLmNvbSZleHRlcm5hbF9pZD0xJm5hbWU9SmltYm8mbm9uY2U9YjQwYWZmYzg0YWQ2NWE1ZTk5MjdlZWU1NWEzMjdhMTQmcmV0dXJuX3Nzb191cmw9aHR0cCUzQSUyRiUyRmxvY2FsaG9zdCUzQTMwMDAlMkZzZXNzaW9uJTJGc3NvX2xvZ2luJnVzZXJuYW1lPWppbW15&sig=d5f8b1d6db66569bef789fda4a3216119c2d42b84725d043c9a57dde1e528842')
end
end
end
end